       
     
          
      
                               huggingface   {"info": {"features": {"commit": {"dtype": "string", "_type": "Value"}, "subject": {"dtype": "string", "_type": "Value"}, "message": {"dtype": "string", "_type": "Value"}, "repos": {"dtype": "string", "_type": "Value"}, "file_path": {"dtype": "string", "_type": "Value"}, "license": {"dtype": "string", "_type": "Value"}, "unix_time": {"dtype": "int64", "_type": "Value"}, "new_contents": {"dtype": "string", "_type": "Value"}, "old_contents": {"dtype": "string", "_type": "Value"}}}}    	     `  4          l   8                         old_contents                       new_contents         $          	   unix_time             @   4                  license $\               	   file_path   P                  repos   x                  message                   subject                               commit                              <W       
     
                                                         <      B              B            H      8                                      B      p              p                  A                                   v      6             6           (<     *      XB             XB            xN             xN           T     +     0 -             0 -           H-     5*         	                                                                                                                                     (   P   x              @  h          0  X             H  p          8  `           (  P  x          @  h          0  X             H  p        	  8	  `	  	  	  	   
  (
  P
  x
  
  
  
    @  h          0  X             H  p          8  `           (  P  x          @  h          0  X             H  p          8  `           (  P  x          @  h          0  X             H  p          8  `           (  P  x          @  h          0  X             H  p          8  `           (  P  x          @  h           0   X                !  H!  p!  !  !  !  "  8"  `"  "  "  "   #  (#  P#  x#  #  #  #  $  @$  h$  $  $  $  %  0%  X%  %  %  %  %   &  H&  p&  &  &  &  '  8'  `'  '  '  '   (  ((  P(  x(  (  (  (  )  @)  h)  )  )  )  *  0*  X*  *  *  *  *   +  H+  p+  +  +  +  ,  8,  `,  ,  ,  ,   -  (-  P-  x-  -  -  -  .  @.  h.  .  .  .  /  0/  X/  /  /  /  /   0  H0  p0  0  0  0  1  81  `1  1  1  1   2  (2  P2  x2  2  2  2  3  @3  h3  3  3  3  4  04  X4  4  4  4  4   5  H5  p5  5  5  5  6  86  `6  6  6  6   7  (7  P7  x7  7  7  7  8  @8  h8  8  8  8  9  09  X9  9  9  9  9   :  H:  p:  :  :  :  ;  8;  `;  ;  ;  ;   <  (<  P<  x<  <      dfe17f69014680a4bfd337b487bd9c7ec0a851d9c35f86d1eb9546b8823128a0a4581f75770b551de63ca1b16833e86817df9e3aea44dd02ae983619bec05e3cdd7fde7c3e561c46d98dfbc58b3cb5185ed6f67f50debe7cb418dd0f32bca6a593b156b473021035bbde0cd8216e57409a40aa457c19dc6cec40034355748dd7fa12d68c88a255abd86f916aaee2bc2fff739b19b423b52fcb197d7e1944201ccb302fd1a44db088ecc4d4dd0aef27b0f30b50c9920d8522dc0de3db70e7258b4476a188bc9268f5a1e041ba907f164751272f97b13e52f24e8d57e151d83bcec5877c440b43cebe7338341a4285cb319375e016143b2e659fc62b9634a334f3850241507d28866a13cd0684098ec406985eaf8d004f29c5a23981e7b55b79ad780593872e933316d2963e09bf1910de58e8d1fd4bf87ed091cee490e56d49df2ced0101b8bb729a34247cc5676955d711c75207ff74ba5bf7beb61c9d8a1d1aa23c88a1e47323c36723471f940b9027fad6da7f46183a0d7d4686d62b3f5373043f9654f4ab6d4b9ab15774a2a619efe47770cf26b38e4d6ebe52005423ad6f3d3db7d7a4cac4bce43955b8000dcb3ddaf4efcc8e8700e65883273b8262c937a61c2fffec8396de5ca097f72854ebcd973facb65c1d6d4739619bbbbd5f98e896e57c36271aa26b91a4d6d4dac6174988d9b3e41d2e133861399d0a580089857dc6d2f153340204931cd71c708a067365a9eda41bcb54256068293373ebc9a3fcac89fbab7642e4c1369dac10829663a028f6be9ad44df87827adc7ab6b0c29201720f445823056b333e9e4c703f8ec781753d9a6620c82331b32fd998358f41cdab00565f07db9d7c287bde02ca20eb598a7ed4e426106f561a68f8340f4466f816c6523f0a36114797e14625a89f856c12ac93205392d7d1ede011a934d027ae1310dc08fbb95addadd8e264b97ec4743b9aaba8aaaf94561f88685ab376576f3df8a6d899feaaa4f8fe8801db397b7f4670aee442b4df8bd2e047733302575d75ae026444670a22aae78abf2a1b707eb86512e0c9c57daf6406985b378b5e49d4e517b0f38eadee8634b207c909a6f780a97c7f68919f8ad6d47fc28229dc2fd98412fb4d1db1404f06e8050bd10368b89f9b2614bbb3633accd446af04c2897952c254e81fd9bafc47b41b45e4389cbc347ffee9645fe4147a74013a7461fa112c2ba9e43346b800a66bf08d7ad46fabf6f86b813720730c854ba0a6c085e096d13c4a2767237e4f1168936874a66eb98ad1710ced6531ccda2080771b62fe8d3d40be5b891ed86054144cc43ebb2b2f91a8660f16e0a16945329db92753955a37b02ea9792e0abe7ad8b957a9f15fbb0b3c00f1c26798cb863e5dfb4b5d6b056bb9db724991d17dfb56c03da8cf4ccf1aeee1ef8d87834d6edc6cef761a671bb59dbba8f73ba5abe9749d0dc8c252b0d0551094706da5b5fb1c59469ddbc4fd06f328f031047c77c405456bc7530ac27c86fc2ef8843d90852a2056ab9dc1e2ea3bb258db5df77e56a6d15a3e3732fde0c63abf5853349c5a5162765168609fab2b690ee7ef5b597cf39cf399c81a6703d8528149bfafa95f233407c5d1ed75e8835ce8ca3a7bb1fb288b82b4cbb0c8705e4ba14babed9c35d29bde371fe24d9ce1465cd5d6003b682e17c3c4a319086b0f166d91e17385b4e2f6674380b24ce21b82cb6ea04f9cc239d3fd26d70bb5bec0f1ff1d2ba1b4e01898108de79645f0b285ecdc143d17257994cac46354b6d9c6e2a7c281ce979e41b948b73a5efea8dcb79719d25d8e7b4ee42302dc4d63f2e4a056e731f2f6f9500dba98de8699f8e83356e6a204081c7a4c8d550b4a102b3f3e02395653a1b24c0e96b6b66d617898bd775940539f8342fe27f5196799b974391fc7dbd4b9f4cf5ad87d2ff016aa43e6c4cf22a93127eb0fcccb3721422d911d278360c9ef4c34eff20343077f86efff48e3c932856a0e3d65c760ec99c4c699a861f9965866303945677cb94223ed0ecfdb0ab32bb2592d2ddbabfcb12ba1b3307a98873523285adb6edbd57fe84bf0699eb37b5d3b60128d9a85bbae41a138e51fe684db24c6b86346d39d641cff25b30ecb0f69071514d5496ef890123988497aa39ca73275d9575cd548e8cb8ef78a327d84ff96bd6dafa261c0a264bdde1028983f7a174a75f391fcda2e01db09fc222a0ab55b9df789323920eed1fa1ed3bc0c46f2ef045b62811e3e66b8f7efdbaff44953cd2a327a46b6bca20d26091dd95fc338cfa763d464df5d482bff5fa5de441d7e6e8ba32bd07f87728b5698dc16e49b7eaafa26982a9f1d6bfa0f7ee05105d330d04347f5dd409b1410dfb150c93994da1516de487ea9334a06853780650785f05c64d8c1bcd324960d651fd7493c2a9e03ee65ee280d756622181889011981eb1b8e306dec346ec7fd942dc6b96ff1589f3842c7c5a698006ca966d20f208bb0d51169b3bbad7684963234782cff08d93005d52aa4316fd739cb9211e20b062d15762cc519594c423228fbdba1cbb8127b3d3976c5343c52612b0a70af17712b70824627199e88bf66cd0378b093e9215edc1d1735568851e0b19da5b4ac0e39412055dae24e68f7dfb1d9cef71b71bb71f703dbb8b5792b62bff4bb381da3f2f143722dc2a6b46db78dac807aea52a529d0f33cfd264d3c7399a97f5906ccd3caa63c56d56da40371690098de02ec81586689fbccee0c2cfd51347b4ff7b1239c728b622613ec3967dc036b8a8d0d22913be094aad97af1534a259cfa0527f0ccdafb308edc533f54b0a81d15572fd30093ed80de53c440dccb11dd81535c0cc1249723501b53c5bf222dd58844f3c302f8ae23b866c303fc0d42bf190853b6ad07b6c8072ef5ca752e59b5425f2c1f959016026f699a3a1e8f7917711e0921a31ad0b6c3deff00cc5c03c4b74987145f4a79f0e72d96663c6aa76ae7444afa1d00dfc7480b456f4650f05741bca84df1f0cc561def477ddd707b5d5c7e7253047babc45a66143d56b31d7e1c487a4c25814dad518d910c0377f89d4f19185653c1b0773999890f9fa6a692ab8daedc1d6e42b8dd506dab6ac5bfbb937a0cdaad8025a176ba9f28a96465c0f806ab2440380afcfd5cc9e5daa6b2778b12242c00856b91cc3f09001a7782ab1011db187f2cf0d3e85f78d46496dcca4f94e749b90c69b6366ce627a2f68b8e06da9e5659958c02da24b6b862886840ccb096232b024d95fd28b40d347b9769c0d7ab9fcc897d78ad0e09bfcf35f318615cbaf4e7d6081f182377097240788d29b9023e99489da7f717cd066bb6b475527f2b3f1d36755bd0b3b8f9828a9cfda694670a63c60d842ae55f411b1bef5f057bd704fab722bad288065af8721839a9313b7e0f5ee2973351df231601814684bd9757bd3995c8eb9db0a1074c0cd40ae0e385d654a7bc5acb8688ff69ddd1934872e401695b9f9ac0358fd6f0def2dcaa7e9bbb94df1c85e349a1819c1ac2640e53eb32ea720b0e9025e918369444b8599f688f4e00a020c289b8d0008cd8b5575c9aea95beb79a4afbb7c891d18f88217365bc4fed07d9156779c767209b6b10e6ca3aa015f3178911704958b566e00315f7b677dace0444d85d3e4ce3049e33a6c63b0da21dfa00e6bfcbe486904dfd4f0ec39bf1c269c2192a7ba92d63f3af16c63b40bde924ff2e7afa31e9d570f8057c22940fe1e446e0f4d8f31dea2f388a98de9d57f5fbe49f9b823868921166ad6adb6910f037a5e6f8fcecef09460e08c735ef81b6cf93460b43477de194ecae9926c5f8c2a7e45306d96558fcd3fa80c1b99092a67c8b55eb8a85c86248541d062ea4a434484fc1918a284da66201b79d736b53e5f6159ebec98ecf49ecea4896f3cd64a4611bce461ccc9d73c21dad80d73ba5d1cf3a782bef790c638d724c52210c52f86b792975e53c0ae89a11d69bc1a1d329a29f17b927beabd2af714f8db6270f1b37338a4399a2952236089daa63e1d3192fd4f492e2c6cdd20e66d9e28a67d2cd3c7ecb3ad5ca5b9783c5e7defd06db01eab128a3e4893c3c73a814eb1dc3e8ea71b66e527d34ce999308e8828a18f37fa15e88dbae167390c4d2592cfb9c9e5f4e8ff74746aaa617fca044d69150ce2c56ae74a8c2ee552d0d17e0f1122826313cd2ea60e0d79fcc3f89b6a600ce5e9a2456485e03564e543081b2f4a42196fa48ac201d78a1b01e5431af35c330fd5fee2aad0330cc6cd0f795165f194eae64d73e148cbeae554e0dab7e7fb5c3d9af79cc18093c6f2a6ddbe9d6481513bb2b873c47076268135b35dd2a2e88715661b0124a9bb0920eee52bdb7c6702d58677404c20a0d3a52513713598c398bef4cbbd774751351c45b29921749f5067055af24e65cb5f306a83a806effe86190eea53b7c862e256d6f3a524092aa6b99a88d036a6019d2ba0258587e426f5baa4c5685e2d683dd2df450cdccf3f97757240f4a00f5d7baeba9f82a453a4b7babd39ab67a79e112fd68c2e648fa847720b86dea50395ba954a73cbeb023fea41a930482c8d91c1861c408a0c24408c6d3efd90041bf531aa3019ba241f730756a269045d7bc48925b0296f3bc5b8b4fe298028d623de83cfbfe486b4d9457e8a62a5bd152fa3cab9db4cb239892cf1a83d5fedc5b51a6f639e3206a5665dc011c1b1980c16f88d75f8a330bbdfc63137041e96fd3778f4ca75f3c5a45e46e67c3acd8c344b3d255e43d16279962d17dbeedb93fd0386ec58281755abb3bde65f854f54898e2adb955c4d26157ed5a7f530734edc6a72b5c32f2f2d25386bf5e84bd61e12435020bf098322615dd2d10263650c176c6365419ceb17e8dc171671dc293c8a9f1d2e5bc3a2be0a15e9f96d1d6b9582abeb47ce204455ad71745d5a05c3a72bf5529050608f313d0198b8ee69da731a0ee6b2eeba808056c5a37e05660f43d023f384a55ba952bb6c496a93c683b67306b6130749e9edbe256d53d10800b9c4592043943a220e247083198c8188264bd65f9c4ff78b34475a667931e6e93cc449df373c3c2b0856f8203a7b37a410a594e167c1a0ffc9534bea7c4fbb52112eb924ae7acda6424e3bf43a438be664d6501b5016dd9031d6f766b203a29e86c2a0f19101044883ccf244b90bc5d76fbf9df277d17ac80214677fc7c171370c0a1bc0bfba1817a7a31ed7c0a020049bd09ee9d43893da0623c72da505350c330aa4b795f578bb81e20dfe625d9d708773f513c21d79ebde2c1bdb066807bd5050891837ba22a7f13faccb09dbd501f618924f00fe35a5e17cb64bdbcc8f0dda842e0e78ccc180eb8658d28673a053b66722801e82bcec476f0fb0bd10aca158a4ffa75f85c867244f157121b322e18e4f731a6e0dfe57b72910332fb7059ec3cd83815dd7121c1114f85063ba683b96a116ce00424381f005e763150d108cddb29346ff5bc25c7e49a3aad3ce0489a4a3414ac9d1ac17da2d435b27618d9c57b448923b2348237d5589367e5e542ad5557c58976c41174b1f864358a01238b971c6ad9bd42891fd40a6ffbe4e86efa7720e1ff055fbdc38384080a7c37f59306712c5e6b77191257a9e2a776341c6e6782da38eca28389bc581b43d3f6577d851cd928e9dc58b6954b5741593cbd5b8433fef7486869138d8bebcec34f929ac4f21f4c7fde0ffb47556a1253e080b2238c253af97fe6f53236c3db03003aee94e84ac0fcf991ab9832da3b8cea31768b1a1f6ae629a78916cb93faae238972e697b2851a023ea188641813768265bfc7e15bb8df1752f9a4a6feada7231ab09d0c983eba18de58d97c6fe29e1c8a66ad4090dc36a8e1778722d5686658bfd7a3b3dfc4f175ecb5e701f69297c6400c5653ec1b041da00808f568546b45952dd20ab7b1eb6043e65120ac6a2e28993228267823fdbed4c1d49313000d3715c27ad33ceea4b050744b8e79de05ea53512b61e6e09bbc5a7a6fbdf12d21b4319c23662393228dbebe50981df19c620207d5b02878bc9de7163d084d48296894fb35ba768446ca32b7d44e6be74dc8cd16115d4330c13ab557296eac2ebd16082944a9f7637525bb105ad6e41e78bf67c04f7931268b69194004e52d4add99ae909081612dfb09bd353be5bd64d25a5b9944f3d15ff694886cf5d669c44ace73dd13a0b08603c2d3ef4de1bbc2880042b5a385d9592b9b7332ed51604332065332e15cad54bbaba55628e3e2813fc760aa6783e88af56a823662e6cb188864811fc1379e48793f8468dede6d21233d2855a228576bdada45627ca94fa2ab2a89c3d4d4403e1cddc9e5d2216aae31bbdafe3f4efb2b741a9dcc89461c486505377ae057fbd51fd753fbc102770d41ae713ee5d3e7e93b73660485812d3fea540453999cf87553b6c241fdee91ce9f6a13869f7295c43428977dfcd971ab7a244068968b5df097b0e5d146caf9ec0d309289c72737dcefdf66f5f0bce2ba0f0774c22d5289ac08dfd5b234a13a3ecd84d54580d155dbf59e1e14f325cb105d18a8d4eb794345f683980a545551ae1261269533dbb9fe4b93a86e083831796a8b16936a59e6d0953a0d28cb217d38aef47a6cca2a40775f3251c092bc6f0bf975b6a15efdbde68005323ba717f403592d355676d5e9f4871cff1973e8806de2e08e6483229dc599687d4582ea7113052ecec5265baae26c80eb84cece3617381a0f6be5794fc2a2f6763ad00173d00847795cd7e36a27a04f224292a39617cdae5353d9c4b8c2ddda25b781af5e49dda6704676b625938067c05186abaf9b06fc96f8fae1ed463c365167442dbaa18554e94cc6f599ab93e300babb785ce472a698d0fd5ad04078c575b55e7b1979bf2215effee85555c3c99d4000c1bfde65a4e2e0b87da73749acd2df60ff4d88ba7a31dd10668da181f001d84627a9c9d950cd7c0ab6e8f2a81460214672fcffda42dc00586f7348c49ad97da8a6857776fc0ab49b4d9754699d7df0c4d24778253767a6691d1b6a24c13c61cbe667a750132a0de94edde905b7d9fa84ef6a9d96000baad18886645e850561367bc173114700cb76eb76d2e49e108a1b497301f4da535f38cdeb3ec4fec9c3c790732d91c1390f92c70e489304fc5d8d884be1004403b3fd2665e696859de64e4989005478a60e8467d9c00eaeb40b9186b7ed772a25e4ca0c8e3e971904a224ff3441c013ad1da0b61d0b4a946162025f3284c9cc339ddf1f058ebc457daf6f3a0b60e5dfcc2d608769a425efb0ea5bf39076844fe8ecbdcdc98903ce344e48536ed6eefda9aaa3858af14754207a262d450f4156bee6820af23bd4f4b994f8122a717e7e5110c30999eeef6875cf456620932f647a835a3daebe5c169c29833964c4b571870767ba9cdf7e5ad1c7ac9bace40d342de4e98fd024e994854add6ee7a43670b0c95947e31a44379aa4ce58ff0a75129015d3e37140be2ec3d10bace4927f8ab6b5523d054ce52a9d2bbe8eceb79e588299d509dd853901b8d0abb50c8b7002d7bd2a6bba11b689c2524268af95a9d5b2c420b87f44ecaa10ea4dfd2481d25bfd57d35fbb6979a650f4c390f66629d807c2ece12b2032c3382972ace402a84bd1425966e7bfcdf068cf9d64146272932ee0363ee73be401b5ae8c2159910bab590f61f33f62c32ed90f6c0df6f90826bdc915e7882612ed6bb1db470b5be1029f98b11f005e8acd9dfe6b4f01e2c6422ce5615c69546f8ac149fdefd88321f87dafdcb6478a9de2e41af22879407cba801747250d2ad3dae0ed838436a8ed866f850b9a2988654da56146f2ec1bd53185013d27287a09b9c0c5dbad2aa43ead12c777e314aaf733669d656ed544a824c3bb110757121ef405a277573bfb1999c11e0ca34e4681dcf53e19d909388ec2eaa64d5e9240a3a13f74b005664fee349a1144dc07b205b0a2c14e816902a6f1355b9df2a0ab9df16f62e738744a898b12c349874c325364a36c856b8ee46af87a72b7d5b57c37690155c99addd0fb80767dc190464c8ca1f2eeb13ce69b538fcc551c4c66134bab163e777a9f4f65c9036a5870b12928e817d503fc02404be5593586ffca8f591a5e40bdf13a1781b3fa245fdc0626bf6a4cd073fb7f2613a7ea4fbbbac39c43395b2ba4c4fa75f492d14ea822f2918b259cf10b035a9bebddec142f0902fe8730e72eff751758337a9a34bb3e795005c515fd88b64914ff887fe93f79006244d4b6ec3cdec2a115a7dbe228037fb31661cce32d227c1ee4e3cb149a74050da56224be0f4556c9001dc2bcc010aaaf50d31e50b6063c7307f9d4749e858818f6d0e898862a3d20aed4e47f5c0a98de9b003a7c4738511f6ec7eb3bc23321ad4f9bcbc23c55bd4a07058cacb69318a6cf49f0229ab7415a2b9e82375fcad175456a9bbb196b4cbae78cbb7072e3462777988dffe6dd5890b1468ab782fb78423b0acab19e768a9e1ab70be76fdf89c1260387491232e24276fb035ba0c897c1f2196de5c100bc1a3cdad58816f9dc8144ef92c182046cb2d0942a645cb73d1fd9780171bd4d6615b987aa8a52d3903e4c75026a41c68a4b9a8f3c5aac404f36f628ca1f2d2f3a5066d4e20c48112396100c0d6865b34e613bb1f8a7858b7270d763e98adc40c3098b179b9aa5f41a5aaf4741687639bae19f22225d69019e36937e5382f5be6ecbe01843bb5394331882f7dc6975dd6d2f6f2d34580fecc0b9c10d213875bcb76f48036aad693fda2361a9a5fdaa6dcf56df1c2f76182c0bf6a84942b518feae037d19b3e62f59ba8ccdb739d4b3c04af5266ef38af82424a9c19a5be41518123b81162aea1a8a210c0fbe1d8d2e7c12e436d1e9fe0ec4021dd2953c996bf1f4100e28feeb0244614aa7aa50b1cc6b7c632a4fcb3f3efc886628ec908ffe7bf26a833f892b3855d54adc8238c2989ae9d5a9ee72573a1fb8287e06a52ab91ec125f8cef5c7e966b869946e2c5eca84e4d98808696c38e9249b9f5b3fcabdd8c836143751a504f5baf3775d3fc6dfb59eb4f54de53a6a1056935595a5f41cdc68a2fc8963c4d903d5cdf2136c614fd57d3901737695a99515937b08e4a985a15dc6a52bef02d9b998518b82446593c25dd56f8d54c8e42155b74b41f707e988901aceb13e79e813307ba110369bb84a8d2eeeaab92e1b46182e83d283469899c5f24d06c5cb7c32c2a2ea882ff2fa5bce274436a62b4c7c0ffbf191b8b7218603e62c07db87efb20c7239bab64cbf93a6f6402d650f22cdb34d65cbb681ae929a7fe7dcddf5cd5df179145c360fef6bdaa1cc7e73f2933dd7d4ee8fa2552b9dccaff3c3ea8ef927b6813932b66f3d9e0c294e6644c2587787c6673fae5a467676d09d09537e2d2725e06e7951ba6e37371ff888eabbc43b139c837d4de9aa3725131aae69435b61af4957d8b236518f3278ac4c7cf9e6909a0c10dc1155799f2b1631eab1ac98be46622955f79a7fc6c9ef0aa3533495bb7baa6615b5250c23ee03dd239c2de4f32a05a65a0c190852f0c8b31acc00cb2a702fd92a24099ccecc655f4f7d9eb3b3a8f16311b6f5c00970a5b29b91f613c6f0e3b982ef18b85b44a8a99fdfcdc649509297db5262585199487aa2872ca13660f4ae141713ba853fed39606ee5ec4416f28502c73b8a98755f0ba568713364ce20879862ac4ea587df7d27f5dbbf67dd885f6c250e47f0c0fa3ad2d04f230efea0339ab611195de5441c4e7e8d5b176be8d8a1f5f98c74383ae35a6e123ac33b5ddb60a7e79975d1b9b901802a1b0859660ce60c19ebbe98f277854d84a2e611d99c9c7a601648ce77498f745f4f11c9b50cab95efb56477e8bd87cfc1cbc97e189d30be753e28d0c2f3d154f95e8a413c34a85d455d2cd4f422fd1c0d05ca3d910e6a4b1d3e771c41c9a58d6266c7f849ff90ab05decbb9726e109525aca8fcc29d43ad6abceedaa13f33d11eed00f93cad5af3f9622d723cd1c548a8dd67d00a71ad9b46da506839563f685e2ff0739e26f0ec0a04ba7e2e163f7cd8bc20a13b09b9bef747d1bed4f67455f0db2dc161959e6c160e4322ee00da1b2ec95028a08a124d16d047b1a68db0a52e7cb5bc756c8cdddb9fc4e76bd21e16d654307a37c419749d089584ce84726d55a9ac9a5e06582f320f8efacfbed4166e9aca4f4f679fcf0c8520ad8f809f627f7bdf340046d4b8861dab321a00fdb14c1a1927374406da241be2466454d2eb049c5ca42aa5e96cb3d876be3b52c482cece34fce84e426ce7aa048bba2f8dbf75956126d5d5cf8ef762ab28a99bc8bece8e9004025e665580ca47e70d20dd358f6d8a140dd842248c875d7a97506bed49d3871fc7b855fc15c33122fd86fe3c264a5a63bc2e953ac36186b882f016e951c0902c0478b0ea18fe3c9832502db2fb7cfeab7bfce30917e66940c0199fdd8cd12aaec5e2f21b7e18430dd40735e1e8d01be51ee43be8ffb84ca5552cfea8d36e9ced967258a294e98b9849567dc7f0085eb88e2ec42b7d21f65ad908286f5b4fa9a19a48562b8f78e996cb5fef466da27cd8abc9204ce1ed7195f6326d6e8029c2fe342d5930bec239aa320a4356d6bf72cabaa5fff584a956c096730216695e3906766e2be97df57dbb625b66ff535cfde652a32e3578a60673978bae7ea84f0463b921d9baddf457a5d4ab878c790808eac694f9548453a9df56b5e5877d8695fbc72744eb1d0b53b421527c884abf0c73640207ce33062a0053d66a1973e52a8fd3085858176f5dc9e50df822eb2f0bd8580641c429c4d5889f34ac6d0b4c3f091c95dca9ac961bb207c5d1135ad2f60fb1da49e66ce0b516152a43f4c0c37b754273c2b85a7af9caf6c373037794d06045c6aca1b0c244d3d65583a1eec3d057d71376754b496a8bce784643311       8   L   l            K    E  v        #        2  c      K  b  l          0  T  c                       *  \  }        	  4	  ^	  	  	  	  	  
  9
  P
  b
  
  
  
  
  
  
    2  `            	     P          H  j            #  =  V  y            $  ;  R          "  <  W  {            .  =  K  a      
  2  N  ]                    0  Q                  :  P  h                3  U          ?  Q    w          &  6  w              #  B  t          @  p          (  W  u        $  U  w          :  g  }    E  R  v            &  W  g               @   `                           *!  4!  E!  U!  !  !  !  "  0"  S"  `"  u"  "  "  "  '#  A#  i#  #  #  #  )$  V$  p$  $  $  $  %  6%  T%  %  %  %  %  &  )&  O&  z&  &  &  &  '   '  >'  i'  '  '  '  (  :(  _(  (  (  (  (  &)  @)  d)  })  )  )  )  )  *  I*  {*  *  *  *  *  *  +  -+  l+  +  +  +  +  ,  5,  L,  ~,  ,  F-  -  -  ?.  v.  .  .  .  .  /  M/  m/  /  /  /  /  /  0  &0  70  C0  0  0  1  1  1  1  1  2  2  +2  e2  ~2  2  2  2  2  3  3  .3  C3  X3  m3  |3  3  3  3  3  )4  4  4  4  v5  5  6  $6  >6  P6  6  6  6  6  7  57  D7  N7  X7  j7  7  7  /8  o8  8  8      add shinydashboard packageInicio de codigo MTR_PublisherAdd channel argument#35 added documentation to file.add explicit ref to signal packageEnsure directory name has "/" endingVerändert, um Rohdatensatz zu erhalten.Neue Funktion cheb.fit.roots mit sektorieller Nullstellensuche in locate_jetstream implementiert. Testlauf folgt.cheb.fit.roots überarbeitet und korrigiert. Nullstellensuche in spez. Sektor und harmonische Randbedingung implementiert und getestet.Funktionen flexibilisiert. Skalierung von Skalaren hinzugefügt, Nullstellensuche in vorgegebenem Bereich möglich.Include submission timestamps in job states tableRemove all output files after job completesoffset date from recent dateupdate read.wcih with new variable namesFehler in cheb.fit.seq korrigiert. Weitere Tests erforderlich.Harmonische Randbedingung in cheb.fit und cheb.fit.seq implementiert. Erfordert noch ausführlichen Test. Schnelltest erfolgreich.Use darker grey for node labels for better readability.Ignore stdout when generating stain_rsa ssh keyFix stain_ssh_setup output bash commandFix ordering of sbatch submission command optionsÜberarbeitung und Flebilisierung der Fit-Fkt. Nun einstellbar, welche Var ausgegeben werden. Schneller Fit als Vektor vs alle Daten als Liste.Fix NA removal when fetching previous n jobsAdd more complex sbatch_dependency_list testsclean up missing data..added todotest to make sure I can pushAdd dependency_list param to submit_commandFix output sbatch option typoRename `view_submission...` to submission_historyFix view_statuses by simplifying error handlingadded summary of the allocation timedisplay formulasave and reuse filtered genotype data of selection candidates..stupid errorloading datatiles fixedConsolidating two FSRS files. I'll probably delate a lot of this newly added material soon.fix bug: convert filtered data.table to data.frame before writing to disk and before using it in rrblup methodsUpdating function variables.Bare bones of new function.Update process_cfsv2_ts_ncdc.rFix markdownTableString with sig digitspoint rjulia to julia0.5 branchSet fetch_output's submit_dir default to "~/stain"Add cancel method to Stain objectUpdate get_cfsv2_ts_ncdc.rUpdate get_cfsv2_ncdc.rSet default submission dir to user@host:~/stainAdd view_submission_history Stain object methodCatch any warnings from stain_ssh_squeueAdd `view_statuses` method to Stain objectAdd job id to submission history on submissionPlotroutinen verbessert.Update process_cfsv2_ts_ncdc.rUpdate process_cfsv2_ts_ncdc.rWhen deleting, remove corresponding Stain instancereset default n.cross in case too largeadd deprecated commentsupdated threds urlUpdate cfsv2_ts_ncdc_sqlite.rUpdate cfsv2_ts_ncdc_sqlite.rUpdate slavicreview.rUpdate slavicreview.rUpdate slavicreview.rUpdate slavicreview.rUpdate slavicreview.rUse packageStartupMessage for startup messageRemove objects directory from `get_files` listRemove `remove_object` Stain methodAdd `fetch_output` method to `Stain` objectfix BLE startfilter out monomorphic SNPs..Update get_cfsv2_ncdc.rUpdate get_cfsv2_ts_ncdc.rUpdate get_cfsv2_ncdc.rUpdate stain_message_globals message for clarityUse message instead of cat for some message funcsMake save_globals private and call inside submitFix stain_message_globals invalid message bugnew analysis and parameter name adjustement in figurenew analysis and parameter name adjustement in figureminor improvement to flow of DGH.rchange S0-S1 to N_0-N_1new results with modified algorithmMake script run again...Change input to folder where dtm isClean code and tweak parametersDo not transform to plaintext docs...Generalize to command lineadd pseudocode as commentAdd submit method to `Stain` objectFix missing report host stain_ssh bugSet Stain ssh key passphrase to an empty stringchange call for catalogAdd snow and veganchange call for catalogchange call for catalogchange call for catalogchange call for catalogadd case of gov't having all bargaining power to DGH.radd minimum threshold to consumersfinish example with SGSL network figurechange edge direction on figureAdd full.names parameter to get_files Stain methodmissing '.' in one sectionUpdate to include tidyverseprefer periods at end of descriptionmove more functions to sectionsremove non-existent topic namesupdate staticdocsupdate figureIgnoreing data from before 1970Dokončan prvi graf, dodani grafi po igralnih položajihcomments, fixesprez order fixadjust parameters nameadjust id to consumers and resourcescalculate number of taxa in SSL for which consumer or resource information is available in S0Add additional packages and descriptionsRazdeljen zemljevid, dodan osnutek grafaadjust accuracy measurementsadded functionsfinished the analysis, only figure missingdodane htmlRemove errant commaUpdate mtcars.rUpdate error.rUpdate LogParser.rUpdate BuildReports.rUpdate BuildReports.rUpdate Main.rMake `options` Stain property privateRemove unused SlurmOptions methodMake the default sbatch options more reasonableallows omitted fixed effectsupdate init.rBetter graph alignment for higher valuesnapoved sklenitevzemljevid - SLOdodane knjižnjiceRemoved core stuffMake script work with several foldersmake id active bindingfix ggplot_builder tilerFlexibility in diffInDiff plot legendadd 2nd x scale to figureadjust figureadjust figureprotect sink, remove . in var namechange figureMake plot somewhat less ugly.minor changes to percent remove processFix MOE & sampleSize with finite NDo not hard code the path to reb-lib-doc.txtMake it work with both r3-legacy and Ren-Cfix object nameminor changes to analysis and figurecorrect error with changes made when substracting food web used for validation from the cataloguePopravek pri uvozulatest version of analysis with less iterations, but an additional wt value = 1 to test whether taxonomic proximity can be efficient for interaction predictions when catalogue is not as comprehensiveadjust script to consider all taxa in S1 when removing percentage instead of only consumer taxaRemove ./.data & ./.stain after slurm job finishesfix xy panels in tilerRename `settings` param to optionsRename save_objects to save_globalsfilter out markers with MAF <5%...'minor comments'change list of thigs to do with ulterior version of the algorithmUpdate help language in find_globalsFix static directory typofixed shj bugDodani pari za ZGODOVINAcleaned R scriptoptimize again, slightlyFix typos in update_globals methodcorrect to optimize calculationOnly create slurm script if creating new containerFix invalid file path bugAdd save_objects method & make add_object privateAdd settings to SlurmContainer initializerRename container param to container_dirAdd loaded object to global if `globals` is emptyFix self$dir undefined when updating globals bugMove data files to top-level ./.data/ directoryGenerate submit.slurm instead of submit.shhave green/red colours aroundDisplay warning if no main function is foundFix invalid method bugCatch error thrown when no main func is presentFix copy bug when adding filesUpdate globals when adding or removing a fileWhen loading globals, check self for existing valsRename update_globals to load_globalsAdd update_globals method to SlurmContainerAdd note about how find_globals only runs on mainMake add_file & remove_file pluralAdd get_files method to SlurmContainerCheck that .stain/ exists before checking sub dirsFix check for existing stainAdd add_file & remove_file SlurmCont abstractionsMove ouput/ outside of .stain/Only create Stain if directory is not a StainRen-C works as r3-makecorrect resource and consumer set measurementscorrect resource and consumer set measurements and evaluate the number of taxa removed as a function of number of taxa with known interactions in food webadjust figurecorrect tanimoto measurement formulaFix ylabel for density histogramCommented unused plots in R fileresponsivity fiddlingset size of figures to reduce responsivity problemsnull checkcomment out un-needed observerremoved a test statement in iRODS bagit rule filePopravki v uvozuUpdate CalcAlleleDiffs.rUpdate CalcAlleleDiffs.rUpdate CalcAlleleDiffs.rUpdate CalcAlleleDiffs.rBetter readability for gsr-video outputFixed gsr-video usage without --tempdirImplemented gameplay/GSR plot video mergingUpdated gsr-plot to use argparseRemoved windows-specific ffmpeg callfix normal equationsadded names and cleanupsame bldimx y separatedremove numeric selectionadjust figurecorrect figureModify gsr-plot's y range to 0..ceil(max(values))dir updatefixed csv patternfixed parametersInitial check-in so I can work from other computer.add figure codeadd functions for accuracy as a function of number of taxa in catalogueThrow error if no input files, allow overridehandle errors separate from outliers.add tukey's outlier removal formulaadjust figureRemove main_file testRemove invalid bash command from static.slurmUse cat instead of message for black ink textImprove find_globals message friendlinessAdd newlines for spacing when writing main_fileFix sbatch_opts_insert bugAdd sbatch_opts_insert for set insertionAdd sbatch option helper methodsrunning through scripts making small fixes when errors are encounteredThu Aug 25 10:27:21 2016: update dnm analysisThu Aug 25 10:26:49 2016: update dnm analysisThu Aug 25 10:22:47 2016: update dnm analysisAdd sbatch_mail_types listThu Aug 25 09:13:08 2016: update dnm analysisThu Aug 25 09:12:26 2016: update dnm analysisThu Aug 25 09:11:43 2016: update dnm analysisincluded figure generation in the scriptFix typo & NA check bugAdd support for email settingsUpdate the selection of points for regressionAdd common slurm setting parametersCopy all but original files back to submit dirLoad Rdata files into the Global environmentFix sourcing codeFix unknown main_file pathProperly name vars save to Rdata filesCopy recursively for source and input filesFlatten input directory & fix typoAdd #!/bin/bash comment to submit bash scriptExport SlurmJob R6 objectRemove newline at top of static bash scriptFix unknown var bugFix main_file bash script pathCreate SlurmBashScript instance in `create`Add write_submit_script SlurmBashScript methodAdd write_slurm_script SlurmBashScript methodCopy main_file into source container directoryRemove SlurmJob container propertyMake main_file and source_files publicRemove add_input_files for simplicityRemove container if error occurs in `create`Only set self$container if file exitsFix SlurmContainer bugsUpdate SlurmJob for new SlurmContainer methodsAdd SlurmContainer add_source & add_input methodsUse add_object in SlurmJobAdd SlurmContainer add_object methodAdd container to SlurmJobMake dir of container full pathCopy input files to input directoryAdd input_files field and methodsVerify source files existCopy source files to containerGenerate slurm job container and write Rdata filesSet the values of all gobals to NA & print globalsFind the global variables that are unassignedUpdated codeFixes error taking log of zero p-valuesDESeq2 vennadjust heightFixed shared loop variablemodifications for results figurebeta function to extract fossil ages directly from a PBDB tableupdate bottom listing with what is done for top listingnormalize if length more than 1fix the bug of missing function GRangesgraphs with coloursAdd diff-in-diff plotget all dates before getting min maxdon't use function nameFix LIST-DIR return result, %mezz-files.r meddlingadded importing the MASS packagechanged use of the "len" variable. previously it was used for all for loops. however, it was not applicable if there was not an etm+ image year for each oli image year.changed the error message to be accurate to the if statement (needs at least 1 image, not 3)added importing the MASS packagechanged how the composite file list is created. previously assumed either 1 or 2 lists, now iterates merging with a for loop.the resample function changed names - updating the callexport significant DE gene namesDrastically reduce max.printremove quote from GSEA rnk filegenerate GSEA rnk filelist all weeks. normalized price and index. typoinvisibly return coordinates of legend from draw.scaleadded width and height to ggsavecleanup. add missing paramgraph functions with more given paramsmodify to export figureChange variable nameremove unnecessary command lineadjust to run analysismarket name and param fixadjust parametersadd functionadd evaluation of similarity between resources based on set of consumersadd evaluation of similarity between resources based on set of consumersadd evaluation of similarity between resources based on set of consumersadjust function to consider consumer and resource similarity based on set of resource and set of consumer, respectivelylist is done.mainly make graph functionsnew functioninclude new function to include set of consumers in Tanimoto_data.RDatadataframe stuff/travis, u thr?removing superfluous comment; let's see if travis kicks inadjust for relative pathsadjust for relative pathst commit Script/serialNext.r git commit init.rmodify relative pathsmodify relative pathsmodify relative pathsmodify relative pathsmodify relative pathsmodify relative pathsmodify relative pathsmodify relative pathsfinalize scriptprepare analysisadd functionadd accuracy calculation and figure output for resultsadd function for plotsadjust function name that was not changed with previous modificationsadded function to avoid overwriting files if multiples analyses are running simultaneouslyadded function to avoid overwriting files if multiples analyses are running simultaneouslyadjusted function namesAdded the option to consider only empirical data in the predictions, hence considering the contribution of the interaction catalogAdded the option to consider only empirical data in the predictions, hence considering the contribution of the interaction catalogmodified process stepsadd origin to POSITXctShow mean and median linesFix wrong var namedisplaychart with given periodtext. the new chart with days and namesExplicit mock.Update SummaryFromFiles.rSaisonale Plots, Jet abhängig von Standardabweichung?Added support for custom lib pathsalso iterate pairs. move to outerindent with essgit test 4git test 3Second commit testInclude flow with concentration to get an idea of the total amounts involved.  Yeah vague I know.Select sites with 9 or more samples.added external function "predict_oli_index" as internal functionadded external function "predict_mss_index" as internal functionGrößerer Datensatz implementiert, Geopot, Temp, Div, u, v, w. Saisonale Veränderungen.Bunch of graphs.       :   N   o           v    r          U      @  h    *  W              @  p              g              !	  C	  {	  	  	  
  =
  h
  
  
  D                    /  D  Y            2  j        L  }        :  R  v            .  R  x              3  j          #  ?  d              -  <  S  x      (  E  U                    ,  N  ~                >  U  n                A  d    '  7  \          ,  C  f           %  ?  M  f  w             R        5    O  m            .   a      X!  !  "  ="  p"  "  "  "  #  ##  R#  #  #   $  A$  b$  x$  $  $  $  %  %  1%  I%  a%  y%  %  %  %  &  ;&  P&  h&  s&  &  &  &  &  &  &  '  '  K'  ['  '  '  p(  (  (  (  (  )  >)  n)  )  )  *  a*  *  *  *  +  4+  b+  +  +  +  +  ,  -  <-  i-  {-  -  -  -  .  :.  T.  .  .  .  .  /  </  k/  /  /  /  0  .0  F0  u0  0  0  0  1  !1  E1  g1  1  1  1  2  42  {2  2  2  2  2  2  3  3  3  4  '4  =4  b4  z4  
6  +6  6  17  R7  7  8  (8  E8  d8  z8  8  8  9  9  E9  ]9  r9  9  9  9  9  9  +:  t:  :  5;  C;  _;  l;  ;  ;  ;  <  )<  C<  r<  <  <  <  <  <  <  =  "=  2=  C=  P=  =  =  =  ?>  >  >  5?  ?  ?  ?  @  @  Z@  i@  @  @  @  @  A  A  $A  7A  A  A  A  @B  B  B      add shinydashboard package
Inicio de codigo MTR_Publisher
Add channel argument#35 added documentation to file.
add explicit ref to signal package

avoid confusion with stats::filter
Ensure directory name has "/" ending
Verändert, um Rohdatensatz zu erhalten.
Neue Funktion cheb.fit.roots mit sektorieller Nullstellensuche in locate_jetstream implementiert. Testlauf folgt.
cheb.fit.roots überarbeitet und korrigiert. Nullstellensuche in spez. Sektor und harmonische Randbedingung implementiert und getestet.
Funktionen flexibilisiert. Skalierung von Skalaren hinzugefügt, Nullstellensuche in vorgegebenem Bereich möglich.
Include submission timestamps in job states table
Remove all output files after job completes
offset date from recent date
update read.wcih with new variable names
Fehler in cheb.fit.seq korrigiert. Weitere Tests erforderlich.
Harmonische Randbedingung in cheb.fit und cheb.fit.seq implementiert. Erfordert noch ausführlichen Test. Schnelltest erfolgreich.
Use darker grey for node labels for better readability.
Ignore stdout when generating stain_rsa ssh key
Fix stain_ssh_setup output bash command
Fix ordering of sbatch submission command options
Überarbeitung und Flebilisierung der Fit-Fkt. Nun einstellbar, welche Var ausgegeben werden. Schneller Fit als Vektor vs alle Daten als Liste.
Fix NA removal when fetching previous n jobs
Add more complex sbatch_dependency_list tests
clean up missing data..
added todo
test to make sure I can pushAdd dependency_list param to submit_command
Fix output sbatch option typo
Rename `view_submission...` to submission_history
Fix view_statuses by simplifying error handling
added summary of the allocation time
display formula
save and reuse filtered genotype data of selection candidates..
stupid error
loading data
tiles fixed
Consolidating two FSRS files. I'll probably delate a lot of this newly added material soon.
fix bug: convert filtered data.table to data.frame before writing to disk and before using it in rrblup methods
Updating function variables.
Bare bones of new function.
Update process_cfsv2_ts_ncdc.r

added filter for days with less than all 5 6-hr forecasts, and a hour_init column to identify the four daily ensemblesFix markdownTableString with sig digits
point rjulia to julia0.5 branch
Set fetch_output's submit_dir default to "~/stain"
Add cancel method to Stain object
Update get_cfsv2_ts_ncdc.r

added remove too-small filesUpdate get_cfsv2_ncdc.r

added remove small file commandsSet default submission dir to user@host:~/stain
Add view_submission_history Stain object method
Catch any warnings from stain_ssh_squeue
Add `view_statuses` method to Stain object
Add job id to submission history on submission
Plotroutinen verbessert.
Update process_cfsv2_ts_ncdc.r

added in 0.1º regridding and mapping to river basins using correspondence file
still writes out csv of 24hr totalsUpdate process_cfsv2_ts_ncdc.r

generalized file, changed write out to csv from rdataWhen deleting, remove corresponding Stain instance
reset default n.cross in case too largeadd deprecated comments
updated threds url
Update cfsv2_ts_ncdc_sqlite.r

added lines to save additional metadata and 24hr rate for easier data processingUpdate cfsv2_ts_ncdc_sqlite.r

removed unneeded lines of code. added code for africa domain as wellUpdate slavicreview.rUpdate slavicreview.rUpdate slavicreview.rUpdate slavicreview.rUpdate slavicreview.rUse packageStartupMessage for startup message
Remove objects directory from `get_files` list
Remove `remove_object` Stain method
Add `fetch_output` method to `Stain` object
fix BLE start
filter out monomorphic SNPs..
Update get_cfsv2_ncdc.r

changed destfile name structureUpdate get_cfsv2_ts_ncdc.r

Fixed bug in functionUpdate get_cfsv2_ncdc.r

Fixed bugs in function. Removed redundant user inputsUpdate stain_message_globals message for clarity
Use message instead of cat for some message funcs
Make save_globals private and call inside submit
Fix stain_message_globals invalid message bug
new analysis and parameter name adjustement in figure
new analysis and parameter name adjustement in figure
minor improvement to flow of DGH.r
change S0-S1 to N_0-N_1
new results with modified algorithm
Make script run again...
Change input to folder where dtm is
Clean code and tweak parameters
Do not transform to plaintext docs...
Generalize to command line
add pseudocode as comment
Add submit method to `Stain` object
Fix missing report host stain_ssh bug
Set Stain ssh key passphrase to an empty string
change call for catalog
Add snow and vegan
change call for catalog
change call for catalog
change call for catalog
change call for catalog
add case of gov't having all bargaining power to DGH.r
add minimum threshold to consumers
finish example with SGSL network figure
change edge direction on figure
Add full.names parameter to get_files Stain method
missing '.' in one section
Update to include tidyverse
prefer periods at end of description
move more functions to sections
remove non-existent topic names
update staticdocs
update figure
Ignoreing data from before 1970
Dokončan prvi graf, dodani grafi po igralnih položajih
comments, fixes
prez order fix
adjust parameters name
adjust id to consumers and resources
calculate number of taxa in SSL for which consumer or resource information is available in S0
Add additional packages and descriptions
Razdeljen zemljevid, dodan osnutek grafa
adjust accuracy measurements
added functions
finished the analysis, only figure missing
dodane html
Remove errant comma
Update mtcars.rUpdate error.rUpdate LogParser.rUpdate BuildReports.rUpdate BuildReports.rUpdate Main.rMake `options` Stain property private
Remove unused SlurmOptions method
Make the default sbatch options more reasonable
allows omitted fixed effectsupdate init.r
Better graph alignment for higher values
napoved sklenitev
zemljevid - SLO
dodane knjižnjice
Removed core stuffMake script work with several folders
make id active binding
fix ggplot_builder tiler
Flexibility in diffInDiff plot legend
add 2nd x scale to figure
adjust figure
adjust figure
protect sink, remove . in var name
change figure
Make plot somewhat less ugly.
minor changes to percent remove process
Fix MOE & sampleSize with finite N
Do not hard code the path to reb-lib-doc.txt

Because build directory can now be different from the source tree.
Make it work with both r3-legacy and Ren-C

found? doesn't exist in Ren-C anymore
fix object name
minor changes to analysis and figure
correct error with changes made when substracting food web used for validation from the catalogue
Popravek pri uvozu
latest version of analysis with less iterations, but an additional wt value = 1 to test whether taxonomic proximity can be efficient for interaction predictions when catalogue is not as comprehensive
adjust script to consider all taxa in S1 when removing percentage instead of only consumer taxa
Remove ./.data & ./.stain after slurm job finishes
fix xy panels in tiler
Rename `settings` param to options
Rename save_objects to save_globals
filter out markers with MAF <5%...
'minor comments'
change list of thigs to do with ulterior version of the algorithm
Update help language in find_globals
Fix static directory typo
fixed shj bug
Dodani pari za ZGODOVINA
cleaned R script
optimize again, slightly
Fix typos in update_globals method
correct to optimize calculation
Only create slurm script if creating new container
Fix invalid file path bug
Add save_objects method & make add_object private
Add settings to SlurmContainer initializer

This is preparation for SlurmJob's removal.
Rename container param to container_dir
Add loaded object to global if `globals` is empty
Fix self$dir undefined when updating globals bug
Move data files to top-level ./.data/ directory

This directory is a hidden directory so it is not copied back to
the submit directory.
Generate submit.slurm instead of submit.sh

The code required to source files, load objects & run main is
now written to `.default_stain_main.R`.
have green/red colours around
Display warning if no main function is found
Fix invalid method bug
Catch error thrown when no main func is present
Fix copy bug when adding files
Update globals when adding or removing a file
When loading globals, check self for existing vals
Rename update_globals to load_globals
Add update_globals method to SlurmContainer

This looks at the available source files and object files and
sets the `globals` property, initializing keys with values found
in their corresponding object files.
Add note about how find_globals only runs on main
Make add_file & remove_file plural

On failure, the copy or removal will be aborted meaning not one
of the files will be copied or removed.
Add get_files method to SlurmContainer
Check that .stain/ exists before checking sub dirs
Fix check for existing stain
Add add_file & remove_file SlurmCont abstractions
Move ouput/ outside of .stain/
Only create Stain if directory is not a Stain
Ren-C works as r3-make
correct resource and consumer set measurements
correct resource and consumer set measurements and evaluate the number of taxa removed as a function of number of taxa with known interactions in food web
adjust figure
correct tanimoto measurement formula
Fix ylabel for density histogram
Commented unused plots in R file
responsivity fiddling
set size of figures to reduce responsivity problems
null check
comment out un-needed observer
removed a test statement in iRODS bagit rule file
Popravki v uvozu
Update CalcAlleleDiffs.rUpdate CalcAlleleDiffs.rUpdate CalcAlleleDiffs.rUpdate CalcAlleleDiffs.rBetter readability for gsr-video output
Fixed gsr-video usage without --tempdir
Implemented gameplay/GSR plot video merging
Updated gsr-plot to use argparse
Removed windows-specific ffmpeg call
fix normal equations
added names and cleanup
same bldim
x y separated
remove numeric selection
adjust figure
correct figure
Modify gsr-plot's y range to 0..ceil(max(values))
dir update
fixed csv pattern
fixed parameters
Initial check-in so I can work from other computer.
add figure code
add functions for accuracy as a function of number of taxa in catalogue
Throw error if no input files, allow override
handle errors separate from outliers.

there are some ficticious salaries (very high or very low) that
cause troubles when graphing data. remove those always.
add tukey's outlier removal formula
adjust figure
Remove main_file test
Remove invalid bash command from static.slurm
Use cat instead of message for black ink text
Improve find_globals message friendliness
Add newlines for spacing when writing main_file
Fix sbatch_opts_insert bug

If the option didn't exist in `opts`, it was never added to the
list.
Add sbatch_opts_insert for set insertion
Add sbatch option helper methods
running through scripts making small fixes when errors are encountered
Thu Aug 25 10:27:21 2016: update dnm analysis
Thu Aug 25 10:26:49 2016: update dnm analysis
Thu Aug 25 10:22:47 2016: update dnm analysis
Add sbatch_mail_types list
Thu Aug 25 09:13:08 2016: update dnm analysis
Thu Aug 25 09:12:26 2016: update dnm analysis
Thu Aug 25 09:11:43 2016: update dnm analysis
included figure generation in the script
Fix typo & NA check bug
Add support for email settings
Update the selection of points for regression

* Try to improve what points are included for regression analysis. Only
  include points in the end of the bin range, and only include points
  where the B coefficient of the curvfit is less than zero.
Add common slurm setting parameters
Copy all but original files back to submit dir
Load Rdata files into the Global environment
Fix sourcing code
Fix unknown main_file path
Properly name vars save to Rdata files
Copy recursively for source and input files
Flatten input directory & fix typo
Add #!/bin/bash comment to submit bash script
Export SlurmJob R6 object
Remove newline at top of static bash script
Fix unknown var bug
Fix main_file bash script path
Create SlurmBashScript instance in `create`
Add write_submit_script SlurmBashScript method
Add write_slurm_script SlurmBashScript method
Copy main_file into source container directory
Remove SlurmJob container property
Make main_file and source_files public
Remove add_input_files for simplicity
Remove container if error occurs in `create`
Only set self$container if file exits
Fix SlurmContainer bugs
Update SlurmJob for new SlurmContainer methods
Add SlurmContainer add_source & add_input methods
Use add_object in SlurmJob
Add SlurmContainer add_object method
Add container to SlurmJob
Make dir of container full path
Copy input files to input directory
Add input_files field and methods
Verify source files exist
Copy source files to container
Generate slurm job container and write Rdata files
Set the values of all gobals to NA & print globals
Find the global variables that are unassigned
Updated code

Simplified fecanalyzer() by adding piped mutate() calls.
Fixes error taking log of zero p-valuesDESeq2 vennadjust heightFixed shared loop variable
modifications for results figure
beta function to extract fossil ages directly from a PBDB table

The new function is:
extract.ages.pbdb(file,sep, extant_species, replicates, cutoff, random)
update bottom listing with what is done for top listing
normalize if length more than 1
fix the bug of missing function GRangesgraphs with colours
Add diff-in-diff plot
get all dates before getting min max
don't use function name
Fix LIST-DIR return result, %mezz-files.r meddling

FUNC and FUNCTION have been changed by default to require a value be
returned.  LIST-DIR returned no value, so this changes it to be
a PROCEDURE.

Goes ahead and changes the other routines in %mezz-files.r to declare
their return result types, format a little more nicely, and use FUNCTION
instead of FUNC.  Incorporates usages of BAR! and DEFAULT
added importing the MASS package
changed use of the "len" variable. previously it was used for all for loops. however, it was not applicable if there was not an etm+ image year for each oli image year.
changed the error message to be accurate to the if statement (needs at least 1 image, not 3)
added importing the MASS package
changed how the composite file list is created. previously assumed either 1 or 2 lists, now iterates merging with a for loop.
the resample function changed names - updating the call
export significant DE gene namesDrastically reduce max.print
remove quote from GSEA rnk filegenerate GSEA rnk filelist all weeks. normalized price and index. typo
invisibly return coordinates of legend from draw.scale
added width and height to ggsave
cleanup. add missing param
graph functions with more given params
modify to export figure
Change variable name
remove unnecessary command line
adjust to run analysis
market name and param fix
adjust parameters
add function
add evaluation of similarity between resources based on set of consumers
add evaluation of similarity between resources based on set of consumers
add evaluation of similarity between resources based on set of consumers
adjust function to consider consumer and resource similarity based on set of resource and set of consumer, respectively
list is done.
mainly make graph functions
new function
include new function to include set of consumers in Tanimoto_data.RData
dataframe stuff/
travis, u thr?
removing superfluous comment; let's see if travis kicks in
adjust for relative paths
adjust for relative paths
t commit Script/serialNext.r
git commit init.r
modify relative paths
modify relative paths
modify relative paths
modify relative paths
modify relative paths
modify relative paths
modify relative paths
modify relative paths
finalize script
prepare analysis
add function
add accuracy calculation and figure output for results
add function for plots
adjust function name that was not changed with previous modifications
added function to avoid overwriting files if multiples analyses are running simultaneously
added function to avoid overwriting files if multiples analyses are running simultaneously
adjusted function names
Added the option to consider only empirical data in the predictions, hence considering the contribution of the interaction catalog
Added the option to consider only empirical data in the predictions, hence considering the contribution of the interaction catalog
modified process steps
add origin to POSITXct
Show mean and median lines
Fix wrong var name
displaychart with given periodtext. the new chart with days and names
Explicit mock.
Update SummaryFromFiles.rSaisonale Plots, Jet abhängig von Standardabweichung?
Added support for custom lib paths
also iterate pairs. move to outer
indent with ess
git test 4
git test 3
Second commit test
Include flow with concentration to get an idea of the total amounts involved.  Yeah vague I know.
Select sites with 9 or more samples.
added external function "predict_oli_index" as internal function
added external function "predict_mss_index" as internal function
Größerer Datensatz implementiert, Geopot, Temp, Div, u, v, w. Saisonale Veränderungen.
Bunch of graphs.
         k                  6  z                 (  o  ~            ]  h              5            <  U  n             6  L  [  j  y              %  7  G  ]  s    1	  	  	  N
  ]
  l
  {
  
  
  
  	    5  D  S  b  q            W        O  t              =  b          
        d        6  U  l  w            5  Z          (  g      $  c  r              #  ;  y          6  [          ,  ?  (    P  u                 /                    E  T  y                      +   :   I   X   g   v                              !  !  #  )#  N#  s#  #  #  #  #  $  x$  $  &  +&  <&  M&  ^&  o&  &  &  &  '  F'  R'  ^'  j'  v'  '  '  '  '  (  (  (  7(  \(  (  (  (  (  )  )  ))  8)  G)  V)  e)  t)  )  )  )  T*  *  *  +  h+  +  +  +  ,  ,  &,  5,  D,  S,  b,  q,  ,  ,  ,  ,  ,  ,  ,  ,  ,  -  -  %-  4-  C-  R-  a-  p-  -  -  -  -  -  -  -  -  -  .  .  $.  3.  d.  s.  .  .  /  C/  /   0  v0  0  +1  >1  1  *2  4  D4  u4  4  4  5  95  x5  5  5  6  6  6  6  B7  7  7  8  '8  L8  8  8  9  19  V9  {9  9  9  t:  :  :  ;  ,;  <;  a;  ;  ;  ;  ;  <  ?<  d<  <  <  <  <  =  B=  g=  =  =  =  =   >  E>  j>  >  >  >  >  >?  T?  e?  ?  ?  @@  @  @  @  A  A  3A  dA  A  A  A      felipenoris/math-server-docker,felipenoris/math-server-docker,felipenoris/AWSFinance,felipenoris/AWSFinanceIFFranciscoME/MachineTradeRjkarl/LandscapeToolbox,jkarl/LandscapeToolboxpdp10/sbpipe,pdp10/sbpipe,pdp10/sbpipeSESman/rbljmousseau/Stainsebaki/clim-jet-stream,sebaki/clim-jet-stream,sebaki/clim-jet-streamsebaki/clim-jet-stream,sebaki/clim-jet-stream,sebaki/clim-jet-streamsebaki/clim-jet-stream,sebaki/clim-jet-stream,sebaki/clim-jet-streamsebaki/clim-jet-stream,sebaki/clim-jet-stream,sebaki/clim-jet-streamjmousseau/Stainjmousseau/Stainrroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstatSESman/rblsebaki/clim-jet-stream,sebaki/clim-jet-stream,sebaki/clim-jet-streamsebaki/clim-jet-stream,sebaki/clim-jet-stream,sebaki/clim-jet-streamMikkelSchubert/paleomix,MikkelSchubert/paleomix,MikkelSchubert/paleomixjmousseau/Stainjmousseau/Stainjmousseau/Stainsebaki/clim-jet-stream,sebaki/clim-jet-stream,sebaki/clim-jet-streamjmousseau/Stainjmousseau/Stainsolgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgnghonk/divaRsmouksassi/ggplotwithyourdata,smouksassi/ggplotwithyourdatajmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainmufajjul/TimetableModelshengqh/ngsperl,shengqh/ngsperl,shengqh/ngsperl,shengqh/ngsperlsolgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgnkhufkens/daymetrkhufkens/daymetrkhufkens/daymetrCSISdefense/Lookup-Tablessolgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgnCSISdefense/Lookup-TablesCSISdefense/Lookup-Tablesdpbroman/hydroforecastdaigotanaka/r-utilsfelipenoris/AWSFinance,felipenoris/math-server-docker,felipenoris/math-server-docker,felipenoris/AWSFinancejmousseau/Stainjmousseau/Staindpbroman/hydroforecastdpbroman/hydroforecastjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainsebaki/clim-jet-stream,sebaki/clim-jet-stream,sebaki/clim-jet-streamdpbroman/hydroforecastdpbroman/hydroforecastjmousseau/Stainperishky/meffilAndySouth/coveragekhufkens/daymetrdpbroman/hydroforecastdpbroman/hydroforecastYaleDHLab/lab-workshops,YaleDHLab/lab-workshops,YaleDHLab/lab-workshops,YaleDHLab/lab-workshopsYaleDHLab/lab-workshops,YaleDHLab/lab-workshops,YaleDHLab/lab-workshops,YaleDHLab/lab-workshopsYaleDHLab/lab-workshops,YaleDHLab/lab-workshops,YaleDHLab/lab-workshops,YaleDHLab/lab-workshopsYaleDHLab/lab-workshops,YaleDHLab/lab-workshops,YaleDHLab/lab-workshops,YaleDHLab/lab-workshopsYaleDHLab/lab-workshops,YaleDHLab/lab-workshops,YaleDHLab/lab-workshops,YaleDHLab/lab-workshopsjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/StainSESman/rblsolgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgndpbroman/hydroforecastdpbroman/hydroforecastdpbroman/hydroforecastjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Staindavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionskbuzard/SOP_repeateddavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsHIIT/digivaalit-2015,HIIT/digivaalit-2015,HIIT/digivaalit-2015HIIT/digivaalit-2015,HIIT/digivaalit-2015,HIIT/digivaalit-2015HIIT/digivaalit-2015,HIIT/digivaalit-2015,HIIT/digivaalit-2015HIIT/digivaalit-2015,HIIT/digivaalit-2015,HIIT/digivaalit-2015HIIT/digivaalit-2015,HIIT/digivaalit-2015,HIIT/digivaalit-2015david-beauchesne/Predict_interactionsjmousseau/Stainjmousseau/Stainjmousseau/Staindavid-beauchesne/Predict_interactionsjkarl/LandscapeToolbox,jkarl/LandscapeToolboxdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionskbuzard/SOP_repeateddavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsjmousseau/Stainrstudio/sparklyr,kevinykuo/sparklyr,kevinykuo/sparklyr,kevinykuo/sparklyr,rstudio/sparklyr,kevinykuo/sparklyr,rstudio/sparklyr,rstudio/sparklyrjkarl/LandscapeToolbox,jkarl/LandscapeToolboxrstudio/sparklyr,kevinykuo/sparklyr,kevinykuo/sparklyr,rstudio/sparklyr,kevinykuo/sparklyr,rstudio/sparklyr,kevinykuo/sparklyr,rstudio/sparklyrkevinykuo/sparklyr,rstudio/sparklyr,rstudio/sparklyr,kevinykuo/sparklyr,kevinykuo/sparklyr,kevinykuo/sparklyr,rstudio/sparklyr,rstudio/sparklyrrstudio/sparklyr,rstudio/sparklyr,kevinykuo/sparklyr,kevinykuo/sparklyr,kevinykuo/sparklyr,rstudio/sparklyr,rstudio/sparklyr,kevinykuo/sparklyrkevinykuo/sparklyr,rstudio/sparklyr,kevinykuo/sparklyr,rstudio/sparklyr,rstudio/sparklyr,kevinykuo/sparklyr,rstudio/sparklyr,kevinykuo/sparklyrdavid-beauchesne/Predict_interactionsharasmussen/PopulationAnimationmihapelhan/APPR-2015-16ghonk/divaRghonk/divaRdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsjkarl/LandscapeToolbox,jkarl/LandscapeToolboxmihapelhan/APPR-2015-16david-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsStangeljL12/APPR-2015-16jkarl/LandscapeToolbox,jkarl/LandscapeToolboxbgweber/RServer,bgweber/RServer,bgweber/RServer,bgweber/RServerbgweber/RServer,bgweber/RServer,bgweber/RServer,bgweber/RServerbgweber/RServer,bgweber/RServer,bgweber/RServer,bgweber/RServerbgweber/RServer,bgweber/RServer,bgweber/RServer,bgweber/RServerbgweber/RServer,bgweber/RServer,bgweber/RServer,bgweber/RServerbgweber/RServer,bgweber/RServer,bgweber/RServer,bgweber/RServerjmousseau/Stainjmousseau/Stainjmousseau/Stainperishky/meffilOwnYourData/app-bank,OwnYourData/app-bankreturnString/node-gsr,returnString/node-gsrStangeljL12/APPR-2015-16StangeljL12/APPR-2015-16StangeljL12/APPR-2015-16HIIT/digivaalit-2015,HIIT/digivaalit-2015,HIIT/digivaalit-2015HIIT/digivaalit-2015,HIIT/digivaalit-2015,HIIT/digivaalit-2015mschubert/clustermq,mschubert/clustermq,mschubert/clustermqswebb1/questdaigotanaka/r-utilsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsmschubert/clustermq,mschubert/clustermq,mschubert/clustermqdavid-beauchesne/Predict_interactionsdanluu/BitFunnel,danluu/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunnel,danluu/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunnel,danluu/BitFunnel,BitFunnel/BitFunnel,danluu/BitFunneldavid-beauchesne/Predict_interactionsdaigotanaka/r-utilshostilefork/rebol,giuliolunati/ren-c,codebybrett/ren-c,draegtun/ren-c,kealist/ren-c,giuliolunati/ren-c,rgchris/ren-c,giuliolunati/ren-c,codebybrett/ren-c,rgchris/ren-c,kealist/ren-c,draegtun/ren-c,kealist/ren-c,rgchris/ren-c,kealist/ren-c,hostilefork/rebol,codebybrett/ren-c,giuliolunati/ren-c,draegtun/ren-c,draegtun/ren-c,rgchris/ren-c,kealist/ren-c,hostilefork/rebol,codebybrett/ren-c,hostilefork/rebol,giuliolunati/ren-c,rgchris/ren-c,codebybrett/ren-c,draegtun/ren-c,hostilefork/rebolrgchris/ren-c,giuliolunati/ren-c,kealist/ren-c,codebybrett/ren-c,kealist/ren-c,giuliolunati/ren-c,rgchris/ren-c,hostilefork/rebol,hostilefork/rebol,codebybrett/ren-c,hostilefork/rebol,rgchris/ren-c,draegtun/ren-c,giuliolunati/ren-c,draegtun/ren-c,kealist/ren-c,codebybrett/ren-c,kealist/ren-c,codebybrett/ren-c,codebybrett/ren-c,kealist/ren-c,giuliolunati/ren-c,draegtun/ren-c,rgchris/ren-c,draegtun/ren-c,giuliolunati/ren-c,rgchris/ren-c,hostilefork/rebol,draegtun/ren-c,hostilefork/rebolsestaton/sesbio,sestaton/sesbio,sestaton/sesbio,sestaton/sesbiodavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsZigaP/APPR-2015-16david-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsjmousseau/Stainswebb1/questjmousseau/Stainjmousseau/Stainsolgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgn,solgenomics/sgnghonk/divaRdavid-beauchesne/Predict_interactionsjmousseau/Stainjmousseau/Stainghonk/divaRUrosKrampelj/APPR-2015-16VCCRI/SVPV,VCCRI/SVPV,VCCRI/SVPVdavid-beauchesne/Predict_interactionsjmousseau/Staindavid-beauchesne/Predict_interactionsjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainfernandezpablo85/sysarmy-salaries-data-2016jmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Staindraegtun/ren-c,rgchris/ren-c,draegtun/ren-c,codebybrett/ren-c,kealist/ren-c,giuliolunati/ren-c,giuliolunati/ren-c,draegtun/ren-c,giuliolunati/ren-c,giuliolunati/ren-c,hostilefork/rebol,rgchris/ren-c,kealist/ren-c,codebybrett/ren-c,kealist/ren-c,draegtun/ren-c,kealist/ren-c,kealist/ren-c,giuliolunati/ren-c,draegtun/ren-c,codebybrett/ren-c,hostilefork/rebol,codebybrett/ren-c,rgchris/ren-c,codebybrett/ren-c,rgchris/ren-c,rgchris/ren-c,hostilefork/rebol,hostilefork/rebol,hostilefork/reboldavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdaigotanaka/r-utilsgeneura-papers/2015_books,geneura-papers/2015_booksAndySouth/coverageAndySouth/coveragerroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstatAndySouth/coverageFescueFungiShare/hydroshare,hydroshare/hydroshare,hydroshare/hydroshare,ResearchSoftwareInstitute/MyHPOM,ResearchSoftwareInstitute/MyHPOM,RENCI/xDCIShare,RENCI/xDCIShare,hydroshare/hydroshare,hydroshare/hydroshare,ResearchSoftwareInstitute/MyHPOM,FescueFungiShare/hydroshare,RENCI/xDCIShare,FescueFungiShare/hydroshare,ResearchSoftwareInstitute/MyHPOM,RENCI/xDCIShare,FescueFungiShare/hydrosharePezdirM14/APPR-2015-16wbooker/PloidyPalwbooker/PloidyPalwbooker/PloidyPalwbooker/PloidyPalreturnString/node-gsr,returnString/node-gsrreturnString/node-gsr,returnString/node-gsrreturnString/node-gsr,returnString/node-gsrreturnString/node-gsr,returnString/node-gsrreturnString/node-gsr,returnString/node-gsrgo-ski/pbdIOgo-ski/pbdIOgo-ski/pbdIOgo-ski/pbdIOgo-ski/pbdIOdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsreturnString/node-gsr,returnString/node-gsrgo-ski/pbdIOgo-ski/pbdIOgo-ski/pbdIOdgabbe/dgutil,dgabbe/dgutilsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsjmousseau/Stainfernandezpablo85/sysarmy-salaries-data-2016fernandezpablo85/sysarmy-salaries-data-2016david-beauchesne/Predict_interactionsjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjae0/bio.snowcrab,jae0/bio.snowcrabcarjed/smaug-genetics,carjed/smaug-genetics,carjed/smaug-genetics,carjed/smaug-geneticscarjed/smaug-genetics,carjed/smaug-genetics,carjed/smaug-genetics,carjed/smaug-geneticscarjed/smaug-genetics,carjed/smaug-genetics,carjed/smaug-genetics,carjed/smaug-geneticsjmousseau/Staincarjed/smaug-genetics,carjed/smaug-genetics,carjed/smaug-genetics,carjed/smaug-geneticscarjed/smaug-genetics,carjed/smaug-genetics,carjed/smaug-genetics,carjed/smaug-geneticscarjed/smaug-genetics,carjed/smaug-genetics,carjed/smaug-genetics,carjed/smaug-geneticsdavid-beauchesne/Predict_interactionsjmousseau/Stainjmousseau/StainCellProfiling/cam_acqjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Stainjmousseau/Staindhmontgomery/pioneer-press-code,pioneerpress/codeperishky/meffilshengqh/ngsperl,shengqh/ngsperl,shengqh/ngsperl,shengqh/ngsperlshengqh/ngsperl,shengqh/ngsperl,shengqh/ngsperl,shengqh/ngsperljkarl/LandscapeToolbox,jkarl/LandscapeToolboxdavid-beauchesne/Predict_interactionsdsilvestro/PyRate,dsilvestro/PyRate,dsilvestro/PyRate,dsilvestro/PyRaterroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstatrroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstatshengqh/ngsperl,shengqh/ngsperl,shengqh/ngsperl,shengqh/ngsperlrroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstatdaigotanaka/r-utilsrroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstatrroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstatkealist/ren-c,hostilefork/rebol,rgchris/ren-c,kealist/ren-c,draegtun/ren-c,hostilefork/rebol,rgchris/ren-c,draegtun/ren-c,draegtun/ren-c,codebybrett/ren-c,giuliolunati/ren-c,kealist/ren-c,codebybrett/ren-c,rgchris/ren-c,draegtun/ren-c,giuliolunati/ren-c,hostilefork/rebol,giuliolunati/ren-c,kealist/ren-c,codebybrett/ren-c,hostilefork/rebol,draegtun/ren-c,giuliolunati/ren-c,giuliolunati/ren-c,rgchris/ren-c,hostilefork/rebol,codebybrett/ren-c,codebybrett/ren-c,rgchris/ren-c,kealist/ren-cjdbcode/LandsatLinkr,DougFirErickson/LandsatLinkrDougFirErickson/LandsatLinkr,jdbcode/LandsatLinkrDougFirErickson/LandsatLinkr,jdbcode/LandsatLinkrjdbcode/LandsatLinkr,DougFirErickson/LandsatLinkrjdbcode/LandsatLinkr,DougFirErickson/LandsatLinkrDougFirErickson/LandsatLinkr,jdbcode/LandsatLinkrshengqh/ngsperl,shengqh/ngsperl,shengqh/ngsperl,shengqh/ngsperlklmr/.files,klmr/.files,klmr/.filesshengqh/ngsperl,shengqh/ngsperl,shengqh/ngsperl,shengqh/ngsperlshengqh/ngsperl,shengqh/ngsperl,shengqh/ngsperl,shengqh/ngsperlrroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstatsushilashenoy/zoom.plotpdp10/sbpipe,pdp10/sbpipe,pdp10/sbpiperroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstatrroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstatdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsrroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstatdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsSobieck00/practice,Sobieck00/practice,Sobieck00/practice,Sobieck00/practice,Sobieck00/practicerroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstatdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsSobieck00/practice,Sobieck00/practice,Sobieck00/practice,Sobieck00/practice,Sobieck00/practicebeast-dev/RBeastbeast-dev/RBeastdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdavid-beauchesne/Predict_interactionsdaigotanaka/r-utilsdaigotanaka/r-utilsdaigotanaka/r-utilsrroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstatrobertzk/syberiaStageswbooker/PloidyPalsebaki/clim-jet-stream,sebaki/clim-jet-stream,sebaki/clim-jet-streamreturnString/rip,returnString/riprroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstatrroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstatjoejcollins/WaterAnalysisjoejcollins/WaterAnalysisjoejcollins/WaterAnalysisjoejcollins/WaterAnalysisjoejcollins/WaterAnalysisjdbcode/LandsatLinkr,DougFirErickson/LandsatLinkrjdbcode/LandsatLinkr,DougFirErickson/LandsatLinkrsebaki/clim-jet-stream,sebaki/clim-jet-stream,sebaki/clim-jet-streamjoejcollins/WaterAnalysis             .   [                    4  G  \  c  z              7  A  ]  t  z                       2  >  D  T  d  {                     &  9  K  b  y                7  W  w                    )  :  K  ^  o                  )  <  B  U  b  o                .  I  W  j              
	  	  	  %	  ,	  K	  f	  	  	  	  	  	  	  	  	  
  ,
  J
  k
  
  
  
  
  
  
  
  
  	  &  5  D  T  a  s  ~            #  ?  I  a  s            +  @  O  b  u  {                  	    -  B  U  h  }                      2  E  X  c  v                  3  S  d  o                +  >  Q  d  s                      /  =  J  X  e  r                    %  :  D  N  X  f  v                    &  8  M  b  w                     -  B  W  d  q  ~                      %  2  ?  L  Y  f  s              &  -  4  D  K  V  ]  d  y                    "  )  8  i  p  w                +  L  h                     3  Q  W  x          
  (  L  j  r                   (  3  >  I  P  i  }                    /  @  `  v      libs/r-packages.rMTR_Publisher/MTR_Publisher.rDIMA_Queries-Reports/DIMA_count_HAF_species.rsb_pipe/pipelines/simulate/plot_timecourses.rR/funs_acc_processing.rR/slurm-container.rlocate_jetstream_polynomial_2d.rlocate_jetstream_polynomial_2d.rpckg.cheb/R/functions-chebyshev.rpckg.cheb/R/functions-chebyshev.rR/slurm-container.rR/slurm-bash-script.rr/lib.rR/funs_acc_processing.rpckg.cheb/R/functions-chebyshev.rpckg.cheb/R/functions-chebyshev.rpaleomix/resources/rscripts/zonkey/tinytree.rR/stain-ssh.rR/stain-ssh.rR/slurm-container.rpckg.cheb/R/functions-chebyshev.rR/sbatch.rtests/testthat/test-sbatch.rR/combine_populations.rinit.rapp.rR/slurm-container.rR/sbatch.rR/slurm-container.rR/slurm-container.rTModel.rlib/Comparison/DESeq2.rR/gs.rR/batch.download.daymet.rR/download.daymet.tiles.rR/download.daymet.tiles.rFSRSimport.rR/gs.rSQLimportTools.rSQLimportTools.rprocess_cfsv2_ts_ncdc.rrmd.rlibs/r-packages.rR/slurm-container.rR/slurm-container.rget_cfsv2_ts_ncdc.rget_cfsv2_ncdc.rR/slurm-container.rR/slurm-container.rR/slurm-container.rR/slurm-container.rR/slurm-container.rprocess_mean_uvw.rprocess_cfsv2_ts_ncdc.rprocess_cfsv2_ts_ncdc.rR/slurm-container.rR/plot-pc-fit.rinst/shiny/covmob1/ui.rR/download.daymet.tiles.rcfsv2_ts_ncdc_sqlite.rcfsv2_ts_ncdc_sqlite.rrstudio_dfrtopics/slavicreview.rrstudio_dfrtopics/slavicreview.rrstudio_dfrtopics/slavicreview.rrstudio_dfrtopics/slavicreview.rrstudio_dfrtopics/slavicreview.rR/stain-message.rR/slurm-container.rR/slurm-container.rR/slurm-container.rR/funs_biopic.rR/gs.rget_cfsv2_ncdc.rget_cfsv2_ts_ncdc.rget_cfsv2_ncdc.rR/stain-message.rR/stain-message.rR/slurm-container.rR/stain-message.rScript/2-6_catalog_predictions.rScript/2-6_catalog_predictions.rDGH.rArticle/decision_diag.rScript/2-8_St_Lawrence_ex.rtopics/topics.rtopics/create_topics.rtopics/topics.rtopics/topics.rtopics/create_dtm.rinit.rR/slurm-container.rR/stain-ssh.rR/stain-ssh.rScript/1-Similarity_matrix.rpackage_installation.rScript/tanimoto_analysis.rScript/catalog_predictions.rScript/2-8_St_Lawrence_ex.rScript/2-4-Multiple_parameters.rDGH.rScript/full_algorithm.rScript/2-8_St_Lawrence_ex.rArticle/box1.rR/slurm-container.rinst/staticdocs/index.rpackage_installation.rinst/staticdocs/index.rinst/staticdocs/index.rinst/staticdocs/index.rinst/staticdocs/index.rArticle/decision_diag.ranimate.ruvoz/uvoz.rutils.rutils.rScript/prediction_accuracy_id.rScript/2-8_St_Lawrence_ex.rScript/2-8_St_Lawrence_ex.rpackage_installation.ruvoz/uvoz.rScript/2-8_St_Lawrence_ex.rinit.rScript/2-8_St_Lawrence_ex.ruvoz/uvoz.rpackage_installation.rtasks/userDemo/mtcars.rtasks/userDemo/error.rtasks/RServerTasks/LogParser.rtasks/RServerTasks/BuildReports.rtasks/RServerPerf/BuildReports.rtasks/HelloWorld/Main.rR/slurm-container.rR/slurm-settings.rR/slurm-settings.rR/adjust.rinit.rbin/gsr-video.ranaliza/analiza.rvizualizacija/vizualizacija.rlib/libraries.rtopics/topics.rtopics/check_k.rR/qsys_base.rR/ggplot_builder.rhighchart.rScript/2-6_catalog_predictions.rScript/2-7_Multiple_parameters2.rScript/2-6_catalog_predictions.rR/qsys_base.rScript/2-7_Multiple_parameters2.rsrc/Scripts/plot-sim.rScript/catalog_predictions.rbinomial.rsrc/tools/make-reb-lib.rsrc/tools/common.rtransposon_annotation/r_scripts/hann_lines_analysis.rScript/2-6_catalog_predictions.rScript/catalog_predictions.ruvoz/uvoz.rScript/2-6_catalog_predictions.rScript/catalog_predictions.rR/slurm-bash-script.rinst/quest/ui.rR/slurm-container.rR/slurm-container.rR/gs.rinit.rScript/two_way_tanimoto_predict.rR/globals.rR/slurm-bash-script.rutils.ranaliza/analiza.rsvpv/SVPV.rScript/tanimoto.rR/slurm-container.rScript/tanimoto.rR/slurm-container.rR/slurm-bash-script.rR/slurm-container.rR/slurm-container.rR/slurm-bash-script.rR/slurm-container.rR/slurm-container.rR/slurm-bash-script.rR/slurm-bash-script.rsysarmy.rR/globals.rR/slurm-job.rR/globals.rR/slurm-container.rR/slurm-container.rR/slurm-container.rR/slurm-container.rR/slurm-container.rR/globals.rR/slurm-container.rR/slurm-container.rR/slurm-container.rR/slurm-container.rR/slurm-container.rR/slurm-container.rR/slurm-container.rsrc/tools/make-make.rScript/tanimoto_analysis.rScript/catalog_predictions.rScript/2-6_catalog_predictions.rScript/tanimoto.rhighchart.rTables_to_figures/generador.rinst/shiny/coverage1/ui.rinst/shiny/coverage1/server.rr/lib.rinst/shiny/coverage1/server.rhydroshare/irods/ruleGenerateBagIt_HS.ruvoz/uvoz.rR/CalcAlleleDiffs.rR/CalcAlleleDiffs.rR/CalcAlleleDiffs.rR/CalcAlleleDiffs.rbin/gsr-video.rbin/gsr-video.rbin/gsr-video.rbin/gsr-plot.rbin/gsr-video.rdemo/matrix.rdemo/matrix.rdemo/matrix.rdemo/matrix.rdemo/matrix.rScript/2-6_catalog_predictions.rScript/2-4-Multiple_parameters.rbin/gsr-plot.rdemo/matrix.rR/comm.fread.rdemo/matrix.rdev/explore.rScript/2-6_catalog_predictions.rinit.rR/slurm-job.rsysarmy.rsysarmy.rScript/2-4-Multiple_parameters.rtests/testthat/test-slurm-job.rR/slurm-bash-script.rR/slurm-job.rR/slurm-job.rR/slurm-bash-script.rR/sbatch.rR/sbatch.rR/sbatch.rR/minilog.db.rR/dnm_analysis.rR/dnm_analysis.rR/dnm_analysis.rR/sbatch.rR/dnm_analysis.rR/dnm_analysis.rR/dnm_analysis.rScript/2-4-Multiple_parameters.rR/slurm-settings.rR/slurm-settings.rcamacq/data/gain.rR/slurm-settings.rR/slurm-bash-script.rR/slurm-bash-script.rR/slurm-bash-script.rR/slurm-bash-script.rR/slurm-container.rR/slurm-container.rR/slurm-bash-script.rR/slurm-bash-script.rR/slurm-job.rR/slurm-bash-script.rR/slurm-job.rR/slurm-bash-script.rR/slurm-job.rR/slurm-bash-script.rR/slurm-bash-script.rR/slurm-job.rR/slurm-job.rR/slurm-job.rR/slurm-job.rR/slurm-job.rR/slurm-job.rR/slurm-container.rR/slurm-job.rR/slurm-container.rR/slurm-job.rR/slurm-container.rR/slurm-job.rR/slurm-container.rR/slurm-job.rR/slurm-job.rR/slurm-job.rR/slurm-job.rR/slurm-job.rR/slurm-job.rR/slurm-job.rfecgrabber/fecgrabber.rR/plot-ewas.rlib/Comparison/DESeq2.rlib/Visualization/Depth.rCalibration_Tool/calibration_checking.rScript/2-5-Similarity_cons_res_blind.rpyrate_utilities.rr/lib.rr/lib.rlib/CNV/cnMops.rr/lib.rhighchart.rr/lib.rr/lib.rsrc/mezz/mezz-files.rR/olical_single.rR/olical.rR/olical.rR/msscal_single.rR/mixel.rR/calibrate_and_composite.rlib/Comparison/DESeq2.r.R/print.rlib/Comparison/DESeq2.rlib/Comparison/DESeq2.rr/lib.rR/decorations.rsb_pipe/pipelines/param_estim/param_estim_utils.rr/lib.rr/lib.rScript/2-3-similarity_cons_res.rScript/tanimoto_analysis.rScript/tanimoto_analysis.rScript/2-3-similarity_cons_res.rr/lib.rScript/tanimoto_analysis.rinit.rScript/similarity_taxon.rScript/similarity_taxon_predict.rScript/1-Similarity_matrix.rScript/two_way_tanimoto_predict.rdatascience/datacamp/intro_to_r/lists.rr/lib.rinit.rScript/0-1-Tanimoto_data.rdatascience/datacamp/intro_to_r/data_frames.rR/plotGLM.rR/plotGLM.rinit.rScript/serialNext.rScript/2-1-Tanimoto_analysis.rinit.rScript/0-2-Interactions_sources.rScript/1-Similarity_matrix.rScript/Test-Catalog_vs_predictions.rScript/0-1-Tanimoto_data.rScript/2-1-Tanimoto_analysis.rScript/tanimoto_accuracy.rScript/2-2-Tanimoto_accuracy.rScript/Test-Catalog_vs_predictions.rScript/2-1-Tanimoto_analysis.rREADME.rScript/Test-Catalog_vs_predictions.rREADME.rScript/tanimoto_accuracy.rScript/Test-Catalog_vs_predictions.rREADME.rREADME.rScript/tanimoto_accuracy.rScript/prediction_matrix.rREADME.rhighchart.rhighchart.rhighchart.rr/lib.rinst/tests/test-adapter.rR/SummaryFromFiles.rlocate_jetstream_polynomial_2d.rrip.rr/lib.rr/lib.rpreliminary_analysis.rpreliminary_analysis.rpreliminary_analysis.rpreliminary_analysis.rpreliminary_analysis.rR/olical_single.rR/msscal_single.rlocate_jetstream_polynomial_2d.rpreliminary_analysis.r                                 "   %   (   0   3   6   9   <   ?   B   E   H   K   N   Q   T   W   Z   ]   `   c   f   p   s   {                                                                                                                          #  &  )  ,  /  2  5  8  ;  >  A  D  G  J  M  P  S  Z  ]  `  c  f  i  l  o  r  u                                                    &  2  5  8  ;  G  J  M  P  S  V  Y  \  f  i  l  o  r  u                                                                                                       #  &  )  ,  6  9  <  ?  B  E  Q  T  W  _  b  n  q  t  w  z  }                                                                         	              %  (  +  .  1  4  7  :  =  @  C  F  I  L  O  R  U  X  [  ^  a  d  g  j  m  p  s  v  y  |                                                          !  +  5  ?  G  J  M  U  ]  `  c  f  i  q  t  w  z  }                                                                                                !  $  '  *      mitmitcc0-1.0mitmitmitmitmitmitmitmitmitagpl-3.0mitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitapache-2.0mitagpl-3.0agpl-3.0agpl-3.0cc0-1.0mitcc0-1.0cc0-1.0mitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitartistic-2.0mitagpl-3.0mitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitcc0-1.0mitmitmitmitmitmitmitmitmitapache-2.0cc0-1.0apache-2.0apache-2.0apache-2.0apache-2.0mitapache-2.0mitmitmitmitmitmitcc0-1.0mitmitmitmitmitcc0-1.0bsd-3-clausebsd-3-clausebsd-3-clausebsd-3-clausebsd-3-clausebsd-3-clausemitmitmitartistic-2.0mitmitmitmitmitmitmitapache-2.0mitmitmitmitmitapache-2.0mitmitmitmitapache-2.0apache-2.0mitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitapache-2.0mitmitmitmitmitartistic-2.0mitmitagpl-3.0mitbsd-3-clausemitmitmitmitmitmitmitmitmitmitmpl-2.0mpl-2.0mpl-2.0mpl-2.0mpl-2.0mitmitmitmpl-2.0mpl-2.0mpl-2.0mitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitapache-2.0mitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitartistic-2.0apache-2.0apache-2.0cc0-1.0mitagpl-3.0agpl-3.0agpl-3.0apache-2.0agpl-3.0mitagpl-3.0agpl-3.0apache-2.0mitmitmitmitmitmitapache-2.0apache-2.0apache-2.0apache-2.0agpl-3.0mitmitagpl-3.0agpl-3.0mitmitmitmitagpl-3.0mitmitmitmitmitmitmitagpl-3.0mitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitmitagpl-3.0mitmitmitmitagpl-3.0agpl-3.0mitmitmitmitmitmitmitmitmit      }W    #W    W    fW    gBW    WW    CW    W    W    W    l	W    W    W    qW    bW    NW    FW    {W    QW    GW    6DW    >W    	>W    14W    "W    ~W    kW    xW    W    W    FW    AW    [W    W    TMW    LW    ."W    6W    9W    AW    cW    ]bW    W    mW    fW    mW    lW    ]W    WW    VW    SW    a2W    W    >>W    I.W    ["W    jW    ӘW    'W    @W    @W    OW    W     W    bW    W    zW    lrW    MrW    kW    CW    7W    &gW    eW    pdW    &DW    TW    5W     W    
W    W    W    W    "W    W    ޙW    ԕW    TW    #W    =lW    W    W    W    >6W    0W    /W    /W    b/W    S/W    .W    W    "W    "W    W    W    CW    3W    W    2W    W    W    W    W    ܨW    W    [W    fW    cW    \W    W    FjW    m7W    6W    51W    6+W    :W    :W    :W    :W    }:W    `:W    W    W    OW    $W    /oW    7W    W    ǸW    W    nW    DW    W    ;W    G*W    ? W     W    W    9W    0W    W    W    W    {W    {W    pW    [W    [W    SW    SW    RW    =@W    2W    W    tW    W    W    ^W    pW    W    W    vW    ,nW    _*W    W    2W    aW    W    W    W    .W    W    EW    W    W    uW    ^W    xW    ]W    W    W    #W    yW    !W    hW    W    W    W    W    W    W    ŻW    W    LW    LW    W    W    ]W    W    2rW    rW    ΈW    N*W    W    W    lW    W    WW    XW    W    DW    W    W    }W    oW    kW    [eW    _W    AQW    W    W    ڞW    KW    (W    7W    `W    W    W    ӕW    dW    aW    ^W    +W    WW    {AW    ?W    'W    W    W    	W    W    J W    ) W    7W    W    W    W    W    ӐW    -ݽW    aܽW    9ؽW    ֽW    ,ͽW    zʽW    JʽW    ɽW    _ƽW    W    W    vW    nW    W    eW    8ݼW    ݼW    $ܼW    _ۼW    ѼW    YѼW    мW    ;мW    ϼW     μW    ͼW    }̼W    #̼W    ʼW    iʼW    ɼW    ȼW    W    W    ɸW    W    W    W    đW    6W    YW    wW    *FW    /DW    #W     ԺW    "W    W    K1W    W    W    W    FW    ޴W    ƴW    ƴW    ƴW    ŴW    rŴW    ŴW    FW    䊴W    aW    2W    /W    1#W    ұW    BW    pW    tW    OW    5W    5W    ϮW    2W    2W    ;+W    ;+W    ;+W    ;+W    $ W    DW    aW    RW    \W    W    W    tW    sW    W    W    W    W    W    W    W    W    W    oƭW    KƭW    5ƭW    44W    4W    iW    W    W    W    LW    +W    W    W    ëW    ֊W    {W    ]W    ZW    FW    FW    \JW    	(W    ZW    W    W    W    tۤW    #ĤW    äW    -W    DW        ,    h  A  ud       'B 	p x ݣ  ; e      d/ ;\ q z ̟ x ]b َ    R I L  
  / f      ( N c_ p  Ҹ   !	 9	 G	 QO	 m	 -|	 @	 Ţ	 5	 m	 	 	 %	 I	 E	 	 
 {/
 M
 _
 ;
 
 
 8
 
   & Kd        D% o& PH [a m Tz ߂ đ A ]  M     .  7 B 4Q Z\ xg dr } ɍ S 5 -  @ b3 P] wj  )  6 ?       t 4 7 N; %D H S T Z \ {g Bi v  f a K   H   s   iA C Se   {  I" HO re { *    < WC H J ٴ  n    A { &2 F LM S a 9j s n{ ю K O   N ^ @    % B/ Y    P  X6 D M #   i% + 1 7 = I T m^ e` e r +  z ܪ  Z ^  C+ : r< V l I{ x ړ    k  X    ? mR )e w T} 
 G    r h l	    V' . 16 k= yD /P 0W b gg r w z E   V  d   e  S {   & 4 C O =X _ r~  " %    8   V/ I  '  R?  ^  h  nr        FS! vT! ! 5-" ;" " (# # i# 0$ 6$ j$ {$ $ z% 2% 9% C% Q% g% % % & 4& 8& I& Z& vp& Nr& 2& & & n& r' =' m' %w' >' 6' ' ' 2( G( Q( G{( ۏ( P( ( ( C( ( ( T) g) op) ) h) ) ** * >* o* * * + 77+ If+ + +     
pkgs <- c(
	"alabama",
	"base64enc",
	"caret",
	"cubature",
	"data.table",
	"DEoptim",
	"devtools",
	"doParallel",
	"doSNOW",
	"dplyr",
	"dyn",
	"dynlm",
	"extrafont",
	"feather",
	"fAsianOptions",
	"fAssets",
	"fBasics",
	"fBonds",
	"fCopulae",
	"fExoticOptions",
	"fExtremes",
	"fGarch",
	"fImport",
	"fMultivar",
	"fNonlinear",
	"fOptions",
	"fPortfolio",
	"fRegression",
	"fTrading",
	"fUnitRoots",
	"foreach",
	"forecast",
	"glmnet",
	"gmailr",
	"ggfortify",
	"ggplot2",
	"ggthemes",
	"gmp",
	"Hmisc",
	"knitr",
	"leaps",
	"linprog",
	"lubridate",
	"lpSolve",
	"lpSolveAPI",
	"mail",
	"mapproj",
	"maptools",
	"microbenchmark",
	"mongolite",
	"NMOF",
	"openxlsx",
	"parcor",
	"party",
	"pbivnorm",
	"plm",
	"plotly",
	"PythonInR",
	"quantmod",
	"R.cache",
	"randomForest",
	"Rcpp",
	"RCurl",
	"rJava",
	"readr",
	"reshape",
	"rmarkdown",
	"Rmpfr",
	"rjson",
	"roxygen2",
	"RQuantLib",
	"RSelenium",
	"RSQLite",
	"rvest",
	"scales",
	"sqldf",
	"shinydashboard",
	"stringr",
	"Synth",
	"plyr",
	"TSA",
	"tikzDevice",
	"x12",
	"xlsx",
	"XML",
	"xml2",
	"xts",
	"zoo"
	)

install.packages(pkgs)

# rjulia
devtools::install_github("armgong/rjulia", ref="julia0.5")

# http://bioconductor.org/packages/release/bioc/html/rhdf5.html
source("https://bioconductor.org/biocLite.R")
biocLite("rhdf5", ask=F) # HDF5 interface to R

# ------------------------------------------------------------------------------------ #
# -- Initial Developer: FranciscoME ----------------------------------------------- -- #
# -- Code: MachineTradeR Machine Trading R -- Publisher --------------------------- -- #
# -- License: MIT ----------------------------------------------------------------- -- #
# ------------------------------------------------------------------------------------ #

Mensajes_Computers <- c(
  "It is far better to foresee even without certainty than not
   to foresee at all. - Henri Poincare",
  "It is through science that we prove,
   but through intuition that we discover. - Henri Poincare")

Mensajes_Computers <- c(
  "A computer once beat me at chess, but it was no match for me at kick 
   boxing. - Emo Philips",
  "The good news about computers is that they do what you tell them to do.
   The bad news is that they do what you tell them to do. - Ted Nelson",
  "To err is human - and to blame it on a computer is even more so. - Robert Orben",
  "It's hardware that makes a machine fast. It's software that makes a
   fast machine slow. Craig Bruce",
  "I am thankful the most important key in history was invented. It's not the key
   to your house, your car, your boat, your safety deposit box, your bike lock or your
   private community. It's the key to order, sanity, and peace of mind. The key is 
   Delete. Elayne Boosler",
  "Computers are like Old Testament gods; lots of rules and no mercy. - Joseph Campbell",
  "Computer science is no more about computers than astronomy is about telescopes.
   Edsger Dijkstra",
  "Imagine if every Thursday your shoes exploded if you tied them the usual way. 
   This happens to us all the time with computers, and nobody thinks of complaining. 
   Jef Raskin",
  "Home computers are being called upon to perform many new functions, including the 
   consumption of homework formerly eaten by the dog. Doug Larson",
  "Computers are useless. They can only give you answers. Pablo Picasso",
  "Part of the inhumanity of the computer is that, once it is competently programmed 
   and working smoothly, it is completely honest. Isaac Asimov",
  "The question of whether a computer can think is no more interesting than the question
   of whether a submarine can swim. Edsger Dijkstra",
  "We're entering a new world in which data may be more important than software.
   Tim O'Reilly",
  "In computing, turning the obvious into the useful is a living definition of the 
   word 'frustration'. Alan Perlis")

HashTags_Generales <- c("#tp_algotrading , #machinelearning , #machineintelligence")


# -- Pelham Jenkins 
# -- Muro de instrumento
# -- Muro de usuario
# -- Twitter

# -- Benito Derman
# -- Muro de instrumento
# -- Muro de usuario
# -- Twitter

# -- Sonni Romano
# -- Muro de instrumento
# -- Muro de usuario
# -- Twitter

# -- Robert Bay
# -- Muro de instrumento
# -- Muro de usuario

# -- Etiquetador y comentarios con seguidores ----------------------------------------- #



library(dplyr)
library(readr)
library(RODBC)

DIMA <- "filepath and filename to DIMA"

## This reduces it to forbs only in the process
haf.list <- read_csv("HAF_preferred_species_by_code.csv") %>% subset(GROWTH.HABIT == "FORB")

channel <- odbcConnectAccess(DIMA) ## Assumes 32-bit R and 32-bit Access. Use odbcConnectAccess2007() if both are 64-bit
species.lists <- sqlQuery(channel, "SELECT joinSitePlotLine.SiteID, joinSitePlotLine.PlotKey, joinSitePlotLine.PlotID, tblSpecRichDetail.SpeciesList FROM joinSitePlotLine INNER JOIN (tblSpecRichHeader LEFT JOIN tblSpecRichDetail ON tblSpecRichHeader.RecKey = tblSpecRichDetail.RecKey) ON joinSitePlotLine.LineKey = tblSpecRichHeader.LineKey;")
odbcCloseAll()


## Counting the number of preferred species in the data
# The semicolons are the way that DIMA delimits the species in its own tables
for (n in 1:nrow(species.lists)){
  ## Take the HAF preferred species list, reduce it to a subset where they are also found in the
  # vector species list extracted from the plot, and count the number of rows in that subset. No loop required.
  species.lists$HAF.preferred.count[n] <- subset(haf.list,
                                                 haf.list$CODE %in%
                                                   unlist(strsplit(as.character(species.lists[n,4]),";"))
                                                 ) %>% nrow()
}
# This file is part of sb_pipe.
#
# sb_pipe is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# sb_pipe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with sb_pipe.  If not, see <http://www.gnu.org/licenses/>.
#
#
# Object: Plotting of the confidence intervals
#
# $Revision: 3.0 $
# $Author: Piero Dalle Pezze $
# $Date: 2016-07-7 11:14:32 $


library(ggplot2)


# Retrieve the environment variable SB_PIPE
SB_PIPE <- Sys.getenv(c("SB_PIPE"))
source(file.path(SB_PIPE,'sb_pipe','utils','R','sb_pipe_ggplot2_themes.r'))



# For each time point compute the most relevant descriptive statistics: mean, sd, var, skew, kurt, ci95, coeffvar, 
# min, 1st quantile, median, 3rd quantile, and max.
#
# :param timepoint.values: array of values for a certain time point
# :param nfiles: the number of files (samples) 
# :return: the statistics for the array of values for a specific time point
compute_descriptive_statistics <- function(timepoint.values, nfiles) {
	timepoint <- list("mean"=0,"sd"=0,"var"=0,"skew"=0,"kurt"=0,"ci95"=0,
			  "coeffvar"=0,"min"=0,"stquantile"=0,"median"=0,"rdquantile"=0,"max"=0)
    # compute mean, standard deviation, error, error.left, error.right
    timepoint$mean <- mean(timepoint.values, na.rm = TRUE)
    timepoint$sd <- sd(timepoint.values, na.rm = TRUE)
    timepoint$var <- var(timepoint.values, na.rm = TRUE)
    #y <- timepoint.values - timepoint.mean
    timepoint$skew <- mean(timepoint.values^3, na.rm = TRUE)/mean(timepoint.values^2, na.rm = TRUE)^1.5
    timepoint$kurt <- mean(timepoint.values^4, na.rm = TRUE)/mean(timepoint.values^2, na.rm = TRUE)^2 -3
    # 0.95 confidence level 
    #timepoint$ci95 <- qt(0.975, df=nfiles-1)*timepoint$sd/sqrt(nfiles)  # quantile t-distribution (few sample, stddev unknown exactly)
    timepoint$ci95 <- qnorm(0.975)*timepoint$sd/sqrt(nfiles) # quantile normal distribution (lot of samples)
    timepoint$coeffvar <- timepoint$sd / timepoint$mean
    timepoint$min <- min(timepoint.values, na.rm = TRUE)
    timepoint$stquantile <- quantile(timepoint.values, na.rm = TRUE)[2]  # Q1
    timepoint$median <- median(timepoint.values, na.rm = TRUE)  # Q2 or quantile(timepoint.values)[3]
    timepoint$rdquantile <- quantile(timepoint.values, na.rm = TRUE)[4]  # Q3
    timepoint$max <- max(timepoint.values, na.rm = TRUE)

    return (timepoint)
}



# Return the column names of the statitics to calculate
#
# :param column.names: an array of column names
# :param readout: the name of the readout
# :return: the column names including the readout name
get_column_names_statistics <- function(column.names, readout) {    
    column.names <- c (column.names,
                       paste(readout, "_Mean", sep=""),
                       paste(readout, "_StdDev", sep=""),
                       paste(readout, "_Variance", sep=""),
                       paste(readout, "_Skewness", sep=""),
                       paste(readout, "_Kurtosis", sep=""),                       
                       paste(readout, "_t-dist_CI95%", sep=""),
                       paste(readout, "_StdErr", sep=""),
                       paste(readout, "_CoeffVar", sep=""),
                       paste(readout, "_Minimum", sep=""),
                       paste(readout, "_1stQuantile", sep=""),
                       paste(readout, "_Median", sep=""),
                       paste(readout, "_3rdQuantile", sep=""),
                       paste(readout, "_Maximum", sep=""))
    #print(readout)
    return (column.names)
}



# Add the statistics for a readout to the table of statistics. The first column is Time.
#
# :param statistics: the table of statistics to fill up
# :param readout: the statistics for this readout.
# :param colidx: the position in the table to put the readout statistics
# :return: The table of statistics including this readout.
get_statistics_table <- function(statistics, readout, colidx=2) {    
    #print(readout$mean) 
    statistics[,colidx]   <- readout$mean
    statistics[,colidx+1] <- readout$sd
    statistics[,colidx+2] <- readout$var
    statistics[,colidx+3] <- readout$skew
    statistics[,colidx+4] <- readout$kurt
    statistics[,colidx+5] <- readout$ci95
    statistics[,colidx+6] <- readout$coeffvar
    statistics[,colidx+7] <- readout$min
    statistics[,colidx+8] <- readout$stquantile
    statistics[,colidx+9] <- readout$median
    statistics[,colidx+10] <- readout$rdquantile
    statistics[,colidx+11] <- readout$max
    return (statistics)
}



# Plot a model readout time course. If specified error bars are also plotted for each time point.
#
# :param outputdir: The output directory
# :param model: the model name
# :param readout: the name of the readout
# :param data: the data to plot (time point means at least)
# :param timepoints: the Time vector
# :param xaxis_label: the xaxis label 
# :param bar_type: the type of bar ("none", "sd", "sd_n_ci95")
plot_error_bars <- function(outputdir, model, readout, data, timepoints, xaxis_label, bar_type="sd") {
    filename = ""

    if(bar_type == "none") {
      # standard error configuration
      filename = file.path(outputdir, paste(model, "_none_", readout, ".png", sep=""))
      # Let's plot this special case now as it does not require error bars
      df <- data.frame(a=timepoints, b=data$mean)      
      g <- ggplot() + geom_line(data=df, aes(x=a, y=b), color="black", size=1.0)
      g <- g + xlab(xaxis_label) + ylab(paste(readout, " level [a.u.]", sep=""))
      ggsave(filename, dpi=300,  width=8, height=6) #, bg = "transparent")      

    } else { 

      df <- data.frame(a=timepoints, b=data$mean, c=data$sd, d=data$ci95)
      #print(df)
      g <- ggplot(df, aes(x=a, y=b))

      # plot the error bars
      g <- g + geom_errorbar(aes(ymin=b-c, ymax=b+c), colour="blue",  size=1.0, width=0.1)    
        
      if(bar_type == "sd") {
        # standard deviation configuration
        filename = file.path(outputdir, paste(model, "_sd_", readout, ".png", sep=""))
      } else {
        # standard deviation + confidence interval configuration
        filename = file.path(outputdir, paste(model, "_sd_n_ci95_", readout, ".png", sep=""))
        # plot the C.I.
        g <- g + geom_errorbar(aes(ymin=b-d, ymax=b+d), colour="lightblue", size=1.0, width=0.1)	
      }

      # plot the line
      g <- g + geom_line(aes(x=a, y=b), color="black", size=1.0)    

      # decorate
      g <- g + xlab(xaxis_label) + ylab(paste(readout, " level [a.u.]", sep="")) + theme(legend.position = "none")
      ggsave(filename, dpi=300,  width=8, height=6)#, bg = "transparent")
   }
}


# Plot model readouts with statistics for each time point.
#
# :param inputdir: the input directory containing the time course files
# :param outputdir: the output directory
# :param model: the model name
# :param files: the array of time course file names
# :param outputfile: the name of the file to store the statistics
# :param xaxis_label: the xaxis label 
plot_error_bars_plus_statistics <- function(inputdir, outputdir, model, files, outputfile, xaxis_label) {
    
    theme_set(tc_theme(28))  

    # Read time course data sets
    timecourses <- read.table( file.path(inputdir, files[1]), header=TRUE, na.strings="NA", dec=".", sep="\t" )
    column <- names (timecourses)

    column.names <- c ("Time")
    
    simulate__start <- timecourses$Time[1]
    simulate__end <- timecourses$Time[length(timecourses$Time)] 
    timepoints <- seq(from=simulate__start, to=simulate__end, by=(simulate__end-simulate__start)/(length(timecourses$Time)-1))
      
    time_length <- length(timepoints)
  

    # statistical table (to export)
    statistics <- matrix( nrow=time_length, ncol=(((length(column)-1)*13)+1) )
    statistics[,1] <- timepoints
    colidx <- 2
    linewidth=14
    
    # an empty colum that we need for creating a data.frame of length(timecourses$Time) rows
    na <- c(rep(NA, length(timecourses$Time)))

    for(j in 1:length(column)) {
      if(column[j] != "Time") {
        print(column[j])

        # Extract column[j] for each file.
        dataset <- data.frame(na)
        for(i in 1:length(files)) {
            dataset <- data.frame(dataset, read.table(file.path(inputdir,files[i]),header=TRUE,na.strings="NA",dec=".",sep="\t")[,j])
        }
        # remove the first column (na)
        dataset <- subset(dataset, select=-c(na))
        
        #print(dataset)
        # structures
        data <-list("mean"=c(),"sd"=c(),"var"=c(),"skew"=c(),"kurt"=c(),"ci95"=c(),
                "coeffvar"=c(),"min"=c(),"stquantile"=c(),"median"=c(),"rdquantile"=c(),"max"=c())
        k <- 1
        # for each computed timepoint
        for( l in 1:length ( timecourses$Time ) ) {

            timepoint.values <- c ( )

            if ( k <= length( timepoints ) && as.character(timepoints[k]) == as.character(timecourses$Time[l]) ) {
                #print(timepoints[k])
                # for each Sample
                for(m in 1:length(files)) {
                    timepoint.values <- c(timepoint.values, dataset[l,m])  
                }
                timepoint <- compute_descriptive_statistics(timepoint.values, length(files))
                # put data in lists
                data$mean <- c ( data$mean, timepoint$mean )
                data$sd <- c ( data$sd, timepoint$sd )
                data$var <- c ( data$var, timepoint$var )
                data$skew <- c ( data$skew, timepoint$skew )
                data$kurt <- c ( data$kurt, timepoint$kurt )
                data$ci95 <- c ( data$ci95, timepoint$ci95 )
                data$coeffvar <- c ( data$coeffvar, timepoint$coeffvar )
                data$min <- c ( data$min, timepoint$min )
                data$stquantile <- c ( data$stquantile, timepoint$stquantile )
                data$median <- c ( data$median, timepoint$median )
                data$rdquantile <- c ( data$rdquantile, timepoint$rdquantile )
                data$max <- c ( data$max, timepoint$max )
                
                #print(data)
                k <- k + 1
            }
        }
        column.names <- get_column_names_statistics(column.names, column[j])
        statistics <- get_statistics_table(statistics, data, colidx)
        colidx <- colidx+13
        plot_error_bars(outputdir, model, column[j], data, timepoints, xaxis_label, "none")
        plot_error_bars(outputdir, model, column[j], data, timepoints, xaxis_label, "sd")  
        plot_error_bars(outputdir, model, column[j], data, timepoints, xaxis_label, "sd_n_ci95")  	
      }
    }
    #print (statistics)
    write.table(statistics, outputfile, sep="\t", col.names = column.names, row.names = FALSE) 
}


#' Import data from Wildlife Computers ".tab" text files
#' 
#' @param x filename to be imported or a TDR dataset to be formated.
#' @param dt if TRUE function will return a data.table object, else, a data.frame.
#' @param ... Arguments to be passed to \code{\link{file}} such as \code{encoding}.
#' @details Wildlife Computers > Instrument helper > Save instrument readings > R format
#' @export
#' @keywords raw_processing
#' @import sqldf data.table
read.wcih <- function(x, dt = TRUE, ...) {
  stopifnot(require("data.table"))
  stopifnot(require("sqldf"))
  if (is.character(x)) {
    f <- file(x, ...)
    nms <- unlist(read.table(x, skip = 3, as.is = TRUE, nrows = 1))
    fmt <- list(skip = 4, header = FALSE, row.names = FALSE, sep = " ")
    x <- sqldf("select * from f", dbname = tempfile(), file.format = fmt)[ , -1]
  } else {
    nms <- names(x)
  }
  
  new_nms <- c(
    "Time" = "time", "Depth" = "depth", 
    "External Temperature" = "temp", "Light Level" = "light", 
    "int aX" = "ax", "int aY" = "ay", "int aZ" = "az", 
    "int mX" = "mx", "int mY" = "my", "int mZ" = "mz", 
    "Velocity" = "spd", "Internal Temperature" = "itemp"
  )
  
  x <- setnames(as.data.table(x), new_nms[nms])
  x <- x[ , lapply(.SD, as.numeric)]
  x <- x[ , time := as.POSIXct(floor(time), origin = "1970-01-01", tz = 'UTC')]
  
  x <- if (dt) 
    data.table(x, key = "time")
  else 
    as.data.frame(x)
}

#' Identify Prey Catch attempts
#' 
#' @param x 3 axes acceleration table with time in the first column and acceleration 
#' axes in the following columns. Variables must be entitled "time" for time, 
#' "ax", "ay", and "az" for x, y and z accelerometer axes.
#' @param fs sampling frequency of the input data (Hz).
#' @param fc Cut-off frequency for the butterworth high pass filter (Hz)
#' @return returns a logical vector of prey catch attempts at 1 Hz frequency. 
#' Value is TRUE if the record belong to prey catch attempt FALSE otherwise.
#' @import data.table signal RcppRoll
#' @export
#' @keywords raw_processing
prey_catch_attempts <- function(x, fs = 16, fc = 2.64) {
  stopifnot(require("data.table"))
  stopifnot(require("signal"))
  stopifnot(require("RcppRoll"))
  # Generate Butterworth filter 
  # Critical frequencies of the filter: f_cutoff / (f_sampling/2)
  bf_pca <- signal::butter(3, W = fc / (0.5*fs), type = 'high')
  
  # Apply filter
  if (!is.data.table(x)) x <- data.table(x, key = "time")
  .f <- function(x) as.numeric(signal::filtfilt(bf_pca, x))
  x <- x[ , 2:4 := lapply(.SD, .f), .SDcols = 2:4]
  gc()
  
  # 1 s fixed window standard deviation + aggregate data to 1 Hz
  x <- x[ , lapply(.SD, sd, na.rm = TRUE), by = time]
  # In case of NAs set ACC to zero
  nas <- lapply(x[ , 2:4, with = FALSE], is.na)
  nas_vector <- Reduce("|", nas)
  if (any(nas_vector)) {
    warning("NAs found and replaced by 0. NA proportion:", mean(nas_vector))
    x$ax[nas$ax] <- 0
    x$ay[nas$ay] <- 0
    x$az[nas$az] <- 0
  }
  gc()
  
  # 5 s moving window standard deviation
  .f <- function(x) c(0,0,roll_sd(x, 5),0,0)
  x <- x[ , 2:4 := lapply(.SD, .f), .SDcols = 2:4]
  gc()
  
  # kmean clutering: "high" = TRUE vs "low" = FALSE
  .f <- function(x) { 
    km_mod <- kmeans(x, 2)
    high_state <- which.max(km_mod$centers)
    as.logical(km_mod$cluster == high_state)
  }
  x <- x[ , 2:4 := lapply(.SD, .f), .SDcols = 2:4]
  
  # Aggregate and return to data.frame
  # records classified as PCA if the three axis are simultaneously in high state
  Reduce("&", x[ , time := NULL])
}

#' Compute swimming effort
#' 
#' @param fc Cut-off frequencies for the butterworth band pass filter (Hz)
#' @inheritParams prey_catch_attempts
#' @param rms Should the root mean square be used (instead of mean of absolute values) 
#' when averaging the acceleration to 1 Hz ?
#' @return returns a vector of swimming effort values at 1 Hz.
#' @details Only Y accelerometer axe is used to compute swimming effort.
#' @import data.table signal
#' @export
#' @keywords raw_processing
swimming_effort <- function(x, fs = 16, fc = c(0.4416, 1.0176), rms = FALSE) {
  stopifnot(require("data.table"))
  stopifnot(require("signal"))
  # Generate a Butterworth filter 
  # Critical frequencies of the filter: f_filter / (f_sampling/2)
  bf_swm <- signal::butter(3, W = fc / (0.5*fs), type = 'pass')
  
  # Apply filter
  if (!is.data.table(x)) x <- data.table(x, key = "time")
  x <- x[ , ay := abs(as.numeric(signal::filtfilt(bf_swm, ay)))]
  x <- x[ , c(2, 4) := NULL, with = FALSE] # remove unused "ax" & "az" columns
  
  # 1 s fixed window average + aggregate data to 1 Hz
  if (!rms) {
    x <- x[ , lapply(.SD, function(x) mean(abs(x), na.rm = TRUE)), by = time]
  } else {
    x <- x[ , lapply(.SD, function(x) sqrt(mean(x^2, na.rm = TRUE))), by = time]
  }
  x <- x$ay
}
globalVariables("ay")

#' Static acceleration
#' 
#' The raw acceleration is first filtered using a low pass butterworth filter. 
#' Then , the extracted signal can be scaled so that the norm of the the vector 
#' G is 1 at each second.
#' 
#' @param fc Cut-off frequency for the butterworth low pass filter (Hz)
#' @param Gscale Should the values be scaled by the norm of the static 
#' acceleration vector ?
#' @param agg_1hz Should the input be aggregated to 1 Hz ?
#' @inheritParams prey_catch_attempts
#' @return returns a data.frame with time, and X, Y and Z static accelearyion at 1 Hz.
#' @details This filtered acceleration can be used to compute pitch and roll angles
#' @import data.table signal
#' @keywords raw_processing
#' @export
static_acc <- function(x, fs = 16, fc = 0.20, Gscale = TRUE, agg_1hz = TRUE) {
  stopifnot(require("data.table"))
  stopifnot(require("signal"))
  # Generate a Butterworth filter 
  # Critical frequencies of the filter: f_filter / (f_sampling/2)
  bf_grav <- signal::butter(3, W = fc / (0.5*fs), type = 'low')
  
  # Apply filter
  if (!is.data.table(x)) x <- data.table(x, key = "time")
  x <- x[ , 2:4 := lapply(.SD, function(x) as.numeric(signal::filtfilt(bf_grav, x))), 
          .SDcols = 2:4]
  
  # 1 s fixed window average + aggregate data to 1 Hz
  if (agg_1hz) {
    x <- x[ , lapply(.SD, mean, na.rm = TRUE), by = time]
  }
  x <- setnames(x, c('time', 'axG', 'ayG', 'azG'))
  
  # Scale axis
  if (Gscale) {
    Gnorm <- sqrt(x$axG^2 + x$ayG^2 + x$azG^2)
    x <- x[ , 2:4 := lapply(.SD, function(x) x / Gnorm), .SDcols = 2:4]
  }
  
  as.data.frame(x)
}

#' Dynamic (Body) acceleration DBA
#' 
#' DBA is calculated by smoothing data for each axis to calculate the static 
#' acceleration (\code{\link{static_acc}}), and then subtracting it from 
#' the raw acceleration.
#' 
#' @param ... Parameters to be passed to \code{\link{static_acc}} (e.g \code{fc}).
#' @inheritParams static_acc
#' @return returns a data.frame with time, and X, Y and Z static accelearyion at 1 Hz.
#' @details This filtered acceleration can be used to compute ODBA and VeDBA.
#' @import data.table signal
#' @export
#' @keywords raw_processing
dynamic_acc <- function(x, fs = 16, agg_1hz = TRUE, ...) {
  static <- static_acc(copy(x), fs = fs, Gscale = FALSE, agg_1hz = FALSE, ...)
  x <- x[ , `:=`(2:4, Map("-", x[ , 2:4, with = FALSE], static[ , 2:4])), with = FALSE]
  rm(list = "static") ; gc()
  if (agg_1hz) {
    x <- x[ , lapply(.SD, mean, na.rm = TRUE), by = time]
  }
  as.data.frame(setnames(x, c("time", "axD", "ayD", "azD")))
}

#' Attitude angles from static accelation
#' 
#' @param object A data frame or TDR table including static acceleration variables 
#' entitled "axG", "ayG", and "azG" for X, Y, and Z axes of the accelerometer.
#' @export
#' @keywords raw_processing
pitch <- function(object) {
  -atan(object$axG/sqrt(object$ayG^2 + object$azG^2))
}

#' @rdname pitch
#' @export
#' @details For roll angle, the x axe is not necessary.
#' @return A vector of pitch/roll of the same length as \code{object}.
#' @keywords raw_processing
roll <- function(object) {
  atan2(object$ayG^2, object$azG)
}

#' Overall Dynamic Body Acceleration (ODBA)
#' 
#' @param object A data frame or TDR table including dynamic acceleration variables 
#' entitled "axD", "ayD", and "azD" for X, Y, and Z axes of the accelerometer.
#' @export
#' @return A vector of ODBA of the same length as \code{object}.
#' @keywords raw_processing
overall_DBA <- function(object) {
  object <- as.data.table(object)
  object <- object[ , tot := abs(axD) + abs(ayD) + abs(azD)]
  object$tot
}

#' Vectorial Dynamic Body Acceleration (VeDBA)
#' 
#' @param object A data frame or TDR table including dynamic acceleration variables 
#' entitled "axD", "ayD", and "azD" for X, Y, and Z axes of the accelerometer.
#' @export
#' @return A vector of VeDBA of the same length as \code{object}.
#' @keywords raw_processing
vectorial_DBA <- function(object) {
  object <- as.data.table(object)
  object <- object[ , tot := sqrt(axD^2 + ayD^2 + azD^2)]
  object$tot
}
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, "", sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        cancel = function(job_ids, user = private$user, host = private$host) {
            job_ids <- paste(job_ids, collapse = ",")

            stain_ssh(user, host, paste("scancel", job_ids))
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host,
                          submit_dir = "~/stain", dependency_list = "") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")

                # Add any dependencies to sbatch command.
                history <- self$submission_history()$job_id
                dependencies <- sbatch_dependency_list(dependency_list, history)

                if (nchar(dependencies) > 0) {
                    dependencies <- sbatch_opt("dependency")(dependencies)
                }

                submit_cmd <- paste("sbatch",
                                    dependencies,
                                    "submit.slurm")
                submit_cmd <- paste("cd", job_dir, "&&", submit_cmd)
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir = "~/stain") {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        submission_history = function() {
            # `stain_sub_history` will warn if submission history is empty.
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                return(history)
            }
        },
        fetch_job_states = function(user = private$user, host = private$host) {
            submission_history <- stain_sub_history(self$dir)
            job_ids <- submission_history$job_id

            verify_state_table <- function(state_table) {
                if (nrow(status_table) > 0) {
                    return(state_table)
                } else {
                    job_ids <- paste(job_ids, collapse = ", ")
                    message(paste("No statuses found for job ids:", job_ids))
                }
            }

            fetch_squeue_table <- function() {
                tryCatch({
                    squeue_table <- stain_ssh_squeue(user, host, job_ids)
                    squeue_table <- squeue_table[, c("JOBID", "STATE")]
                    colnames(squeue_table) <- c("job_id", "state")
                    # Will throw error if data frame has no rows.
                    squeue_table$exit_code <- NA
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    squeue_table <- data.frame()
                }, finally = return(squeue_table))
            }

            fetch_sacct_table <- function() {
                tryCatch({
                    sacct_table <- stain_ssh_sacct(user, host, job_ids)
                    colnames(sacct_table) <- c("job_id", "state", "exit_code")
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    sacct_table <- data.frame()
                }, finally = return(sacct_table))
            }

            squeue_table <- fetch_squeue_table()
            sacct_table <- fetch_sacct_table()
            states <- rbind(squeue_table, sacct_table)
            states <- aggregate(states, list(states$job_id), function(x) {
                na.omit(x)[1]
            })[,-1]

            return(merge(states, submission_history))
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
######################################################################
######################################################################
## ROUTINE ZUM EINLESEN VON ERA-DATEN (ZONAL-WIND) IM NCDF-FORMAT
## UND AUFFINDEN DES JETSTREAMS AUF NORDHEMISPHÄRE
## source('~/Master_Thesis/02-r-code-git/locate_jetstream_polynomial_2d.r')
######################################################################
######################################################################


######################################################################
## AUFRUF WICHTIGER BIBLIOTHEKEN UND PAKETE
######################################################################
##

library(ncdf4)
library(parallel)
library(chron)

# eigenes package für least squares fit mit chebyshev polynomen
# install.packages("pckg.cheb_0.9.tar.gz", repos = NULL, type = "source")
library(pckg.cheb)

setwd("~/Master_Thesis/02-r-code-git/")
path <- "data/"
# path <- "/home/skiefer/era/raw/"
file <- "era-t63-1957-2016.nh-trop-inv.nc"  # Nordhemisphäre + Tropen


######################################################################
## KLEINE HILFSFUNKTIONEN
######################################################################
##

fun.fill <- function(x, n) {
  while (length(x) < n) {
    x <- c(x, NA)
  }
  return(x)
}


######################################################################
## EINLESEN DER DATEN
## ERA40 / ERA-INTERIM
## T63 - GRID - GAUSSIAN
## NORDHEMISPHÄRE & TROPEN
## 192 (lat) * 64 (lon)
######################################################################
##

nc <- nc_open(paste(path, file, sep = ""))
# print(nc)
u.monmean <- ncvar_get(nc, "var131") # U-Wind-Komponente
v.monmean <- ncvar_get(nc, "var132") # V-Wind-Komponente
# w.monmean <- ncvar_get(nc, "var135") # W-Wind-Komponente
# z.monmean <- ncvar_get(nc, "var129") # Geopotenzial
# t.monmean <- ncvar_get(nc, "var130") # Temperatur
# d.monmean <- ncvar_get(nc, "var155") # Divergenz

lon <- ncvar_get(nc, "lon") # Längengrad
lat <- ncvar_get(nc, "lat") # Breitengrad
lev <- ncvar_get(nc, "lev") # Drucklevel
date.help <- ncvar_get(nc, "time")

nc_close(nc)
rm(nc)

uv.monmean <- sqrt( u.monmean ** 2 + v.monmean **2 )

######################################################################
## VARIABLEN UND PARAMETER
######################################################################
##

n.cpu <- 24 # Anzahl der CPUs für parApply
n.order.lat <- 31 # Ordnung des Least-Square-Verfahrens für Fit über Breitengrad
n.order.lon <- 8 # Ordnung des Least-Square-Verfahrens für Fit über Längengrad

## Räumliche Auflösung
n.lat <- length(lat)
n.lon <- length(lon)

## Zeitliche Auflösung
dts = chron(dates. = date.help/24, origin. = c(month = 9,day = 1,year = 1957), format = "day mon year")
dts.month <- months(dts, abbreviate = TRUE)
dts.year <- years(dts)

## Zeitlich gemittelter Zonalwind
# u.mean <- apply(u.monmean,c(1,2),mean)
# u.std <- apply(u.monmean,c(1,2),sd)

## Meridional und zeitlich gemittelter Zonalwind
# u.mon.mer.mean <- apply(u.monmean, 2, mean)
# u.mon.mer.sd <- apply(u.mean, 2, sd)

## Meridional gemittelter Zonalwind
# u.monmean.mermean <- apply(u.monmean, c(2,3), mean)
# u.monmean.mersd <- apply(u.monmean, c(2,3), sd)



######################################################################
## LEAST SQUARES FIT 
## CHEBYSHEV POLYNOME 23-TER ORDNUNG
## AN ZONAL WIND IN MERIDIONALER RICHTUNG
######################################################################
##

# list.model.lat <- apply(u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
list.model.lat <- parApply(cl, u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.roots, x.axis = lat, n = n.order.lat, bc.harmonic = FALSE, roots.bound.l = 20, roots.bound.u = 80)
stopCluster(cl)
dim.list <- dim(list.model.lat)
# 
# ## Chebyshev-Koeffizienten
# cheb.coeff <- sapply(list.model.lat, "[[", 1)
# cheb.coeff <- apply(array(data = cheb.coeff, dim = c((n.order.lat + 1), dim.list[1], dim.list[2])) , c(1,3), t)
# 
# ## Gefiltertes Modell für Zonal-Wind
# model.u <- sapply(list.model.lat, "[[", 2)
# model.u <- apply(array(data = model.u, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Erste Ableitung des gefilterten Modells für Zonalwind
# model.u.deriv.1st <- sapply(list.model.lat, "[[", 3)
# model.u.deriv.1st <- apply(array(data = model.u.deriv.1st, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Extrema des Modells (Positionen und Werte)
# model.extr.lat <- sapply(list.model.lat, "[[", 4)
# model.extr.u <- sapply(list.model.lat, "[[", 5)
# model.extr.lat <- sapply(model.extr.lat, fun.fill, n = 24)
# model.extr.lat <- apply(array(model.extr.lat, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# model.extr.u <- sapply(model.extr.u, fun.fill, n = 24)
# model.extr.u <- apply(array(model.extr.u, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# 
# ## Maxima des Modells (Positionen und Werte)
# model.max.u <- apply(model.extr.u, c(1,3), max, na.rm = TRUE)
# model.max.lat <- array(rep(0, 192*664), c(dim.list))
# for (i in 1:dim.list[2]) {
#   for (j in 1:dim.list[1]) {
#     model.max.lat[j,i] <- model.extr.lat[j, which(model.extr.u[j,,i] == model.max.u[j,i]), i]
#   }
# }
# rm(list.model.lat, dim.list)
# 
# 
# ######################################################################
# ## LEAST SQUARES FIT 
# ## CHEBYSHEV POLYNOME 8-TER ORDNUNG
# ## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
# ######################################################################
# ##
# 
# #list.model.lon <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
# cl <- makeCluster(getOption("cl.cores", n.cpu))
# list.model.lon <- parApply(cl, model.max.lat, 2, pckg.cheb:::cheb.fit.roots, x.axis = lon, n = n.order.lon, bc.harmonic = TRUE)
# stopCluster(cl)
# 
# ## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
# #model.max.lon <- list.model.lon, "[[", 2)
# #rm(list.model.lon)
# 
# 
# ######################################################################
# ## FEHLERGRÖẞEN
# ## MSE
# ## RMSE
# ######################################################################
# ##
# 
# residuals.cheb <- u.monmean - model.u
# #residuals.cheb.seq <- u.monmean - model.u.seq
# mse <- sum(residuals.cheb ** 2) / length(residuals.cheb)
# #mse.seq <- sum(residuals.cheb.seq **2) / length(residuals.cheb.seq)
# rmse <- sqrt(sum(residuals.cheb ** 2) / length(residuals.cheb))
# #rmse.seq <- sqrt(sum(residuals.cheb.seq **2) / length(residuals.cheb.seq))
# 
# ## rmse.seq = 0.4079846  ## mse.seq = 0.1664514
# ## rmse     = 0.2911683  ## mse     = 0.08477901


######################################################################
######################################################################
save.image(file = ".RData")



######################################################################
## Berechnung von Mean und Sd
## über fünf Jahre & saisonal
######################################################################
# dts.year.mn <- seq(1960, 2010, 5)
# 
# ind.mam <- which(dts.month == "Mar" | dts.month == "Apr" | dts.month == "May")
# ind.jja <- which(dts.month == "Jun" | dts.month == "Jul" | dts.month == "Aug")
# ind.son <- which(dts.month == "Sep" | dts.month == "Oct" | dts.month == "Nov")
# ind.djf <- which(dts.month == "Dec" | dts.month == "Jan" | dts.month == "Feb")
# 
# ## Mittelwerte global
# u.seas.mam.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.mam.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.jja.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.jja.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.son.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.son.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.djf.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.djf.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# 
# ## Mittelwerte meridional *???*
# u.mer.seas.mam.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.mam.sd <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.jja.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.jja.sd <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.son.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.son.sd <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.djf.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.djf.sd <- array( NA , dim = c(n.lat, 11))
# 
# for (i in seq(1, 11)) {
#   print(i)
#   yr.i <- dts.year.mn[i]
#   ind.yr <- which(dts.year ==  yr.i | dts.year == (yr.i + 1) | dts.year == (yr.i + 2) | dts.year == (yr.i + 3) | dts.year == (yr.i + 4) )
#   ## Mar Apr May
#   ind.mam.yr <- intersect(ind.yr, ind.mam)
#   u.seas.mam.mean[,,i] <- apply(u.monmean[,, ind.mam.yr], c(1,2), mean)
#   u.seas.mam.sd[,,i] <- apply(u.monmean[,, ind.mam.yr], c(1,2), sd)
#   u.mer.seas.mam.mean[,i] <- apply(u.monmean[,, ind.mam.yr], 2, mean)
#   u.mer.seas.mam.sd[,i] <- apply(u.monmean[,, ind.mam.yr], 2, sd)
#   ## Jun Jul Aug
#   ind.jja.yr <- intersect(ind.yr, ind.jja)
#   u.seas.jja.mean[,,i] <- apply(u.monmean[,, ind.jja.yr], c(1,2), mean)
#   u.seas.jja.sd[,,i] <- apply(u.monmean[,, ind.jja.yr], c(1,2), sd)
#   u.mer.seas.jja.mean[,i] <- apply(u.monmean[,, ind.jja.yr], 2, mean)
#   u.mer.seas.jja.sd[,i] <- apply(u.monmean[,, ind.jja.yr], 2, sd)
#   ## Sep Oct Nov
#   ind.son.yr <- intersect(ind.yr, ind.son)
#   u.seas.son.mean[,,i] <- apply(u.monmean[,, ind.son.yr], c(1,2), mean)
#   u.seas.son.sd[,,i] <- apply(u.monmean[,, ind.son.yr], c(1,2), sd)
#   u.mer.seas.son.mean[,i] <- apply(u.monmean[,, ind.son.yr], 2, mean)
#   u.mer.seas.son.sd[,i] <- apply(u.monmean[,, ind.son.yr], 2, sd)
#   ## Dec Jan Feb
#   ind.djf.yr <- intersect(ind.yr, ind.djf)
#   u.seas.djf.mean[,,i] <- apply(u.monmean[,, ind.djf.yr], c(1,2), mean)
#   u.seas.djf.sd[,,i] <- apply(u.monmean[,, ind.djf.yr], c(1,2), sd)
#   u.mer.seas.djf.mean[,i] <- apply(u.monmean[,, ind.djf.yr], 2, mean)
#   u.mer.seas.djf.sd[,i] <- apply(u.monmean[,, ind.djf.yr], 2, sd)
#   ## Löschen von Übergangsvariablen
#   rm(yr.i, ind.yr, ind.mam.yr, ind.jja.yr, ind.son.yr, ind.djf.yr, i)
# }
# 
# max(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
# min(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
# range(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
# 
# max(u.seas.mam.mean)
# min(u.seas.mam.mean)
# range(u.seas.mam.mean)
# 
# max(u.seas.jja.mean)
# min(u.seas.jja.mean)
# range(u.seas.jja.mean)
# 
# max(u.seas.son.mean)
# min(u.seas.son.mean)
# range(u.seas.son.mean)
# 
# max(u.seas.djf.mean)
# min(u.seas.djf.mean)
# range(u.seas.djf.mean)
# 
# 
# image.plot(lon, lat, u.mean+u.std)
# contour(lon, lat, u.std[,,1], add=TRUE)
# addland(col= "grey50", lwd = 1)
# 
# cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
# list.lat.m.sd <- parApply(cl, (u.mean[,] - u.std[,]), 1, pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
# list.lat.mn <- parApply(cl, u.mean[,], 1, pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
# list.lat.p.sd <- parApply(cl, (u.mean[,] + u.std[,]), 1, pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
# stopCluster(cl)
# 
# model.extr.lat.m.sd <- sapply(list.lat.m.sd, "[[", 4)
# model.extr.lat.mn <- sapply(list.lat.mn, "[[", 4)
# model.extr.lat.p.sd <- sapply(list.lat.m.sd, "[[", 4)
# 
# model.extr.u.m.sd <- sapply(list.lat.m.sd, "[[", 5)
# model.extr.u.mn <- sapply(list.lat.mn, "[[", 5)
# model.extr.u.p.sd <- sapply(list.lat.p.sd, "[[", 5)
# 
# model.extr.lat.m.sd <- sapply(model.extr.lat.m.sd, fun.fill, n = 16)
# model.extr.lat.mn <- sapply(model.extr.lat.mn, fun.fill, n = 16)
# model.extr.lat.p.sd <- sapply(model.extr.lat.p.sd, fun.fill, n = 16)
# 
# model.extr.u.m.sd <- sapply(model.extr.u.m.sd, fun.fill, n = 16)
# model.extr.u.mn <- sapply(model.extr.u.mn, fun.fill, n = 16)
# model.extr.u.p.sd <- sapply(model.extr.u.p.sd, fun.fill, n = 16)
# 
# model.max.u.m.sd <- apply(model.extr.u.m.sd, 2, max, na.rm = TRUE)
# model.max.u.mn <- apply(model.extr.u.mn, 2, max, na.rm = TRUE)
# model.max.u.p.sd <- apply(model.extr.u.p.sd, 2, max, na.rm = TRUE)
# 
# model.max.lat.m.sd <- array(rep(0, 192))
# model.max.lat.mn <- array(rep(0, 192))
# model.max.lat.p.sd <- array(rep(0, 192))
# 
# for (i in 1:192) {
#   model.max.lat.m.sd[i] <- model.extr.lat.m.sd[which(model.extr.u.m.sd[,i] == model.max.u.m.sd[i]), i]
#   model.max.lat.mn[i] <- model.extr.lat.mn[which(model.extr.u.mn[,i] == model.max.u.mn[i]), i]
#   model.max.lat.p.sd[i] <- model.extr.lat.p.sd[which(model.extr.u.p.sd[,i] == model.max.u.p.sd[i]), i]
# }
# 
# list.lon.m.sd <- pckg.cheb:::cheb.fit(d = model.max.lat.m.sd, x.axis = lon, n = 11)
# list.lon.mn <- pckg.cheb:::cheb.fit(d = model.max.lat.mn, x.axis = lon, n = 11)
# list.lon.p.sd <- pckg.cheb:::cheb.fit(d = model.max.lat.p.sd, x.axis = lon, n = 11)
# 
# model.max.lon.m.sd <- list.lon.m.sd[[2]]
# model.max.lon.mn <- list.lon.mn[[2]]
# model.max.lon.p.sd <- list.lon.p.sd[[2]]
# 
# 
# lines(lon, model.max.lon.m.sd)
# lines(lon, model.max.lon.mn)
# lines(lon, model.max.lon.p.sd)




####################################################################################################
########## ableitung des drehimpulses ##############################################################
########## aus zonal wind ##########################################################################
####################################################################################################
### ref: m = 
### formel noch inkorrekt
### keine schleife benutzen
##
# m <- matrix(NA,n.lon,n.lat)
# for (i in 1:n.lon){
#   for (j in 1:n.lat){
#     m[i,j] <- u.era.t63.monmean[i,j,1]*cos(lat.era.t63[j]) + 1/86400*u.era.t63.monmean[i,j,1]**2*cos(lat.era.t63[j])**2
#   }
# }
# #m <- u.era.t63.monmean*cos(lat.era.t63)
# 




# ######################################################################
# ## LEAST SQUARES FIT ÜBER **SEQUENZEN** (l=8)
# ## CHEBYSHEV POLYNOME 3-TER ORDNUNG
# ## AN ZONAL-WIND IN MERIDIONALER RICHTUNG
# ######################################################################
# ##
# 
# # list.model.lat.seq <- apply(u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
# list.model.lat.seq <- parApply(cl, u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# stopCluster(cl)
# dim.list <- dim(list.model.lat.seq)
# 
# ## Gefiltertes Modell für Zonal-Wind
# model.u.seq <- sapply(list.model.lat.seq, "[[", 1)
# model.u.seq <- apply(array(data = model.u.seq, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Erste Ableitung des gefilterten Modells für Zonalwind
# model.u.deriv.1st.seq <- sapply(list.model.lat.seq, "[[", 2)
# model.u.deriv.1st.seq <- apply(array(data = model.u.deriv.1st.seq, dim = c(n.lon, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Extrema des Modells (Positionen und Werte)
# model.extr.lat.seq <- sapply(list.model.lat.seq, "[[", 3)
# model.extr.lat.seq <- sapply(model.extr.lat.seq, fun.fill, n = 24)
# model.extr.lat.seq <- apply(array(model.extr.lat.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# model.extr.u.seq <- sapply(list.model.lat.seq, "[[", 4)
# model.extr.u.seq <- sapply(model.extr.u.seq, fun.fill, n = 24)
# model.extr.u.seq <- apply(array(model.extr.u.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# 
# ## Maxima des Modells (Positionen und Werte)
# model.max.u.seq <- apply(model.extr.u.seq, c(1,3), max, na.rm = TRUE)
# model.max.lat.seq <- array(rep(0, dim.list[1]*dim.list[2]), c(dim.list))
# for (i in 1:dim.list[2]) {
#   for (j in 1:dim.list[1]) {
#     model.max.lat.seq[j,i] <- model.extr.lat.seq[j, which(model.extr.u.seq[j,,i] == model.max.u.seq[j,i]), i]
#   }
# }
# rm(list.model.lat.seq, dim.list)
# 
# 
# ######################################################################
# ## LEAST SQUARES FIT 
# ## CHEBYSHEV POLYNOME 8-TER ORDNUNG
# ## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
# ## ANGEWANDT AUF SEQUENZIERTES MODELL
# ######################################################################
# ##
# 
# #list.model.lon.seq <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = 8)
# cl <- makeCluster(getOption("cl.cores", n.cpu))
# list.model.lon.seq <- parApply(cl, model.max.lat.seq, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
# stopCluster(cl)
# 
# ## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
# model.max.lon.seq <- sapply(list.model.lon.seq, "[[", 2)
# rm(list.model.lon.seq)

######################################################################
######################################################################
## ROUTINE ZUM EINLESEN VON ERA-DATEN (ZONAL-WIND) IM NCDF-FORMAT
## UND AUFFINDEN DES JETSTREAMS AUF NORDHEMISPHÄRE
## source('~/Master_Thesis/02-r-code-git/locate_jetstream_polynomial_2d.r')
######################################################################
######################################################################


######################################################################
## AUFRUF WICHTIGER BIBLIOTHEKEN UND PAKETE
######################################################################
##

library(ncdf4)
library(parallel)
library(chron)

# eigenes package für least squares fit mit chebyshev polynomen
# install.packages("pckg.cheb_0.9.tar.gz", repos = NULL, type = "source")
library(pckg.cheb)

setwd("~/Master_Thesis/02-r-code-git/")
path <- "data/"
# path <- "/home/skiefer/era/raw/"
file <- "era-t63-1957-2016.nh-trop-inv.nc"  # Nordhemisphäre + Tropen


######################################################################
## KLEINE HILFSFUNKTIONEN
######################################################################
##

fun.fill <- function(x, n) {
  while (length(x) < n) {
    x <- c(x, NA)
  }
  return(x)
}


######################################################################
## EINLESEN DER DATEN
## ERA40 / ERA-INTERIM
## T63 - GRID - GAUSSIAN
## NORDHEMISPHÄRE & TROPEN
## 192 (lat) * 64 (lon)
######################################################################
##

nc <- nc_open(paste(path, file, sep = ""))
# print(nc)
u.monmean <- ncvar_get(nc, "var131") # U-Wind-Komponente
v.monmean <- ncvar_get(nc, "var132") # V-Wind-Komponente
# w.monmean <- ncvar_get(nc, "var135") # W-Wind-Komponente
# z.monmean <- ncvar_get(nc, "var129") # Geopotenzial
# t.monmean <- ncvar_get(nc, "var130") # Temperatur
# d.monmean <- ncvar_get(nc, "var155") # Divergenz

lon <- ncvar_get(nc, "lon") # Längengrad
lat <- ncvar_get(nc, "lat") # Breitengrad
lev <- ncvar_get(nc, "lev") # Drucklevel
date.help <- ncvar_get(nc, "time")

nc_close(nc)
rm(nc)

uv.monmean <- sqrt( u.monmean ** 2 + v.monmean **2 )

######################################################################
## VARIABLEN UND PARAMETER
######################################################################
##

n.cpu <- 24 # Anzahl der CPUs für parApply
n.order.lat <- 31 # Ordnung des Least-Square-Verfahrens für Fit über Breitengrad
n.order.lon <- 8 # Ordnung des Least-Square-Verfahrens für Fit über Längengrad

## Räumliche Auflösung
n.lat <- length(lat)
n.lon <- length(lon)

## Zeitliche Auflösung
dts = chron(dates. = date.help/24, origin. = c(month = 9,day = 1,year = 1957), format = "day mon year")
dts.month <- months(dts, abbreviate = TRUE)
dts.year <- years(dts)

## Zeitlich gemittelter Zonalwind
# u.mean <- apply(u.monmean,c(1,2),mean)
# u.std <- apply(u.monmean,c(1,2),sd)

## Meridional und zeitlich gemittelter Zonalwind
# u.mon.mer.mean <- apply(u.monmean, 2, mean)
# u.mon.mer.sd <- apply(u.mean, 2, sd)

## Meridional gemittelter Zonalwind
# u.monmean.mermean <- apply(u.monmean, c(2,3), mean)
# u.monmean.mersd <- apply(u.monmean, c(2,3), sd)



######################################################################
## LEAST SQUARES FIT 
## CHEBYSHEV POLYNOME 23-TER ORDNUNG
## AN ZONAL WIND IN MERIDIONALER RICHTUNG
######################################################################
##

# list.model.lat <- apply(u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
list.model.lat <- parApply(cl, u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.roots, x.axis = lat, n = n.order.lat, bc.harmonic = FALSE, roots.bound.l = 20, roots.bound.u = 80)
stopCluster(cl)
dim.list <- dim(list.model.lat)

## Chebyshev-Koeffizienten
cheb.coeff <- sapply(list.model.lat, "[[", 1)
cheb.coeff <- apply(array(data = cheb.coeff, dim = c((n.order.lat + 1), dim.list[1], dim.list[2])) , c(1,3), t)

## Gefiltertes Modell für Zonal-Wind
model.u <- sapply(list.model.lat, "[[", 2)
model.u <- apply(array(data = model.u, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)

## Erste Ableitung des gefilterten Modells für Zonalwind
model.u.deriv.1st <- sapply(list.model.lat, "[[", 3)
model.u.deriv.1st <- apply(array(data = model.u.deriv.1st, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)

## Extrema des Modells (Positionen und Werte)
model.extr.lat <- sapply(list.model.lat, "[[", 4)
model.extr.u <- sapply(list.model.lat, "[[", 5)
model.extr.lat <- sapply(model.extr.lat, fun.fill, n = 24)
model.extr.lat <- apply(array(model.extr.lat, c(24, dim.list[1], dim.list[2])), c(1,3), t)
model.extr.u <- sapply(model.extr.u, fun.fill, n = 24)
model.extr.u <- apply(array(model.extr.u, c(24, dim.list[1], dim.list[2])), c(1,3), t)

## Maxima des Modells (Positionen und Werte)
model.max.u <- apply(model.extr.u, c(1,3), max, na.rm = TRUE)
model.max.lat <- array(rep(0, 192*664), c(dim.list))
for (i in 1:dim.list[2]) {
  for (j in 1:dim.list[1]) {
    model.max.lat[j,i] <- model.extr.lat[j, which(model.extr.u[j,,i] == model.max.u[j,i]), i]
  }
}
rm(list.model.lat, dim.list)


######################################################################
## LEAST SQUARES FIT 
## CHEBYSHEV POLYNOME 8-TER ORDNUNG
## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
######################################################################
##

#list.model.lon <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
cl <- makeCluster(getOption("cl.cores", n.cpu))
list.model.lon <- parApply(cl, model.max.lat, 2, pckg.cheb:::cheb.fit.roots, x.axis = lon, n = n.order.lon, bc.harmonic = TRUE)
stopCluster(cl)

## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
#model.max.lon <- list.model.lon, "[[", 2)
#rm(list.model.lon)


######################################################################
## FEHLERGRÖẞEN
## MSE
## RMSE
######################################################################
##

residuals.cheb <- u.monmean - model.u
#residuals.cheb.seq <- u.monmean - model.u.seq
mse <- sum(residuals.cheb ** 2) / length(residuals.cheb)
#mse.seq <- sum(residuals.cheb.seq **2) / length(residuals.cheb.seq)
rmse <- sqrt(sum(residuals.cheb ** 2) / length(residuals.cheb))
#rmse.seq <- sqrt(sum(residuals.cheb.seq **2) / length(residuals.cheb.seq))

## rmse.seq = 0.4079846  ## mse.seq = 0.1664514
## rmse     = 0.2911683  ## mse     = 0.08477901


######################################################################
######################################################################
save.image()



######################################################################
## Berechnung von Mean und Sd
## über fünf Jahre & saisonal
######################################################################
# dts.year.mn <- seq(1960, 2010, 5)
# 
# ind.mam <- which(dts.month == "Mar" | dts.month == "Apr" | dts.month == "May")
# ind.jja <- which(dts.month == "Jun" | dts.month == "Jul" | dts.month == "Aug")
# ind.son <- which(dts.month == "Sep" | dts.month == "Oct" | dts.month == "Nov")
# ind.djf <- which(dts.month == "Dec" | dts.month == "Jan" | dts.month == "Feb")
# 
# ## Mittelwerte global
# u.seas.mam.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.mam.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.jja.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.jja.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.son.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.son.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.djf.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.djf.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# 
# ## Mittelwerte meridional *???*
# u.mer.seas.mam.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.mam.sd <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.jja.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.jja.sd <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.son.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.son.sd <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.djf.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.djf.sd <- array( NA , dim = c(n.lat, 11))
# 
# for (i in seq(1, 11)) {
#   print(i)
#   yr.i <- dts.year.mn[i]
#   ind.yr <- which(dts.year ==  yr.i | dts.year == (yr.i + 1) | dts.year == (yr.i + 2) | dts.year == (yr.i + 3) | dts.year == (yr.i + 4) )
#   ## Mar Apr May
#   ind.mam.yr <- intersect(ind.yr, ind.mam)
#   u.seas.mam.mean[,,i] <- apply(u.monmean[,, ind.mam.yr], c(1,2), mean)
#   u.seas.mam.sd[,,i] <- apply(u.monmean[,, ind.mam.yr], c(1,2), sd)
#   u.mer.seas.mam.mean[,i] <- apply(u.monmean[,, ind.mam.yr], 2, mean)
#   u.mer.seas.mam.sd[,i] <- apply(u.monmean[,, ind.mam.yr], 2, sd)
#   ## Jun Jul Aug
#   ind.jja.yr <- intersect(ind.yr, ind.jja)
#   u.seas.jja.mean[,,i] <- apply(u.monmean[,, ind.jja.yr], c(1,2), mean)
#   u.seas.jja.sd[,,i] <- apply(u.monmean[,, ind.jja.yr], c(1,2), sd)
#   u.mer.seas.jja.mean[,i] <- apply(u.monmean[,, ind.jja.yr], 2, mean)
#   u.mer.seas.jja.sd[,i] <- apply(u.monmean[,, ind.jja.yr], 2, sd)
#   ## Sep Oct Nov
#   ind.son.yr <- intersect(ind.yr, ind.son)
#   u.seas.son.mean[,,i] <- apply(u.monmean[,, ind.son.yr], c(1,2), mean)
#   u.seas.son.sd[,,i] <- apply(u.monmean[,, ind.son.yr], c(1,2), sd)
#   u.mer.seas.son.mean[,i] <- apply(u.monmean[,, ind.son.yr], 2, mean)
#   u.mer.seas.son.sd[,i] <- apply(u.monmean[,, ind.son.yr], 2, sd)
#   ## Dec Jan Feb
#   ind.djf.yr <- intersect(ind.yr, ind.djf)
#   u.seas.djf.mean[,,i] <- apply(u.monmean[,, ind.djf.yr], c(1,2), mean)
#   u.seas.djf.sd[,,i] <- apply(u.monmean[,, ind.djf.yr], c(1,2), sd)
#   u.mer.seas.djf.mean[,i] <- apply(u.monmean[,, ind.djf.yr], 2, mean)
#   u.mer.seas.djf.sd[,i] <- apply(u.monmean[,, ind.djf.yr], 2, sd)
#   ## Löschen von Übergangsvariablen
#   rm(yr.i, ind.yr, ind.mam.yr, ind.jja.yr, ind.son.yr, ind.djf.yr, i)
# }
# 
# max(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
# min(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
# range(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
# 
# max(u.seas.mam.mean)
# min(u.seas.mam.mean)
# range(u.seas.mam.mean)
# 
# max(u.seas.jja.mean)
# min(u.seas.jja.mean)
# range(u.seas.jja.mean)
# 
# max(u.seas.son.mean)
# min(u.seas.son.mean)
# range(u.seas.son.mean)
# 
# max(u.seas.djf.mean)
# min(u.seas.djf.mean)
# range(u.seas.djf.mean)
# 
# 
# image.plot(lon, lat, u.mean+u.std)
# contour(lon, lat, u.std[,,1], add=TRUE)
# addland(col= "grey50", lwd = 1)
# 
# cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
# list.lat.m.sd <- parApply(cl, (u.mean[,] - u.std[,]), 1, pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
# list.lat.mn <- parApply(cl, u.mean[,], 1, pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
# list.lat.p.sd <- parApply(cl, (u.mean[,] + u.std[,]), 1, pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
# stopCluster(cl)
# 
# model.extr.lat.m.sd <- sapply(list.lat.m.sd, "[[", 4)
# model.extr.lat.mn <- sapply(list.lat.mn, "[[", 4)
# model.extr.lat.p.sd <- sapply(list.lat.m.sd, "[[", 4)
# 
# model.extr.u.m.sd <- sapply(list.lat.m.sd, "[[", 5)
# model.extr.u.mn <- sapply(list.lat.mn, "[[", 5)
# model.extr.u.p.sd <- sapply(list.lat.p.sd, "[[", 5)
# 
# model.extr.lat.m.sd <- sapply(model.extr.lat.m.sd, fun.fill, n = 16)
# model.extr.lat.mn <- sapply(model.extr.lat.mn, fun.fill, n = 16)
# model.extr.lat.p.sd <- sapply(model.extr.lat.p.sd, fun.fill, n = 16)
# 
# model.extr.u.m.sd <- sapply(model.extr.u.m.sd, fun.fill, n = 16)
# model.extr.u.mn <- sapply(model.extr.u.mn, fun.fill, n = 16)
# model.extr.u.p.sd <- sapply(model.extr.u.p.sd, fun.fill, n = 16)
# 
# model.max.u.m.sd <- apply(model.extr.u.m.sd, 2, max, na.rm = TRUE)
# model.max.u.mn <- apply(model.extr.u.mn, 2, max, na.rm = TRUE)
# model.max.u.p.sd <- apply(model.extr.u.p.sd, 2, max, na.rm = TRUE)
# 
# model.max.lat.m.sd <- array(rep(0, 192))
# model.max.lat.mn <- array(rep(0, 192))
# model.max.lat.p.sd <- array(rep(0, 192))
# 
# for (i in 1:192) {
#   model.max.lat.m.sd[i] <- model.extr.lat.m.sd[which(model.extr.u.m.sd[,i] == model.max.u.m.sd[i]), i]
#   model.max.lat.mn[i] <- model.extr.lat.mn[which(model.extr.u.mn[,i] == model.max.u.mn[i]), i]
#   model.max.lat.p.sd[i] <- model.extr.lat.p.sd[which(model.extr.u.p.sd[,i] == model.max.u.p.sd[i]), i]
# }
# 
# list.lon.m.sd <- pckg.cheb:::cheb.fit(d = model.max.lat.m.sd, x.axis = lon, n = 11)
# list.lon.mn <- pckg.cheb:::cheb.fit(d = model.max.lat.mn, x.axis = lon, n = 11)
# list.lon.p.sd <- pckg.cheb:::cheb.fit(d = model.max.lat.p.sd, x.axis = lon, n = 11)
# 
# model.max.lon.m.sd <- list.lon.m.sd[[2]]
# model.max.lon.mn <- list.lon.mn[[2]]
# model.max.lon.p.sd <- list.lon.p.sd[[2]]
# 
# 
# lines(lon, model.max.lon.m.sd)
# lines(lon, model.max.lon.mn)
# lines(lon, model.max.lon.p.sd)




####################################################################################################
########## ableitung des drehimpulses ##############################################################
########## aus zonal wind ##########################################################################
####################################################################################################
### ref: m = 
### formel noch inkorrekt
### keine schleife benutzen
##
# m <- matrix(NA,n.lon,n.lat)
# for (i in 1:n.lon){
#   for (j in 1:n.lat){
#     m[i,j] <- u.era.t63.monmean[i,j,1]*cos(lat.era.t63[j]) + 1/86400*u.era.t63.monmean[i,j,1]**2*cos(lat.era.t63[j])**2
#   }
# }
# #m <- u.era.t63.monmean*cos(lat.era.t63)
# 




# ######################################################################
# ## LEAST SQUARES FIT ÜBER **SEQUENZEN** (l=8)
# ## CHEBYSHEV POLYNOME 3-TER ORDNUNG
# ## AN ZONAL-WIND IN MERIDIONALER RICHTUNG
# ######################################################################
# ##
# 
# # list.model.lat.seq <- apply(u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
# list.model.lat.seq <- parApply(cl, u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# stopCluster(cl)
# dim.list <- dim(list.model.lat.seq)
# 
# ## Gefiltertes Modell für Zonal-Wind
# model.u.seq <- sapply(list.model.lat.seq, "[[", 1)
# model.u.seq <- apply(array(data = model.u.seq, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Erste Ableitung des gefilterten Modells für Zonalwind
# model.u.deriv.1st.seq <- sapply(list.model.lat.seq, "[[", 2)
# model.u.deriv.1st.seq <- apply(array(data = model.u.deriv.1st.seq, dim = c(n.lon, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Extrema des Modells (Positionen und Werte)
# model.extr.lat.seq <- sapply(list.model.lat.seq, "[[", 3)
# model.extr.lat.seq <- sapply(model.extr.lat.seq, fun.fill, n = 24)
# model.extr.lat.seq <- apply(array(model.extr.lat.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# model.extr.u.seq <- sapply(list.model.lat.seq, "[[", 4)
# model.extr.u.seq <- sapply(model.extr.u.seq, fun.fill, n = 24)
# model.extr.u.seq <- apply(array(model.extr.u.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# 
# ## Maxima des Modells (Positionen und Werte)
# model.max.u.seq <- apply(model.extr.u.seq, c(1,3), max, na.rm = TRUE)
# model.max.lat.seq <- array(rep(0, dim.list[1]*dim.list[2]), c(dim.list))
# for (i in 1:dim.list[2]) {
#   for (j in 1:dim.list[1]) {
#     model.max.lat.seq[j,i] <- model.extr.lat.seq[j, which(model.extr.u.seq[j,,i] == model.max.u.seq[j,i]), i]
#   }
# }
# rm(list.model.lat.seq, dim.list)
# 
# 
# ######################################################################
# ## LEAST SQUARES FIT 
# ## CHEBYSHEV POLYNOME 8-TER ORDNUNG
# ## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
# ## ANGEWANDT AUF SEQUENZIERTES MODELL
# ######################################################################
# ##
# 
# #list.model.lon.seq <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = 8)
# cl <- makeCluster(getOption("cl.cores", n.cpu))
# list.model.lon.seq <- parApply(cl, model.max.lat.seq, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
# stopCluster(cl)
# 
# ## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
# model.max.lon.seq <- sapply(list.model.lon.seq, "[[", 2)
# rm(list.model.lon.seq)

## source('~/Master_Thesis/pckg.cheb/R/functions-chebyshev.r')
##
## library(devtools)
## library(roxygen2)
##
## Build and Reload Package:  'Ctrl + Shift + B'
## Check Package:             'Ctrl + Shift + E'
## Test Package:              'Ctrl + Shift + T'


##
#' @title Scaling of X-Axis
#' @param x.axis ursprüngliche beliebige X-Achse (Vektor)
#' @return x.cheb.scaled skalierte X-Achse (Vektor)
#' @description
#' \code{cheb.scale} skaliert beliebige X-Achse auf Achse, die für Polynom-fits verträglich ist.
#' @examples
#' x.axis <- c(0:30)
#' x.cheb.scaled <- cheb.scale(x.axis)
cheb.scale <- function(x.axis, x.val = NA) {#, scale) {
  ## Funktion zur Skalierung von Stützpunkten
  ## von beliebigen Gittern auf [-1, 1]
  ## ##
  if ( is.na(x.val) == TRUE ) {
    x.cheb.scaled <- 2 * (x.axis - min(x.axis)) / (max(x.axis) - min(x.axis)) - 1
    #return(x.cheb.scaled)
  }
  if ( is.na(x.val) == FALSE ) {
    x.cheb.scaled <- 2 * (x.val - min(x.axis)) / (max(x.axis) - min(x.axis)) - 1
  }
  return(x.cheb.scaled)
}


##
#' @title Rescaling of X-Axis
#' @param x.cheb skalierte X-Achse (Skalar oder Vektor)
#' @param x.axis beliebige X-Achse (Vektor)
#' @return x.rescaled reskalierte X-Achse (Skalar oder Sektor)
#' @description
#' cheb.rescale reskaliert die für den Fit erzeugte Achse auf die Ursprüngliche
#' @examples
#' x.rescaled <- cheb.rescale(x.cheb, x.axis)
cheb.rescale <- function(x.cheb, x.axis) {
  ## Funktion zur Reskalierung vom [-1, 1]-Gitter
  ## auf das Ursprungsgitter (in diesem Fall - Lat)
  x.rescaled <- (1/2 * (x.cheb + 1) * (max(x.axis) - min(x.axis))) + x.axis[1]
  return(x.rescaled)
}


##
#' @title Generating Chebyshev Polynomials of first kind
#' @param x.axis beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.t Chebyshev-Polynome Erster Art (Vektor)
#' @description
#' cheb.1st erzeugt Chebyshev Polynome erster Art aus beliebiger X-Achse
#' @examples
#' cheb.t <- cheb.1st(x.axis, n)
cheb.1st <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Erster Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis  ### ###
  m <- n + 1
  # Rekursionsformel Wiki / Bronstein
  cheb.t.0 <- 1;  cheb.t.1 <- x.cheb;
  cheb.t <- cbind(cheb.t.0, cheb.t.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.t.i <- 2 * x.cheb * cheb.t[,(i - 1)] - cheb.t[,(i - 2)]
      cheb.t <- cbind(cheb.t, cheb.t.i)
      rm(cheb.t.i)
    }
  }
  return(cheb.t)
}


##
#' @title Generating Chebyshev Polynomials of second kind
#' @param x.axis beliebigie X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.u Chebyshev-Polynome Zweiter Art (Vektor)
#' @description
#' cheb.2nd erzeugt Chebyshev Polynome zweiter Art aus beliebiger X-Achse
#' @examples
#' cheb.u <- cheb.2nd(x.axis, n)
cheb.2nd <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Zweiter Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis
  m <- n + 1
  cheb.u.0 <- 1; cheb.u.1 <-  2*x.cheb
  cheb.u <- cbind(cheb.u.0, cheb.u.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.u.i <- 2 * x.cheb * cheb.u[,(i - 1)] - cheb.u[,(i - 2)]
      cheb.u <- cbind(cheb.u, cheb.u.i)
      rm(cheb.u.i)
    }
  }
  return(cheb.u)
}


##
#' @title Calculation of Values of the model fit
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model gefiltertes Modell (Skalar oder Vektor)
#' @description
#' cheb.model berechnet aus den Chebyshev-Koeffizienten die Y-Werte
#' @examples
#' cheb.model <- cheb.model.filter(x.axis, cheb.coeff)
cheb.model.filter <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte aus X-Stellen und Cheb-Koeffizienten
  ## ##
  n <- length(cheb.coeff) - 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.model <- cheb.t %*% cheb.coeff
  return(cheb.model)
}


##
#' @title Calculation of the values of the first derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv.1st Erste Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.1st berechnet aus den Chebyshev-Koeffizienten die Werte der ersten Ableitung
#' @examples
#' cheb.model.deriv <- cheb.deriv.1st(x.axis, cheb.coeff)
cheb.deriv.1st <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte der Ableitung des Modells
  ## aus X-Stellen und Chebyshev-Koeffizienten
  ## ##
  if (length(x.axis) != 0) { ### Überprüfen, ob nötig
    n <- length(cheb.coeff) - 1
    m <- n + 1
    cheb.u <- cheb.2nd(x.axis, n)

    # berechnung der ableitung der polynome erster art
    # rekursionsformel 0
    # dT/dx = n * U_(n-1)
    cheb.t.deriv <- if (length(x.axis) == 1) (2:m)*t(cheb.u[,1:n]) else t((2:m)*t(cheb.u[,1:n]))
    cheb.model.deriv.1st <- cheb.t.deriv %*% cheb.coeff[2:m]
    return(cheb.model.deriv.1st)
  }
}


##
#' @title Calculation of the values of the second derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv Zweite Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.2nd berechnet aus den Chebyshev-Koeffizienten die Werte der zweiten Ableitung
#' @examples
#' cheb.model.deriv.2nd <- cheb.deriv.2nd(x.axis, cheb.coeff)
cheb.deriv.2nd <- function(x.axis, cheb.coeff) {
  n <- length(cheb.coeff) - 1
  m <- n + 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.u <- cheb.2nd(x.axis, n)
  x.cheb <- cheb.scale(x.axis)
  cheb.t.deriv.2nd <- t((((1:m) ** 2) + (1:m)) %*% t(1 / (x.cheb ** 2 - 1)) * t(cheb.t - cheb.u))
  cheb.t.deriv.2nd[1,] <- (-1) * ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.t.deriv.2nd[length(x.cheb),] <- ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.model.deriv.2nd <- cheb.t.deriv.2nd %*% cheb.coeff
  return(cheb.model.deriv.2nd)
}


##
#' @title Curve Fitting with Chebyshev Polynomials
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit <- function(d, x.axis, n, bc.harmonic = FALSE){
  # Fallunterscheidung für harmonische Randbedingung
  if (bc.harmonic == FALSE) {
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  } else if (bc.harmonic == TRUE) {
    d <- c(d, d[1])
    x.axis <- c(x.axis, (x.axis[1] + 360))
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  }

  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # löschen des letzten eintrags für den harmonischen fall
  if (bc.harmonic == TRUE) {
    cheb.model <- cheb.model[-(length(cheb.model))]
  }

  # Übergabe der Variablen
  return(cheb.model)
}


##
#' @title Curve Fitting with Chebyshev Polynomials over Sequences
#' @description
#' Fittet ein Chebyshev Polynom beliebiger Ordnung an einen sequenzierten Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.fit.seq(d, x.axis, n, l)
cheb.fit.seq <- function(d, x.axis, n, l, bc.harmonic = FALSE){
  x.mat <- matrix(x.axis, ncol = l, byrow = TRUE)
  d.mat <- matrix(d, ncol = l, byrow = TRUE)
  end.loop <- length(x.mat[,1])

  # schleife über sequenzen des Datensatzes
  for (i in 1:end.loop) {
    # erstellung der sequenzen und fallunterscheidung für harmonische randbedingung
    if (bc.harmonic == FALSE) {
      d.seq <- if (i != end.loop) c(d.mat[i,], d.mat[(i + 1), 1]) else c(d.mat[i,])
      x.seq <- if (i != end.loop) c(x.mat[i,], x.mat[(i + 1), 1]) else c(x.mat[i,])
    } else if (bc.harmonic == TRUE) {
      d.seq <- if (i != end.loop) c(d.mat[i,], d.mat[(i + 1), 1]) else c(d.mat[i,], d.mat[1,1])
      x.seq <- if (i != end.loop) c(x.mat[i,], x.mat[(i + 1), 1]) else c(x.mat[i,], x.mat[1,1] + 360)
    }
    x.cheb.seq <- cheb.scale(x.seq)
    cheb.t.seq <- cheb.1st(x.seq, n)

    ## modell berechnungen
    # berechnung der koeffizienten des polyfits
    cheb.coeff.seq <- solve(t(cheb.t.seq) %*% cheb.t.seq) %*% t(cheb.t.seq) %*% d.seq
    cheb.coeff <- if (i == 1) cheb.coeff.seq else cbind(cheb.coeff, cheb.coeff.seq)
    # berechnung des gefilterten modells
    cheb.model.seq <- cheb.model.filter(x.cheb.seq, cheb.coeff.seq)
    if (bc.harmonic == FALSE) {
      cheb.model <- if (i == 1) cheb.model.seq[-(l + 1)] else if (i > 1 & i != end.loop) c(cheb.model, cheb.model.seq[-(l + 1)]) else c(cheb.model, cheb.model.seq)
    } else if (bc.harmonic == TRUE) {
      cheb.model <- if (i == 1) cheb.model.seq[-(l + 1)] else if (i > 1 & i != end.loop) c(cheb.model, cheb.model.seq[-(l + 1)]) else c(cheb.model, cheb.model.seq[-(l + 1)])
    }
  }

  ## übergabe der variable
  return(cheb.model)
}


##
#' @title Curve Fitting with Chebyshev Polynomials and Finding of its Roots
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit.roots <- function(d, x.axis, n, bc.harmonic = FALSE, roots.bound.l = NA, roots.bound.u = NA){
  library(rootSolve)
  # Fallunterscheidung für harmonische Randbedingung
  if (bc.harmonic == FALSE) {
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  } else if (bc.harmonic == TRUE) {
    d <- c(d, d[1])
    x.axis <- c(x.axis, (x.axis[1] + 360)) ## 360 sinnvoll? besser length() ??
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  }

  #  cheb.u <- cheb.2nd(x.axis, n)
  #  m <- n + 1
  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # berechnung des abgeleiteten modells
  cheb.model.deriv.1st <- cheb.deriv.1st(x.cheb, cheb.coeff)
  # löschen der letzten einträge des modells und der ableitung für den harmonischen fall
  cheb.model <- if (bc.harmonic == TRUE) cheb.model[-(length(cheb.model))]
  cheb.model.deriv.1st <- if (bc.harmonic == TRUE) cheb.model.deriv.1st[-(length(cheb.model.deriv.1st))]

  # berechnung der nullstellen über extremwerte der ableitung
  if (is.na(roots.bound.l) == TRUE) {
    lower <- -1
  } else if (is.na(roots.bound.l) == FALSE) {
    lower <- cheb.scale(x.axis, x.val = roots.bound.l)
  }
  if (is.na(roots.bound.u) == TRUE) {
    upper <- 1
  } else if (is.na(roots.bound.u) == FALSE) {
    upper <- cheb.scale(x.axis, x.val = roots.bound.u)
  }

  extr <- rootSolve::uniroot.all(cheb.deriv.1st, cheb.coeff = cheb.coeff, lower = lower, upper = upper)
  # reskalierung der Nullstellen auf normale Lat- Achse
  x.extr <- if (length(extr) != 0) cheb.rescale(extr, x.axis = x.axis)
  y.extr <- if (length(extr) != 0) cheb.model.filter(x.axis = extr, cheb.coeff = cheb.coeff)

  cheb.list <- list(cheb.coeff = cheb.coeff, cheb.model = cheb.model, cheb.model.deriv.1st = cheb.model.deriv.1st, x.extr = x.extr, y.extr = y.extr)
  return(cheb.list)
}



## source('~/Master_Thesis/pckg.cheb/R/functions-chebyshev.r')
##
## library(devtools)
## library(roxygen2)
##
## Build and Reload Package:  'Ctrl + Shift + B'
## Check Package:             'Ctrl + Shift + E'
## Test Package:              'Ctrl + Shift + T'


##
#' @title Scaling of X-Axis
#' @param x.axis ursprüngliche beliebige X-Achse (Vektor)
#' @return x.cheb.scaled skalierte X-Achse (Vektor)
#' @description
#' \code{cheb.scale} skaliert beliebige X-Achse auf Achse, die für Polynom-fits verträglich ist.
#' @examples
#' x.axis <- c(0:30)
#' x.cheb.scaled <- cheb.scale(x.axis)
cheb.scale <- function(x.axis, x.val = NULL) {#, scale) {
  ## Funktion zur Skalierung von Stützpunkten
  ## von beliebigen Gittern auf [-1, 1]
  ## ##
  x.cheb.scaled <- 2 * (x.axis - min(x.axis)) / (max(x.axis) - min(x.axis)) -1
  if ( x.val == NULL) {
    return(x.cheb.scaled)
  }
  if (x.val != NULL) {
    x.val.scaled <- 2 * (x.val - min(x.axis)) / (max(x.axis) - min(x.axis)) - 1
    return(x.val.scaled)
  }
}


##
#' @title Rescaling of X-Axis
#' @param x.cheb skalierte X-Achse (Skalar oder Vektor)
#' @param x.axis beliebige X-Achse (Vektor)
#' @return x.rescaled reskalierte X-Achse (Skalar oder Sektor)
#' @description
#' cheb.rescale reskaliert die für den Fit erzeugte Achse auf die Ursprüngliche
#' @examples
#' x.rescaled <- cheb.rescale(x.cheb, x.axis)
cheb.rescale <- function(x.cheb, x.axis) {
  ## Funktion zur Reskalierung vom [-1, 1]-Gitter
  ## auf das Ursprungsgitter (in diesem Fall - Lat)
  ## ##
  if (x.cheb >= -1 & x.cheb <= 1) {
    x.rescaled <- (1/2 * (x.cheb + 1) * (max(x.axis) - min(x.axis))) + x.axis[1]
    return(x.rescaled)
  } else
    print("Error: x.cheb went out of boundaries (less -1 or greater 1).")
}


##
#' @title Generating Chebyshev Polynomials of first kind
#' @param x.axis beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.t Chebyshev-Polynome Erster Art (Vektor)
#' @description
#' cheb.1st erzeugt Chebyshev Polynome erster Art aus beliebiger X-Achse
#' @examples
#' cheb.t <- cheb.1st(x.axis, n)
cheb.1st <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Erster Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis  ### ###
  m <- n + 1
  # Rekursionsformel Wiki / Bronstein
  cheb.t.0 <- 1;  cheb.t.1 <- x.cheb;
  cheb.t <- cbind(cheb.t.0, cheb.t.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.t.i <- 2 * x.cheb * cheb.t[,(i - 1)] - cheb.t[,(i - 2)]
      cheb.t <- cbind(cheb.t, cheb.t.i)
      rm(cheb.t.i)
    }
  }
  return(cheb.t)
}


##
#' @title Generating Chebyshev Polynomials of second kind
#' @param x.axis beliebigie X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.u Chebyshev-Polynome Zweiter Art (Vektor)
#' @description
#' cheb.2nd erzeugt Chebyshev Polynome zweiter Art aus beliebiger X-Achse
#' @examples
#' cheb.u <- cheb.2nd(x.axis, n)
cheb.2nd <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Zweiter Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis
  m <- n + 1
  cheb.u.0 <- 1; cheb.u.1 <-  2*x.cheb
  cheb.u <- cbind(cheb.u.0, cheb.u.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.u.i <- 2 * x.cheb * cheb.u[,(i - 1)] - cheb.u[,(i - 2)]
      cheb.u <- cbind(cheb.u, cheb.u.i)
      rm(cheb.u.i)
    }
  }
  return(cheb.u)
}


##
#' @title Calculation of Values of the model fit
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model gefiltertes Modell (Skalar oder Vektor)
#' @description
#' cheb.model berechnet aus den Chebyshev-Koeffizienten die Y-Werte
#' @examples
#' cheb.model <- cheb.model.filter(x.axis, cheb.coeff)
cheb.model.filter <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte aus X-Stellen und Cheb-Koeffizienten
  ## ##
  n <- length(cheb.coeff) - 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.model <- cheb.t %*% cheb.coeff
  return(cheb.model)
}


##
#' @title Calculation of the values of the first derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv.1st Erste Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.1st berechnet aus den Chebyshev-Koeffizienten die Werte der ersten Ableitung
#' @examples
#' cheb.model.deriv <- cheb.deriv.1st(x.axis, cheb.coeff)
cheb.deriv.1st <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte der Ableitung des Modells
  ## aus X-Stellen und Chebyshev-Koeffizienten
  ## ##
  if (length(x.axis) != 0) { ### Überprüfen, ob nötig
    n <- length(cheb.coeff) - 1
    m <- n + 1
    cheb.u <- cheb.2nd(x.axis, n)

    # berechnung der ableitung der polynome erster art
    # rekursionsformel 0
    # dT/dx = n * U_(n-1)
    cheb.t.deriv <- if (length(x.axis) == 1) (2:m)*t(cheb.u[,1:n]) else t((2:m)*t(cheb.u[,1:n]))
    cheb.model.deriv.1st <- cheb.t.deriv %*% cheb.coeff[2:m]
    return(cheb.model.deriv.1st)
  }
}


##
#' @title Calculation of the values of the second derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv Zweite Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.2nd berechnet aus den Chebyshev-Koeffizienten die Werte der zweiten Ableitung
#' @examples
#' cheb.model.deriv.2nd <- cheb.deriv.2nd(x.axis, cheb.coeff)
cheb.deriv.2nd <- function(x.axis, cheb.coeff) {
  n <- length(cheb.coeff) - 1
  m <- n + 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.u <- cheb.2nd(x.axis, n)
  x.cheb <- cheb.scale(x.axis)
  cheb.t.deriv.2nd <- t((((1:m) ** 2) + (1:m)) %*% t(1 / (x.cheb ** 2 - 1)) * t(cheb.t - cheb.u))
  cheb.t.deriv.2nd[1,] <- (-1) * ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.t.deriv.2nd[length(x.cheb),] <- ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.model.deriv.2nd <- cheb.t.deriv.2nd %*% cheb.coeff
  return(cheb.model.deriv.2nd)
}


##
#' @title Curve Fitting with Chebyshev Polynomials
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit <- function(d, x.axis, n, bc.harmonic = FALSE){
  # Fallunterscheidung für harmonische Randbedingung
  if (bc.harmonic == FALSE) {
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  } else if (bc.harmonic == TRUE) {
    d <- c(d, d[1])
    x.axis <- c(x.axis, (x.axis[1] + 360))
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  }

  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # löschen des letzten eintrags für den harmonischen fall
  cheb.model <- if (bc.harmonic == TRUE) cheb.model[-(length(cheb.model))]

  # Übergabe der Variablen
  return(cheb.model)
}


##
#' @title Curve Fitting with Chebyshev Polynomials over Sequences
#' @description
#' Fittet ein Chebyshev Polynom beliebiger Ordnung an einen sequenzierten Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.fit.seq(d, x.axis, n, l)
cheb.fit.seq <- function(d, x.axis, n, l, bc.harmonic = FALSE){
  x.mat <- matrix(x.axis, ncol = l, byrow = TRUE)
  d.mat <- matrix(d, ncol = l, byrow = TRUE)
  end.loop <- length(x.mat[,1])

  # schleife über sequenzen des Datensatzes
  for (i in 1:end.loop) {
    # erstellung der sequenzen und fallunterscheidung für harmonische randbedingung
    if (bc.harmonic == FALSE) {
      d.seq <- if (i != end.loop) c(d.mat[i,], d.mat[(i + 1), 1]) else c(d.mat[i,])
      x.seq <- if (i != end.loop) c(x.mat[i,], x.mat[(i + 1), 1]) else c(x.mat[i,])
    } else if (bc.harmonic == TRUE) {
      d.seq <- if (i != end.loop) c(d.mat[i,], d.mat[(i + 1), 1]) else c(d.mat[i,], d.mat[1,1])
      x.seq <- if (i != end.loop) c(x.mat[i,], x.mat[(i + 1), 1]) else c(x.mat[i,], x.mat[1,1] + 360)
    }
    x.cheb.seq <- cheb.scale(x.seq)
    cheb.t.seq <- cheb.1st(x.seq, n)

    ## modell berechnungen
    # berechnung der koeffizienten des polyfits
    cheb.coeff.seq <- solve(t(cheb.t.seq) %*% cheb.t.seq) %*% t(cheb.t.seq) %*% d.seq
    cheb.coeff <- if (i == 1) cheb.coeff.seq else cbind(cheb.coeff, cheb.coeff.seq)
    # berechnung des gefilterten modells
    cheb.model.seq <- cheb.model.filter(x.cheb.seq, cheb.coeff.seq)
    if (bc.harmonic == FALSE) {
      cheb.model <- if (i == 1) cheb.model.seq[-(l + 1)] else if (i > 1 & i != end.loop) c(cheb.model, cheb.model.seq[-(l + 1)]) else c(cheb.model, cheb.model.seq)
    } else if (bc.harmonic == TRUE) {
      cheb.model <- if (i == 1) cheb.model.seq[-(l + 1)] else if (i > 1 & i != end.loop) c(cheb.model, cheb.model.seq[-(l + 1)]) else c(cheb.model, cheb.model.seq[-(l + 1)])
    }
  }

  ## übergabe der variable
  return(cheb.model)
}


##
#' @title Curve Fitting with Chebyshev Polynomials and Finding of its Roots
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit.roots <- function(d, x.axis, n, bc.harmonic = FALSE, roots.bound.l = NULL, roots.bound.u = NULL){
  library(rootSolve)
  # Fallunterscheidung für harmonische Randbedingung
  if (bc.harmonic == FALSE) {
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  } else if (bc.harmonic == TRUE){
    d <- c(d, d[1])
    x.axis <- c(x.axis, (x.axis[1] + 360))
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  }

  #  cheb.u <- cheb.2nd(x.axis, n)
  #  m <- n + 1
  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # berechnung des abgeleiteten modells
  cheb.model.deriv.1st <- cheb.deriv.1st(x.cheb, cheb.coeff)
  # löschen der letzten einträge des modells und der ableitung für den harmonischen fall
  cheb.model <- if (bc.harmonic == TRUE) cheb.model[-(length(cheb.model))]
  cheb.model.deriv.1st <- if (bc.harmonic == TRUE) cheb.model.deriv.1st[-(length(cheb.model.deriv.1st))]

  # berechnung der nullstellen
  lower <- cheb.scale(x.axis, x.val = roots.bound.l)
  upper <- cheb.scale(x.axis, x.val = roots.bound.u)
  extr <- rootSolve::uniroot.all(cheb.deriv.1st, cheb.coeff = cheb.coeff, lower, upper)
  # reskalierung der Nullstellen auf normale Lat- Achse
  x.extr <- if (length(extr) != 0) cheb.rescale(extr, x.axis = x.axis)
  y.extr <- if (length(extr) != 0) cheb.model.filter(x.axis = extr, cheb.coeff = cheb.coeff)

  cheb.list <- list(cheb.coeff = cheb.coeff, cheb.model = cheb.model, cheb.model.deriv.1st = cheb.model.deriv.1st, x.extr = x.extr, y.extr = y.extr)
  return(cheb.list)
}



#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        cancel = function(job_ids, user = private$user, host = private$host) {
            job_ids <- paste(job_ids, collapse = ",")

            stain_ssh(user, host, paste("scancel", job_ids))
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host,
                          submit_dir = "~/stain", dependency_list = "") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")

                # Add any dependencies to sbatch command.
                history <- self$submission_history()$job_id
                dependencies <- sbatch_dependency_list(dependency_list, history)

                if (nchar(dependencies) > 0) {
                    dependencies <- sbatch_opt("dependency")(dependencies)
                }

                submit_cmd <- paste("sbatch",
                                    dependencies,
                                    "submit.slurm")
                submit_cmd <- paste("cd", job_dir, "&&", submit_cmd)
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir = "~/stain") {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        submission_history = function() {
            # `stain_sub_history` will warn if submission history is empty.
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                return(history)
            }
        },
        fetch_job_states = function(user = private$user, host = private$host) {
            submission_history <- stain_sub_history(self$dir)
            job_ids <- submission_history$job_id

            verify_state_table <- function(state_table) {
                if (nrow(status_table) > 0) {
                    return(state_table)
                } else {
                    job_ids <- paste(job_ids, collapse = ", ")
                    message(paste("No statuses found for job ids:", job_ids))
                }
            }

            fetch_squeue_table <- function() {
                tryCatch({
                    squeue_table <- stain_ssh_squeue(user, host, job_ids)
                    squeue_table <- squeue_table[, c("JOBID", "STATE")]
                    colnames(squeue_table) <- c("job_id", "state")
                    # Will throw error if data frame has no rows.
                    squeue_table$exit_code <- NA
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    squeue_table <- data.frame()
                }, finally = return(squeue_table))
            }

            fetch_sacct_table <- function() {
                tryCatch({
                    sacct_table <- stain_ssh_sacct(user, host, job_ids)
                    colnames(sacct_table) <- c("job_id", "state", "exit_code")
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    sacct_table <- data.frame()
                }, finally = return(sacct_table))
            }

            squeue_table <- fetch_squeue_table()
            sacct_table <- fetch_sacct_table()
            states <- rbind(squeue_table, sacct_table)
            states <- aggregate(states, list(states$job_id), function(x) {
                na.omit(x)[1]
            })[,-1]

            return(merge(states, submission_history))
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container_dir, options) {
            private$options <- options

            private$cat_main_file_magic(container_dir)
            private$write_slurm_script(container_dir)
        }
    ),
    private = list(
        options = NA,
        cat_main_file_magic = function(dir) {
            main_file <- ".default_stain_main.R"
            file <- paste0(dir, "/.stain/sources/", main_file)
            sourcing <- paste("sapply(list.files('./.stain/sources', full.names = TRUE)[!(list.files('./.stain/sources')) %in%",
                              paste0("'", main_file, "'"), "], source)")
            loading <- paste("sapply(list.files('./.stain/objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./.stain $PFSDIR
mkdir ./output
cd $PFSDIR

mkdir ./data
mv ./.stain/data/* ./data

module load hpc-ods
module load pandoc

R CMD BATCH ./.stain/sources/.default_stain_main.R

rm -rf ./data ./.stain

cp -r * $SLURM_SUBMIT_DIR/output

rm -rf *"

            write(paste(private$options$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, "submit.slurm", sep = "/"))
        }
    )
)
                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

# not used

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

# not used. and slow

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    list1 <- df1$id
    list2 <- df2$id
    for (j in 1:length(list2)) {
        id <- list2[j]
        list[id] <- NA
        i <- match(id, list1)
        if (!is.na(i)) {
            list[id] <- j - i
        }
    }
    return (list)
}

# slow. not used

getperiodmapold <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
#        list12 <- stocklistperiod[period, 2][[1]]
#        for (i in 1:max) {
#            print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
#        }
        for (i in 1:max) {
            id <- list11$id[i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
                if (is.null(rise)) {
                    rise <- 0
                }
            }
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), rise, list11$id[[i]]))
        }
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
                                        #    list12 <- stocklistperiod[period, 2][[1]]
                                        #
                                        #    len <- nrow(list12)
                                        #    len <- len + 1

                                        #    for (i in 1:max) {
                                        #        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
                                        #    }

                                        #    len <- nrow(list11)
                                        #    len <- len + 1

        len <- nrow(list11)
        len <- len + 1
        for (i in 1:max) {
            id <- list11$id[len - i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
                if (is.null(rise)) {
                    rise <- 0
                }
            }
            
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), rise, list11$id[[len - i]]))
        }
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, mynames, topbottom, periodtext, maindate, olddate, days) {
    dev.new()
    colours <- rainbow(topbottom)
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE, col = colours[i], pch = i)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o", lty = i, col = colours[i], pch = i)
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(mynames[1]))
        legend(1, g_range[2], mynames, cex=0.8, lty=1:6, pch=1:25, col=colours) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (type == pricetype) {
        return (df$price)
    }
    if (type == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    offset <- 0
    if (is.double(mydate)) {
        offset <- round(mydate)
        mydate <- NULL
    }
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex - offset
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    normalize <- 0
    if (length(ids) > 1) {
        if (periodtext == "price") {
            normalize <- 1
        }
        if (periodtext == "index") {
            normalize <- 1
        }
    }
    
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, pricetype)
        perioddata[["text"]] <- pairs
        perioddatamap[["price"]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, indextype)
        perioddata[["text"]] <- pairs
        perioddatamap[["index"]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    dayset <- list()
    ls <- list()
    mynames <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        if (normalize == 1) {
                            str("minmax")
                            str(l)
                            mymin <- abs(min(l))
                            mymax <- abs(max(l))
                            if (mymin > mymax) {
                                mymax <- mymin
                            }
                            for (j in 1:length(l)) {
                                l[j] <- l[j] * 100 / mymax;
                            }
                            str(l)
                        }
                        
                        dayset <- append(dayset, bigretl[[2]])
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        mynames[c] <- df$name
                    }
                }
            }
        }
    }
    daynames <- names(dayset)
    olddate <- min(daynames)
    newdate <- max(daynames)
    displaychart(ls, mynames, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

#' Import data from Wildlife Computers ".tab" text files
#' 
#' @param x filename to be imported or a TDR dataset to be formated.
#' @param dt if TRUE function will return a data.table object, else, a data.frame.
#' @param ... Arguments to be passed to \code{\link{file}} such as \code{encoding}.
#' @details Wildlife Computers > Instrument helper > Save instrument readings > R format
#' @export
#' @keywords raw_processing
#' @import sqldf data.table
read.wcih <- function(x, dt = TRUE, ...) {
  stopifnot(require("data.table"))
  stopifnot(require("sqldf"))
  if (is.character(x)) {
    f <- file(x, ...)
    nms <- unlist(read.table(x, skip = 3, as.is = TRUE, nrows = 1))
    fmt <- list(skip = 4, header = FALSE, row.names = FALSE, sep = " ")
    x <- sqldf("select * from f", dbname = tempfile(), file.format = fmt)[ , -1]
  } else {
    nms <- names(x)
  }
  
  new_nms <- c(
    "Time" = "time", "Depth" = "depth", 
    "External Temperature" = "temp", "Light Level" = "light", 
    "int aX" = "ax", "int aY" = "ay", "int aZ" = "az", 
    "int mX" = "mx", "int mY" = "my", "int mZ" = "mz", 
    "Velocity" = "spd", "Internal Temperature" = "itemp"
  )
  
  x <- setnames(as.data.table(x), new_nms[nms])
  x <- x[ , lapply(.SD, as.numeric)]
  x <- x[ , time := as.POSIXct(floor(time), origin = "1970-01-01", tz = 'UTC')]
  
  x <- if (dt) 
    data.table(x, key = "time")
  else 
    as.data.frame(x)
}

#' Identify Prey Catch attempts
#' 
#' @param x 3 axes acceleration table with time in the first column and acceleration 
#' axes in the following columns. Variables must be entitled "time" for time, 
#' "ax", "ay", and "az" for x, y and z accelerometer axes.
#' @param fs sampling frequency of the input data (Hz).
#' @param fc Cut-off frequency for the butterworth high pass filter (Hz)
#' @return returns a logical vector of prey catch attempts at 1 Hz frequency. 
#' Value is TRUE if the record belong to prey catch attempt FALSE otherwise.
#' @import data.table signal RcppRoll
#' @export
#' @keywords raw_processing
prey_catch_attempts <- function(x, fs = 16, fc = 2.64) {
  stopifnot(require("data.table"))
  stopifnot(require("signal"))
  stopifnot(require("RcppRoll"))
  # Generate Butterworth filter 
  # Critical frequencies of the filter: f_cutoff / (f_sampling/2)
  bf_pca  <- butter(3, W = fc / (0.5*fs), type = 'high')
  
  # Apply filter
  if (!is.data.table(x)) x <- data.table(x, key = "time")
  .f <- function(x) as.numeric(filtfilt(bf_pca, x))
  x <- x[ , 2:4 := lapply(.SD, .f), .SDcols = 2:4]
  gc()
  
  # 1 s fixed window standard deviation + aggregate data to 1 Hz
  x <- x[ , lapply(.SD, sd, na.rm = TRUE), by = time]
  # In case of NAs set ACC to zero
  nas <- lapply(x[ , 2:4, with = FALSE], is.na)
  nas_vector <- Reduce("|", nas)
  if (any(nas_vector)) {
    warning("NAs found and replaced by 0. NA proportion:", mean(nas_vector))
    x$ax[nas$ax] <- 0
    x$ay[nas$ay] <- 0
    x$az[nas$az] <- 0
  }
  gc()
  
  # 5 s moving window standard deviation
  .f <- function(x) c(0,0,roll_sd(x, 5),0,0)
  x <- x[ , 2:4 := lapply(.SD, .f), .SDcols = 2:4]
  gc()
  
  # kmean clutering: "high" = TRUE vs "low" = FALSE
  .f <- function(x) { 
    km_mod <- kmeans(x, 2)
    high_state <- which.max(km_mod$centers)
    as.logical(km_mod$cluster == high_state)
  }
  x <- x[ , 2:4 := lapply(.SD, .f), .SDcols = 2:4]
  
  # Aggregate and return to data.frame
  # records classified as PCA if the three axis are simultaneously in high state
  Reduce("&", x[ , time := NULL])
}

#' Compute swimming effort
#' 
#' @param fc Cut-off frequencies for the butterworth band pass filter (Hz)
#' @inheritParams prey_catch_attempts
#' @param rms Should the root mean square be used (instead of mean of absolute values) 
#' when averaging the acceleration to 1 Hz ?
#' @return returns a vector of swimming effort values at 1 Hz.
#' @details Only Y accelerometer axe is used to compute swimming effort.
#' @import data.table signal
#' @export
#' @keywords raw_processing
swimming_effort <- function(x, fs = 16, fc = c(0.4416, 1.0176), rms = FALSE) {
  stopifnot(require("data.table"))
  stopifnot(require("signal"))
  # Generate a Butterworth filter 
  # Critical frequencies of the filter: f_filter / (f_sampling/2)
  bf_swm  <-  butter(3, W = fc / (0.5*fs), type = 'pass')
  
  # Apply filter
  if (!is.data.table(x)) x <- data.table(x, key = "time")
  x <- x[ , ay := abs(as.numeric(filtfilt(bf_swm, ay)))]
  x <- x[ , c(2, 4) := NULL, with = FALSE] # remove unused "ax" & "az" columns
  
  # 1 s fixed window average + aggregate data to 1 Hz
  if (!rms) {
    x <- x[ , lapply(.SD, function(x) mean(abs(x), na.rm = TRUE)), by = time]
  } else {
    x <- x[ , lapply(.SD, function(x) sqrt(mean(x^2, na.rm = TRUE))), by = time]
  }
  x <- x$ay
}
globalVariables("ay")

#' Static acceleration
#' 
#' The raw acceleration is first filtered using a low pass butterworth filter. 
#' Then , the extracted signal can be scaled so that the norm of the the vector 
#' G is 1 at each second.
#' 
#' @param fc Cut-off frequency for the butterworth low pass filter (Hz)
#' @param Gscale Should the values be scaled by the norm of the static 
#' acceleration vector ?
#' @param agg_1hz Should the input be aggregated to 1 Hz ?
#' @inheritParams prey_catch_attempts
#' @return returns a data.frame with time, and X, Y and Z static accelearyion at 1 Hz.
#' @details This filtered acceleration can be used to compute pitch and roll angles
#' @import data.table signal
#' @keywords raw_processing
#' @export
static_acc <- function(x, fs = 16, fc = 0.20, Gscale = TRUE, agg_1hz = TRUE) {
  stopifnot(require("data.table"))
  stopifnot(require("signal"))
  # Generate a Butterworth filter 
  # Critical frequencies of the filter: f_filter / (f_sampling/2)
  bf_grav  <-  butter(3, W = fc / (0.5*fs), type = 'low')
  
  # Apply filter
  if (!is.data.table(x)) x <- data.table(x, key = "time")
  x <- x[ , 2:4 := lapply(.SD, function(x) as.numeric(filtfilt(bf_grav, x))), 
          .SDcols = 2:4]
  
  # 1 s fixed window average + aggregate data to 1 Hz
  if (agg_1hz) {
    x <- x[ , lapply(.SD, mean, na.rm = TRUE), by = time]
  }
  x <- setnames(x, c('time', 'axG', 'ayG', 'azG'))
  
  # Scale axis
  if (Gscale) {
    Gnorm <- sqrt(x$axG^2 + x$ayG^2 + x$azG^2)
    x <- x[ , 2:4 := lapply(.SD, function(x) x / Gnorm), .SDcols = 2:4]
  }
  
  as.data.frame(x)
}

#' Dynamic (Body) acceleration DBA
#' 
#' DBA is calculated by smoothing data for each axis to calculate the static 
#' acceleration (\code{\link{static_acc}}), and then subtracting it from 
#' the raw acceleration.
#' 
#' @param ... Parameters to be passed to \code{\link{static_acc}} (e.g \code{fc}).
#' @inheritParams static_acc
#' @return returns a data.frame with time, and X, Y and Z static accelearyion at 1 Hz.
#' @details This filtered acceleration can be used to compute ODBA and VeDBA.
#' @import data.table signal
#' @export
#' @keywords raw_processing
dynamic_acc <- function(x, fs = 16, agg_1hz = TRUE, ...) {
  static <- static_acc(copy(x), fs = fs, Gscale = FALSE, agg_1hz = FALSE, ...)
  x <- x[ , `:=`(2:4, Map("-", x[ , 2:4, with = FALSE], static[ , 2:4])), with = FALSE]
  rm(list = "static") ; gc()
  if (agg_1hz) {
    x <- x[ , lapply(.SD, mean, na.rm = TRUE), by = time]
  }
  as.data.frame(setnames(x, c("time", "axD", "ayD", "azD")))
}

#' Attitude angles from static accelation
#' 
#' @param object A data frame or TDR table including static acceleration variables 
#' entitled "axG", "ayG", and "azG" for X, Y, and Z axes of the accelerometer.
#' @export
#' @keywords raw_processing
pitch <- function(object) {
  -atan(object$axG/sqrt(object$ayG^2 + object$azG^2))
}

#' @rdname pitch
#' @export
#' @details For roll angle, the x axe is not necessary.
#' @return A vector of pitch/roll of the same length as \code{object}.
#' @keywords raw_processing
roll <- function(object) {
  atan2(object$ayG^2, object$azG)
}

#' Overall Dynamic Body Acceleration (ODBA)
#' 
#' @param object A data frame or TDR table including dynamic acceleration variables 
#' entitled "axD", "ayD", and "azD" for X, Y, and Z axes of the accelerometer.
#' @export
#' @return A vector of ODBA of the same length as \code{object}.
#' @keywords raw_processing
overall_DBA <- function(object) {
  object <- as.data.table(object)
  object <- object[ , tot := abs(axD) + abs(ayD) + abs(azD)]
  object$tot
}

#' Vectorial Dynamic Body Acceleration (VeDBA)
#' 
#' @param object A data frame or TDR table including dynamic acceleration variables 
#' entitled "axD", "ayD", and "azD" for X, Y, and Z axes of the accelerometer.
#' @export
#' @return A vector of VeDBA of the same length as \code{object}.
#' @keywords raw_processing
vectorial_DBA <- function(object) {
  object <- as.data.table(object)
  object <- object[ , tot := sqrt(axD^2 + ayD^2 + azD^2)]
  object$tot
}
## source('~/Master_Thesis/pckg.cheb/R/functions-chebyshev.r')
##
## library(devtools)
## library(roxygen2)
##
## Build and Reload Package:  'Ctrl + Shift + B'
## Check Package:             'Ctrl + Shift + E'
## Test Package:              'Ctrl + Shift + T'


##
#' @title Scaling of X-Axis
#' @param x.axis ursprüngliche beliebige X-Achse (Vektor)
#' @return x.cheb.scaled skalierte X-Achse (Vektor)
#' @description
#' \code{cheb.scale} skaliert beliebige X-Achse auf Achse, die für Polynom-fits verträglich ist.
#' @examples
#' x.axis <- c(0:30)
#' x.cheb.scaled <- cheb.scale(x.axis)
cheb.scale <- function(x.axis) {#, scale) {
  ## Funktion zur Skalierung von Stützpunkten
  ## von beliebigen Gittern auf [-1, 1]
  ## ##
  #  if (type == "cheb") {
  x.cheb.scaled <- (2 * (x.axis - x.axis[1]) / (max(x.axis) - min(x.axis))) - 1
  #  }
  return(x.cheb.scaled)
}


##
#' @title Rescaling of X-Axis
#' @param x.cheb skalierte X-Achse (Skalar oder Vektor)
#' @param x.axis beliebige X-Achse (Vektor)
#' @return x.rescaled reskalierte X-Achse (Skalar oder Sektor)
#' @description
#' cheb.rescale reskaliert die für den Fit erzeugte Achse auf die Ursprüngliche
#' @examples
#' x.rescaled <- cheb.rescale(x.cheb, x.axis)
cheb.rescale <- function(x.cheb, x.axis) {
  ## Funktion zur Reskalierung vom [-1, 1]-Gitter
  ## auf das Ursprungsgitter (in diesem Fall - Lat)
  ## ##
  if (x.cheb >= -1 & x.cheb <= 1) {
    x.rescaled <- (1/2 * (x.cheb + 1) * (max(x.axis) - min(x.axis))) + x.axis[1]
    return(x.rescaled)
  } else
    print("Error: x.cheb went out of boundaries (less -1 or greater 1).")
}


##
#' @title Generating Chebyshev Polynomials of first kind
#' @param x.axis beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.t Chebyshev-Polynome Erster Art (Vektor)
#' @description
#' cheb.1st erzeugt Chebyshev Polynome erster Art aus beliebiger X-Achse
#' @examples
#' cheb.t <- cheb.1st(x.axis, n)
cheb.1st <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Erster Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis  ### ###
  m <- n + 1
  # Rekursionsformel Wiki / Bronstein
  cheb.t.0 <- 1;  cheb.t.1 <- x.cheb;
  cheb.t <- cbind(cheb.t.0, cheb.t.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.t.i <- 2 * x.cheb * cheb.t[,(i - 1)] - cheb.t[,(i - 2)]
      cheb.t <- cbind(cheb.t, cheb.t.i)
      rm(cheb.t.i)
    }
  }
  return(cheb.t)
}


##
#' @title Generating Chebyshev Polynomials of second kind
#' @param x.axis beliebigie X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.u Chebyshev-Polynome Zweiter Art (Vektor)
#' @description
#' cheb.2nd erzeugt Chebyshev Polynome zweiter Art aus beliebiger X-Achse
#' @examples
#' cheb.u <- cheb.2nd(x.axis, n)
cheb.2nd <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Zweiter Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis
  m <- n + 1
  cheb.u.0 <- 1; cheb.u.1 <-  2*x.cheb
  cheb.u <- cbind(cheb.u.0, cheb.u.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.u.i <- 2 * x.cheb * cheb.u[,(i - 1)] - cheb.u[,(i - 2)]
      cheb.u <- cbind(cheb.u, cheb.u.i)
      rm(cheb.u.i)
    }
  }
  return(cheb.u)
}


##
#' @title Calculation of Values of the model fit
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model gefiltertes Modell (Skalar oder Vektor)
#' @description
#' cheb.model berechnet aus den Chebyshev-Koeffizienten die Y-Werte
#' @examples
#' cheb.model <- cheb.model.filter(x.axis, cheb.coeff)
cheb.model.filter <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte aus X-Stellen und Cheb-Koeffizienten
  ## ##
  n <- length(cheb.coeff) - 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.model <- cheb.t %*% cheb.coeff
  return(cheb.model)
}


##
#' @title Calculation of the values of the first derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv.1st Erste Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.1st berechnet aus den Chebyshev-Koeffizienten die Werte der ersten Ableitung
#' @examples
#' cheb.model.deriv <- cheb.deriv.1st(x.axis, cheb.coeff)
cheb.deriv.1st <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte der Ableitung des Modells
  ## aus X-Stellen und Chebyshev-Koeffizienten
  ## ##
  if (length(x.axis) != 0) { ### Überprüfen, ob nötig
    n <- length(cheb.coeff) - 1
    m <- n + 1
    cheb.u <- cheb.2nd(x.axis, n)

    # berechnung der ableitung der polynome erster art
    # rekursionsformel 0
    # dT/dx = n * U_(n-1)
    cheb.t.deriv <- if (length(x.axis) == 1) (2:m)*t(cheb.u[,1:n]) else t((2:m)*t(cheb.u[,1:n]))
    cheb.model.deriv.1st <- cheb.t.deriv %*% cheb.coeff[2:m]
    return(cheb.model.deriv.1st)
  }
}


##
#' @title Calculation of the values of the second derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv Zweite Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.2nd berechnet aus den Chebyshev-Koeffizienten die Werte der zweiten Ableitung
#' @examples
#' cheb.model.deriv.2nd <- cheb.deriv.2nd(x.axis, cheb.coeff)
cheb.deriv.2nd <- function(x.axis, cheb.coeff) {
  n <- length(cheb.coeff) - 1
  m <- n + 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.u <- cheb.2nd(x.axis, n)
  x.cheb <- cheb.scale(x.axis)
  cheb.t.deriv.2nd <- t((((1:m) ** 2) + (1:m)) %*% t(1 / (x.cheb ** 2 - 1)) * t(cheb.t - cheb.u))
  cheb.t.deriv.2nd[1,] <- (-1) * ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.t.deriv.2nd[length(x.cheb),] <- ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.model.deriv.2nd <- cheb.t.deriv.2nd %*% cheb.coeff
  return(cheb.model.deriv.2nd)
}


##
#' @title Curve Fitting with Chebyshev Polynomials
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit <- function(d, x.axis, n, harmonic = FALSE){
  # Fallunterscheidung für harmonische Randbedingung
  if (harmonic == FALSE) {
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  } else if (harmonic == TRUE) {
    d <- c(d, d[1])
    x.axis <- c(x.axis, (x.axis[1] + 360))
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  }

  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # löschen des letzten eintrags für den harmonischen fall
  cheb.model <- if (harmonic == TRUE) cheb.model[-(length(cheb.model))]

  # Übergabe der Variablen
  return(cheb.model)
}



##
#' @title Curve Fitting with Chebyshev Polynomials and Finding of its Roots
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit.roots <- function(d, x.axis, n){
  library(rootSolve)
  x.cheb <- cheb.scale(x.axis)
  cheb.t <- cheb.1st(x.axis, n)
  #  cheb.u <- cheb.2nd(x.axis, n)
  #  m <- n + 1
  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # berechnung des abgeleiteten modells
  cheb.model.deriv.1st <- cheb.deriv.1st(x.cheb, cheb.coeff)

  # berechnung der nullstellen
  extr <- rootSolve::uniroot.all(cheb.deriv.1st, cheb.coeff = cheb.coeff, lower = (-1), upper = 1)
  # reskalierung der Nullstellen auf normale Lat- Achse
  x.extr <- if (length(extr) != 0) cheb.rescale(extr, x.axis = x.axis)
  y.extr <- if (length(extr) != 0) cheb.model.filter(x.axis = extr, cheb.coeff = cheb.coeff)

  cheb.list <- list(cheb.coeff = cheb.coeff, cheb.model = cheb.model, cheb.model.deriv.1st = cheb.model.deriv.1st, x.extr = x.extr, y.extr = y.extr)
  return(cheb.list)
}



##
#' @title Curve Fitting with Chebyshev Polynomials over Sequences
#' @description
#' Fittet ein Chebyshev Polynom beliebiger Ordnung an einen sequenzierten Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.fit.seq(d, x.axis, n, l)
cheb.fit.seq <- function(d, x.axis, n, l, harmonic = FALSE){
  x.mat <- matrix(x.axis, ncol = l, byrow = TRUE)
  d.mat <- matrix(d, ncol = l, byrow = TRUE)
  end.loop <- length(x.mat[,1])

  # schleife über sequenzen des Datensatzes
  for (i in 1:end.loop) {
    # erstellung der sequenzen und fallunterscheidung für harmonische randbedingung
    if (harmonic == FALSE) {
      d.seq <- if (i != end.loop) c(d.mat[i,], d.mat[(i + 1), 1]) else c(d.mat[i,])
      x.seq <- if (i != end.loop) c(x.mat[i,], x.mat[(i + 1), 1]) else c(x.mat[i,])
    } else if (harmonic == TRUE) {
      d.seq <- if (i != end.loop) c(d.mat[i,], d.mat[(i + 1), 1]) else c(d.mat[i,], d.mat[1,1])
      x.seq <- if (i != end.loop) c(x.mat[i,], x.mat[(i + 1), 1]) else c(x.mat[i,], x.mat[1,1] + 360)
    }
    x.cheb.seq <- cheb.scale(x.seq)
    cheb.t.seq <- cheb.1st(x.seq, n)

    ## modell berechnungen
    # berechnung der koeffizienten des polyfits
    cheb.coeff.seq <- solve(t(cheb.t.seq) %*% cheb.t.seq) %*% t(cheb.t.seq) %*% d.seq
    cheb.coeff <- if (i == 1) cheb.coeff.seq else cbind(cheb.coeff, cheb.coeff.seq)
    # berechnung des gefilterten modells
    cheb.model.seq <- cheb.model.filter(x.cheb.seq, cheb.coeff.seq)
    if (harmonic == FALSE) {
      cheb.model <- if (i == 1) cheb.model.seq[-(l + 1)] else if (i > 1 & i != end.loop) c(cheb.model, cheb.model.seq[-(l + 1)]) else c(cheb.model, cheb.model.seq)
    } else if (harmonic == TRUE) {
      cheb.model <- if (i == 1) cheb.model.seq[-(l + 1)] else if (i > 1 & i != end.loop) c(cheb.model, cheb.model.seq[-(l + 1)]) else c(cheb.model, cheb.model.seq[-(l + 1)])
    }
  }

  ## übergabe der variable
  return(cheb.model)
}

## source('~/Master_Thesis/pckg.cheb/R/functions-chebyshev.r')
##
## library(devtools)
## library(roxygen2)
##
## Build and Reload Package:  'Ctrl + Shift + B'
## Check Package:             'Ctrl + Shift + E'
## Test Package:              'Ctrl + Shift + T'


##
#' @title Scaling of X-Axis
#' @param x.axis ursprüngliche beliebige X-Achse (Vektor)
#' @return x.cheb.scaled skalierte X-Achse (Vektor)
#' @description
#' \code{cheb.scale} skaliert beliebige X-Achse auf Achse, die für Polynom-fits verträglich ist.
#' @examples
#' x.axis <- c(0:30)
#' x.cheb.scaled <- cheb.scale(x.axis)
cheb.scale <- function(x.axis) {#, scale) {
  ## Funktion zur Skalierung von Stützpunkten
  ## von beliebigen Gittern auf [-1, 1]
  ## ##
  #  if (type == "cheb") {
  x.cheb.scaled <- (2 * (x.axis - x.axis[1]) / (max(x.axis) - min(x.axis))) - 1
  #  }
  return(x.cheb.scaled)
}


##
#' @title Rescaling of X-Axis
#' @param x.cheb skalierte X-Achse (Skalar oder Vektor)
#' @param x.axis beliebige X-Achse (Vektor)
#' @return x.rescaled reskalierte X-Achse (Skalar oder Sektor)
#' @description
#' cheb.rescale reskaliert die für den Fit erzeugte Achse auf die Ursprüngliche
#' @examples
#' x.rescaled <- cheb.rescale(x.cheb, x.axis)
cheb.rescale <- function(x.cheb, x.axis) {
  ## Funktion zur Reskalierung vom [-1, 1]-Gitter
  ## auf das Ursprungsgitter (in diesem Fall - Lat)
  ## ##
  if (x.cheb >= -1 & x.cheb <= 1) {
    x.rescaled <- (1/2 * (x.cheb + 1) * (max(x.axis) - min(x.axis))) + x.axis[1]
    return(x.rescaled)
  } else
    print("Error: x.cheb went out of boundaries (less -1 or greater 1).")
}


##
#' @title Generating Chebyshev Polynomials of first kind
#' @param x.axis beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.t Chebyshev-Polynome Erster Art (Vektor)
#' @description
#' cheb.1st erzeugt Chebyshev Polynome erster Art aus beliebiger X-Achse
#' @examples
#' cheb.t <- cheb.1st(x.axis, n)
cheb.1st <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Erster Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis  ### ###
  m <- n + 1
  # Rekursionsformel Wiki / Bronstein
  cheb.t.0 <- 1;  cheb.t.1 <- x.cheb;
  cheb.t <- cbind(cheb.t.0, cheb.t.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.t.i <- 2 * x.cheb * cheb.t[,(i - 1)] - cheb.t[,(i - 2)]
      cheb.t <- cbind(cheb.t, cheb.t.i)
      rm(cheb.t.i)
    }
  }
  return(cheb.t)
}


##
#' @title Generating Chebyshev Polynomials of second kind
#' @param x.axis beliebigie X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.u Chebyshev-Polynome Zweiter Art (Vektor)
#' @description
#' cheb.2nd erzeugt Chebyshev Polynome zweiter Art aus beliebiger X-Achse
#' @examples
#' cheb.u <- cheb.2nd(x.axis, n)
cheb.2nd <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Zweiter Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis
  m <- n + 1
  cheb.u.0 <- 1; cheb.u.1 <-  2*x.cheb
  cheb.u <- cbind(cheb.u.0, cheb.u.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.u.i <- 2 * x.cheb * cheb.u[,(i - 1)] - cheb.u[,(i - 2)]
      cheb.u <- cbind(cheb.u, cheb.u.i)
      rm(cheb.u.i)
    }
  }
  return(cheb.u)
}


##
#' @title Calculation of Values of the model fit
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model gefiltertes Modell (Skalar oder Vektor)
#' @description
#' cheb.model berechnet aus den Chebyshev-Koeffizienten die Y-Werte
#' @examples
#' cheb.model <- cheb.model.filter(x.axis, cheb.coeff)
cheb.model.filter <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte aus X-Stellen und Cheb-Koeffizienten
  ## ##
  n <- length(cheb.coeff) - 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.model <- cheb.t %*% cheb.coeff
  return(cheb.model)
}


##
#' @title Calculation of the values of the first derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv.1st Erste Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.1st berechnet aus den Chebyshev-Koeffizienten die Werte der ersten Ableitung
#' @examples
#' cheb.model.deriv <- cheb.deriv.1st(x.axis, cheb.coeff)
cheb.deriv.1st <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte der Ableitung des Modells
  ## aus X-Stellen und Chebyshev-Koeffizienten
  ## ##
  if (length(x.axis) != 0) { ### Überprüfen, ob nötig
    n <- length(cheb.coeff) - 1
    m <- n + 1
    cheb.u <- cheb.2nd(x.axis, n)

    # berechnung der ableitung der polynome erster art
    # rekursionsformel 0
    # dT/dx = n * U_(n-1)
    cheb.t.deriv <- if (length(x.axis) == 1) (2:m)*t(cheb.u[,1:n]) else t((2:m)*t(cheb.u[,1:n]))
    cheb.model.deriv.1st <- cheb.t.deriv %*% cheb.coeff[2:m]
    return(cheb.model.deriv.1st)
  }
}


##
#' @title Calculation of the values of the second derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv Zweite Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.2nd berechnet aus den Chebyshev-Koeffizienten die Werte der zweiten Ableitung
#' @examples
#' cheb.model.deriv.2nd <- cheb.deriv.2nd(x.axis, cheb.coeff)
cheb.deriv.2nd <- function(x.axis, cheb.coeff) {
  n <- length(cheb.coeff) - 1
  m <- n + 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.u <- cheb.2nd(x.axis, n)
  x.cheb <- cheb.scale(x.axis)
  cheb.t.deriv.2nd <- t((((1:m) ** 2) + (1:m)) %*% t(1 / (x.cheb ** 2 - 1)) * t(cheb.t - cheb.u))
  cheb.t.deriv.2nd[1,] <- (-1) * ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.t.deriv.2nd[length(x.cheb),] <- ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.model.deriv.2nd <- cheb.t.deriv.2nd %*% cheb.coeff
  return(cheb.model.deriv.2nd)
}


##
#' @title Curve Fitting with Chebyshev Polynomials
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit <- function(d, x.axis, n, harmonic = FALSE){
  # Fallunterscheidung für harmonische Randbedingung
  if (harmonic == FALSE) {
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  } else if (harmonic == TRUE) {
    d <- c(d, d[1])
    x.axis <- c(x.axis, (x.axis[1] + 360))
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  }

  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # löschen des letzten eintrags für den harmonischen fall
  cheb.model <- if (harmonic == TRUE) cheb.model[-(length(cheb.model))]

  # Übergabe der Variablen
  return(cheb.model)
}



##
#' @title Curve Fitting with Chebyshev Polynomials and Finding of its Roots
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit.roots <- function(d, x.axis, n){
  library(rootSolve)
  x.cheb <- cheb.scale(x.axis)
  cheb.t <- cheb.1st(x.axis, n)
  #  cheb.u <- cheb.2nd(x.axis, n)
  #  m <- n + 1
  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # berechnung des abgeleiteten modells
  cheb.model.deriv.1st <- cheb.deriv.1st(x.cheb, cheb.coeff)

  # berechnung der nullstellen
  extr <- rootSolve::uniroot.all(cheb.deriv.1st, cheb.coeff = cheb.coeff, lower = (-1), upper = 1)
  # reskalierung der Nullstellen auf normale Lat- Achse
  x.extr <- if (length(extr) != 0) cheb.rescale(extr, x.axis = x.axis)
  y.extr <- if (length(extr) != 0) cheb.model.filter(x.axis = extr, cheb.coeff = cheb.coeff)

  cheb.list <- list(cheb.coeff = cheb.coeff, cheb.model = cheb.model, cheb.model.deriv.1st = cheb.model.deriv.1st, x.extr = x.extr, y.extr = y.extr)
  return(cheb.list)
}



##
#' @title Curve Fitting with Chebyshev Polynomials over Sequences
#' @description
#' Fittet ein Chebyshev Polynom beliebiger Ordnung an einen sequenzierten Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.fit.seq(d, x.axis, n, l)
cheb.fit.seq <- function(d, x.axis, n, l, harmonic == FALSE){
  x.mat <- matrix(x.axis, ncol = l, byrow = TRUE)
  d.mat <- matrix(d, ncol = l, byrow = TRUE)
  end.loop <- length(x.mat[,1])

  # schleife über sequenzen des Datensatzes
  for (i in 1:end.loop) {
    # erstellung der sequenzen und fallunterscheidung für harmonische randbedingung
    if (harmonic == FALSE) {
      d.seq <- if (i != end.loop) c(d.mat[i,], d.mat[(i + 1), 1]) else c(d.mat[i,])
      x.seq <- if (i != end.loop) c(x.mat[i,], x.mat[(i + 1), 1]) else c(x.mat[i,])
    } else if (harmonic == TRUE) {
      d.seq <- if (i != end.loop) c(d.mat[i,], d.mat[(i + 1), 1]) else c(d.mat[i,], d.mat[1,1])
      x.seq <- if (i != end.loop) c(x.mat[i,], x.mat[(i + 1), 1]) else c(x.mat[i,], x.mat[1,1] + 360)
    }
    x.cheb.seq <- cheb.scale(x.seq)
    cheb.t.seq <- cheb.1st(x.seq, n)

    ## modell berechnungen
    # berechnung der koeffizienten des polyfits
    cheb.coeff.seq <- solve(t(cheb.t.seq) %*% cheb.t.seq) %*% t(cheb.t.seq) %*% d.seq
    cheb.coeff <- if (i == 1) cheb.coeff.seq else cbind(cheb.coeff, cheb.coeff.seq)
    # berechnung des gefilterten modells
    cheb.model.seq <- cheb.model.filter(x.cheb.seq, cheb.coeff.seq)
    cheb.model <- if (i == 1) cheb.model.seq[-l] else c(cheb.model, cheb.model.seq[-l])
  }

  ## übergabe der variable
  return(cheb.model)
}

#!/usr/bin/env Rscript
# Copyright (c) 2015 Mikkel Schubert <MSchubert@snm.ku.dk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# Required for 'read.tree'
library(ape)
library(ggplot2)
library(grid)
library(methods)


TTBar <- setRefClass("TTBar",
            fields = list(leftmax = "numeric",
                          left = "numeric",
                          right = "numeric",
                          rightmax = "numeric"))


TTNode <- setRefClass("TTNode",
            fields = list(children = "list",
                          bar = 'TTBar',
                          len = "numeric",
                          label = "character",
                          group = "character"
                          ),
            methods = list(
                "initialize" = function(children = NULL, bar = NULL, len = 0,
                                        label = "", group = "") {
                    .self$children <- as.list(children)
                    if (!is.null(bar)) {
                        .self$bar <- bar
                    }
                    .self$len <- len
                    .self$label <- label
                    .self$group <- group
                },

                "show" = function() {
                    print(node$pformat())
                },

                "pformat" = function() {
                    return(paste(to_str(), ";", sep=""))
                },

                "to_str" = function() {
                    fields <- NULL
                    if (length(children)) {
                        child_str <- NULL
                        for (child in children) {
                            child_str <- c(child_str, child$to_str())
                        }

                        fields <- c(fields, "(", paste(child_str, sep="", collapse=","), ")")
                    }

                    if (nchar(label) > 0) {
                        fields <- c(fields, label)
                    }

                    if (length(len) > 0) {
                        fields <- c(fields, ":", len)
                    }

                    return(paste(fields, sep="", collapse=""))
                },

                "height_above" = function() {
                    total <- ifelse(length(children) > 0, 0, 1)
                    for (child in children_above()) {
                        total <- total + child$height_above() + child$height_below()
                    }

                    return(total)
                },

                "height_below" = function() {
                    total <- ifelse(length(children) > 0, 0, 1)
                    for (child in children_below()) {
                        total <- total + child$height_above() + child$height_below()
                    }

                    return(total)
                },

                "height" = function() {
                    return(height_above() + height_below())
                },

                "width" = function() {
                    total <- 0

                    for (child in children) {
                        total <- max(total, child$width())
                    }

                    if (length(len) > 0) {
                        total <- total + len
                    }

                    return(total)
                },

                "to_tables" = function(from_x=0, from_y=0) {
                    current_x <- from_x + ifelse(length(len) > 0, len, 0)

                    # Horizontal line
                    tables <- list(
                        labels=data.frame(
                            start_x=current_x,
                            start_y=from_y + calc_offset(from_y),
                            label=label,
                            group=get_labelgroup()
                        ),
                        segments=data.frame(
                            start_x=from_x,
                            start_y=from_y + calc_offset(from_y),
                            end_x=current_x,
                            end_y=from_y + calc_offset(from_y),
                            group=get_linegroup()),
                        bars=to_bar(current_x, from_y + calc_offset(from_y)))

                    max_y <- from_y
                    current_y <- max_y
                    for (child in children_above()) {
                        current_y <- current_y + child$height_below()
                        tables <- merge_tables(tables, child$to_tables(current_x, current_y))
                        max_y <- current_y + child$calc_offset(current_y)
                        current_y <- current_y + child$height_above()
                    }

                    min_y <- from_y
                    current_y <- min_y
                    for (child in children_below()) {
                        current_y <- current_y - child$height_above()
                        tables <- merge_tables(tables, child$to_tables(current_x, current_y))
                        min_y <- current_y + child$calc_offset(current_y)
                        current_y <- current_y - child$height_below()
                    }

                    # Vertical line
                    tables$segments <- rbind(tables$segments,
                        data.frame(
                            start_x=current_x,
                            start_y=max_y,
                            end_x=current_x,
                            end_y=min_y,
                            group=get_linegroup()))

                    return(tables)
                },

                "to_bar" = function(current_x, current_y) {
                    if (length(c(bar$leftmax, bar$left, bar$right, bar$rightmax)) != 4) {
                        return(data.frame())
                    }

                    return(data.frame(
                        start_x=c(bar$leftmax, bar$left, bar$right) + current_x,
                        end_x=c(bar$left, bar$right, bar$rightmax) + current_x,
                        start_y=current_y - c(0.25, 0.5, 0.25),
                        end_y=current_y + c(0.25, 0.5, 0.25)))
                },

                "merge_tables" = function(tbl_a, tbl_b) {
                    result <- list()
                    for (name in unique(names(tbl_a), names(tbl_b))) {
                        result[[name]] <- rbind(tbl_a[[name]], tbl_b[[name]])
                    }
                    return(result)
                },

                "clade" = function(taxa) {
                    # FIXME: Handle multiple tips with identical label
                    if (length(intersect(taxa, tips())) != length(taxa)) {
                        return(NULL)
                    }

                    for (child in children) {
                        if (length(intersect(taxa, child$tips())) == length(taxa)) {
                            return(child$clade(taxa))
                        }
                    }

                    return(.self)
                },

                "tips" = function(taxa) {
                    if (length(children) == 0) {
                        return(label)
                    } else {
                        result <- NULL
                        for (child in children) {
                            result <- c(result, child$tips())
                        }
                        return(result)
                    }
                },

                "calc_offset" = function(from_y) {
                    max_y <- from_y
                    current_y <- from_y
                    for (child in children_above()) {
                        current_y <- current_y + child$height_below()
                        max_y <- current_y + child$calc_offset(current_y)
                        current_y <- current_y + child$height_above()
                    }

                    min_y <- from_y
                    current_y <- from_y
                    for (child in children_below()) {
                        current_y <- current_y - child$height_above()
                        min_y <- current_y + child$calc_offset(current_y)
                        current_y <- current_y - child$height_below()
                    }

                    return(max_y - from_y - (max_y - min_y) / 2)
                },

                "children_above" = function() {
                    if (length(children) < 1) {
                        return(list())
                    }
                    return(children[1:ceiling(length(children) / 2)])
                },

                "children_below" = function() {
                    if (length(children) < 1) {
                        return(list())
                    }
                    return(children[(ceiling(length(children) / 2) + 1):length(children)])
                },

                "get_labelgroup" = function(prefix=NULL) {
                    if (is.null(prefix)) {
                        prefix <- ifelse(length(children) > 0, "node", "leaf")
                    }

                    if (nchar(group) > 0) {
                        prefix <- paste(prefix, ":", group, sep="")
                    }

                    return(prefix)
                },

                "get_linegroup" = function() {
                    prefix <- "line"
                    if (nchar(group) > 0) {
                        prefix <- paste(prefix, ":", group, sep="")
                    }

                    return(prefix)
                },

                "set_group" = function(value=NULL) {
                    .self$group <- ifelse(is.null(value), "line", value)
                    for (child in children) {
                        child$set_group(value)
                    }
                },

                "is_leaf" = function() {
                    '
                    Convinience function; returns true if the node is a leaf.
                    '
                    return(length(children) == 0)
                },

                "collect" = function() {
                    '
                    Returns a vector of all in the tree, including this node.
                    '
                    result <- .self
                    for (child in children) {
                        result <- c(result, child$collect())
                    }
                    return(result)
                },

                "sort_nodes" = function() {
                    if (!is_leaf()) {
                        widths <- NULL
                        for (child in children) {
                            widths <- c(widths, child$width())
                            child$sort_nodes()
                        }

                        .self$children <- children[order(widths, decreasing=FALSE)]
                    }
                }))


print.TTNode <- function(node)
{
    print(node$pformat())
}


tinytree.phylo.to.tt <- function(phylo)
{
    nnodes <- nrow(phylo$edge) + 1
    lengths <- phylo$edge.length
    to.node <- phylo$edge[, 2]
    from.node <- phylo$edge[, 1]

    nodes <- list()
    labels <- c(phylo$tip.label, phylo$node.label)
    for (edge in 1:nnodes) {
        len <- lengths[to.node == edge]
        nodes[[edge]] <- TTNode(label = labels[edge],
                                len = as.numeric(len))
    }

    for (edge in 1:nnodes) {
        from <- from.node[to.node == edge]
        if (length(from) != 0 && from != 0) {
            children <- nodes[[from]]$children
            children[[length(children) + 1]] <- nodes[[edge]]
            nodes[[from]]$children <- children
        }
    }

    root <- nodes[[length(phylo$tip.label) + 1]]
    root$len <- 0

    return(root)
}


tinytree.read.newick <- function(filename)
{
	return(tinytree.phylo.to.tt(read.tree(filename)))
}


tinytree.defaults.collect <- function(tt, defaults, values)
{
    stopifnot(!any(is.null(names(values))) || length(values) == 0)

    # Overwrite using user supplied values
    for (idx in seq(values)) {
        defaults[[names(values)[idx]]] <- values[[idx]]
    }

    # Set default values based on type (line, node, leaf, etc.)
    for (node in tt$collect()) {
        for (type in c(node$get_labelgroup(), node$get_linegroup())) {
            if (!(type %in% names(defaults))) {
                root <- unlist(strsplit(type, ":"))[[1]]
                stopifnot(root %in% names(defaults))
                defaults[[type]] <- defaults[[root]]
            }
        }
    }

    return(defaults)
}


tinytree.default.colours <- function(pp, tt, ...)
{
    defaults <- c("line"="black",
                  "node"="darkgrey",
                  "leaf"="black",
                  "bar"="blue")
    defaults <- tinytree.defaults.collect(tt, defaults, list(...))

    return(pp +
           scale_colour_manual(values=defaults) +
           scale_fill_manual(values=defaults))
}


tinytree.default.sizes <- function(pp, tt, ...)
{
    defaults <- c("line"=0.5,
                  "node"=4,
                  "leaf"=5)
    defaults <- tinytree.defaults.collect(tt, defaults, list(...))

    return(pp + scale_size_manual(values=defaults))
}


tinytree.draw <- function(tt, default.scales=TRUE, xaxis="scales", padding=0.3)
{
    tbl <- tt$to_tables(-tt$len)

    pp <- ggplot()
    pp <- pp + geom_segment(data=tbl$segments, lineend="round",
                            aes(x=start_x, y=start_y, xend=end_x, yend=end_y,
                                color=group, size=group))

    if (nrow(tbl$bars) > 0) {
        pp <- pp + geom_rect(data=tbl$bars, alpha=0.3,
                             aes(xmin=start_x, xmax=end_x, ymin=start_y, ymax=end_y,
                                 fill="bar"))
    }

    if (any(!is.na(tbl$labels$label))) {
        labels <- tbl$labels[!is.na(tbl$labels$label),]
        pp <- pp + geom_text(data=labels, hjust=0,
                             aes(label=sprintf(" %s", label),
                                 x=start_x, y=start_y, color=group, size=group))
    }

    pp <- pp + theme_minimal()

    # Disable legend
    pp <- pp + theme(legend.position="none",
    # Disable y axis + y axis labels + grid
                     axis.ticks.y=element_blank(),
                     axis.text.y=element_blank(),
                     panel.grid.minor.y=element_blank(),
                     panel.grid.major.y=element_blank(),
                     panel.grid.major  = element_line(colour = "grey90", size = 0.4),
                     panel.grid.minor  = element_line(colour = "grey90", size = 0.2))

    if (xaxis != "axis") {
        stopifnot(xaxis %in% c("scales", "none"))
        pp <- pp + theme(axis.ticks.x=element_blank(),
                         axis.text.x=element_blank(),
                         panel.grid.minor.x=element_blank(),
                         panel.grid.major.x=element_blank())

        if (xaxis == "scales") {
            y_offset <- min(tbl$segments$start_y, tbl$segments$end_y) - 3
            x_offset <- max(tbl$segments$end_x) * 0.2

            df <- data.frame(x=0, y=y_offset, xend=x_offset, yend=y_offset)
            pp <- pp + geom_segment(data=df,
                                    aes(color="line", size="line",
                                        x=x, xend=xend, y=y, yend=yend))

            df <- data.frame(x=x_offset, y=y_offset, label=paste("", signif(x_offset, 2)))
            pp <- pp + geom_text(data=df, aes(x=x, y=y, hjust=0, label=label,
                                              size="leaf", colour="leaf"))
        }
    }

    # Disable axis labels by default
    pp <- pp + xlab(NULL)
    pp <- pp + ylab(NULL)

    # Default colors; may be overwritten
    if (default.scales) {
        pp <- tinytree.default.sizes(pp, tt)
        pp <- tinytree.default.colours(pp, tt)
    }

    range <- max(tbl$segments$end_x) - min(tbl$segments$start_x)
    pp <- pp + coord_cartesian(xlim=c(min(tbl$segments$start_x),
                                      max(tbl$segments$end_x) + padding * range))

    return(pp)
}


plot.tree <- function(filename, sample_names, padding=0.3)
{
    samples <- read.table(sample_names, as.is=TRUE, comment.char="", header=TRUE)
    tt <- tinytree.read.newick(filename)
    tt$sort_nodes()

    for (node in tt$collect()) {
        if (node$is_leaf()) {
            node$set_group(node$label)
        }
    }

    pp <- tinytree.draw(tt,
                        default.scales=FALSE,
                        padding=padding)
    pp <- tinytree.default.sizes(pp, tt, "node"=3, "leaf"=4, "line"=0.75)

    defaults <- c("line"="black",
                  "node"="grey40",
                  "leaf"="black",
                  "bar"="blue")
    defaults <- tinytree.defaults.collect(tt, defaults, list())

    for (row in 1:nrow(samples)) {
        row <- samples[row, , drop=FALSE]
        key <- sprintf("leaf:%s", row$Name)
        print(c(key, row$Color))

        defaults[[key]] <- row$Color
    }
    print(defaults)

    return(pp +
           scale_colour_manual(values=defaults) +
           scale_fill_manual(values=defaults))
}


args <- commandArgs(trailingOnly = TRUE)
if (length(args) != 3) {
    cat("Usage: ggtinytree.R <input_file> <sample_names> <output_prefix>\n", file=stderr())
    quit(status=1)
}

input_file <- args[1]
sample_names <- args[2]
output_prefix <- args[3]

pdf(paste(output_prefix, ".pdf", sep=""))
plot.tree(input_file, sample_names)
dev.off()

# bitmap is preferred, since it works in a headless environment
bitmap(paste(output_prefix, ".png", sep=""), height=6, width=6, res=96, taa=4, gaa=4)
plot.tree(input_file, sample_names)
dev.off()

#' ssh with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param cmds A sting of one or more commands to run on the remote host.
#'
#' @param intern Indicates whether to capture the output of the command
#' as an R character vector.
#'
stain_ssh <- function(user, host, cmds = "", intern = FALSE) {
    if (is.null(user) | is.null(host)) {
        stop("No user or host specified.", call. = FALSE)
    }

    if (!stain_ssh_key_exists()) {
        invisible(stain_ssh_key_gen())
    }

    remote_host <- paste(user, host, sep = "@")
    system(paste("ssh", remote_host, "-t -t -i ~/.ssh/stain_rsa",
                 paste0("\"", cmds, "\"")),
           intern = intern)
}


#' scp with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param from The directory or file to copy.
#'
#' @param to The destination.
stain_scp <- function(from, to) {
    system(paste("scp -i ~/.ssh/stain_rsa -r", from, to))
}


#' Get squeue info on certain jobs.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param job_ids A collection of job ids for which to fetch statuses.
#'
#' @return A data frame with columns corresponding to those produced
#' by the \code{squeue -l} command.
stain_ssh_squeue <- function(user, host, job_ids) {
    job_ids <- paste(job_ids, collapse = ",")
    remote_host <- paste(user, host, sep = "@")

    squeue_cmd <- paste("squeue -l -j", job_ids)
    output <- stain_ssh(user, host, squeue_cmd, intern = TRUE)

    output_table <- sapply(output, USE.NAMES = FALSE, function(row) {
        tokens <- strsplit(row, " ")[[1]]
        return(tokens[tokens != ""])
    })

    csv_header <- paste(output_table[[2]], collapse = "\t")
    csv_header <-  gsub("[\r]", "", csv_header)

    if (length(output_table) > 2) {
        csv_body <- paste(lapply(output_table[3:length(output_table)], function(row) {
            row <- paste(row, collapse = "\t")
            row <-  gsub("[\r]", "", row)
            return(row)
        }), collapse = "\n")
        csv <- paste(csv_header, csv_body, sep = "\n")
    } else {
        csv <- csv_header
    }

    state_table <- utils::read.delim(textConnection(csv))

    return(state_table)
}


#' Get sacct info on certain jobs.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param job_ids A collection of job ids for which to fetch statuses.
#'
#' @return A data frame with columns corresponding to those produced
#' by the \code{sacct --brief --jobs} command.
stain_ssh_sacct <- function(user, host, job_ids) {
    job_ids <- paste(job_ids, collapse = ",")
    remote_host <- paste(user, host, sep = "@")

    sacct_cmd <- paste("sacct --brief --jobs", job_ids)
    output <- stain_ssh(user, host, sacct_cmd, intern = TRUE)
    output[2] <- NA
    output <- output[!is.na(output)]

    output_table <- t(sapply(output, USE.NAMES = FALSE, function(row) {
        tokens <- strsplit(row, " ")[[1]]
        return(tokens[tokens != "" & tokens != "\r"])
    }))

    csv_header <- output_table[1, ]
    csv_body <- output_table[-1, ]
    state_table <- as.data.frame(csv_body)

    if (nrow(state_table) > 0) {
        colnames(state_table) <- csv_header
        state_table <- state_table[seq(1, length(state_table[, 1]), by = 2), ]
    }

    return(state_table)
}


#' Check for a Stain ssh key.
#'
#' @return If a public/private key pair exists in \code{~/.ssh/} with the name
#' \code{stain_rsa}, return TRUE, otherwise return FALSE.
stain_ssh_key_exists <- function() {
    return("stain_rsa" %in% list.files("~/.ssh/"))
}


#' Generate a Stain ssh key.
#'
#' A 4096 bit key will be generated and stored in \code{~/.ssh/} with the name
#' \code{stain_rsa}.
#'
#' @param overwrite Should an existing Stain ssh key be overwritten. Default
#' value is FALSE.
stain_ssh_key_gen <- function(overwrite = FALSE) {
    if (overwrite | !(overwrite | stain_ssh_key_exists())) {
        system("ssh-keygen -b 4096 -f ~/.ssh/stain_rsa -N ''",
               ignore.stdout = TRUE)
    }
}


#' Create bash code for ssh setup.
#'
#' In order for a remote submission to work, an ssh public key for Stain must
#' be present in the remote host's \code{~/.ssh/authorized_keys} list. This
#' process requires two steps. 1) To \code{scp} the public key and 2) to add
#' the key to \code{~/.ssh/authorized_keys}. This function will autogenerate
#' the necessary bash code to complete these steps.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @return A single bash command to run.
#'
#' @export
stain_ssh_setup <- function(user, host) {
    remote_host <- paste(user, host, sep = "@")
    scp <- paste0("scp ~/.ssh/stain_rsa.pub ", remote_host, ":~/.ssh/stain_rsa.pub")
    ssh <- paste("ssh", remote_host, "'echo `cat ~/.ssh/stain_rsa.pub` >> ~/.ssh/authorized_keys'")
    cmd <- paste(scp, "&&", ssh)

    if (Sys.info()["sysname"] == "Darwin") {
        cat("The bash command to setup remote submission has been copied to your clipboard. Run it in your terminal.")
        utils::write.table(cmd, file = pipe("pbcopy"), sep = "\t",
                           col.names = F, row.names = F , quote = F)
    } else {
        cat("Run the following bash command in your terminal to setup remote submission:")
        cat(cmd)
    }
}
#' ssh with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param cmds A sting of one or more commands to run on the remote host.
#'
#' @param intern Indicates whether to capture the output of the command
#' as an R character vector.
#'
stain_ssh <- function(user, host, cmds = "", intern = FALSE) {
    if (is.null(user) | is.null(host)) {
        stop("No user or host specified.", call. = FALSE)
    }

    if (!stain_ssh_key_exists()) {
        invisible(stain_ssh_key_gen())
    }

    remote_host <- paste(user, host, sep = "@")
    system(paste("ssh", remote_host, "-t -t -i ~/.ssh/stain_rsa",
                 paste0("\"", cmds, "\"")),
           intern = intern)
}


#' scp with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param from The directory or file to copy.
#'
#' @param to The destination.
stain_scp <- function(from, to) {
    system(paste("scp -i ~/.ssh/stain_rsa -r", from, to))
}


#' Get squeue info on certain jobs.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param job_ids A collection of job ids for which to fetch statuses.
#'
#' @return A data frame with columns corresponding to those produced
#' by the \code{squeue -l} command.
stain_ssh_squeue <- function(user, host, job_ids) {
    job_ids <- paste(job_ids, collapse = ",")
    remote_host <- paste(user, host, sep = "@")

    squeue_cmd <- paste("squeue -l -j", job_ids)
    output <- stain_ssh(user, host, squeue_cmd, intern = TRUE)

    output_table <- sapply(output, USE.NAMES = FALSE, function(row) {
        tokens <- strsplit(row, " ")[[1]]
        return(tokens[tokens != ""])
    })

    csv_header <- paste(output_table[[2]], collapse = "\t")
    csv_header <-  gsub("[\r]", "", csv_header)

    if (length(output_table) > 2) {
        csv_body <- paste(lapply(output_table[3:length(output_table)], function(row) {
            row <- paste(row, collapse = "\t")
            row <-  gsub("[\r]", "", row)
            return(row)
        }), collapse = "\n")
        csv <- paste(csv_header, csv_body, sep = "\n")
    } else {
        csv <- csv_header
    }

    state_table <- utils::read.delim(textConnection(csv))

    return(state_table)
}


#' Get sacct info on certain jobs.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param job_ids A collection of job ids for which to fetch statuses.
#'
#' @return A data frame with columns corresponding to those produced
#' by the \code{sacct --brief --jobs} command.
stain_ssh_sacct <- function(user, host, job_ids) {
    job_ids <- paste(job_ids, collapse = ",")
    remote_host <- paste(user, host, sep = "@")

    sacct_cmd <- paste("sacct --brief --jobs", job_ids)
    output <- stain_ssh(user, host, sacct_cmd, intern = TRUE)
    output[2] <- NA
    output <- output[!is.na(output)]

    output_table <- t(sapply(output, USE.NAMES = FALSE, function(row) {
        tokens <- strsplit(row, " ")[[1]]
        return(tokens[tokens != "" & tokens != "\r"])
    }))

    csv_header <- output_table[1, ]
    csv_body <- output_table[-1, ]
    state_table <- as.data.frame(csv_body)

    if (nrow(state_table) > 0) {
        colnames(state_table) <- csv_header
        state_table <- state_table[seq(1, length(state_table[, 1]), by = 2), ]
    }

    return(state_table)
}


#' Check for a Stain ssh key.
#'
#' @return If a public/private key pair exists in \code{~/.ssh/} with the name
#' \code{stain_rsa}, return TRUE, otherwise return FALSE.
stain_ssh_key_exists <- function() {
    return("stain_rsa" %in% list.files("~/.ssh/"))
}


#' Generate a Stain ssh key.
#'
#' A 4096 bit key will be generated and stored in \code{~/.ssh/} with the name
#' \code{stain_rsa}.
#'
#' @param overwrite Should an existing Stain ssh key be overwritten. Default
#' value is FALSE.
stain_ssh_key_gen <- function(overwrite = FALSE) {
    if (overwrite | !(overwrite | stain_ssh_key_exists())) {
        system("ssh-keygen -b 4096 -f ~/.ssh/stain_rsa -N ''")
    }
}


#' Create bash code for ssh setup.
#'
#' In order for a remote submission to work, an ssh public key for Stain must
#' be present in the remote host's \code{~/.ssh/authorized_keys} list. This
#' process requires two steps. 1) To \code{scp} the public key and 2) to add
#' the key to \code{~/.ssh/authorized_keys}. This function will autogenerate
#' the necessary bash code to complete these steps.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @return A single bash command to run.
#'
#' @export
stain_ssh_setup <- function(user, host) {
    remote_host <- paste(user, host, sep = "@")
    scp <- paste0("scp ~/.ssh/stain_rsa.pub ", remote_host, ":~/.ssh/stain_rsa.pub")
    ssh <- paste("ssh", remote_host, "'echo `cat ~/.ssh/stain_rsa.pub` >> ~/.ssh/authorized_keys'")
    cmd <- paste(scp, "&&", ssh)

    if (Sys.info()["sysname"] == "Darwin") {
        cat("The bash command to setup remote submission has been copied to your clipboard. Run it in your terminal.")
        utils::write.table(cmd, file = pipe("pbcopy"), sep = "\t",
                           col.names = F, row.names = F , quote = F)
    } else {
        cat("Run the following bash command in your terminal to setup remote submission:")
        cat(cmd)
    }
}
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        cancel = function(job_ids, user = private$user, host = private$host) {
            job_ids <- paste(job_ids, collapse = ",")

            stain_ssh(user, host, paste("scancel", job_ids))
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host,
                          submit_dir = "~/stain", dependency_list = "") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")

                # Add any dependencies to sbatch command.
                history <- self$submission_history()$job_id
                dependencies <- sbatch_dependency_list(dependency_list, history)
                submit_cmd <- paste("sbatch",
                                    sbatch_opt("dependency")(dependencies),
                                    "submit.slurm")
                submit_cmd <- paste("cd", job_dir, "&&", submit_cmd)
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir = "~/stain") {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        submission_history = function() {
            # `stain_sub_history` will warn if submission history is empty.
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                return(history)
            }
        },
        fetch_job_states = function(user = private$user, host = private$host) {
            job_ids <- stain_sub_history(self$dir)$job_id

            verify_state_table <- function(state_table) {
                if (nrow(status_table) > 0) {
                    return(state_table)
                } else {
                    job_ids <- paste(job_ids, collapse = ", ")
                    message(paste("No statuses found for job ids:", job_ids))
                }
            }

            fetch_squeue_table <- function() {
                tryCatch({
                    squeue_table <- stain_ssh_squeue(user, host, job_ids)
                    squeue_table <- squeue_table[, c("JOBID", "STATE")]
                    colnames(squeue_table) <- c("job_id", "state")
                    # Will throw error if data frame has no rows.
                    squeue_table$exit_code <- NA
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    squeue_table <- data.frame()
                }, finally = return(squeue_table))
            }

            fetch_sacct_table <- function() {
                tryCatch({
                    sacct_table <- stain_ssh_sacct(user, host, job_ids)
                    colnames(sacct_table) <- c("job_id", "state", "exit_code")
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    sacct_table <- data.frame()
                }, finally = return(sacct_table))
            }

            squeue_table <- fetch_squeue_table()
            sacct_table <- fetch_sacct_table()
            states <- rbind(squeue_table, sacct_table)
            states <- aggregate(states, list(states$job_id), function(x) {
                na.omit(x)[1]
            })[,-1]

            return(states)
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
## source('~/Master_Thesis/pckg.cheb/R/functions-chebyshev.r')
##
## library(devtools)
## library(roxygen2)
##
## Build and Reload Package:  'Ctrl + Shift + B'
## Check Package:             'Ctrl + Shift + E'
## Test Package:              'Ctrl + Shift + T'


##
#' @title Scaling of X-Axis
#' @param x.axis ursprüngliche beliebige X-Achse (Vektor)
#' @return x.cheb.scaled skalierte X-Achse (Vektor)
#' @description
#' \code{cheb.scale} skaliert beliebige X-Achse auf Achse, die für Polynom-fits verträglich ist.
#' @examples
#' x.axis <- c(0:30)
#' x.cheb.scaled <- cheb.scale(x.axis)
cheb.scale <- function(x.axis) {#, scale) {
  ## Funktion zur Skalierung von Stützpunkten
  ## von beliebigen Gittern auf [-1, 1]
  ## ##
  #  if (type == "cheb") {
  x.cheb.scaled <- (2 * (x.axis - x.axis[1]) / (max(x.axis) - min(x.axis))) - 1
  #  }
  return(x.cheb.scaled)
}


##
#' @title Rescaling of X-Axis
#' @param x.cheb skalierte X-Achse (Skalar oder Vektor)
#' @param x.axis beliebige X-Achse (Vektor)
#' @return x.rescaled reskalierte X-Achse (Skalar oder Sektor)
#' @description
#' cheb.rescale reskaliert die für den Fit erzeugte Achse auf die Ursprüngliche
#' @examples
#' x.rescaled <- cheb.rescale(x.cheb, x.axis)
cheb.rescale <- function(x.cheb, x.axis) {
  ## Funktion zur Reskalierung vom [-1, 1]-Gitter
  ## auf das Ursprungsgitter (in diesem Fall - Lat)
  ## ##
  if (x.cheb >= -1 & x.cheb <= 1) {
    x.rescaled <- (1/2 * (x.cheb + 1) * (max(x.axis) - min(x.axis))) + x.axis[1]
    return(x.rescaled)
  } else
    print("Error: x.cheb went out of boundaries (less -1 or greater 1).")
}


##
#' @title Generating Chebyshev Polynomials of first kind
#' @param x.axis beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.t Chebyshev-Polynome Erster Art (Vektor)
#' @description
#' cheb.1st erzeugt Chebyshev Polynome erster Art aus beliebiger X-Achse
#' @examples
#' cheb.t <- cheb.1st(x.axis, n)
cheb.1st <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Erster Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis  ### ###
  m <- n + 1
  # Rekursionsformel Wiki / Bronstein
  cheb.t.0 <- 1;  cheb.t.1 <- x.cheb;
  cheb.t <- cbind(cheb.t.0, cheb.t.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.t.i <- 2 * x.cheb * cheb.t[,(i - 1)] - cheb.t[,(i - 2)]
      cheb.t <- cbind(cheb.t, cheb.t.i)
      rm(cheb.t.i)
    }
  }
  return(cheb.t)
}


##
#' @title Generating Chebyshev Polynomials of second kind
#' @param x.axis beliebigie X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.u Chebyshev-Polynome Zweiter Art (Vektor)
#' @description
#' cheb.2nd erzeugt Chebyshev Polynome zweiter Art aus beliebiger X-Achse
#' @examples
#' cheb.u <- cheb.2nd(x.axis, n)
cheb.2nd <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Zweiter Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis
  m <- n + 1
  cheb.u.0 <- 1; cheb.u.1 <-  2*x.cheb
  cheb.u <- cbind(cheb.u.0, cheb.u.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.u.i <- 2 * x.cheb * cheb.u[,(i - 1)] - cheb.u[,(i - 2)]
      cheb.u <- cbind(cheb.u, cheb.u.i)
      rm(cheb.u.i)
    }
  }
  return(cheb.u)
}


##
#' @title Calculation of Values of the model fit
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model gefiltertes Modell (Skalar oder Vektor)
#' @description
#' cheb.model berechnet aus den Chebyshev-Koeffizienten die Y-Werte
#' @examples
#' cheb.model <- cheb.model.filter(x.axis, cheb.coeff)
cheb.model.filter <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte aus X-Stellen und Cheb-Koeffizienten
  ## ##
  n <- length(cheb.coeff) - 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.model <- cheb.t %*% cheb.coeff
  return(cheb.model)
}


##
#' @title Calculation of the values of the first derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv.1st Erste Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.1st berechnet aus den Chebyshev-Koeffizienten die Werte der ersten Ableitung
#' @examples
#' cheb.model.deriv <- cheb.deriv.1st(x.axis, cheb.coeff)
cheb.deriv.1st <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte der Ableitung des Modells
  ## aus X-Stellen und Chebyshev-Koeffizienten
  ## ##
  if (length(x.axis) != 0) { ### Überprüfen, ob nötig
    n <- length(cheb.coeff) - 1
    m <- n + 1
    cheb.u <- cheb.2nd(x.axis, n)

    # berechnung der ableitung der polynome erster art
    # rekursionsformel 0
    # dT/dx = n * U_(n-1)
    cheb.t.deriv <- if (length(x.axis) == 1) (2:m)*t(cheb.u[,1:n]) else t((2:m)*t(cheb.u[,1:n]))
    cheb.model.deriv.1st <- cheb.t.deriv %*% cheb.coeff[2:m]
    return(cheb.model.deriv.1st)
  }
}


##
#' @title Calculation of the values of the second derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv Zweite Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.2nd berechnet aus den Chebyshev-Koeffizienten die Werte der zweiten Ableitung
#' @examples
#' cheb.model.deriv.2nd <- cheb.deriv.2nd(x.axis, cheb.coeff)
cheb.deriv.2nd <- function(x.axis, cheb.coeff) {
  n <- length(cheb.coeff) - 1
  m <- n + 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.u <- cheb.2nd(x.axis, n)
  x.cheb <- cheb.scale(x.axis)
  cheb.t.deriv.2nd <- t((((1:m) ** 2) + (1:m)) %*% t(1 / (x.cheb ** 2 - 1)) * t(cheb.t - cheb.u))
  cheb.t.deriv.2nd[1,] <- (-1) * ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.t.deriv.2nd[length(x.cheb),] <- ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.model.deriv.2nd <- cheb.t.deriv.2nd %*% cheb.coeff
  return(cheb.model.deriv.2nd)
}


##
#' @title Curve Fitting with Chebyshev Polynomials
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit <- function(d, x.axis, n, tp.return = 'NULL'){
  x.cheb <- cheb.scale(x.axis)
  cheb.t <- cheb.1st(x.axis, n)
  # Fallunterscheidung
  if (tp.return == 'all') {
    ## modell berechnungen
    # berechnung der koeffizienten des polyfits
    cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
    # berechnung des gefilterten modells
    cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
    # berechnung des abgeleiteten modells
    cheb.model.deriv.1st <- cheb.deriv.1st(x.cheb, cheb.coeff)
    ## Übergabe der Var.
    cheb.list <- list(cheb.coeff = cheb.coeff, cheb.model = cheb.model, cheb.model.deriv.1st = cheb.model.deriv.1st)
    return(cheb.list)
  } else {
    ## modell berechnungen
    # berechnung der koeffizienten des polyfits
    cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
    # berechnung des gefilterten modells
    cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
    # Übergabe der Var.
    return(cheb.model)
  }
}


##
#' @title Curve Fitting with Chebyshev Polynomials
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit.roots <- function(d, x.axis, n){
  library(rootSolve)
  x.cheb <- cheb.scale(x.axis)
  cheb.t <- cheb.1st(x.axis, n)
  #  cheb.u <- cheb.2nd(x.axis, n)
  #  m <- n + 1
  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # berechnung des abgeleiteten modells
  cheb.model.deriv.1st <- cheb.deriv.1st(x.cheb, cheb.coeff)

  # berechnung der nullstellen
  extr <- rootSolve::uniroot.all(cheb.deriv.1st, cheb.coeff = cheb.coeff, lower = (-1), upper = 1)
  # reskalierung der Nullstellen auf normale Lat- Achse
  x.extr <- if (length(extr) != 0) cheb.rescale(extr, x.axis = x.axis)
  y.extr <- if (length(extr) != 0) cheb.model.filter(x.axis = extr, cheb.coeff = cheb.coeff)

  cheb.list <- list(cheb.coeff = cheb.coeff, cheb.model = cheb.model, cheb.model.deriv.1st = cheb.model.deriv.1st, x.extr = x.extr, y.extr = y.extr)
  return(cheb.list)
}



##
#' @title Curve Fitting with Chebyshev Polynomials over Sequences
#' @description
#' Fittet ein Chebyshev Polynom beliebiger Ordnung an einen sequenzierten Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.fit.seq(d, x.axis, n, l)
cheb.fit.seq <- function(d, x.axis, n, l){
  library(rootSolve)
  x.mat <- matrix(x.axis, ncol = l, byrow = TRUE)
  d.mat <- matrix(d, ncol = l, byrow = TRUE)

  # schleife über sequenzen des Datensatzes
  for (i in 1:length(x.mat[,1])) {
    # print(i)
    # erstellung der sequenzen
    x.seq <- if (i == 1) c(x.mat[i,]) else c(x.mat[(i - 1), dim(x.mat)[2]], x.mat[i,])
    x.cheb.seq <- cheb.scale(x.seq)
    d.seq <- if (i == 1) c(d.mat[i,]) else c(d.mat[(i - 1), dim(d.mat)[2]], d.mat[i,])
    cheb.t.seq <- cheb.1st(x.seq, n)
    ## modell berechnungen
    # berechnung der koeffizienten des polyfits
    cheb.coeff.seq <- solve(t(cheb.t.seq) %*% cheb.t.seq) %*% t(cheb.t.seq) %*% d.seq
    cheb.coeff <- if (i == 1) cheb.coeff.seq else cbind(cheb.coeff, cheb.coeff.seq)
    # berechnung des gefilterten modells
    cheb.model.seq <- cheb.model.filter(x.cheb.seq, cheb.coeff.seq)
    cheb.model <- if (i == 1) cheb.model.seq else c(cheb.model, cheb.model.seq[2:(l+1)])
    # berechnung des abgeleiteten modells
    cheb.model.deriv.1st.seq <- cheb.deriv.1st(x.cheb.seq, cheb.coeff.seq)
    cheb.model.deriv.1st <- if (i == 1) cheb.model.deriv.1st.seq else c(cheb.model.deriv.1st, cheb.model.deriv.1st.seq[2:(l+1)])

    # berechnung der nullstellen
    extr.seq <- rootSolve::uniroot.all(cheb.deriv.1st, cheb.coeff = cheb.coeff.seq, lower = (-1), upper = 1)
    # reskalierung der Nullstellen auf normale Lat- Achse
    x.extr.seq <- if (length(extr.seq) != 0) cheb.rescale(extr.seq, x.axis = x.seq)
    y.extr.seq <- if (length(extr.seq) != 0) cheb.model.filter(x.axis = extr.seq, cheb.coeff = cheb.coeff.seq)
    #
    if (exists("x.extr.seq") == TRUE & exists("x.extr") == FALSE) {
      x.extr <- x.extr.seq
      y.extr <- y.extr.seq
    } else if (exists("x.extr.seq") == TRUE & exists("x.extr") == TRUE) {
      x.extr <- c(x.extr, x.extr.seq)
      y.extr <- c(y.extr, y.extr.seq)
    }
  }

  ## übergabe der variablen als liste
  cheb.list <- list(cheb.model = cheb.model, cheb.model.deriv.1st = cheb.model.deriv.1st, extr.x = x.extr, extr.y = y.extr)
  return(cheb.list)
}

#' Create an SBATCH option
#'
#' @param key The key for the sbatch option.
#'
#' @return A function that takes a single argument representing
#' the value for the \code{key}.
sbatch_opt <- function(key) {
    return(function(value) {
        return(paste0("--", key, "=", value))
    })
}


#' Test sbatch options for equality.
#'
#' sbatch option equallity is achieved if the keys of the options
#' are the same.
#'
#' @param opt_1 An sbatch option string.
#'
#' @param opt_2 An sbatch option string.
#'
#' @return A boolean value.
sbatch_opts_equal <- function(opt_1, opt_2) {
    return(sbatch_opt_key(opt_1) == sbatch_opt_key(opt_2))
}


#' Insert an sbatch option into a set.
#'
#' @param opt The sbatch option to insert
#'
#' @param opts A set of sbatch options. Default value is the empty
#' set.
#'
#' @return A set with \code{opt} inserted.
sbatch_opts_insert <- function(opt, opts = c()) {
    did_set <- FALSE

    for (i in 1:length(opts)) {
        if (sbatch_opts_equal(opt, opts[i])) {
            opts[i] = opt
            did_set = TRUE
        }
    }

    if(!did_set) {
        opts <- c(opts, opt)
    }

    return(opts)
}


#' Get the key of an sbatch.
#'
#' @param opt An sbatch option string.
#'
#' @return The \code{opt}'s key.
sbatch_opt_key <- function(opt) {
    return(strsplit(opt, "=")[[1]][1])
}


#' Get the value of an sbatch option.
#'
#' @param opt An sbatch option string.
#'
#' @return The \code{opt}'s value.
sbatch_opt_value <- function(opt) {
    return(strsplit(opt, "=")[[1]][2])
}


#' A list of sbatch options.
#'
#' The value of each item in the list is a string or a function
#' which takes a string as a parameter, using \code{sbatch_opt}.
#'
#' To ensure proper formatting, the \code{mail_type} option should
#' be set using \code{sbatch_mail_types}. Multiple mail types need
#' to be comma seperated.
#'
#' @export
sbatch_opts <- list (
    begin = sbatch_opt("begin"),
    cpus_per_task = sbatch_opt("cpus-per-task"),
    mail_user = sbatch_opt("mail-user"),
    memory = sbatch_opt("mem"),
    nodes = sbatch_opt("nodes"),
    output = sbatch_opt("output"),
    time = sbatch_opt("time")
)


#' A list of sbatch mail types.
#'
#' The value of each item in the list is a string representing
#' a mail type option.
#'
#' @export
sbatch_mail_type_opts <- list(
    all = sbatch_opt("mail-type")("ALL"),
    begin = sbatch_opt("mail-type")("BEGIN"),
    end = sbatch_opt("mail-type")("END"),
    fail = sbatch_opt("mail-type")("FAIL"),
    none = sbatch_opt("mail-type")("NONE"),
    requeue = sbatch_opt("mail-type")("REQUEUE"),
    stage_out = sbatch_opt("mail-type")("STAGE_OUT"),
    time_limit = sbatch_opt("mail-type")("TIME_LIMIT"),
    time_limit_90 = sbatch_opt("mail-type")("TIME_LIMIT_90"),
    time_limit_80 = sbatch_opt("mail-type")("TIME_LIMIT_80"),
    time_limit_50 = sbatch_opt("mail-type")("TIME_LIMIT_50")
)


#' Create single sbatch mail type key value pair.
#'
#' A user may specific multiple \code{sbatch_mail_type_opts},
#' which must be combined into a single key value pair that
#' contains the options seperated by commas.
#'
#' @param opts A list of sbatch mail type options.
sbatch_mail_type_combine <- function(opts) {
    opt_keys <- sapply(opts, sbatch_opt_key, USE.NAMES = FALSE)
    mail_type_opts <- which(opt_keys == "--mail-type")

    mail_type_opt_vals <- sapply(opts[mail_type_opts], sbatch_opt_value,
                                 USE.NAMES = FALSE)
    mail_type_opt_val <- paste(unique(mail_type_opt_vals), collapse = ",")
    mail_type_opt <- sbatch_opt("mail-type")(mail_type_opt_val)

    return(c(opts[-mail_type_opts], mail_type_opt))
}


#' Fill in dependency list placeholders.
#'
#' The placeholders \code{PREVIOUS(ALL)} and \code{PREVIOUS(<n>)} can be used in
#' a sbatch dependency list and are replaced by all or n of the previous
#' submission job ids.
#'
#' @param dep_list The string dependency list value of the key-value pair
#' for a sbatch dependency list options.
#'
#' @param job_id_sub_history An array of job ids ordered oldest to newest.
#'
#' @return A dependency list with the proper job ids in the list.
sbatch_dependency_list <- function(dep_list, job_id_sub_history) {
    # Order from newest to oldest.
    job_id_sub_history <- rev(job_id_sub_history)

    regex <- "PREVIOUS[(]([1-9]+)[)]"
    to_replace <- stringr::str_match_all(dep_list, regex)[[1]]

    if (length(to_replace) > 0) {
        to_replace <- as.data.frame(to_replace)
        colnames(to_replace) <- c("regexp", "n")
        to_replace$n <- as.numeric(as.character(to_replace$n))
        to_replace$regexp <- as.character(to_replace$regexp)

        # Create a literal parentheses regex expression.
        to_replace$regexp <- sapply(to_replace$regexp, function(exp) {
            exp <- gsub("[(]", "[(]", exp)
            exp <- gsub("[)]", "[)]", exp)
            return(exp)
        })

        prev_n_jobs <- function(n) {
            job_ids <- job_id_sub_history[1:n]
            job_ids <- job_ids[!is.na(job_ids)]
            return(paste(job_ids, collapse = ":"))
        }

        to_replace$replacement <- sapply(to_replace$n, prev_n_jobs)

        for (i in length(to_replace$replacement)) {
            row <- to_replace[i, ]
            dep_list <- gsub(row$regexp, row$replacement, dep_list)
        }
    }

    regex <- "PREVIOUS[(]ALL[)]"
    dep_list <- gsub(regex, paste(job_id_sub_history, collapse = ":"), dep_list)

    return(dep_list)
}
context("sbatch")


test_that("All options are formated correctly", {
    expect_equal(sbatch_opts$begin("00:00:01"), "--begin=00:00:01")
    expect_equal(sbatch_opts$cpus_per_task(12), "--cpus-per-task=12")
    expect_equal(sbatch_opts$mail_user("user@address"),
                 "--mail-user=user@address")
    expect_equal(sbatch_opts$memory(1200), "--mem=1200")
    expect_equal(sbatch_opts$memory("16g"), "--mem=16g")
    expect_equal(sbatch_opts$nodes(1), "--nodes=1")
    expect_equal(sbatch_opts$output("file.txt"), "--output=file.txt")
    expect_equal(sbatch_opts$time("00:00:01"), "--time=00:00:01")
})

test_that("sbatch_opt creates a new key-value option.", {
    expect_equal(sbatch_opt("key")("value"), "--key=value")
})

test_that("Options equality is base on option keys.", {
    a <- sbatch_opt("a")("true")
    b <- sbatch_opt("b")("false")
    a_ <- sbatch_opt("a")("false")

    expect_true(sbatch_opts_equal(a, a_))
    expect_false(sbatch_opts_equal(a, b))

    expect_equal(sbatch_opts_insert(a_, c(a, b)), c(a_, b))
    expect_equal(sbatch_opts_insert(a, c(b)), c(b, a))
})

test_that("Multiple sbatch mail type options are combined while other options
          remain the same.", {
    # Note that the option duplication is on purpose.
    opts <- c(
        sbatch_mail_type_opts$begin,
        sbatch_mail_type_opts$begin,
        sbatch_mail_type_opts$end,
        sbatch_mail_type_opts$fail,
        sbatch_opts$memory("16g")
    )

    expected <- c(
        sbatch_opts$memory("16g"),
        sbatch_opt("mail-type")("BEGIN,END,FAIL")
    )

    expect_equal(sbatch_mail_type_combine(opts), expected)
})

test_that("Dependency list macros are replaced with correct job ids.", {
    job_history <- c("1", "2", "3", "4")

    expect_equal(sbatch_dependency_list("after:PREVIOUS(1)", job_history),
                 "after:4")
    expect_equal(sbatch_dependency_list("after:PREVIOUS(2)", job_history),
                 "after:4:3")
    expect_equal(sbatch_dependency_list("after:PREVIOUS(3)", job_history),
                 "after:4:3:2")
    expect_equal(sbatch_dependency_list("after:PREVIOUS(4)", job_history),
                 "after:4:3:2:1")
    expect_equal(sbatch_dependency_list("after:PREVIOUS(5)", job_history),
                 "after:4:3:2:1")
    expect_equal(sbatch_dependency_list("after:PREVIOUS(ALL)", job_history),
                 "after:4:3:2:1")
})
#formats and combines phenotype (of a single trait)
#and genotype datasets of multiple
#populations

options(echo = FALSE)

library(stats)
library(stringr)
library(randomForest)
library(plyr)
library(lme4)
library(data.table)


allArgs <- commandArgs()

inFile <- grep("input_files",
               allArgs,
               ignore.case = TRUE,
               perl = TRUE,
               value = TRUE
               )

outFile <- grep("output_files",
                allArgs,
                ignore.case = TRUE,
                perl = TRUE,
                value = TRUE
                )

outFiles <- scan(outFile,
                 what = "character"
                 )

combinedGenoFile <- grep("genotype_data",
                         outFiles,
                         ignore.case = TRUE,
                         fixed = FALSE,
                         value = TRUE
                         )

combinedPhenoFile <- grep("phenotype_data",
                          outFiles,
                          ignore.case = TRUE,
                          fixed = FALSE,
                          value = TRUE
                          )

inFiles <- scan(inFile,
                what = "character"
                )
print(inFiles)

traitFile <- grep("trait_",
                  inFiles,
                  ignore.case = TRUE,
                  fixed = FALSE,
                  value = TRUE
                  )

trait <- scan(traitFile,
              what = "character",
              )

traitInfo<-strsplit(trait, "\t");
traitId<-traitInfo[[1]]
traitName<-traitInfo[[2]]

#extract trait phenotype data from all populations
#and combine them into one dataset

allPhenoFiles <- grep("phenotype_data",
                  inFiles,
                  ignore.case = TRUE,
                  fixed = FALSE,
                  value = TRUE
                  )
message("phenotype files: ", allPhenoFiles)

allGenoFiles <- grep("genotype_data",
                  inFiles,
                  ignore.case = TRUE,
                  fixed = FALSE,
                  value = TRUE
                  )

popsPhenoSize     <- length(allPhenoFiles)
popsGenoSize      <- length(allGenoFiles)
popIds            <- c()
combinedPhenoPops <- c()

for (popPhenoNum in 1:popsPhenoSize)
  {
    popId <- str_extract(allPhenoFiles[[popPhenoNum]], "\\d+")
    popIds <- append(popIds, popId)

    phenoData <- fread(allPhenoFiles[[popPhenoNum]],
                            na.strings = c("NA", " ", "--", "-", "."),
                           )


    phenoTrait <- subset(phenoData,
                         select = c("object_name", "object_id", "design", "block", "replicate", traitName)
                         )
  
    experimentalDesign <- phenoTrait[2, 'design']
    
    if (is.na(experimentalDesign) == TRUE) {experimentalDesign <- c('No Design')}

    if ((experimentalDesign == 'Augmented' || experimentalDesign == 'RCBD')  &&  unique(phenoTrait$block) > 1) { 

      message("experimental design: ", experimentalDesign)

      augData <- subset(phenoTrait,
                        select = c("object_name", "object_id",  "block",  traitName)
                        )

      colnames(augData)[1] <- "genotypes"
      colnames(augData)[4] <- "trait"

      model <- try(lmer(trait ~ 0 + genotypes + (1|block),
                        augData,
                        na.action = na.omit
                        ))
     
      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
        
        colnames(phenoTrait) <- traitName

        nn <- gsub('genotypes', '', rownames(phenoTrait))  
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
  
        formattedPhenoData[, traitName] <- phenoTrait
      }
      
    } else if (experimentalDesign == 'Alpha') {

      alphaData <-  phenoTrait 

      colnames(alphaData)[1] <- "genotypes"
      colnames(alphaData)[5] <- "trait"
         
      model <- try(lmer(trait ~ 0 + genotypes + (1|replicate/block),
                        alphaData,
                        na.action = na.omit
                        ))
        
      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
      
        colnames(phenoTrait) <- traitName

        nn <- gsub('genotypes', '', rownames(phenotrait))     
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)

        formattedPhenoData[, i] <- phenoTrait
      }
      
  } else {

    phenoTrait <- subset(phenoData,
                         select = c("object_name", "stock_id", traitName)
                         )
    
    if (sum(is.na(phenoTrait)) > 0) {
      message("No. of pheno missing values: ", sum(is.na(phenoTrait))) 
     
      phenoTrait <- na.omit(phenoTrait)
       
      #calculate mean of reps/plots of the same accession and
      #create new df with the accession means
      phenoTrait$stock_id <- NULL
      phenoTrait   <- phenoTrait[order(row.names(phenoTrait)), ]
   
      print('phenotyped lines before averaging')
      print(length(row.names(phenoTrait)))
        
      phenoTrait<-ddply(phenoTrait, "object_name", colwise(mean))
        
      print('phenotyped lines after averaging')
      print(length(row.names(phenoTrait)))
   
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1] <- NULL

      phenoTrait <- round(phenoTrait, digits = 2)

    } else {
      print ('No missing data')
      phenoTrait$stock_id <- NULL
      phenoTrait   <- phenoTrait[order(row.names(phenoTrait)), ]
   
      print('phenotyped lines before averaging')
      print(length(row.names(phenoTrait)))
      
      phenoTrait<-ddply(phenoTrait, "object_name", colwise(mean))
      
      print('phenotyped lines after averaging')
      print(length(row.names(phenoTrait)))

      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1] <- NULL

      phenoTrait <- round(phenoTrait, digits = 2)

    }
  }    
    newTraitName = paste(traitName, popId, sep = "_")
    colnames(phenoTrait)[1] <- newTraitName

    if (popPhenoNum == 1 )
      {
        print('no need to combine, yet')       
        combinedPhenoPops <- phenoTrait
        
      } else {
      print('combining...') 
      combinedPhenoPops <- merge(combinedPhenoPops, phenoTrait,
                            by = 0,
                            all=TRUE,
                            )

      rownames(combinedPhenoPops) <- combinedPhenoPops[, 1]
      combinedPhenoPops$Row.names <- NULL
      
    }   
}

#fill in missing data in combined phenotype dataset
#using row means
naIndices <- which(is.na(combinedPhenoPops), arr.ind=TRUE)
combinedPhenoPops <- as.matrix(combinedPhenoPops)
combinedPhenoPops[naIndices] <- rowMeans(combinedPhenoPops, na.rm=TRUE)[naIndices[,1]]
combinedPhenoPops <- as.data.frame(combinedPhenoPops)

message("combined total number of stocks in phenotype dataset (before averaging): ", length(rownames(combinedPhenoPops)))

combinedPhenoPops$Average<-round(apply(combinedPhenoPops,
                                       1,
                                       function(x)
                                       { mean(x) }
                                       ),
                                 digits = 2
                                 )

markersList      <- c()
combinedGenoPops <- c()

for (popGenoNum in 1:popsGenoSize)
  {
    popId <- str_extract(allGenoFiles[[popGenoNum]], "\\d+")
    popIds <- append(popIds, popId)

    genoData <- fread(allGenoFiles[[popGenoNum]],
                            na.strings = c("NA", " ", "--", "-"),
                           )

    genoData           <- as.data.frame(genoData)
    rownames(genoData) <- genoData[, 1]
    genoData[, 1]      <- NULL
    
    popMarkers <- colnames(genoData)
    message("No of markers from population ", popId, ": ", length(popMarkers))
    
    message("sum of geno missing values: ", sum(is.na(genoData)))
    genoData <- genoData[, colSums(is.na(genoData)) < nrow(genoData) * 0.5]
    message("sum of geno missing values: ", sum(is.na(genoData)))

    if (sum(is.na(genoData)) > 0)
      {
        message("sum of geno missing values: ", sum(is.na(genoData)))
        genoData <- na.roughfix(genoData)
        message("total number of stocks for pop ", popId,": ", length(rownames(genoData)))
      }

    if (popGenoNum == 1 )
      {
        print('no need to combine, yet')       
        combinedGenoPops <- genoData
        
      } else {
        print('combining genotype datasets...') 
        combinedGenoPops <-rbind(combinedGenoPops, genoData)
      }   
    
 
  }
message("combined total number of stocks in genotype dataset: ", length(rownames(combinedGenoPops)))
#discard duplicate clones
combinedGenoPops <- unique(combinedGenoPops)
message("combined unique number of stocks in genotype dataset: ", length(rownames(combinedGenoPops)))

message("writing data into files...")
#if(length(combinedPhenoFile) != 0 )
#  {
      write.table(combinedPhenoPops,
                  file = combinedPhenoFile,
                  sep = "\t",
                  quote = FALSE,
                  col.names = NA,
                  )
#  }

#if(length(combinedGenoFile) != 0 )
#  {
      write.table(combinedGenoPops,
                  file = combinedGenoFile,
                  sep = "\t",
                  quote = FALSE,
                  col.names = NA,
                  )
#  }

q(save = "no", runLast = FALSE)
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #

#             dddddddd                                                                    
#             d::::::d  iiii                                          RRRRRRRRRRRRRRRRR   
#             d::::::d i::::i                                         R::::::::::::::::R  
#             d::::::d  iiii                                          R::::::RRRRRR:::::R 
#             d:::::d                                                 RR:::::R     R:::::R
#     ddddddddd:::::d iiiiiiivvvvvvv           vvvvvvvaaaaaaaaaaaaa     R::::R     R:::::R
#   dd::::::::::::::d i:::::i v:::::v         v:::::v a::::::::::::a    R::::R     R:::::R
#  d::::::::::::::::d  i::::i  v:::::v       v:::::v  aaaaaaaaa:::::a   R::::RRRRRR:::::R 
# d:::::::ddddd:::::d  i::::i   v:::::v     v:::::v            a::::a   R:::::::::::::RR  
# d::::::d    d:::::d  i::::i    v:::::v   v:::::v      aaaaaaa:::::a   R::::RRRRRR:::::R 
# d:::::d     d:::::d  i::::i     v:::::v v:::::v     aa::::::::::::a   R::::R     R:::::R
# d:::::d     d:::::d  i::::i      v:::::v:::::v     a::::aaaa::::::a   R::::R     R:::::R
# d::::::ddddd::::::ddi::::::i       v:::::::v      a::::a    a:::::a RR:::::R     R:::::R
#  d:::::::::::::::::di::::::i        v:::::v       a:::::aaaa::::::a R::::::R     R:::::R
#   d:::::::::ddd::::di::::::i         v:::v         a::::::::::aa:::aR::::::R     R:::::R
#    ddddddddd   dddddiiiiiiii          vvv           aaaaaaaaaa  aaaaRRRRRRRR     RRRRRRR

#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #

# # # bug in plot_train for continuous? or two feature?
# # # bug in plot where those stray points appear at origin and max
# # # need to test batch

# # # load utilities script
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
source('utils.r')

# # # Initialize model parameters
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
model <- list(num_blocks    = 20,
			  num_inits     = 5,
			  wts_range     = 1,
			  num_hids      = 3,
			  learning_rate = 0.15,
			  beta_val      = 5,
			  out_rule      = 'sigmoid') # linear / tan not implemented

# # # run demo ? 
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
demo <- TRUE  # run demo
# demo <- FALSE # do something else

if (demo == TRUE) {
  # # # create training results 
  training = matrix(rep(0, model$num_blocks * 7), ncol = 7)
  
  # # # initialize model and run it on each SHJ category structure
  for (shj in 1:7) { 

    # # # get shj stimuli
    cases <- shj_cats(shj)
    model$inputs <- cases$inputs
    model$labels <- cases$labels

    # # # train model
    result <- run_diva(model)

  # # # add result to training matrix
  training[,shj] <- result$training

  }

  # # # display results
  print(training)
  train_plot(training)
  save.image('diva_run.rdata')
}

# warnings()


suppressMessages (library(shiny))
suppressMessages (library(ggplot2))
suppressMessages (library(ggrepel))
suppressMessages (library(scales))
suppressMessages (library(DT))
suppressMessages (library(tidyr))
suppressMessages (library(dplyr))
suppressMessages (library(ggkm))
suppressMessages (library(Hmisc))
suppressMessages (library(quantreg))



stat_sum_df <- function(fun, geom="point", ...) {
  stat_summary(fun.data=fun,  geom=geom,  ...)
}
stat_sum_single <- function(fun, geom="point", ...) {
  stat_summary(fun.y=fun,  geom=geom,  ...)
}

median.n <- function(x){
  return(c(y = ifelse(median(x)<0,median(x),median(x)),
           label = round(median(x),2))) 
}
give.n <- function(x){
  return(c(y = min(x)*1,  label = length(x))) 
}

options(shiny.maxRequestSize=100*1024^2) 
#options(shiny.reactlog=TRUE) 
tableau10 <- c("#1F77B4","#FF7F0E","#2CA02C","#D62728","#9467BD",
               "#8C564B","#E377C2","#7F7F7F","#BCBD22","#17BECF")



ui  <-  fluidPage(
    titlePanel("Hello GHAP HBGDki Member!"),
    sidebarLayout(
  sidebarPanel(
    tabsetPanel(
      tabPanel("Inputs", 
               fileInput("datafile", "Choose csv file to upload",
                         multiple = FALSE, accept = c("csv")),
               uiOutput("ycol"),uiOutput("xcol"),
               tabsetPanel(id = "filtercategorize",
                           tabPanel("Categorize/Rename", 
                                    uiOutput("catvar"),
                                    uiOutput("ncuts"),
                                    uiOutput("catvar2"),
                                    uiOutput("catvar3"),
                                    uiOutput("ncuts2"),
                                    uiOutput("asnumeric"),
                                    textOutput("bintext"),
                                    uiOutput("catvar4"),
                                    textOutput("labeltext"),
                                    uiOutput("nlabels")
                                    ),
                           
                           tabPanel("Combine Variables", 
                                    uiOutput("pastevar")
                           ),
                           tabPanel("Filters", 
                                    uiOutput("maxlevels"),
                                    uiOutput("filtervar1"),
                                    uiOutput("filtervar1values"),
                                    uiOutput("filtervar2"),
                                    uiOutput("filtervar2values"),
                                    uiOutput("filtervar3"),
                                    uiOutput("filtervar3values"),
                                    uiOutput("filtervarcont1"),
                                    uiOutput("fslider1"),
                                    uiOutput("filtervarcont2"),
                                    uiOutput("fslider2"),
                                    uiOutput("filtervarcont3"),
                                    uiOutput("fslider3")
                           ),
                           tabPanel("Simple Rounding",
                                    uiOutput("roundvar"),
                                    numericInput("rounddigits",label = "N Digits",value = 0,min=0,max=10) 
                           ),
                           tabPanel("Reorder Variables", 
                                    uiOutput("reordervar"),
                                    conditionalPanel(condition = "input.reordervarin!='' " ,
                                                     selectizeInput(  "functionordervariable", 'The:',
                                                                      choices =c("Median","Mean","Minimum","Maximum") ,multiple=FALSE)
                                    ),
                                    uiOutput("variabletoorderby"),
                                    conditionalPanel(condition = "input.reordervarin!='' " ,
                                                     checkboxInput('reverseorder', 'Reverse Order ?', value = FALSE) ),
                                    
                                    uiOutput("reordervar2"),
                                    uiOutput("reordervar2values")
                           )
               ),
               hr()
      ), # tabsetPanel
      
      
      tabPanel("Graph Options",
               tabsetPanel(id = "graphicaloptions",
                           tabPanel(  "X/Y Log /Labels",
                                      hr(),
                                      textInput('ylab', 'Y axis label', value = "") ,
                                      textInput('xlab', 'X axis label', value = "") ,
                                      hr(),
                                      checkboxInput('logy', 'Log Y axis', value = FALSE) ,
                                      checkboxInput('logx', 'Log X axis', value = FALSE) ,
                                      conditionalPanel(condition = "!input.logy" ,
                                                       checkboxInput('scientificy', 'Comma separated Y axis ticks', value = FALSE)),
                                      conditionalPanel(condition = "!input.logx" ,
                                                       checkboxInput('scientificx', 'Comma separated X axis ticks', value = FALSE)),
                                      checkboxInput('rotateyticks', 'Rotate/Justify Y axis Ticks ?', value = FALSE),
                                      checkboxInput('rotatexticks', 'Rotate/Justify X axis Ticks ?', value = FALSE),
                                      conditionalPanel(condition = "input.rotateyticks" , 
                                                       sliderInput("yticksrotateangle", "Y axis ticks angle:", min=0, max=360, value=c(0),step=10),
                                                       sliderInput("ytickshjust", "Y axis ticks horizontal justification:", min=0, max=1, value=c(0.5),step=0.1),
                                                       sliderInput("yticksvjust", "Y axis ticks vertical justification:", min=0, max=1, value=c(0.5),step=0.1)
                                      ),
                                      conditionalPanel(condition = "input.rotatexticks" , 
                                                       sliderInput("xticksrotateangle", "X axis ticks angle:", min=0, max=360, value=c(20),step=10),
                                                       sliderInput("xtickshjust", "X axis ticks horizontal justification:", min=0, max=1, value=c(1),step=0.1),
                                                       sliderInput("xticksvjust", "X axis ticks vertical justification:", min=0, max=1, value=c(1),step=0.1)
                                      )
                                      
                           ),
                           tabPanel(  "Graph Size/Zoom",
                                      sliderInput("height", "Plot Height", min=1080/4, max=1080, value=480, animate = FALSE),
                                      h6("X Axis Zoom only works if facet x scales are not set to be free."),
                                      uiOutput("xaxiszoom")
                                      
                           ),
                           
                           tabPanel(  "Background Color and Legend Position",
                                      selectInput('backgroundcol', label ='Background Color',
                                                  choices=c("Gray" ="gray97","White"="white","Dark Gray"="grey90"),
                                                  multiple=FALSE, selectize=TRUE,selected="white"),
                                      selectInput('legendposition', label ='Legend Position',
                                                  choices=c("left", "right", "bottom", "top","none"),
                                                  multiple=FALSE, selectize=TRUE,selected="bottom"),
                                      selectInput('legenddirection', label ='Layout of Items in Legends',
                                                  choices=c("horizontal", "vertical"),
                                                  multiple=FALSE, selectize=TRUE,selected="horizontal"),
                                      selectInput('legendbox', label ='Arrangement of Multiple Legends ',
                                                  choices=c("horizontal", "vertical"),
                                                  multiple=FALSE, selectize=TRUE,selected="vertical")
                           ),
                           tabPanel(  "Facets Options",
                                      
                                      uiOutput("facetscales"),
                                      selectInput('facetspace' ,'Facet Spaces:',c("fixed","free_x","free_y","free")),
                                      
                                      selectizeInput(  "facetswitch", "Facet Switch to Near Axis:",
                                                       choices = c("x","y","both"),
                                                       options = list(  maxItems = 1 ,
                                                                        placeholder = 'Please select an option',
                                                                        onInitialize = I('function() { this.setValue(""); }')  )  ),
                                      checkboxInput('facetmargin', 'Show Facet(s) Margin(s) ?'),
                                      
                                      selectInput('facetlabeller' ,'Facet Label:',c(
                                        "Variable(s) Name(s) and Value(s)" ="label_both",
                                        "Value(s)"="label_value",
                                        "Parsed Expression" ="label_parsed"),
                                        selected="label_both"),
                                      
                                      checkboxInput('facetwrap', 'Use facet_wrap?'),
                                      conditionalPanel(condition = "input.facetwrap" ,
                                                       checkboxInput('customncolnrow', 'Control N columns an N rows?')),
                                      conditionalPanel(condition = "input.customncolnrow" ,
                                                       h6("An error (nrow*ncol >= n is not TRUE) will show up if the total number of facets/panels is greater than the product of the specified  N columns x N rows. Increase the N columns and/or N rows to avoid the error. The default empty values will use ggplot automatic algorithm."),        
                                                       numericInput("wrapncol",label = "N columns",value =NA,min=1,max =10) ,
                                                       numericInput("wrapnrow",label = "N rows",value = NA,min=1,max=10) 
                                      )
                                      
                           ) ,
                           
                           tabPanel(  "Reference Lines",
                                      checkboxInput('identityline', 'Identity Line')    ,   
                                      checkboxInput('horizontalzero', 'Horizontol Zero Line'),
                                      checkboxInput('customline1', 'Vertical Line'),
                                      conditionalPanel(condition = "input.customline1" , 
                                                       numericInput("vline",label = "",value = 1) ),
                                      checkboxInput('customline2', 'Horizontal Line'),
                                      conditionalPanel(condition = "input.customline2" , 
                                                       numericInput("hline",label = "",value = 1) )
                           ),
                           tabPanel(  "Additional Themes Options",
                                      sliderInput("themebasesize", "Theme Size (affects all text elements in the plot):", min=1, max=100, value=c(16),step=1),
                                      checkboxInput('themetableau', 'Use Tableau Colors and Fills ? (maximum of 10 colours are provided)',value=TRUE),
                                      conditionalPanel(condition = "input.themetableau" ,
                                                       h6("If you have more than 10 color groups the plot will not work and you get /Error: Insufficient values in manual scale. ## needed but only 10 provided./  Uncheck Use Tableau Colors and Fills to use default ggplot2 colors.")),
                                      checkboxInput('themecolordrop', 'Keep All levels of Colors and Fills ?',value=TRUE) , 
                                      
                                      checkboxInput('themebw', 'Use Black and White Theme ?',value=TRUE), 
                                      checkboxInput('themeaspect', 'Use custom aspect ratio ?')   ,  
                                      conditionalPanel(condition = "input.themeaspect" , 
                                                       numericInput("aspectratio",label = "Y/X ratio",
                                                                    value = 1,min=0.1,max=10,step=0.01)),
                                      checkboxInput('sepguides', 'Separate Legend Guides for Median/PI ?',value = TRUE),       
                                      checkboxInput('labelguides', 'Hide the Names of the Guides ?',value = FALSE)  
                           ) #tabpanel
               )#tabsetpanel
      ), # tabpanel
      #) ,#tabsetPanel(),
      
      tabPanel("How To",
               h5("1. Upload your data file in CSV format. R default options for read.csv will apply except for missing values where both (NA) and dot (.) are treated as missing. If your data has columns with other non-numeric missing value codes then they be treated as factors."),
               h5("2. The UI is dynamic and changes depending on your choices of options, x ,y, filter, group and so on."),
               h5("3. It is assumed that your data is tidy and ready for plotting (long format)."),
               h5("4. x and y variable(s) input allow numeric and factor variables."),
               h5("5. You can now select more than one y variable. The data will always be automatically stacked using tidyr::gather and result in yvars and yvalues variables.if you select factor and continuous variables, all selected variables will be transformed to factor. The internal variable yvalues is used for y variable mapping and you can select yvars for facetting. The app automatically select additional row split as yvars and set Facet Scales to free_y. To change Facet Scales and many other options go to Graph Options tab."),
               h5("6. Inputs, Categorize, Recode into Binned Categories: Include the numeric variable to change to categorical in the list and then choose a number of cuts (default is 3). This helps when you want to group or color by cuts of a continuous variable."),
               h5("7. Inputs, Categorize, Treat as Categories: This changes a numeric variable to factor without binning. This helps when you want to group or color by numerical variable that has few unique values e.g. 1,2,3."),
               h5("8. Inputs, Categorize, Custom cuts: You can cut a numeric variable to factor using specified cutoffs, by default the min, median, max are used."),
               h5("9.Inputs, Categorize, Treat as Numeric: This checkbox recodes categorical/factor variables to numeric values that start with 0. This is useful to recode Yes/No to 1/0 and overlay a logistic smooth. Numeric Codes/values correspondence are shown in text below the checkbox."),
               h5("10.Inputs, Categorize, Combine Variables: This allows to paste together two variables (e.g. Sex with values: Male and Female and Treatment with values: TRT1, TRT2 and TRT3) to construct a new one called combinedvariable with values: Male TRT1, Male TRT2, Male TRT3, Female TRT1, Female TRT2, Female TRT3. Once specified the combinedvariable becomes available to color, group and any other mapping"),
               h5("11. Inputs, Filters: There is six slots for Filter variables. Filter variables 1, 2,3,4,5 and 6 are applied sequentially. Values shown for filter variable 2 will depend on your selected data exclusions using filter variable 1 and so on. The first three filters accept numeric and non numeric columns while the last three are sliders and only work with numeric variables. For performance improvement the first three filters only show variables with a default maximum number of levels of 500 but you can increase it to your needs."),
               
               h5("12. New ! You can use additional smoothing functions including linear and logistic fits. Please make sure that data is compatible with the smoothing used i.e. for logistic a 0/1 variable is expected."),
               h5("13. Additional support to include boxplots. More work/feedback needed. Boxplots grouping might not be what is intented when the x axis variable is continuous, you can change the Group By: variable in the Color/Group/Split/Size/Fill Mappings (?) to better reflect your needs."),
               h5("14. Initial support to enable Kaplan-Meier Plots."),
               h5("15. Download the plot using the options on the 'Download' tab. This section is based on code from Mason DeCamillis ggplotLive app."),
               h5("16. Visualize the data table in the 'Data' tab. You can reorder the columns, filter and much more."),
               p(),
               h5("Samer Mouksassi 2016"),
               h5("Contact me @ samermouksassi@gmail.com for feedback/Bugs/features requests!")
               
      )# tabpanel 
    )
  ), #sidebarPanel
  mainPanel(
    tabsetPanel(
      tabPanel("Plot"  , 
               uiOutput('ui_plot'),
               hr(),
               uiOutput("clickheader"),
               tableOutput("plot_clickedpoints"),
               uiOutput("brushheader"),
               tableOutput("plot_brushedpoints"),
               #actionButton("plotButton", "Update Plot"),
               uiOutput("optionsmenu") ,
               
               conditionalPanel(
                 condition = "input.showplottypes" , 
                 
                 fluidRow(
                   
                   column (12, hr()),
                   column (3,
                           radioButtons("Points", "Points/Jitter:",
                                        c("Points" = "Points",
                                          "Jitter" = "Jitter",
                                          "None" = "None")),
                           conditionalPanel( " input.Points!= 'None' ",
                                             sliderInput("pointstransparency", "Points Transparency:", min=0, max=1, value=c(0.5),step=0.01),
                                             checkboxInput('pointignorecol', 'Ignore Mapped Color')
                           )),
                   column(3,
                          conditionalPanel( " input.Points!= 'None' ",
                                            sliderInput("pointsizes", "Points Size:", min=0, max=4, value=c(1),step=0.1),
                                            numericInput('pointtypes','Points Type:',16, min = 1, max = 25),
                                            conditionalPanel( " input.pointignorecol ",
                                                              selectInput('colpoint', label ='Points Color', choices=colors(),multiple=FALSE, selectize=TRUE, selected="black") 
                                            )
                          )
                   ),                  
                   column(3,
                          radioButtons("line", "Lines:",
                                       c("Lines" = "Lines",
                                         "None" = "None"),selected="None"),
                          conditionalPanel( " input.line== 'Lines' ",
                                            sliderInput("linestransparency", "Lines Transparency:", min=0, max=1, value=c(0.5),step=0.01),
                                            checkboxInput('lineignorecol', 'Ignore Mapped Color')
                          )
                          
                   ),
                   column(3,
                          conditionalPanel( " input.line== 'Lines' ",
                                            sliderInput("linesize", "Lines Size:", min=0, max=4, value=c(1),step=0.1),
                                            selectInput('linetypes','Lines Type:',c("solid","dotted")),
                                            conditionalPanel( " input.lineignorecol ",
                                                              selectInput('colline', label ='Lines Color', choices=colors(),multiple=FALSE, selectize=TRUE,selected="black") 
                                            )
                          ),
                          checkboxInput('boxplotaddition', 'Add a Boxplot ? (makes sense if x variable is categorical and
                                        you Group By a sensible choice. By default the x variable is used for grouping)'),
                          checkboxInput('boxplotignoregroup', 'Ignore Mapped Group ? (can me helpful to superpose a loess or median on top of the boxplot)')
                          
                   ),
                   column (12, h6("Points and Lines Size will apply only if Size By: in the Color Group Split Size Fill Mappings are set to None"))
                   
                 )#fluidrow
               ) ,
               conditionalPanel(
                 condition = "input.showfacets" , 
                 fluidRow(
                   column (12, hr()),
                   column (3, uiOutput("colour"),uiOutput("group")),
                   column(3, uiOutput("facet_col"),uiOutput("facet_row")),
                   column (3, uiOutput("facet_col_extra"),uiOutput("facet_row_extra")),
                   column (3, uiOutput("pointsize"),uiOutput("fill")),
                   column (12, h6("Make sure not to choose a variable that is in the y variable(s) list otherwise you will get an error Variable not found. These variables are stacked and become yvars and yvalues." ))
                   
                 )
               ),
               
               #rqss quantile regression
               conditionalPanel(
                 condition = "input.showrqss" , 
                 
                 fluidRow(
                   column(12,hr()),
                   column(3,
                          checkboxInput('Tauvalue', 'Dynamic and Preset Quantiles', value = FALSE),
                          h5("Preset Quantiles"),
                          checkboxInput('up', '95%'),
                          checkboxInput('ninetieth', '90%'),
                          checkboxInput('mid', '50%', value = FALSE),
                          checkboxInput('tenth', '10%'),
                          checkboxInput('low', '5%')
                   ),
                   column(5,
                          sliderInput("Tau", label = "Dynamic Quantile Value:",
                                      min = 0, max = 1, value = 0.5, step = 0.01)  ,
                          sliderInput("Penalty", label = "Spline sensitivity adjustment:",
                                      min = 0, max = 10, value = 1, step = 0.1)  ,
                          selectInput("Constraints", label = "Spline constraints:",
                                      choices = c("N","I","D","V","C","VI","VD","CI","CD"), selected = "N")
                   ),
                   column(3,
                          checkboxInput('ignorecolqr', 'Ignore Mapped Color'),
                          checkboxInput('ignoregroupqr', 'Ignore Mapped Group',value = TRUE),
                          checkboxInput('hidedynamic', 'Hide Dynamic Quantile'),
                          selectInput('colqr', label ='QR Color', choices=colors(),multiple=FALSE, selectize=TRUE,selected="black")
                   )
                   
                 )#fluidrow
               ),
               
               conditionalPanel(
                 condition = "input.showSmooth" , 
                 
                 fluidRow(
                   column(12,hr()),
                   column (3, 
                           radioButtons("Smooth", "Smooth:",
                                        c("Smooth" = "Smooth",
                                          "Smooth and SE" = "Smooth and SE",
                                          "None" = "None"),selected="None")
                   ),
                   column (3, 
                           conditionalPanel( " input.Smooth!= 'None' ",
                                             selectInput('smoothmethod', label ='Smoothing Method',
                                                         choices=c("Loess" ="loess","Linear Fit"="lm","Logistic"="glm"),
                                                         multiple=FALSE, selectize=TRUE,selected="loess"),
                                             
                                             sliderInput("loessens", "Loess Span:", min=0, max=1, value=c(0.75),step=0.05)
                           ) 
                   ),
                   
                   
                   
                   
                   
                   column (3,  conditionalPanel( " input.Smooth!= 'None' ",
                                                 checkboxInput('ignorecol', 'Ignore Mapped Color'),
                                                 uiOutput("weight")
                   )
                   ),
                   column (3, conditionalPanel( " input.Smooth!= 'None' ",
                                                checkboxInput('ignoregroup', 'Ignore Mapped Group',value = TRUE),
                                                conditionalPanel( " input.ignorecol ",
                                                                  selectInput('colsmooth', label ='Smooth Color', choices=colors(),multiple=FALSE, selectize=TRUE,selected="black") )
                   ) )
                   
                 )#fluidrow
               )
               ,
               ### Mean CI section
               conditionalPanel(
                 condition = "input.showMean" , 
                 
                 fluidRow(
                   column(12,hr()),
                   column (3, 
                           radioButtons("Mean", "Mean:",
                                        c("Mean" = "Mean",
                                          "Mean (95% CI)" = "Mean (95% CI)",
                                          "None" = "None") ,selected="None") 
                   ),
                   column (3,
                           
                           conditionalPanel( " input.Mean== 'Mean (95% CI)' ",
                                             sliderInput("CI", "CI %:", min=0, max=1, value=c(0.95),step=0.01),
                                             numericInput( inputId = "errbar",label = "CI bar width:",value = 2,min = 1,max = NA)      
                           )
                           
                   )
                   ,
                   column (3,
                           conditionalPanel( " input.Mean!= 'None' ",
                                             checkboxInput('meanpoints', 'Show points') ,
                                             checkboxInput('meanlines', 'Show lines', value=TRUE),
                                             checkboxInput('meanignorecol', 'Ignore Mapped Color') ,
                                             conditionalPanel( " input.meanignorecol ",
                                                               selectInput('colmean', label ='Mean Color', choices=colors(),multiple=FALSE, selectize=TRUE,selected="black") )
                                             
                           ) ),
                   
                   
                   column(3,
                          conditionalPanel( " input.Mean!= 'None' ",
                                            checkboxInput('meanignoregroup', 'Ignore Mapped Group',value = TRUE),
                                            sliderInput("meanlinesize", "Mean(s) Line(s) Size:", min=0, max=3, value=1,step=0.05)
                          ) 
                   )
                 ) #fluidrow
               ), # conditional panel for mean
               
               ### median PI section
               
               
               conditionalPanel(
                 condition = "input.showMedian" , 
                 fluidRow(
                   column(12,hr()),
                   column (3,
                           radioButtons("Median", "Median:",
                                        c("Median" = "Median",
                                          "Median/PI" = "Median/PI",
                                          "None" = "None") ,selected="None") ,
                           conditionalPanel( " input.Median!= 'None' ",
                                             checkboxInput('medianvalues', 'Label Values?') ,
                                             checkboxInput('medianN', 'Label N?') )
                           
                   ),
                   column (3,
                           conditionalPanel( " input.Median== 'Median' ",
                                             checkboxInput('medianpoints', 'Show points') ,
                                             checkboxInput('medianlines', 'Show lines',value=TRUE)),
                           conditionalPanel( " input.Median== 'Median/PI' ",
                                             sliderInput("PI", "PI %:", min=0, max=1, value=c(0.95),step=0.01),
                                             sliderInput("PItransparency", "PI Transparency:", min=0, max=1, value=c(0.2),step=0.01)
                           )
                   ),
                   column (3,
                           conditionalPanel( " input.Median!= 'None' ",
                                             checkboxInput('medianignorecol', 'Ignore Mapped Color'),
                                             conditionalPanel( " input.medianignorecol ",
                                                               selectInput('colmedian', label ='Median Color', choices=colors(),multiple=FALSE, selectize=TRUE,selected="black") )
                                             
                           ) ),
                   column (3,
                           conditionalPanel( " input.Median!= 'None' ",
                                             
                                             checkboxInput('medianignoregroup', 'Ignore Mapped Group',value = TRUE),
                                             sliderInput("medianlinesize", "Median(s) Line(s) Size:", min=0, max=4, value=c(1),step=0.1)
                                             
                           )
                   )
                   
                 )#fluidrow
               ),
               ### median PI section
               
               ### KM section
               
               
               conditionalPanel(
                 condition = "input.showKM" , 
                 fluidRow(
                   column(12,hr()),
                   column (12, h6("KM curves support is currently experimental some features might not work. When a KM curve is added nothing else will be plotted (e.g. points, lines etc.).Color/Fill/Group/Facets are expected to work." )),
                   column (3,
                           radioButtons("KM", "KM:",
                                        c("KM" = "KM",
                                          "KM/CI" = "KM/CI",
                                          "None" = "None") ,selected="None") 
                   ),
                   column (3,
                           conditionalPanel( " input.KM!= 'None' ",
                                             checkboxInput('censoringticks', 'Show Censoring Ticks?') ,
                                             conditionalPanel( " input.KM== 'KM/CI' ",
                                                               sliderInput("KMCI", "KM CI:", min=0, max=1, value=c(0.95),step=0.01),
                                                               sliderInput("KMCItransparency", "KM CI Transparency:", min=0, max=1, value=c(0.2),step=0.01)
                                             )
                           )),
                   
                   column (3,
                           conditionalPanel( " input.KM!= 'None' ",
                                             selectInput('KMtrans', label ='KM Transformation',
                                                         choices=c("None" ="identity","event"="event","cumhaz"="cumhaz","cloglog"="cloglog"),
                                                         multiple=FALSE, selectize=TRUE,selected="loess")  
                           )
                   )
                 )#fluidrow
               )
               ### KM section
               
               ),#tabPanel1
      tabPanel("Download", 
               selectInput(
                 inputId = "downloadPlotType",
                 label   = h5("Select download file type"),
                 choices = list("PDF"  = "pdf","BMP"  = "bmp","JPEG" = "jpeg","PNG"  = "png")),
               
               # Allow the user to set the height and width of the plot download.
               h5(HTML("Set download image dimensions<br>(units are inches for PDF, pixels for all other formats)")),
               numericInput(
                 inputId = "downloadPlotHeight",label = "Height (inches)",value = 7,min = 1,max = 100),
               numericInput(
                 inputId = "downloadPlotWidth",label = "Width (inches)",value = 7,min = 1,max = 100),
               # Choose download filename.
               textInput(
                 inputId = "downloadPlotFileName",
                 label = h5("Enter file name for download")),
               
               # File downloads when this button is clicked.
               downloadButton(
                 outputId = "downloadPlot", 
                 label    = "Download Plot")
      ),
      
      tabPanel('Data',  dataTableOutput("mytablex") 
      )#tabPanel2
    )#tabsetPanel
  )#mainPanel
  )#sidebarLayout
)#fluidPage
server <-  function(input, output, session) {
  filedata <- reactive({
    infile <- input$datafile
    if (is.null(infile)) {
      # User has not uploaded a file yet
      return(NULL)
    }
    read.csv(infile$datapath,na.strings = c("NA","."))
    
    
  })
  
  
  
  myData <- reactive({
    df=filedata()
    if (is.null(df)) return(NULL)
  })
  
  output$optionsmenu <-  renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    
    fluidRow(
      column (12, h6("Select the checkbox(es) for the options to be showed")),
      hr(),
      column(4,checkboxInput('showplottypes',
                             'Plot types, Points, Lines (?)',
                             value = TRUE)),
      column(4,checkboxInput('showfacets',
                             'Color/Group/Split/Size/Fill Mappings (?)',
                             value = TRUE) ),
      column(4,checkboxInput('showrqss',
                             'Quantile Regression (?)',
                             value = TRUE)),
      column(4,checkboxInput('showSmooth',
                             'Smooth/Linear/Logistic Regressions (?)',
                             value = TRUE)),
      column(4,checkboxInput('showMean' , 'Mean CI (?)', value = FALSE)),
      column(4,checkboxInput('showMedian','Median PIs (?)', value = FALSE)),
      column(3,checkboxInput('showKM','Kaplan-Meier (?)', value = FALSE))
      
    )
  })
  
  output$ycol <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    selectInput("y", "y variable(s):",choices=items,selected = items[1],multiple=TRUE,selectize=TRUE)
  })
  
  output$xcol <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    selectInput("x", "x variable:",items,selected=items[2])
    
  })
  
  outputOptions(output, "ycol", suspendWhenHidden=FALSE)
  outputOptions(output, "xcol", suspendWhenHidden=FALSE)
  
  output$catvar <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    MODEDF <- sapply(df, function(x) is.numeric(x))
    NAMESTOKEEP2<- names(df)  [ MODEDF ]
    selectInput('catvarin',label = 'Recode into Binned Categories:',choices=NAMESTOKEEP2,multiple=TRUE)
  })
  
  
  output$ncuts <- renderUI({
    if (length(input$catvarin ) <1)  return(NULL)
    sliderInput('ncutsin',label = 'N of Cut Breaks:', min=2, max=10, value=c(3),step=1)
  })
  
  output$catvar2 <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    MODEDF <- sapply(df, function(x) is.numeric(x))
    NAMESTOKEEP2<- names(df)  [ MODEDF ]
    if (length(input$catvarin ) >=1) {
      NAMESTOKEEP2<-NAMESTOKEEP2 [ !is.element(NAMESTOKEEP2,input$catvarin) ]
    }
    
    selectInput('catvar2in',label = 'Treat as Categories:',choices=NAMESTOKEEP2,multiple=TRUE)
    
  })
  
  output$catvar3 <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    MODEDF <- sapply(df, function(x) is.numeric(x))
    NAMESTOKEEP2<- names(df)  [ MODEDF ]
    if (length(input$catvarin ) >=1) {
      NAMESTOKEEP2<-NAMESTOKEEP2 [ !is.element(NAMESTOKEEP2,input$catvarin) ]
    }
    if (length(input$catvar2in ) >=1) {
      NAMESTOKEEP2<-NAMESTOKEEP2 [ !is.element(NAMESTOKEEP2,input$catvar2in) ]
    }
    selectizeInput(  "catvar3in", 'Custom cuts of this variable, defaults to min, median, max before any applied filtering:',
                     choices =NAMESTOKEEP2 ,multiple=FALSE,
                     options = list(    placeholder = 'Please select a variable',
                                        onInitialize = I('function() { this.setValue(""); }')
                     )
    )
  })
  output$ncuts2 <- renderUI({
    df <-filedata()
    if (length(input$catvar3in ) <1)  return(NULL)
    if ( input$catvar3in!=""){
      textInput("xcutoffs", label =  paste(input$catvar3in,"Cuts"),
                value = as.character(paste(
                  min(df[,input$catvar3in] ,na.rm=T),
                  median(df[,input$catvar3in],na.rm=T),
                  max(df[,input$catvar3in],na.rm=T) ,sep=",")
                )
      )
    }
    
  })
  

  
  output$asnumeric <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    if (length(input$catvar3in ) <1)  return(NULL)
    if ( input$catvar3in!=""){
      column(12,
             checkboxInput('asnumericin', 'Treat as Numeric (helpful to overlay a smooth/regression line on top of a boxplot or to convert a variable into 0/1 and overlay a logistic fit', value = FALSE)
             #,checkboxInput('useasxaxislabels', 'Use the Categories Names as x axis label (makes sense only if you really chose it as x axis variable)', value = FALSE), 
             #checkboxInput('useasyaxislabels', 'Use the Categories Names as y axis label (makes sense only if you really chose it as y axis variable)', value = FALSE) 
      )
    }
  })
  
  
  outputOptions(output, "catvar", suspendWhenHidden=FALSE)
  outputOptions(output, "ncuts", suspendWhenHidden=FALSE)
  outputOptions(output, "catvar2", suspendWhenHidden=FALSE)
  outputOptions(output, "catvar3", suspendWhenHidden=FALSE)
  outputOptions(output, "ncuts2", suspendWhenHidden=FALSE)
  outputOptions(output, "asnumeric", suspendWhenHidden=FALSE)

  
  
    
  recodedata1  <- reactive({
    df <- filedata() 
    if (is.null(df)) return(NULL)
    if(length(input$catvarin ) >=1) {
      for (i in 1:length(input$catvarin ) ) {
        varname<- input$catvarin[i]
        df[,varname] <- cut(df[,varname],input$ncutsin)
        df[,varname]   <- as.factor( df[,varname])
      }
    }
    df
  })
  
  
  recodedata2  <- reactive({
    df <- recodedata1()
    if (is.null(df)) return(NULL)
    if(length(input$catvar2in ) >=1) {
      for (i in 1:length(input$catvar2in ) ) {
        varname<- input$catvar2in[i]
        df[,varname]   <- as.factor( df[,varname])
      }
    }
    df
  })
  
  recodedata3  <- reactive({
    df <- recodedata2()
    if (is.null(df)) return(NULL)
    if(input$catvar3in!="") {
      varname<- input$catvar3in
      xlimits <- input$xcutoffs 
      nxintervals <- length(as.numeric(unlist (strsplit(xlimits, ",")) )) -1
      df[,varname] <- cut( as.numeric ( as.character(  df[,varname])),
                           breaks=   as.numeric(unlist (strsplit(xlimits, ","))),include.lowest=TRUE)
      df[,"custombins"] <-   df[,varname] 
      
      if(input$asnumericin) {
        df[,varname] <- as.numeric(as.factor(df[,varname]) ) -1 
      }
    }
    
    df
  })
  output$bintext <- renderText({
    df <- recodedata3()
    if (is.null(df)) return(NULL)
    bintextout <- ""
    if(input$catvar3in!="") {
      varname<- input$catvar3in
      if(!input$asnumericin){
        bintextout <- levels(df[,"custombins"] )
      }
      if(input$asnumericin){
        bintextout <- paste( sort(unique(as.numeric(as.factor(df[,varname]) ) -1))  ,levels(df[,"custombins"] ),sep="/") 
      }}
    bintextout   
  })   
  #  xaxislabels <-levels(cut( as.numeric ( as.character( dataedafilter$month_ss)), breaks=   as.numeric(unlist (strsplit(ageglimits, ",") )),include.lowest=TRUE))
  #+ scale_x_continuous(breaks=seq(0,length(xaxislabels)-1),labels=xaxislabels )   useasxaxislabels
  output$catvar4 <- renderUI({
    df <-recodedata3()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    MODEDF <- sapply(df, function(x) is.numeric(x))
    NAMESTOKEEP2<- names(df)  [! MODEDF ]
    
    selectizeInput(  "catvar4in", 'Change labels of this variable:',
                     choices =NAMESTOKEEP2 ,multiple=FALSE,
                     options = list(    placeholder = 'Please select a variable',
                                        onInitialize = I('function() { this.setValue(""); }')
                     )
    )
  })
  
  output$labeltext <- renderText({
    df <- recodedata3()
    if (is.null(df)) return(NULL)
    labeltextout <- ""
    if(input$catvar4in!="") {
      varname<- input$catvar4in
      labeltextout <- c("Old labels",levels(df[,varname] ))
    }
    labeltextout   
  })   
  
  
  
  
  output$nlabels <- renderUI({
    df <-recodedata3()
    if (length(input$catvar4in ) <1)  return(NULL)
    if ( input$catvar4in!=""){
      nlevels <- length( unique( levels(as.factor( df[,input$catvar4in] ))))
      levelsvalues <- levels(as.factor( df[,input$catvar4in] ))
      textInput("customvarlabels", label =  paste(input$catvar4in,"requires",nlevels,"new labels,
                                                  type in a comma separated list below"),
                value =
                  # paste("\"",as.character(levelsvalues),"\"",collapse=", ",sep="")
                  #paste("'",as.character(1:nlevels),"'",collapse=", ",sep="")
                  paste(as.character(1:nlevels),collapse=", ",sep="")
      )
    }
    
  })
  
  outputOptions(output, "catvar4", suspendWhenHidden=FALSE)
  outputOptions(output, "nlabels", suspendWhenHidden=FALSE)
  
  
  recodedata4  <- reactive({
    df <- recodedata3()
    if (is.null(df)) return(NULL)
    if(input$catvar4in!="") {
      varname<- input$catvar4in
      xlabels <- input$customvarlabels 
     # xlabels <- c("a","b")
      nxxlabels <- length(as.numeric(unlist (strsplit(xlabels, ",")) )) -1
      df[,varname] <- as.factor(df[,varname])
      levels(df[,varname])  <-  unlist (strsplit(xlabels, ",") )
    }
    #print(head(df))
    df
  })
  
  
  output$pastevar <- renderUI({
    df <- recodedata4()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    MODEDF <- sapply(df, function(x) is.numeric(x))
    NAMESTOKEEP2<- names(df)  [! MODEDF ]
    selectizeInput("pastevarin", "Combine the categories of these two variables:", choices = NAMESTOKEEP2,multiple=TRUE,
                   options = list(
                     maxItems = 2 ,
                     placeholder = 'Please select some variables',
                     onInitialize = I('function() { this.setValue(""); }'),
                     plugins = list('remove_button', 'drag_drop')
                   )
    )
  })
  
  
  outputOptions(output, "pastevar", suspendWhenHidden=FALSE)
  outputOptions(output, "bintext", suspendWhenHidden=FALSE)
  
  
  
  
  output$maxlevels <- renderUI({
    df <-recodedata4()
    if (is.null(df)) return(NULL)
    numericInput( inputId = "inmaxlevels",label = "Max number of unique values for Filter variable (1),(2),(3) (this is to avoid performance issues):",value = 500,min = 1,max = NA)
    
  })
  outputOptions(output, "maxlevels", suspendWhenHidden=FALSE)
  
  
  output$filtervar1 <- renderUI({
    df <-recodedata4()
    if (is.null(df)) return(NULL)
    NUNIQUEDF <- sapply(df, function(x) length(unique(x)))
    NAMESTOKEEP<- names(df)  [ NUNIQUEDF  < input$inmaxlevels ]
    selectInput("infiltervar1" , "Filter variable (1):",c('None',NAMESTOKEEP ) )
  })
  
  output$filtervar2 <- renderUI({
    df <- recodedata4()
    if (is.null(df)) return(NULL)
    NUNIQUEDF <- sapply(df, function(x) length(unique(x)))
    NAMESTOKEEP<- names(df)  [ NUNIQUEDF  < input$inmaxlevels ]
    #NAMESTOKEEP<-  NAMESTOKEEP[ NAMESTOKEEP!=input$infiltervar1 ]
    selectInput("infiltervar2" , "Filter variable (2):",c('None',NAMESTOKEEP ) )
  })
  
  output$filtervar3 <- renderUI({
    df <- recodedata4()
    if (is.null(df)) return(NULL)
    NUNIQUEDF <- sapply(df, function(x) length(unique(x)))
    NAMESTOKEEP<- names(df)  [ NUNIQUEDF  < input$inmaxlevels ]
    #NAMESTOKEEP<-  NAMESTOKEEP[ NAMESTOKEEP!=input$infiltervar1 ]# allow nested filters
    #NAMESTOKEEP<-  NAMESTOKEEP[ NAMESTOKEEP!=input$infiltervar2 ]
    selectInput("infiltervar3" , "Filter variable (3):",c('None',NAMESTOKEEP ) )
  })
  
  
  output$filtervarcont1 <- renderUI({
    df <-recodedata4()
    if (is.null(df)) return(NULL)
    NUNIQUEDF <- sapply(df, function(x) length(unique(x)))
    NAMESTOKEEP<- names(df)
    NAMESTOKEEP<- NAMESTOKEEP[ is.element ( NAMESTOKEEP,names(df[sapply(df,is.numeric)]))]
    selectInput("infiltervarcont1" , "Filter continuous (1):",c('None',NAMESTOKEEP ) )
  })
  output$filtervarcont2 <- renderUI({
    df <-recodedata4()
    if (is.null(df)) return(NULL)
    NUNIQUEDF <- sapply(df, function(x) length(unique(x)))
    NAMESTOKEEP<- names(df)  
    NAMESTOKEEP<- NAMESTOKEEP[ is.element ( NAMESTOKEEP,names(df[sapply(df,is.numeric)]))]
    selectInput("infiltervarcont2" , "Filter continuous (2):",c('None',NAMESTOKEEP ) )
  })
  output$filtervarcont3 <- renderUI({
    df <-recodedata4()
    if (is.null(df)) return(NULL)
    NUNIQUEDF <- sapply(df, function(x) length(unique(x)))
    NAMESTOKEEP<- names(df)  
    NAMESTOKEEP<- NAMESTOKEEP[ is.element ( NAMESTOKEEP,names(df[sapply(df,is.numeric)]))]
    selectInput("infiltervarcont3" , "Filter continuous (3):",c('None',NAMESTOKEEP ) )
  })
  output$filtervar1values <- renderUI({
    df <-recodedata4()
    validate(       need(!is.null(df), "Please select a data set"))
    
    if (is.null(df)) return(NULL)
    if(input$infiltervar1=="None") {return(NULL)}
    if(input$infiltervar1!="None" )  {
      choices <- levels(as.factor(df[,input$infiltervar1]))
      selectInput('infiltervar1valuesnotnull',
                  label = paste("Select values", input$infiltervar1),
                  choices = c(choices),
                  selected = choices,
                  multiple=TRUE, selectize=FALSE)   
    }
  }) 
  
  filterdata  <- reactive({
    if (is.null(filedata())) return(NULL)
    df <-   recodedata4()
    if (is.null(df)) return(NULL)
    if(is.null(input$infiltervar1)) {
      df <-  df 
    }
    if(!is.null(input$infiltervar1)&input$infiltervar1!="None") {
      
      df <-  df [ is.element(df[,input$infiltervar1],input$infiltervar1valuesnotnull),]
    }
    
    df
  })
  
  output$filtervar2values <- renderUI({
    df <- filterdata()
    if (is.null(df)) return(NULL)
    if(input$infiltervar2=="None") {
      selectInput('infiltervar2valuesnull',
                  label ='No filter variable 2 specified', 
                  choices = list(""),multiple=TRUE, selectize=FALSE)   
    }
    if(input$infiltervar2!="None"&!is.null(input$infiltervar2) )  {
      choices <- levels(as.factor(as.character(df[,input$infiltervar2])))
      selectInput('infiltervar2valuesnotnull',
                  label = paste("Select values", input$infiltervar2),
                  choices = c(choices),
                  selected = choices,
                  multiple=TRUE, selectize=TRUE)   
    }
  })
  
  filterdata2  <- reactive({
    df <- filterdata()
    if (is.null(df)) return(NULL)
    if(!is.null(input$infiltervar2)&input$infiltervar2!="None") {
      df <-  df [ is.element(df[,input$infiltervar2],input$infiltervar2valuesnotnull),]
    }
    if(input$infiltervar2=="None") {
      df 
    }
    df
  }) 
  output$filtervar3values <- renderUI({
    df <- filterdata2()
    if (is.null(df)) return(NULL)
    if(input$infiltervar3=="None") {
      selectInput('infiltervar3valuesnull',
                  label ='No filter variable 2 specified', 
                  choices = list(""),multiple=TRUE, selectize=FALSE)   
    }
    if(input$infiltervar3!="None"&!is.null(input$infiltervar3) )  {
      choices <- levels(as.factor(as.character(df[,input$infiltervar3])))
      selectInput('infiltervar3valuesnotnull',
                  label = paste("Select values", input$infiltervar3),
                  choices = c(choices),
                  selected = choices,
                  multiple=TRUE, selectize=TRUE)   
    }
  })
  
  filterdata3  <- reactive({
    df <- filterdata2()
    if (is.null(df)) return(NULL)
    if(!is.null(input$infiltervar3)&input$infiltervar3!="None") {
      df <-  df [ is.element(df[,input$infiltervar3],input$infiltervar3valuesnotnull),]
    }
    if(input$infiltervar3=="None") {
      df 
    }
    df
  })  
  
  output$fslider1 <- renderUI({ 
    df <-  filterdata3()
    if (is.null(df)) return(NULL)
    xvariable<- input$infiltervarcont1
    if(input$infiltervarcont1=="None" ){
      return(NULL)  
    }
    if (!is.numeric(df[,xvariable]) ) return(NULL)
    if(input$infiltervarcont1!="None" ){
      sliderInput("infSlider1", paste("Select",xvariable,"Range"),
                  min=min(df[,xvariable],na.rm=T),
                  max=max(df[,xvariable],na.rm=T),
                  value=c(min(df[,xvariable],na.rm=T),max(df[,xvariable],na.rm=T)) 
      )
    }             
  })
  filterdata4  <- reactive({
    df <- filterdata3()
    if (is.null(df)) return(NULL)
    if(input$infiltervarcont1!="None" ){
      if(is.numeric( input$infSlider1[1]) & is.numeric(df[,input$infiltervarcont1])) {
        df <- df [!is.na(df[,input$infiltervarcont1]),]
        df <-  df [df[,input$infiltervarcont1] >= input$infSlider1[1]&df[,input$infiltervarcont1] <= input$infSlider1[2],]
      }
    }
    
    df
  })
  output$fslider2 <- renderUI({ 
    df <-  filterdata4()
    if (is.null(df)) return(NULL)
    xvariable<- input$infiltervarcont2
    if(input$infiltervarcont2=="None" ){
      return(NULL)  
    }
    if (!is.numeric(df[,xvariable]) ) return(NULL)
    if(input$infiltervarcont2!="None" ){
      sliderInput("infSlider2", paste("Select",xvariable,"Range"),
                  min=min(df[,xvariable],na.rm=T),
                  max=max(df[,xvariable],na.rm=T),
                  value=c(min(df[,xvariable],na.rm=T),max(df[,xvariable],na.rm=T)) 
      )
    }             
  })
  
  
  filterdata5  <- reactive({
    df <- filterdata4()
    if (is.null(df)) return(NULL)
    if(input$infiltervarcont2!="None" ){
      if(is.numeric( input$infSlider2[1]) & is.numeric(df[,input$infiltervarcont2])) {
        df<- df [!is.na(df[,input$infiltervarcont2]),]
        df<-df [df[,input$infiltervarcont2] >= input$infSlider2[1]&df[,input$infiltervarcont2] <= input$infSlider2[2],]
      }
    }
    
    df
  })
  
  output$fslider3 <- renderUI({ 
    df <-  filterdata5()
    if (is.null(df)) return(NULL)
    xvariable<- input$infiltervarcont3
    if(input$infiltervarcont3=="None" ){
      return(NULL)  
    }
    if (!is.numeric(df[,xvariable]) ) return(NULL)
    if(input$infiltervarcont3!="None" ){
      sliderInput("infSlider3", paste("Select",xvariable,"Range"),
                  min=min(df[,xvariable],na.rm=T),
                  max=max(df[,xvariable],na.rm=T),
                  value=c(min(df[,xvariable],na.rm=T),max(df[,xvariable],na.rm=T)) 
      )
    }             
  })
  
  
  filterdata6  <- reactive({
    df <- filterdata5()
    if (is.null(df)) return(NULL)
    if(input$infiltervarcont3!="None" ){
      if(is.numeric( input$infSlider3[1]) & is.numeric(df[,input$infiltervarcont3])) {
        df<- df [!is.na(df[,input$infiltervarcont3]),]
        df<-df [df[,input$infiltervarcont3] >= input$infSlider3[1]&df[,input$infiltervarcont3] <= input$infSlider3[2],]
      }
    }
    
    df
  })
  
  outputOptions(output, "filtervar1", suspendWhenHidden=FALSE)
  outputOptions(output, "filtervar2", suspendWhenHidden=FALSE)
  outputOptions(output, "filtervar3", suspendWhenHidden=FALSE)
  
  outputOptions(output, "filtervarcont1", suspendWhenHidden=FALSE)
  outputOptions(output, "filtervarcont2", suspendWhenHidden=FALSE)
  outputOptions(output, "filtervarcont3", suspendWhenHidden=FALSE)
  outputOptions(output, "filtervar1values", suspendWhenHidden=FALSE)
  outputOptions(output, "filtervar2values", suspendWhenHidden=FALSE)
  outputOptions(output, "filtervar3values", suspendWhenHidden=FALSE)
  
  outputOptions(output, "fslider1", suspendWhenHidden=FALSE)
  outputOptions(output, "fslider2", suspendWhenHidden=FALSE)
  outputOptions(output, "fslider3", suspendWhenHidden=FALSE)
  
  
  
  output$roundvar <- renderUI({
    df <- filterdata6()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    MODEDF <- sapply(df, function(x) is.numeric(x))
    NAMESTOKEEP2<- names(df)  [MODEDF]
    selectizeInput(  "roundvarin", "Round the Values to the Specified N Digits:", choices = NAMESTOKEEP2,multiple=TRUE,
                     options = list(
                       placeholder = 'Please select some variables',
                       onInitialize = I('function() { this.setValue(""); }')
                     )
    )
    
  }) 
  outputOptions(output, "roundvar", suspendWhenHidden=FALSE)
  
  stackdata <- reactive({
    
    df <- filterdata6() 
    
    if (is.null(df)) return(NULL)
    if (!is.null(df)){
      validate(  need(!is.element(input$x,input$y) , "Please select a different x variable or remove the x variable from the list of y variable(s)"))
      #   validate(
      #    need(!is.null(length(input$y)| length(input$y) <1) , 
      #         "Please select a at least one y variable"))
      
      
      if(       all( sapply(df[,as.vector(input$y)], is.numeric)) )
      {
        tidydata <- df %>%
          gather_( "yvars", "yvalues", gather_cols=as.vector(input$y) ) %>%
          mutate(combinedvariable="Choose two variables to combine first")
      }
      if(       any( sapply(df[,as.vector(input$y)], is.factor)) |
                any( sapply(df[,as.vector(input$y)], is.character)))
      {
        tidydata <- df %>%
          gather_( "yvars", "yvalues", gather_cols=as.vector(input$y) ) %>%
          mutate(yvalues=as.factor(as.factor(as.character(yvalues)) ))%>%
          mutate(combinedvariable="Choose two variables to combine first")
      } 
      
      if(       all( sapply(df[,as.vector(input$y)], is.factor)) |
                all( sapply(df[,as.vector(input$y)], is.character)))
      {
        tidydata <- df %>%
          gather_( "yvars", "yvalues", gather_cols=as.vector(input$y) ) %>%
          mutate(yvalues=as.factor(as.character(yvalues) ))%>%
          mutate(combinedvariable="Choose two variables to combine first")
      }    
      
      
    }
    
    if( !is.null(input$pastevarin)   ) {
      if (length(input$pastevarin) > 1) {
        tidydata <- tidydata %>%
          unite_("combinedvariable" , c(input$pastevarin[1], input$pastevarin[2] ),
                 remove=FALSE)
      }
    }
    
    tidydata
  })
  
  rounddata <- reactive({
    if (is.null(df)) return(NULL)
    df <- stackdata()
    if(length(input$roundvarin ) >=1) {
      for (i in 1:length(input$roundvarin ) ) {
        varname<- input$roundvarin[i]
        df[,varname]   <- round( df[,varname],input$rounddigits)
      }
    }
    df
  })  
  
  
  output$reordervar <- renderUI({
    df <- rounddata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    MODEDF <- sapply(df, function(x) is.numeric(x))
    NAMESTOKEEP2<- names(df)  [ !MODEDF ]
    selectizeInput(  "reordervarin", 'Reorder This Variable By:',
                     choices =NAMESTOKEEP2 ,multiple=FALSE,
                     options = list(    placeholder = 'Please select a variable',
                                        onInitialize = I('function() { this.setValue(""); }')
                     )
    )
  })
  
  
  
  output$variabletoorderby <- renderUI({
    if (is.null(df)) return(NULL)
    if (length(input$reordervarin ) <1)  return(NULL)
    if ( input$reordervarin!=""){
      df <-rounddata()
      yinputs <- input$y
      items=names(df)
      names(items)=items
      MODEDF <- sapply(df, function(x) is.numeric(x))
      NAMESTOKEEP2<- names(df)  [ MODEDF ]
      selectInput('varreorderin',label = 'Of this Variable:', choices=NAMESTOKEEP2,multiple=FALSE)
    }
  })
  
  

  
  outputOptions(output, "reordervar", suspendWhenHidden=FALSE)
  outputOptions(output, "variabletoorderby", suspendWhenHidden=FALSE)
  
  
  
  reorderdata <- reactive({
    df <- rounddata()
    if (is.null(df)) return(NULL)
    
    if(length(input$reordervarin ) >=1 &
       length(input$varreorderin ) >=1 & input$reordervarin!=""  ) {
      varname<- input$reordervarin[1]
      if(input$functionordervariable=="Median" )  {
        df[,varname]   <- reorder( df[,varname],df[,input$varreorderin], FUN=function(x) median(x[!is.na(x)]))
      }
      if(input$functionordervariable=="Mean" )  {
        df[,varname]   <- reorder( df[,varname],df[,input$varreorderin],  FUN=function(x) mean(x[!is.na(x)]))
      }
      if(input$functionordervariable=="Minimum" )  {
        df[,varname]   <- reorder( df[,varname],df[,input$varreorderin],  FUN=function(x) min(x[!is.na(x)]))
      }
      if(input$functionordervariable=="Maximum" )  {
        df[,varname]   <- reorder( df[,varname],df[,input$varreorderin],  FUN=function(x) max(x[!is.na(x)]))
      }
      if(input$reverseorder )  {
        df[,varname] <- factor( df[,varname], levels=rev(levels( df[,varname])))
        
      }
    }
    df
  })  
  
  
    output$reordervar2 <- renderUI({
      df <- reorderdata()
      if (is.null(df)) return(NULL)
      MODEDF <- sapply(df, function(x) is.numeric(x))
      NAMESTOKEEP<- names(df)  [ !MODEDF ]
      if(length(input$reordervarin ) >=1  ){
        NAMESTOKEEP<- NAMESTOKEEP  [ NAMESTOKEEP!=input$reordervarin ]
        
      }
      selectInput("reordervar2in" , "Custom Reorder this variable:",c('None',NAMESTOKEEP ) )
    })

      output$reordervar2values <- renderUI({
        df <- reorderdata()
        if (is.null(df)) return(NULL)
        if(input$reordervar2in=="None") {
          selectInput('reordervar2valuesnull',
                      label ='No reorder variable specified', 
                      choices = list(""),multiple=TRUE, selectize=FALSE)   
        }
        if(input$reordervar2in!="None"&!is.null(input$reordervar2in) )  {
          choices <- levels(as.factor(as.character(df[,input$reordervar2in])))
          selectizeInput('reordervar2valuesnotnull',
                      label = paste("Drag/Drop to reorder",input$reordervar2in, "values"),
                      choices = c(choices),
                      selected = choices,
                      multiple=TRUE,  options = list(
                      plugins = list('drag_drop')
                      )
                      )   
        }
      })
    outputOptions(output, "reordervar2", suspendWhenHidden=FALSE)
    outputOptions(output, "reordervar2values", suspendWhenHidden=FALSE)
    
    reorderdata2 <- reactive({
      df <- reorderdata()
      if (is.null(df)) return(NULL)
      
      if(input$reordervar2in!="None"  ) {
df [,input$reordervar2in] <- factor(df [,input$reordervar2in],
                                    levels = input$reordervar2valuesnotnull)

}
      df
    })
    
  output$xaxiszoom <- renderUI({
    df <-reorderdata2()
    if (is.null(df)| !is.numeric(df[,input$x] ) ) return(NULL)
    if (is.numeric(df[,input$x]) &
        input$facetscalesin!="free_x"&
        input$facetscalesin!="free"){
      xvalues <- df[,input$x][!is.na( df[,input$x])]
      xmin <- min(xvalues)
      xmax <- max(xvalues)
      xstep <- (xmax -xmin)/100
      sliderInput('xaxiszoomin',label = 'Zoom to X variable range:', min=xmin, max=xmax, value=c(xmin,xmax),step=xstep)
      
    }
    
    
  })
  outputOptions(output, "xaxiszoom", suspendWhenHidden=FALSE)
  
  
  output$colour <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    selectInput("colorin", "Colour By:",c("None",items,"yvars", "yvalues","combinedvariable") )
    
  })
  
  
  output$group <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items 
    
    if (input$boxplotaddition ){
      items= c(input$x,"None",items[items!=input$x], "yvars","yvalues","combinedvariable")    
    }
    if (!input$boxplotaddition ){
      items= c("None",input$x,items[items!=input$x],"yvars", "yvalues","combinedvariable")    
    }
    selectInput("groupin", "Group By:",items)
  })
  
  
  output$facet_col <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    selectInput("facetcolin", "Column Split:",c(None='.',items,"yvars", "yvalues","combinedvariable"))
  })
  output$facet_row <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    selectInput("facetrowin", "Row Split:",    c(None=".",items,"yvars", "yvalues","combinedvariable"))
  })
  
  output$facet_col_extra <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    selectInput("facetcolextrain", "Extra Column Split:",c(None='.',items,"yvars", "yvalues","combinedvariable"))
  })
  output$facet_row_extra <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    if (length(input$y) > 1 ){
      items= c("yvars",None=".",items, "yvalues","combinedvariable")    
    }
    if (length(input$y) < 2 ){
      items= c(None=".",items,"yvars", "yvalues","combinedvariable")    
    }
    selectInput("facetrowextrain", "Extra Row Split:",items)
  })
  
  
  output$facetscales <- renderUI({
    if (length(input$y) > 1 ){
      items= c("free_y","fixed","free_x","free")    
    }
    if (length(input$y) < 2 ){
      items= c("fixed","free_x","free_y","free")   
    }
    selectInput('facetscalesin','Facet Scales:',items)
  })
  outputOptions(output, "facetscales", suspendWhenHidden=FALSE)
  
  
  
  output$pointsize <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    selectInput("pointsizein", "Size By:",c("None",items,"yvars", "yvalues","combinedvariable") )
    
  })
  
  output$fill <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    selectInput("fillin", "Fill By:"    ,c("None",items,"yvars", "yvalues","combinedvariable") )
  })
  
  output$weight <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    selectInput("weightin", "Weight By:",c("None",items,"yvars", "yvalues","combinedvariable") )
  })
  outputOptions(output, "weight", suspendWhenHidden=FALSE)
  
  
  output$mytablex = renderDataTable({
    datatable( recodedata4() , # reorderdata2
               extensions = c('ColReorder','Buttons','FixedColumns'),
               options = list(dom = 'Bfrtip',
                              searchHighlight = TRUE,
                              pageLength=-1 ,
                              lengthMenu = list(c(5, 10, 15, -1), c('5','10', '15', 'All')),
                              colReorder = list(realtime = TRUE),
                              buttons = 
                                list('colvis', 'pageLength','print','copy', list(
                                  extend = 'collection',
                                  buttons = list(
                                    list(extend='csv'  ,filename = 'plotdata'),
                                    list(extend='excel',filename = 'plotdata'),
                                    list(extend='pdf'  ,filename = 'plotdata')),
                                  text = 'Download'
                                )),
                              scrollX = TRUE,scrollY = 400,
                              fixedColumns = TRUE
               ), 
               filter = 'bottom',
               style = "bootstrap")
  })
  
  
  
  plotObject <- reactive({
    validate(
      need(!is.null(reorderdata2()), "Please select a data set") 
    )
    
    plotdata <- reorderdata2()
    
    
    if(!is.null(plotdata)) {
      
      if (input$themetableau){
        scale_colour_discrete <- function(...) 
          scale_colour_manual(..., values = tableau10,drop=!input$themecolordrop)
        scale_fill_discrete <- function(...) 
          scale_fill_manual(..., values = tableau10,drop=!input$themecolordrop)
      }
      
      p <- ggplot(plotdata, aes_string(x=input$x, y="yvalues")) 
      
      if (input$colorin != 'None')
        p <- p + aes_string(color=input$colorin)
      if (input$fillin != 'None')
        p <- p + aes_string(fill=input$fillin)
      if (input$pointsizein != 'None')
        p <- p  + aes_string(size=input$pointsizein)
      
      # if (input$groupin != 'None' & !is.factor(plotdata[,input$x]))
      if (input$groupin != 'None')
        p <- p + aes_string(group=input$groupin)
      if (input$groupin == 'None' & !is.numeric(plotdata[,input$x]) 
          & input$colorin == 'None')
        p <- p + aes(group=1)
      
      if (input$Points=="Points"&input$pointsizein == 'None'&!input$pointignorecol)
        p <- p + geom_point(,alpha=input$pointstransparency,shape=input$pointtypes,size=input$pointsizes)  
      if (input$Points=="Points"&input$pointsizein != 'None'&!input$pointignorecol)
        p <- p + geom_point(,alpha=input$pointstransparency,shape=input$pointtypes)
      
      if (input$Points=="Jitter"&input$pointsizein == 'None'&!input$pointignorecol)
        p <- p + geom_jitter(,alpha=input$pointstransparency,shape=input$pointtypes,size=input$pointsizes)
      if (input$Points=="Jitter"&input$pointsizein != 'None'&!input$pointignorecol)
        p <- p + geom_jitter(,alpha=input$pointstransparency,shape=input$pointtypes)
      
      
      if (input$Points=="Points"&input$pointsizein == 'None'&input$pointignorecol)
        p <- p + geom_point(,alpha=input$pointstransparency,shape=input$pointtypes,size=input$pointsizes,colour=input$colpoint)  
      if (input$Points=="Points"&input$pointsizein != 'None'&input$pointignorecol)
        p <- p + geom_point(,alpha=input$pointstransparency,shape=input$pointtypes,colour=input$colpoint)
      
      if (input$Points=="Jitter"&input$pointsizein == 'None'&input$pointignorecol)
        p <- p + geom_jitter(,alpha=input$pointstransparency,shape=input$pointtypes,size=input$pointsizes,colour=input$colpoint)
      if (input$Points=="Jitter"&input$pointsizein != 'None'&input$pointignorecol)
        p <- p + geom_jitter(,alpha=input$pointstransparency,shape=input$pointtypes,colour=input$colpoint)
      
      
      
      if (input$line=="Lines"&input$pointsizein == 'None'& !input$lineignorecol)
        p <- p + geom_line(,size=input$linesize,alpha=input$linestransparency,linetype=input$linetypes)
      if (input$line=="Lines"&input$pointsizein != 'None'& !input$lineignorecol)
        p <- p + geom_line(,alpha=input$linestransparency,linetype=input$linetypes)
      if (input$line=="Lines"&input$pointsizein == 'None'&input$lineignorecol)
        p <- p + geom_line(,size=input$linesize,alpha=input$linestransparency,linetype=input$linetypes,colour=input$colline)
      if (input$line=="Lines"&input$pointsizein != 'None'& input$lineignorecol)
        p <- p + geom_line(,alpha=input$linestransparency,linetype=input$linetypes,colour=input$colline)
      
      
      if (input$boxplotaddition){
        if (input$groupin != 'None'& !input$boxplotignoregroup ){
          p <- p + aes_string(group=input$groupin)
          p <- p + geom_boxplot()
        }
        if (input$groupin == 'None'){
          p <- p + geom_boxplot(aes(group=NULL))
        }  
        if (input$boxplotignoregroup ){
          p <- p + geom_boxplot(aes(group=NULL))
        } 
        
        
      }
      
      
      ###### Mean section  START 
      
      
      if (!input$meanignoregroup) {
        if (!input$meanignorecol) {
          
          if (input$Mean=="Mean") {
            if(input$meanlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line")
            if(input$meanlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line",size=input$meanlinesize)
            
            
            if(input$meanpoints)           
              p <- p + 
                stat_sum_single(mean, geom = "point")
            
          }
          
          if (input$Mean=="Mean (95% CI)"){
            p <- p + 
              stat_sum_df("mean_cl_normal", geom = "errorbar",fun.args=list(conf.int=input$CI),width=input$errbar)
            if(input$meanlines&input$pointsizein != 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line")
            if(input$meanlines&input$pointsizein == 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line",size=input$meanlinesize)
            if(input$meanpoints)           
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "point")
            
          }
        }
        
        
        if (input$meanignorecol) {
          meancol <- input$colmean
          if (input$Mean=="Mean") {
            if(input$meanlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line",col=meancol)
            
            if(input$meanlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line",col=meancol,size=input$meanlinesize)
            
            if(input$meanpoints)           
              p <- p + 
                stat_sum_single(mean, geom = "point",col=meancol)
            
          }
          
          if (input$Mean=="Mean (95% CI)"){
            p <- p + 
              stat_sum_df("mean_cl_normal", geom = "errorbar",fun.args=list(conf.int=input$CI),width=input$errbar, col=meancol)
            if(input$meanlines&input$pointsizein != 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line", col=meancol)
            if(input$meanlines&input$pointsizein == 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line", col=meancol,size=input$meanlinesize)
            
            if(input$meanpoints)           
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "point", col=meancol)
            
          }
        }
      }
      
      if (input$meanignoregroup) {
        if (!input$meanignorecol) {
          
          if (input$Mean=="Mean") {
            if(input$meanlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line",aes(group=NULL))
            if(input$meanlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line",aes(group=NULL),size=input$meanlinesize)
            
            if(input$meanpoints)           
              p <- p + 
                stat_sum_single(mean, geom = "point",aes(group=NULL))
            
          }
          
          if (input$Mean=="Mean (95% CI)"){
            p <- p + 
              stat_sum_df("mean_cl_normal", geom = "errorbar",fun.args=list(conf.int=input$CI), width=input$errbar,aes(group=NULL))
            if(input$meanlines&input$pointsizein != 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line",aes(group=NULL))
            if(input$meanlines&input$pointsizein == 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line",aes(group=NULL),size=input$meanlinesize)
            if(input$meanpoints)           
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "point",aes(group=NULL))
            
          }
        }
        
        
        if (input$meanignorecol) {
          meancol <- input$colmean
          if (input$Mean=="Mean") {
            if(input$meanlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line",col=meancol,aes(group=NULL))
            if(input$meanlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line",col=meancol,aes(group=NULL),size=input$meanlinesize)
            
            
            if(input$meanpoints)           
              p <- p + 
                stat_sum_single(mean, geom = "point",col=meancol,aes(group=NULL))
            
          }
          
          if (input$Mean=="Mean (95% CI)"){
            p <- p + 
              stat_sum_df("mean_cl_normal", geom = "errorbar",fun.args=list(conf.int=input$CI), width=input$errbar, col=meancol, aes(group=NULL))
            if(input$meanlines&input$pointsizein != 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line",col=meancol,aes(group=NULL))
            if(input$meanlines&input$pointsizein == 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line",col=meancol,aes(group=NULL),size=input$meanlinesize)
            
            if(input$meanpoints)           
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "point",col=meancol,aes(group=NULL))
            
          }
        }
      }
      ###### Mean section  END 
      
      ###### Smoothing Section START
      if(!is.null(input$Smooth) ){
        familyargument <- ifelse(input$smoothmethod=="glm","binomial","gaussian") 
        
        if ( input$ignoregroup) {
          if (!input$ignorecol) {
            spanplot <- input$loessens
            if (input$Smooth=="Smooth")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot,aes(group=NULL))
            
            if (input$Smooth=="Smooth and SE")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot,aes(group=NULL))
            
            if (input$Smooth=="Smooth"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot,aes(group=NULL))+  
                aes_string(weight=input$weightin)
            
            if (input$Smooth=="Smooth and SE"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot,aes(group=NULL))+  
                aes_string(weight=input$weightin)
          }
          if (input$ignorecol) {
            spanplot <- input$loessens
            colsmooth <- input$colsmooth
            if (input$Smooth=="Smooth")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot,col=colsmooth,aes(group=NULL))
            
            if (input$Smooth=="Smooth and SE")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot,col=colsmooth,aes(group=NULL))
            
            if (input$Smooth=="Smooth"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot,col=colsmooth,aes(group=NULL))+  
              aes_string(weight=input$weightin)
            
            if (input$Smooth=="Smooth and SE"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot,col=colsmooth,aes(group=NULL))+  
              aes_string(weight=input$weightin)
          }
          
        }
        
        if ( !input$ignoregroup) {
          if (!input$ignorecol) {
            spanplot <- input$loessens
            if (input$Smooth=="Smooth")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot)
            
            if (input$Smooth=="Smooth and SE")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot)
            
            if (input$Smooth=="Smooth"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot)+  
                aes_string(weight=input$weightin)
            
            if (input$Smooth=="Smooth and SE"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot)+  
                aes_string(weight=input$weightin)
          }
          if (input$ignorecol) {
            spanplot <- input$loessens
            colsmooth <- input$colsmooth
            if (input$Smooth=="Smooth")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot,col=colsmooth)
            
            if (input$Smooth=="Smooth and SE")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot,col=colsmooth)
            
            if (input$Smooth=="Smooth"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot,col=colsmooth)+  
              aes_string(weight=input$weightin)
            
            if (input$Smooth=="Smooth and SE"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot,col=colsmooth)+  
              aes_string(weight=input$weightin)
          }
          
        }
        
        ###### smooth Section END
      }
      
      
      ###### Median PI section  START  
      if (!input$medianignoregroup) {
        
        if (!input$medianignorecol) {
          
          if (input$Median=="Median") {
            if(input$medianlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line")
            
            if(input$medianlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line",size=input$medianlinesize)
            
            
            if(input$medianpoints)           
              p <- p + 
                stat_sum_single(median, geom = "point")
            
          }
          
          if (input$Median=="Median/PI"&input$pointsizein == 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon",fun.args=list(conf.int=input$PI) ,size=input$medianlinesize,alpha=input$PItransparency,col=NA)+ 
              stat_sum_df("median_hilow", geom = "smooth",fun.args=list(conf.int=input$PI) ,size=input$medianlinesize,alpha=0)
            
            if ( input$sepguides )
              p <-   p + 
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
            
          }
          
          if (input$Median=="Median/PI"&input$pointsizein != 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon",fun.args=list(conf.int=input$PI), alpha=input$PItransparency,col=NA)+
              stat_sum_df("median_hilow", geom = "smooth"  ,fun.args=list(conf.int=input$PI),alpha=0)
            
            if ( input$sepguides )
              p <-   p +
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
            
          }
          
          if (input$Median!="None" & input$medianvalues )  {
            p <-   p   +
              stat_summary(fun.data = median.n,geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold",
                           show.legend=FALSE,size=6)}
          if (input$Median!="None" & input$medianN)  {
            p <-   p   +
              stat_summary(fun.data = give.n, geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold", 
                           show.legend=FALSE,size=6)      
          }  
        }
        
        
        
        if (input$medianignorecol) {
          mediancol <- input$colmedian
          if (input$Median=="Median") {
            if(input$medianlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line",col=mediancol)
            
            if(input$medianlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line",col=mediancol,size=input$medianlinesize)
            
            if(input$medianpoints)           
              p <- p + 
                stat_sum_single(median, geom = "point",col=mediancol)
            
          }
          
          if (input$Median=="Median/PI"&input$pointsizein == 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon", fun.args=list(conf.int=input$PI), alpha=input$PItransparency,col=NA)+
              stat_sum_df("median_hilow", geom = "smooth", fun.args=list(conf.int=input$PI), size=input$medianlinesize,col=mediancol,alpha=0)
            
            if ( input$sepguides )
              p <-   p +
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
          }
          if (input$Median=="Median/PI"&input$pointsizein != 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon",fun.args=list(conf.int=input$PI),alpha=input$PItransparency,col=NA)+
              stat_sum_df("median_hilow", geom = "smooth",fun.args=list(conf.int=input$PI),col=mediancol,
                          alpha=0)          
            
            if ( input$sepguides )
              p <-   p +
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
          }
          if (input$Median!="None" & input$medianvalues )  {
            p <-   p   +
              stat_summary(fun.data = median.n,geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold",colour=mediancol,
                           show.legend=FALSE,size=6)}
          if (input$Median!="None" & input$medianN)  {
            p <-   p   +
              stat_summary(fun.data = give.n, geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold", colour=mediancol,
                           show.legend=FALSE,size=6)      
          }       
          
        }
      }
      
      
      if (input$medianignoregroup) {
        if (!input$medianignorecol) {
          if (input$Median=="Median") {
            if(input$medianlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line",aes(group=NULL))
            if(input$medianlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line",aes(group=NULL),size=input$medianlinesize)
            
            if(input$medianpoints)           
              p <- p + 
                stat_sum_single(median, geom = "point",aes(group=NULL))
            
          }
          
          if (input$Median=="Median/PI"&input$pointsizein == 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon",fun.args=list(conf.int=input$PI),aes(group=NULL),alpha=input$PItransparency,col=NA)+ 
              stat_sum_df("median_hilow", geom = "smooth",fun.args=list(conf.int=input$PI),aes(group=NULL),size=input$medianlinesize,alpha=0)   
            if ( input$sepguides )
              p <-   p +
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
          }
          
          if (input$Median=="Median/PI"&input$pointsizein != 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon",fun.args=list(conf.int=input$PI),aes(group=NULL),alpha=input$PItransparency,col=NA)+ 
              stat_sum_df("median_hilow", geom = "smooth",fun.args=list(conf.int=input$PI),aes(group=NULL),alpha=0)
            if ( input$sepguides )
              p <-   p +
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
          }
          if (input$Median!="None" & input$medianvalues )  {
            p <-   p   +
              stat_summary(fun.data = median.n, aes(group=NULL),geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold",fill="white",
                           show.legend=FALSE,
                           size=6)}
          if (input$Median!="None" & input$medianN)  {
            p <-   p   +
              stat_summary(fun.data = give.n, aes(group=NULL), geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold", fill="white",
                           show.legend=FALSE,size=6)      
          }
          
          
        }
        
        
        if (input$medianignorecol) {
          mediancol <- input$colmedian
          if (input$Median=="Median") {
            if(input$medianlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line",col=mediancol,aes(group=NULL))
            if(input$medianlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line",col=mediancol,aes(group=NULL),size=input$medianlinesize)
            
            if(input$medianpoints)           
              p <- p + 
                stat_sum_single(median, geom = "point",col=mediancol,aes(group=NULL))
            
          }
          
          if (input$Median=="Median/PI"&input$pointsizein == 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon",fun.args=list(conf.int=input$PI),aes(group=NULL),alpha=input$PItransparency,col=NA)+ 
              stat_sum_df("median_hilow", geom = "smooth",fun.args=list(conf.int=input$PI),col=mediancol,aes(group=NULL),size=input$medianlinesize,alpha=0)
            if ( input$sepguides )
              p <-   p +
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
          }
          if (input$Median=="Median/PI"&input$pointsizein != 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon",fun.args=list(conf.int=input$PI),aes(group=NULL),alpha=input$PItransparency,col=NA)+ 
              stat_sum_df("median_hilow", geom = "smooth",fun.args=list(conf.int=input$PI),col=mediancol,aes(group=NULL),alpha=0)
            
            
            
            if ( input$sepguides )
              p <-   p +
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
          }
          
          
          if (input$Median!="None" & input$medianvalues )  {
            p <-   p   +
              stat_summary(fun.data = median.n, aes(group=NULL),geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold",colour=mediancol,
                           show.legend=FALSE,size=6)}
          if (input$Median!="None" & input$medianN)  {
            p <-   p   +
              stat_summary(fun.data = give.n, aes(group=NULL), geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold", colour=mediancol,
                           show.legend=FALSE,size=6)      
          }
          
        }
      }
      
      
      
      ###### Median PI section  END
      
      
      
      ###### RQSS SECTION START  
      if (!input$ignoregroupqr) {
        if (!input$ignorecolqr) {
          if (input$Tauvalue) {
            if(!input$hidedynamic){
              p <- p +  stat_quantile(method = "rqss",quantiles =input$Tau,size=1.5,
                                      linetype="solid", 
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))       
            }
            
            if (input$mid)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.5,size=1.5,
                                      linetype="solid",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$ninetieth)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.90,size=1,
                                      linetype="dashed",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$tenth)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.1,size=1,
                                      linetype="dashed",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$up)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.95,size=1,
                                      linetype="dashed",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$low) 
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.05,size=1,
                                      linetype="dashed",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            
            
          }
        }
        if (input$ignorecolqr) {
          colqr <- input$colqr
          if (input$Tauvalue) {
            if(!input$hidedynamic){
              p <- p +  stat_quantile(method = "rqss",quantiles =input$Tau,size=1.5,
                                      linetype="solid", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty)) 
            }
            
            
            if (input$mid)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.5,size=1.5,
                                      linetype="solid", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$ninetieth)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.90,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$tenth)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.1,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$up)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.95,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$low) 
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.05,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            
            
          }
        }
      }
      
      
      if (input$ignoregroupqr) {
        if (!input$ignorecolqr) {
          if (input$Tauvalue) {
            if(!input$hidedynamic){
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles =input$Tau,size=1.5,
                                      linetype="solid",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty)) 
            }
            
            if (input$mid)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.5,size=1.5,
                                      linetype="solid",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$ninetieth)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.90,size=1,
                                      linetype="dashed", 
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$tenth)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.1,size=1,
                                      linetype="dashed",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$up)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.95,size=1,
                                      linetype="dashed", 
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$low) 
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.05,size=1,
                                      linetype="dashed", 
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
          }
        }
        if (input$ignorecolqr) {
          colqr <- input$colqr
          if (input$Tauvalue) {
            if(!input$hidedynamic){
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles =input$Tau,size=1.5,
                                      linetype="solid",col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))     
            }
            
            
            if (input$mid)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.5,size=1.5,
                                      linetype="solid", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$ninetieth)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.90,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$tenth)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.1,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$up)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.95,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$low) 
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.05,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
          }
        }
      }
      
      
      ###### RQSS SECTION END
      
      ###### KM SECTION START
      
      if (input$KM!="None") {
        p <- ggplot(plotdata, aes_string(time=input$x, status="yvalues")) 
        if (input$colorin != 'None')
          p <- p + aes_string(color=input$colorin)
        if (input$fillin != 'None')
          p <- p + aes_string(fill=input$fillin)
        if (input$groupin != 'None' & !is.factor(plotdata[,input$x]))
          p <- p + aes_string(group=input$groupin)
      }
      
      if (input$KM=="KM/CI") {
        p <- p +
          geom_kmband(alpha=input$KMCItransparency,conf.int = input$KMCI,trans=input$KMtrans)                 }
      
      
      if (input$KM!="None") {
        p  <- p +
          geom_smooth(stat="km",trans=input$KMtrans)
      }
      if (input$censoringticks) {
        p  <- p +
          geom_kmticks(trans=input$KMtrans)
      }
      
      
      
      
      ###### KM SECTION END
      
      
      facets <- paste(input$facetrowin,'~', input$facetcolin)
      
      if (input$facetrowextrain !="."&input$facetrowin !="."){
        facets <- paste(input$facetrowextrain ,"+", input$facetrowin, '~', input$facetcolin)
      }  
      if (input$facetrowextrain !="."&input$facetrowin =="."){
        facets <- paste( input$facetrowextrain, '~', input$facetcolin)
      }  
      
      if (input$facetcolextrain !="."){
        facets <- paste( facets, "+",input$facetcolextrain)
      }  
      if (facets != '. ~ .')
        p <- p + facet_grid(facets,scales=input$facetscalesin,space=input$facetspace
                            ,labeller=input$facetlabeller,margins=input$facetmargin )
      
      if (facets != '. ~ .' & input$facetswitch!="" )
        
        p <- p + facet_grid(facets,scales=input$facetscalesin,space=input$facetspace,
                            switch=input$facetswitch
                            , labeller=input$facetlabeller,
                            margins=input$facetmargin )
      
      if (facets != '. ~ .'&input$facetwrap) {
        p <- p + facet_wrap(    c(input$facetrowextrain ,input$facetrowin,input$facetcolin,input$facetcolextrain ) [
          c(input$facetrowextrain ,input$facetrowin,input$facetcolin,input$facetcolextrain )!="."]
          ,scales=input$facetscalesin)
        
        if (input$facetwrap&input$customncolnrow) {
          p <- p + facet_wrap(    c(input$facetrowextrain ,input$facetrowin,input$facetcolin,input$facetcolextrain ) [
            c(input$facetrowextrain ,input$facetrowin,input$facetcolin,input$facetcolextrain )!="."]
            ,scales=input$facetscalesin,ncol=input$wrapncol,nrow=input$wrapnrow)
        }
      }
      
      
      
      
      if (input$logy)
        p <- p + scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),
                               labels = trans_format("log10", math_format(10^.x))) 
      
      if (input$logx)
        p <- p + scale_x_log10(breaks = trans_breaks("log10", function(x) 10^x),
                               labels = trans_format("log10", math_format(10^.x))) 
      
      
      
      if (input$scientificy )
        p <- p  + 
        scale_y_continuous(labels=comma )
      
      if (input$scientificx )
        p <- p  + 
        scale_x_continuous(labels=comma) 
      
      
      
      
      if (length(input$y) >= 2 & input$ylab=="" ){
        p <- p + ylab("Y variable(s)")
      }
      if (length(input$y) < 2 & input$ylab=="" ){
        p <- p + ylab(input$y)
      }
      
      if (input$xlab!="")
        p <- p + xlab(input$xlab)
      if (input$ylab!="")
        p <- p + ylab(input$ylab)
      
      
      if (input$horizontalzero)
        p <-    p+
        geom_hline(aes(yintercept=0))
      
      if (input$customline1)
        p <-    p+
        geom_vline(xintercept=input$vline)
      
      
      if (input$customline2)
        p <-    p+
        geom_hline(yintercept=input$hline)
      
      
      
      if (input$identityline)
        p <-    p+ geom_abline(intercept = 0, slope = 1)
      
      if (input$themebw) {
        p <-    p+
          theme_bw(base_size=input$themebasesize)     
      }
      
      
      if (!input$themebw){
        p <- p +
          theme_gray(base_size=input$themebasesize)+
          theme(  
            #axis.title.y = element_text(size = rel(1.5)),
            #axis.title.x = element_text(size = rel(1.5))#,
            #strip.text.x = element_text(size = 16),
            #strip.text.y = element_text(size = 16)
          )
      }
      
      
      p <-    p+theme(
        legend.position=input$legendposition,
        legend.box=input$legendbox,
        legend.direction=input$legenddirection,
        panel.background = element_rect(fill=input$backgroundcol))
      
      if (input$labelguides)
        p <-    p+
        theme(legend.title=element_blank())
      if (input$themeaspect)
        p <-    p+
        theme(aspect.ratio=input$aspectratio)
      if (!input$themetableau){
        p <-  p +
          scale_colour_hue(drop=!input$themecolordrop)+
          scale_fill_hue(drop=!input$themecolordrop)
      }
      
      if (grepl("^\\s+$", input$ylab) ){
        p <- p + theme(
          axis.title.y=element_blank())
      }
      if (grepl("^\\s+$", input$xlab) ){
        p <- p + theme(
          axis.title.x=element_blank())
      }
      
      if (input$rotatexticks ){
        p <-  p+
          theme(axis.text.x = element_text(angle = input$xticksrotateangle,
                                           hjust = input$xtickshjust,
                                           vjust = input$xticksvjust) )
        
      }
      if (input$rotateyticks ){
        p <-  p+
          theme(axis.text.y = element_text(angle = input$yticksrotateangle,
                                           hjust = input$ytickshjust,
                                           vjust = input$yticksvjust) )                              
      }    
      
      if (!is.null(input$xaxiszoomin[1])&
          is.numeric(plotdata[,input$x] )&
          input$facetscalesin!="free_x"&
          input$facetscalesin!="free"
      ){
        p <- p +
          coord_cartesian(xlim= c(input$xaxiszoomin[1],input$xaxiszoomin[2])  )
      }
      
      #p <- ggplotly(p)
      p
    }
  })
  
  output$plot <- renderPlot({
    plotObject()
  })
  
  
  output$ui_plot <-  renderUI({                 
    plotOutput('plot',  width = "100%" ,height = input$height,
               click = "plot_click",
               hover = hoverOpts(id = "plot_hover", delayType = "throttle"),
               brush = brushOpts(id = "plot_brush"))
  })
  
  output$plotinfo <- renderPrint({
    df<- reorderdata2()  
    if (is.null(df)) return(NULL)
    nearPoints( reorderdata2(), input$plot_click, threshold = 5, maxpoints = 5,
                addDist = TRUE) #,xvar=input$x, yvar=input$y
  })
  
  
  output$clickheader <-  renderUI({
    df <-reorderdata2()
    if (is.null(df)) return(NULL)
    h4("Clicked points")
  })
  
  output$brushheader <-  renderUI({
    df <- reorderdata2()
    if (is.null(df)) return(NULL)
    h4("Brushed points")
    
  })
  
  output$plot_clickedpoints <- renderTable({
    # For base graphics, we need to specify columns, though for ggplot2,
    # it's usually not necessary.
    df<- reorderdata2()  
    if (is.null(df)) return(NULL)
    
    res <- nearPoints(reorderdata2(), input$plot_click, input$x, "yvalues")
    if (nrow(res) == 0|is.null(res))
      return(NULL)
    res
  })
  output$plot_brushedpoints <- renderTable({
    df<- reorderdata2()  
    if (is.null(df)) return(NULL)
    res <- brushedPoints(reorderdata2(), input$plot_brush, input$x,"yvalues")
    if (nrow(res) == 0|is.null(res))
      return(NULL)
    res
  })
  
  
  
  
  downloadPlotType <- reactive({
    input$downloadPlotType  
  })
  
  observe({
    plotType    <- input$downloadPlotType
    plotTypePDF <- plotType == "pdf"
    plotUnit    <- ifelse(plotTypePDF, "inches", "pixels")
    plotUnitDef <- ifelse(plotTypePDF, 7, 480)
    
    updateNumericInput(
      session,
      inputId = "downloadPlotHeight",
      label = sprintf("Height (%s)", plotUnit),
      value = plotUnitDef)
    
    updateNumericInput(
      session,
      inputId = "downloadPlotWidth",
      label = sprintf("Width (%s)", plotUnit),
      value = plotUnitDef)
    
  })
  
  
  # Get the download dimensions.
  downloadPlotHeight <- reactive({
    input$downloadPlotHeight
  })
  
  downloadPlotWidth <- reactive({
    input$downloadPlotWidth
  })
  
  # Get the download file name.
  downloadPlotFileName <- reactive({
    input$downloadPlotFileName
  })
  
  # Include a downloadable file of the plot in the output list.
  output$downloadPlot <- downloadHandler(
    filename = function() {
      paste(downloadPlotFileName(), downloadPlotType(), sep=".")   
    },
    # The argument content below takes filename as a function
    # and returns what's printed to it.
    content = function(con) {
      # Gets the name of the function to use from the 
      # downloadFileType reactive element. Example:
      # returns function pdf() if downloadFileType == "pdf".
      plotFunction <- match.fun(downloadPlotType())
      plotFunction(con, width = downloadPlotWidth(), height = downloadPlotHeight())
      print(plotObject())
      dev.off(which=dev.cur())
    }
  )
  
  
}

shinyApp(ui = ui, server = server,  options = list(height = 1000))
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        cancel = function(job_ids, user = private$user, host = private$host) {
            job_ids <- paste(job_ids, collapse = ",")

            stain_ssh(user, host, paste("scancel", job_ids))
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host,
                          submit_dir = "~/stain", dependency_list = "") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")

                # Add any dependencies to sbatch command.
                history <- self$submission_history()$job_id
                dependencies <- sbatch_dependency_list(dependency_list, history)
                submit_cmd <- paste("sbatch submit.slurm",
                                    sbatch_opt("-d", dependencies))
                submit_cmd <- paste("cd", job_dir, "&&", submit_cmd)
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir = "~/stain") {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        submission_history = function() {
            # `stain_sub_history` will warn if submission history is empty.
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                return(history)
            }
        },
        fetch_job_states = function(user = private$user, host = private$host) {
            job_ids <- stain_sub_history(self$dir)$job_id

            verify_state_table <- function(state_table) {
                if (nrow(status_table) > 0) {
                    return(state_table)
                } else {
                    job_ids <- paste(job_ids, collapse = ", ")
                    message(paste("No statuses found for job ids:", job_ids))
                }
            }

            fetch_squeue_table <- function() {
                tryCatch({
                    squeue_table <- stain_ssh_squeue(user, host, job_ids)
                    squeue_table <- squeue_table[, c("JOBID", "STATE")]
                    colnames(squeue_table) <- c("job_id", "state")
                    # Will throw error if data frame has no rows.
                    squeue_table$exit_code <- NA
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    squeue_table <- data.frame()
                }, finally = return(squeue_table))
            }

            fetch_sacct_table <- function() {
                tryCatch({
                    sacct_table <- stain_ssh_sacct(user, host, job_ids)
                    colnames(sacct_table) <- c("job_id", "state", "exit_code")
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    sacct_table <- data.frame()
                }, finally = return(sacct_table))
            }

            squeue_table <- fetch_squeue_table()
            sacct_table <- fetch_sacct_table()
            states <- rbind(squeue_table, sacct_table)
            states <- aggregate(states, list(states$job_id), function(x) {
                na.omit(x)[1]
            })[,-1]

            return(states)
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' Create an SBATCH option
#'
#' @param key The key for the sbatch option.
#'
#' @return A function that takes a single argument representing
#' the value for the \code{key}.
sbatch_opt <- function(key) {
    return(function(value) {
        return(paste0("--", key, "=", value))
    })
}


#' Test sbatch options for equality.
#'
#' sbatch option equallity is achieved if the keys of the options
#' are the same.
#'
#' @param opt_1 An sbatch option string.
#'
#' @param opt_2 An sbatch option string.
#'
#' @return A boolean value.
sbatch_opts_equal <- function(opt_1, opt_2) {
    return(sbatch_opt_key(opt_1) == sbatch_opt_key(opt_2))
}


#' Insert an sbatch option into a set.
#'
#' @param opt The sbatch option to insert
#'
#' @param opts A set of sbatch options. Default value is the empty
#' set.
#'
#' @return A set with \code{opt} inserted.
sbatch_opts_insert <- function(opt, opts = c()) {
    did_set <- FALSE

    for (i in 1:length(opts)) {
        if (sbatch_opts_equal(opt, opts[i])) {
            opts[i] = opt
            did_set = TRUE
        }
    }

    if(!did_set) {
        opts <- c(opts, opt)
    }

    return(opts)
}


#' Get the key of an sbatch.
#'
#' @param opt An sbatch option string.
#'
#' @return The \code{opt}'s key.
sbatch_opt_key <- function(opt) {
    return(strsplit(opt, "=")[[1]][1])
}


#' Get the value of an sbatch option.
#'
#' @param opt An sbatch option string.
#'
#' @return The \code{opt}'s value.
sbatch_opt_value <- function(opt) {
    return(strsplit(opt, "=")[[1]][2])
}


#' A list of sbatch options.
#'
#' The value of each item in the list is a string or a function
#' which takes a string as a parameter, using \code{sbatch_opt}.
#'
#' To ensure proper formatting, the \code{mail_type} option should
#' be set using \code{sbatch_mail_types}. Multiple mail types need
#' to be comma seperated.
#'
#' @export
sbatch_opts <- list (
    begin = sbatch_opt("begin"),
    cpus_per_task = sbatch_opt("cpus-per-task"),
    mail_user = sbatch_opt("mail-user"),
    memory = sbatch_opt("mem"),
    nodes = sbatch_opt("nodes"),
    output = sbatch_opt("output"),
    time = sbatch_opt("time")
)


#' A list of sbatch mail types.
#'
#' The value of each item in the list is a string representing
#' a mail type option.
#'
#' @export
sbatch_mail_type_opts <- list(
    all = sbatch_opt("mail-type")("ALL"),
    begin = sbatch_opt("mail-type")("BEGIN"),
    end = sbatch_opt("mail-type")("END"),
    fail = sbatch_opt("mail-type")("FAIL"),
    none = sbatch_opt("mail-type")("NONE"),
    requeue = sbatch_opt("mail-type")("REQUEUE"),
    stage_out = sbatch_opt("mail-type")("STAGE_OUT"),
    time_limit = sbatch_opt("mail-type")("TIME_LIMIT"),
    time_limit_90 = sbatch_opt("mail-type")("TIME_LIMIT_90"),
    time_limit_80 = sbatch_opt("mail-type")("TIME_LIMIT_80"),
    time_limit_50 = sbatch_opt("mail-type")("TIME_LIMIT_50")
)


#' Create single sbatch mail type key value pair.
#'
#' A user may specific multiple \code{sbatch_mail_type_opts},
#' which must be combined into a single key value pair that
#' contains the options seperated by commas.
#'
#' @param opts A list of sbatch mail type options.
sbatch_mail_type_combine <- function(opts) {
    opt_keys <- sapply(opts, sbatch_opt_key, USE.NAMES = FALSE)
    mail_type_opts <- which(opt_keys == "--mail-type")

    mail_type_opt_vals <- sapply(opts[mail_type_opts], sbatch_opt_value,
                                 USE.NAMES = FALSE)
    mail_type_opt_val <- paste(unique(mail_type_opt_vals), collapse = ",")
    mail_type_opt <- sbatch_opt("mail-type")(mail_type_opt_val)

    return(c(opts[-mail_type_opts], mail_type_opt))
}

#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        cancel = function(job_ids, user = private$user, host = private$host) {
            job_ids <- paste(job_ids, collapse = ",")

            stain_ssh(user, host, paste("scancel", job_ids))
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host, submit_dir = "~/stain") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir = "~/stain") {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        submission_history = function() {
            # `stain_sub_history` will warn if submission history is empty.
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                return(history)
            }
        },
        fetch_job_states = function(user = private$user, host = private$host) {
            job_ids <- stain_sub_history(self$dir)$job_id

            verify_state_table <- function(state_table) {
                if (nrow(status_table) > 0) {
                    return(state_table)
                } else {
                    job_ids <- paste(job_ids, collapse = ", ")
                    message(paste("No statuses found for job ids:", job_ids))
                }
            }

            fetch_squeue_table <- function() {
                tryCatch({
                    squeue_table <- stain_ssh_squeue(user, host, job_ids)
                    squeue_table <- squeue_table[, c("JOBID", "STATE")]
                    colnames(squeue_table) <- c("job_id", "state")
                    # Will throw error if data frame has no rows.
                    squeue_table$exit_code <- NA
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    squeue_table <- data.frame()
                }, finally = return(squeue_table))
            }

            fetch_sacct_table <- function() {
                tryCatch({
                    sacct_table <- stain_ssh_sacct(user, host, job_ids)
                    colnames(sacct_table) <- c("job_id", "state", "exit_code")
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    sacct_table <- data.frame()
                }, finally = return(sacct_table))
            }

            squeue_table <- fetch_squeue_table()
            sacct_table <- fetch_sacct_table()
            states <- rbind(squeue_table, sacct_table)
            states <- aggregate(states, list(states$job_id), function(x) {
                na.omit(x)[1]
            })[,-1]

            return(states)
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        cancel = function(job_ids, user = private$user, host = private$host) {
            job_ids <- paste(job_ids, collapse = ",")

            stain_ssh(user, host, paste("scancel", job_ids))
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host, submit_dir = "~/stain") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir = "~/stain") {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        view_submission_history = function() {
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                View(history)
                invisible(history)
            }
        },
        view_statuses = function(user = private$user, host = private$host, should_view = TRUE) {
            job_ids <- stain_sub_history(self$dir)$job_id

            verify_state_table <- function(state_table) {
                if (nrow(status_table) > 0) {
                    return(state_table)
                } else {
                    job_ids <- paste(job_ids, collapse = ", ")
                    message(paste("No statuses found for job ids:", job_ids))
                }
            }

            fetch_squeue_table <- function() {
                tryCatch({
                    squeue_table <- stain_ssh_squeue(user, host, job_ids)
                    squeue_table <- squeue_table[, c("JOBID", "STATE")]
                    colnames(squeue_table) <- c("job_id", "state")
                    # Will throw error if data frame has no rows.
                    squeue_table$exit_code <- NA
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    squeue_table <- data.frame()
                }, finally = return(squeue_table))
            }

            fetch_sacct_table <- function() {
                tryCatch({
                    sacct_table <- stain_ssh_sacct(user, host, job_ids)
                    colnames(sacct_table) <- c("job_id", "state", "exit_code")
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    sacct_table <- data.frame()
                }, finally = return(sacct_table))
            }

            squeue_table <- fetch_squeue_table()
            sacct_table <- fetch_sacct_table()
            states <- rbind(squeue_table, sacct_table)
            states <- aggregate(states, list(states$job_id), function(x) {
                na.omit(x)[1]
            })[,-1]

            return(states)
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
###############################################################################################################################################################
# Timetable Model
# Author Mufy 
# Date 24/09/2016
# Description --  This script models the teaching hours per academic based on their teaching load.  The data for the model is extracted from the timetabling 
#  spreadsheet.

##############################################################################################################################################################

#library(readxl)
library(xlsx)
require(xlsx)
#library(RODBC)
library(hashmap)

#Set path to the timetable
setwd("/Users/mufy/Dropbox/teaching/UEL/2015-2016/timetable")

#Change the filename if changes or updated
file.name <- "CSI 2016-17-v7.xlsx"
sheet.name <- "ML"

tAllocation <- read.xlsx(file.name, 4, header=FALSE, keepFormulas=FALSE, startRow = 2, endRow =25)
timetable <- read.xlsx(file.name, 3, header=FALSE, keepFormulas=FALSE, startRow = 2, endRow =172)

# Get the current list of staff names 
staffNames <- tAllocation[1]

#get all the teaching allocated staff names 
allocatedStaffNamesOnTimetable <- timetable[12];


#List to hold all the calculated values

#TODO - Find a way to initilize
staffAllocationMap <-  hashmap("","")
staffAllocationMap$erase("")


# Functions for calculating all the teaching hours 

calculateLectureHours <- function(semester, hours, npar=TRUE,print=TRUE){
	
	hourCalc <- 0
	
	#cat ("\n calc semester: ", semester, " : hours: ", hours, "\n")
	
	if (toString(semester) == "1 & 2"){
		
		hourCalc =	(2* hours * 24)/43
	#	cat ("\n hour calc: ", hourCalc, "\n")
		return (hourCalc)
		
	}else{
		hourCalc =	(2*hours * 12)/43
	#	cat ("\n hour calc: ", hourCalc, "\n")
		return (hourCalc)
		
	}
}

calculateTutorialHours <- function(semester, hours, npar=TRUE,print=TRUE){
	
	hourCalc <- 0
	
	if (semester == "1 & 2"){		
		hourCalc <-	(1.5* hours * 24)/43
	}else{
		hourCalc <-	(1.5* hours * 12)/43
	}
	
	return (hourCalc)
}

#TODO - Should take into account the module length, currently only module size
calculateModuleLeadership <- function(semester, moduleSize, npar=TRUE,print=TRUE){
		
	small <- 25
	medium <- 75
		
	#cat ("\n module size: ", moduleSize, "\n")	
	
	if (as.numeric(moduleSize) < small) {
		return (1)
	}else if ((as.numeric(moduleSize) > small) & (as.numeric(moduleSize) < medium)){
		return (1.5)
	}else{
		return (2)
	}
}


allocationSummary <- function (){
    
    cat ("\n############################### Summary ########################### \n")


    keys <- staffAllocationMap$keys()
    
    for (key in keys){
        
            cat ("staff: ", key, "  ====>  allocation: ", staffAllocationMap$find(key), "\n")
    }
    
    cat ("\n################################################################### \n")

    
}


#TODO -- Not very efficient algorithm, improve the algorith from 0(N^2) to (NLogN) 
#IMPROVEMENT -- consider using HashMAP


for (i in 1: nrow (staffNames)){
	print (toString(staffNames[i,1]))
	
	totalAllocation <- 0
	totalModuleLeadership <-0
	
	for (j in 1: nrow(allocatedStaffNamesOnTimetable)) {
		if (toString(staffNames[i,1]) == toString(allocatedStaffNamesOnTimetable[j,1])){
			if (toString(timetable[j:j,4]) == "Lecture"){
							
				#calculate mornalized teaching time 			
				normalizedHours <- calculateLectureHours (toString(timetable[j:j,5]), (as.numeric(toString(timetable[j:j,9])))*24) 
				totalAllocation <- totalAllocation + normalizedHours							

				# calculate module leadership 
				moduleLeadership <- calculateModuleLeadership(toString(timetable[j:j,5]), (as.numeric(toString(timetable[j:j,11]))))			
				totalModuleLeadership <- totalModuleLeadership+ moduleLeadership;
							
				cat ("current lec allocation: ", normalizedHours, "total allocation: ",totalAllocation, " module code: ",toString(timetable[j:j,2]), "module size:", (as.numeric(toString(timetable[j:j,11]))),  " ;semester: ", toString(timetable[j:j,5]), "; hours: ", (as.numeric(toString(timetable[j:j,9])))*24, "module leadership: ", moduleLeadership, "\n")
			}else{

				normalizedHours <- calculateLectureHours (toString(timetable[j:j,5]), (as.numeric(toString(timetable[j:j,9])))*24) 
				totalAllocation <- totalAllocation + normalizedHours

				cat ("current tut allocation: ", normalizedHours, "total allocation: ",totalAllocation, " module code: ",toString(timetable[j:j,2]), "module size:", (as.numeric(toString(timetable[j:j,11]))), " ;semester: ", toString(timetable[j:j,5]), "; hours: ", (as.numeric(toString(timetable[j:j,9])))*24, "\n")				
			}
			
			#Handle joint module leaders 
		}else{ 
		
			if (regexpr("/", toString(allocatedStaffNamesOnTimetable[j,1]))[1]!=-1){
				namesList <- unlist(strsplit(toString(allocatedStaffNamesOnTimetable[j,1]), "/"))

				for (k in 1: length(namesList)){
				
					if (toString(staffNames[i,1]) == namesList[k]){
						if (toString(timetable[j:j,4]) == "Lecture"){
							
							#calculate mornalized teaching time 			
							normalizedHours <- calculateLectureHours (toString(timetable[j:j,5]), ((as.numeric(toString(timetable[j:j,9])))*24)/length(namesList)) 
							totalAllocation <- totalAllocation + normalizedHours							

								cat ("Shared current lec allocation: ", normalizedHours, "total allocation: ",totalAllocation, " module code: " , toString(timetable[j:j,2]), "module size:", (as.numeric(toString(timetable[j:j,11]))), " ;semester: ", toString(timetable[j:j,5]), "; hours: ", (as.numeric(toString(timetable[j:j,9])))*24, "module leadership: ", moduleLeadership, "\n")


							# calculate module leadership, only the first person is the module leader 
							if (k ==1){				
								moduleLeadership <- calculateModuleLeadership(toString(timetable[j:j,5]), (as.numeric(toString(timetable[j:j,11]))))			
								totalModuleLeadership <- totalModuleLeadership+ moduleLeadership;
							
								cat ("Shared current lec allocation, with module leadership: ", normalizedHours, "total allocation: ",totalAllocation, " module code: " , toString(timetable[j:j,2]), "module size:", (as.numeric(toString(timetable[j:j,11]))), " ;semester: ", toString(timetable[j:j,5]), "; hours: ", (as.numeric(toString(timetable[j:j,9])))*24, "module leadership: ", moduleLeadership, "\n")
							}					
						}else{

							normalizedHours <- calculateLectureHours (toString(timetable[j:j,5]), ((as.numeric(toString(timetable[j:j,9])))*24)/length(namesList)) 
							totalAllocation <- totalAllocation + normalizedHours

							cat ("Shared current tut allocation: ", normalizedHours, "total allocation: ",totalAllocation, " module code: " ,toString(timetable[j:j,2]),  "module size:", (as.numeric(toString(timetable[j:j,11]))), " ;semester: ", toString(timetable[j:j,5]), "; hours: ", (as.numeric(toString(timetable[j:j,9])))*24, "\n")				
						}
						
					break	
					}
				}				
			}
		}
		
	}
	
	totalAllocation <- totalAllocation + totalModuleLeadership;
 	cat (" Total Allocation time with module leadership for: ",toString(staffNames[i,1]), " is: ", totalAllocation, "\n")
    
    staffAllocationMap$insert(toString(staffNames[i,1]),totalAllocation)

    totalAllocation <- 0
	totalModuleLeadership <-0
    
  		
}

allocationSummary()








##predefined_condition_begin

rootdir<-"H:/shengquanhu/projects/20160701_smallRNA_3018-KCV-77_78_79_mouse/class_independent/deseq2_top100Reads/result"
inputfile<-"KCV-77_78_79.design"

showLabelInPCA<-1
showDEGeneCluster<-1
pvalue<-0.05
foldChange<-1.5
minMedianInGroup<-2
addCountOne<-1

##predefined_condition_end

library("DESeq2")
library("heatmap3")
library("lattice")
library("reshape")
library("ggplot2")
library("grid")
library("scales")
library("reshape2")
library("VennDiagram")
library("RColorBrewer")

setwd(rootdir)  
comparisons_data<-read.table(inputfile, header=T, check.names=F , sep="\t", stringsAsFactors = F)

##Solving node stack overflow problem start###
#when there are too many genes, drawing dendrogram may failed due to node stack overflow,
#It could be solved by forcing stats:::plotNode to be run as interpreted code rather then byte-compiled code via a nasty hack.
#http://stackoverflow.com/questions/16559250/error-in-heatmap-2-gplots/25877485#25877485

# Convert a byte-compiled function to an interpreted-code function 
unByteCode <- function(fun)
{
  FUN <- eval(parse(text=deparse(fun)))
  environment(FUN) <- environment(fun)
  FUN
}

# Replace function definition inside of a locked environment **HACK** 
assignEdgewise <- function(name, env, value)
{
  unlockBinding(name, env=env)
  assign( name, envir=env, value=value)
  lockBinding(name, env=env)
  invisible(value)
}

# Replace byte-compiled function in a locked environment with an interpreted-code
# function
unByteCodeAssign <- function(fun)
{
  name <- gsub('^.*::+','', deparse(substitute(fun)))
  FUN <- unByteCode(fun)
  retval <- assignEdgewise(name=name,
                           env=environment(FUN),
                           value=FUN
  )
  invisible(retval)
}

# Use the above functions to convert stats:::plotNode to interpreted-code:
unByteCodeAssign(stats:::plotNode)

# Now raise the interpreted code recursion limit (you may need to adjust this,
#  decreasing if it uses to much memory, increasing if you get a recursion depth error ).
options(expressions=5e4)

##Solving node stack overflow problem end###

hmcols <- colorRampPalette(c("green", "black", "red"))(256)

drawHCA<-function(prefix, rldselect, ispaired, designData, conditionColors, gnames){
  htfile<-paste0(prefix, "_DESeq2-vsd-heatmap.png")
  cat("saving HCA to ", htfile, "\n")
  genecount<-nrow(rldselect)
  if(genecount > 2){
    png(filename=htfile, width=3000, height=3000, res=300)
    cexCol = max(1.0, 0.2 + 1/log10(ncol(rldselect)))
    if(ispaired){
      htColors<-rainbow(length(unique(designData$Paired)))
      gsColors<-as.matrix(data.frame(Group=conditionColors, Sample=htColors[designData$Paired]))
    }else{
      gsColors = conditionColors;
    }
    heatmap3(rldselect, 
             col = hmcols, 
             ColSideColors = gsColors, 
             margins=c(12,5), 
             scale="r", 
             dist=dist, 
             labRow=NA,
             main=paste0("Hierarchical Cluster Using ", genecount, " Genes"),  
             cexCol=cexCol, 
             useRaster=FALSE,
             legendfun=function() showLegend(legend=paste0("Group ", gnames), col=c("red","blue"),cex=1.0,x="center"))
    dev.off()
  }
}

drawPCA<-function(prefix, rldmatrix, showLabelInPCA, designData, conditionColors){
  #filename<-paste0(prefix, "_DESeq2-vsd-pca.png")
  filename<-paste0(prefix, "_DESeq2-vsd-pca.pdf")
  genecount<-nrow(rldmatrix)
  if(genecount > 2){
    cat("saving PCA to ", filename, "\n")
    #png(filename=filename, width=3000, height=3000, res=300) # 10 X 10 inches
    pdf(filename, width=10, height=10)
    pca<-prcomp(t(rldmatrix))
    supca<-summary(pca)$importance
    pcadata<-data.frame(pca$x)
    pcalabs=paste0(colnames(pcadata), "(", round(supca[2,] * 100), "%)")
    pcadata["sample"]<-row.names(pcadata)
    
    if(showLabelInPCA){
      g <- ggplot(pcadata, aes(x=PC1, y=PC2, label=sample)) + 
        geom_text(vjust=-0.6, size=4) +
        geom_point(col=conditionColors, size=4) + 
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) +
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) + 
        xlab(pcalabs[1]) + ylab(pcalabs[2])
    }else{
      g <- ggplot(pcadata, aes(x=PC1, y=PC2)) + 
        geom_point(col=conditionColors, size=4) + 
        labs(color = "Group") +
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) + 
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) +
        xlab(pcalabs[1]) + ylab(pcalabs[2]) + 
        theme(legend.position="top")
    }
    
    print(g)
    dev.off()
  }
}

#for volcano plot
reverselog_trans <- function(base = exp(1)) {
  trans <- function(x) -log(x, base)
  inv <- function(x) base^(-x)
  trans_new(paste0("reverselog-", format(base)), trans, inv, 
            log_breaks(base = base), 
            domain = c(1e-100, Inf))
}

countfiles<-unlist(unique(comparisons_data$CountFile))

countfile_index = 1
for(countfile_index in c(1:length(countfiles))){
  countfile = countfiles[countfile_index]
  comparisons = comparisons_data[comparisons_data$CountFile == countfile,]
  
  if (grepl(".csv$",countfile)) {
    data<-read.csv(countfile,header=T,row.names=1,as.is=T,check.names=FALSE)
  } else {
    data<-read.delim(countfile,header=T,row.names=1,as.is=T,check.names=FALSE)
  }
  
  data<-data[,colnames(data) != "Feature_length"]
  colClass<-sapply(data, class)
  countNotNumIndex<-which(colClass!="numeric" & colClass!="integer")
  if (length(countNotNumIndex)==0) {
    index<-1;
    indecies<-c()
  } else {
    index<-max(countNotNumIndex)+1
    indecies<-c(1:(index-1))
  }
  
  countData<-data[,c(index:ncol(data))]
  countData[is.na(countData)] <- 0
  countData<-round(countData)
  
  if(addCountOne){
    countData<-countData+1
  }
  
  comparisonNames=comparisons$ComparisonName
  
  dir.create("details", showWarnings = FALSE)
  
  pairedspearman<-list()
  resultAllOut<-data
  resultAllOutVar<-c("log2FoldChange","pvalue","padj")
  
  comparison_index = 1
  for(comparison_index in c(1:nrow(comparisons))){
    comparisonName=comparisons$ComparisonName[comparison_index]
    str(comparisonName)
    designFile=comparisons$ConditionFile[comparison_index]
    gnames=unlist(comparisons[comparison_index, c("ReferenceGroupName", "SampleGroupName")])
    
    designData<-read.table(designFile, sep="\t", header=T)
    designData$Condition<-factor(designData$Condition, levels=gnames)
    
    if(ncol(designData) >= 3){
      cat("Data with covariances!\n")
    }else{
      cat("Data without covariances!\n")
    }
    if (any(colnames(designData)=="Paired")) {
      ispaired<-TRUE
      cat("Paired Data!\n")
    }else{
      ispaired<-FALSE
      cat("Not Paired Data!\n")
    }
    temp<-apply(designData,2,function(x) length(unique(x)))
    if (any(temp==1)) {
      cat(paste0("Factors with only 1 level in design matrix: ",colnames(designData)[which(temp==1)],"\n"))
      cat("They will be removed")
      cat("\n")
      designData<-designData[,which(temp!=1)]
    }
    temp<-apply(designData[,-1,drop=F],2,rank)
    if (length(unique(rowSums(temp)))==1 | identical(temp[,1],temp[,-1])) {
      cat(paste0("The model matrix is not full rank, so the model cannot be fit as specified"))
      cat("\n")
      cat("Only Condition variable will be kept.")
      cat("\n")
      designData<-designData[,which(colnames(designData)%in% c("Sample","Condition"))]
    }
    
    comparisonData<-countData[,colnames(countData) %in% as.character(designData$Sample),drop=F]
    if(ncol(comparisonData) != nrow(designData)){
      message=paste0("Data not matched, there are ", nrow(designData), " samples in design file ", designFile, " but ", ncol(comparisonData), " samples in data ")
      warning(message)
      writeLines(message,paste0(comparisonName,".error"))
      next
    }
    comparisonData<-comparisonData[,as.character(designData$Sample)]
    
    prefix<-comparisonName
    curdata<-data
    if(minMedianInGroup > 0){
      conds<-unique(designData$Condition)
      data1<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[1]]]
      data2<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[2]]]
      med1<-apply(data1, 1, median) >= minMedianInGroup
      med2<-apply(data2, 1, median) >= minMedianInGroup
      med<-med1 | med2
      comparisonData<-comparisonData[med,]
      cat(nrow(comparisonData), " genes with minimum median count in group larger or equals than ", minMedianInGroup, "\n")
      
      if (nrow(comparisonData)==0) {
        message=paste0("Error: 0 Genes can be used in DESeq2 analysis in comparison ",comparisonName," \n")
        warning(message)
        writeLines(message,paste0(comparisonName,".error"))
        next;
      }
      
      prefix<-paste0(comparisonName, "_min", minMedianInGroup)
      curdata<-data[med,]
    }
    
    if(ispaired){
      pairedSamples = unique(designData$Paired)
      
      spcorr<-unlist(lapply(c(1:length(pairedSamples)), function(x){
        samples<-designData$Sample[designData$Paired==pairedSamples[x]]
        cor(comparisonData[,samples[1]],comparisonData[,samples[2]],method="spearman")
      }))
      
      
      sptable<-data.frame(Name=pairedSamples, Spcorr=spcorr)
      write.csv(sptable, file=paste0(prefix, "_Spearman.csv"), row.names=FALSE)
      
      lapply(c(1:length(pairedSamples)), function(x){
        samples<-designData$Sample[designData$Paired==pairedSamples[x]]
        log2c1<-log2(comparisonData[,samples[1]]+1)
        log2c2<-log2(comparisonData[,samples[2]]+1)
        png(paste0("details/", prefix, "_Spearman_", pairedSamples[x], ".png"), width=2000, height=2000, res=300)
        plot(log2c1, log2c2, xlab=paste0(samples[1], " [log2(Count + 1)]"), ylab=paste0(samples[2], " [log2(Count + 1)]"))
        text(3,15,paste0("SpearmanCorr=", sprintf("%0.3f", spcorr[x])))
        dev.off()
      })
      
      pairedspearman[[comparisonName]]<-spcorr
    }
    
    notEmptyData<-apply(comparisonData, 1, max) > 0
    comparisonData<-comparisonData[notEmptyData,]
    curdata<-curdata[notEmptyData,]
    
    if(ispaired){
      colnames(comparisonData)<-unlist(lapply(c(1:ncol(comparisonData)), function(i){paste0(designData$Paired[i], "_", colnames(comparisonData)[i])}))
    }
    rownames(designData)<-colnames(comparisonData)
    conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
    
    write.csv(comparisonData, file=paste0(prefix, ".csv"))
    
    #some basic graph
    dds=DESeqDataSetFromMatrix(countData = comparisonData,
                               colData = designData,
                               design = ~1)
    
    colnames(dds)<-colnames(comparisonData)
    
    #draw density graph
    rldmatrix<-as.matrix(log2(counts(dds,normalized=FALSE) + 1))
    rsdata<-melt(rldmatrix)
    colnames(rsdata)<-c("Gene", "Sample", "log2Count")
    png(filename=paste0(prefix, "_DESeq2-log2-density.png"), width=4000, height=3000, res=300)
    g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + xlab("DESeq2 log2 transformed count")
    print(g)
    dev.off()
    
    width=max(4000, ncol(rldmatrix) * 40 + 1000)
    height=max(3000, ncol(rldmatrix) * 40)
    png(filename=paste0(prefix, "_DESeq2-log2-density-individual.png"), width=width, height=height, res=300)
    g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + facet_wrap(~Sample, scales = "free") + xlab("DESeq2 log2 transformed count")
    print(g)
    dev.off()
    
    
    #varianceStabilizingTransformation
    
    allDesignData<-designData
    allComparisonData<-comparisonData
    
    excludedSample<-c()
    zeronumbers<-apply(comparisonData, 2, function(x){sum(x==0)})
    zeronumbers<-names(zeronumbers[order(zeronumbers)])
    percent10<-max(1, round(length(zeronumbers) * 0.1))
    
    removed<-0
    
    excludedCountFile<-paste0(prefix, "_DESeq2-exclude-count.csv")
    excludedDesignFile<-paste0(prefix, "_DESeq2-exclude-design.csv")
    if(file.exists(excludedCountFile)){
      file.remove(excludedCountFile)
    }
    if(file.exists(excludedDesignFile)){
      file.remove(excludedDesignFile)
    }
    
    fitType<-"parametric"
    while(1){
      #varianceStabilizingTransformation
      vsdres<-try(vsd <- varianceStabilizingTransformation(dds, blind=TRUE,fitType=fitType))
      if(class(vsdres) == "try-error" && grepl("every gene contains at least one zero", vsdres[1])){
        removed<-removed+1
        keptNumber<-length(zeronumbers) - percent10 * removed
        keptSample<-zeronumbers[1:keptNumber]
        excludedSample<-zeronumbers[(keptNumber+1):length(zeronumbers)]
        
        comparisonData<-comparisonData[, colnames(comparisonData) %in% keptSample]
        designData<-designData[rownames(designData) %in% keptSample,]
        dds=DESeqDataSetFromMatrix(countData = comparisonData,
                                   colData = designData,
                                   design = ~1)
        
        colnames(dds)<-colnames(comparisonData)
      } else if (class(vsdres) == "try-error" && grepl("newsplit: out of vertex space", vsdres[1])) {
        message=paste0("Warning: varianceStabilizingTransformation function can't run. fitType was set to local to try again")
        warning(message)
        fitType<-"mean"
        writeLines(message,paste0(comparisonName,".error"))
      } else{
        conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
        break
      }
    }
    if (nrow(comparisonData)<=1) {
      message=paste0("Error: All genes in ",comparisonName," has at least one 0 value. Can't do DESeq2.")
      warning(message)
      writeLines(message,paste0(comparisonName,".error"))
      next;
    }
    
    if(length(excludedSample) > 0){
      excludedCountData<-allComparisonData[,colnames(allComparisonData) %in% excludedSample]
      write.csv(file=excludedCountFile, excludedCountData)
      excludedDesignData<-allDesignData[rownames(allDesignData) %in% excludedSample,]
      write.csv(file=excludedDesignFile, excludedDesignData)
    }
    
    assayvsd<-assay(vsd)
    write.csv(assayvsd, file=paste0(prefix, "_DESeq2-vsd.csv"))
    
    vsdiqr<-apply(assayvsd, 1, IQR)
    assayvsd<-assayvsd[order(vsdiqr, decreasing=T),]
    
    rldmatrix=as.matrix(assayvsd)
    
    #draw pca graph
    drawPCA(paste0(prefix,"_geneAll"), rldmatrix, showLabelInPCA, designData, conditionColors)
    
    #draw heatmap
    #drawHCA(paste0(prefix,"_gene500"), rldmatrix[1:min(500, nrow(rldmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
    drawHCA(paste0(prefix,"_geneAll"), rldmatrix, ispaired, designData, conditionColors, gnames)
    
    #different expression analysis
    designFormula=as.formula(paste0("~",paste0(c(colnames(designData)[-c(1:2)],"Condition"),collapse="+")))
	
	cat(paste0("Formula = ", designFormula), "\n")
	
    dds=DESeqDataSetFromMatrix(countData = comparisonData,
                               colData = designData,
                               design = designFormula)
    
    dds <- DESeq(dds,fitType=fitType)
    res<-results(dds,cooksCutoff=FALSE)
    
    cat("DESeq2 finished.\n")
    
    select<-(!is.na(res$padj)) & (res$padj<pvalue) & ((res$log2FoldChange >= log2(foldChange)) | (res$log2FoldChange <= -log2(foldChange)))
    
    if(length(indecies) > 0){
      inddata<-curdata[,indecies,drop=F]
      tbb<-cbind(inddata, comparisonData, res)
    }else{
      tbb<-cbind(comparisonData, res)
    }
    tbb$FoldChange<-2^tbb$log2FoldChange
    tbbselect<-tbb[select,,drop=F]
    tbbAllOut<-as.data.frame(tbb[,resultAllOutVar,drop=F])
    tbbAllOut$Significant<-select
    colnames(tbbAllOut)<-paste0(colnames(tbbAllOut)," (",comparisonName,")")
    resultAllOut<-cbind(resultAllOut,tbbAllOut[row.names(resultAllOut),])
    
    tbb<-tbb[order(tbb$padj),,drop=F]
    write.csv(as.data.frame(tbb),paste0(prefix, "_DESeq2.csv"))
    
    tbbselect<-tbbselect[order(tbbselect$padj),,drop=F]
    write.csv(as.data.frame(tbbselect),paste0(prefix, "_DESeq2_sig.csv"))
    
    if("Feature_gene_name" %in% colnames(tbb)){
      write.table(tbb[,c("Feature_gene_name", "stat"),drop=F],paste0(prefix, "_DESeq2_GSEA.rnk"),row.names=F,col.names=F,sep="\t", quote=F)
      write.table(tbbselect[,c("Feature_gene_name"),drop=F], paste0(prefix, "_DESeq2_sig_genename.txt"),row.names=F,col.names=F,sep="\t", quote=F)
    }
    
    if(showDEGeneCluster){
      siggenes<-rownames(rldmatrix) %in% rownames(tbbselect)
      
      nonDEmatrix<-rldmatrix[!siggenes,,drop=F]
      DEmatrix<-rldmatrix[siggenes,,drop=F]
      
      drawPCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, showLabelInPCA, designData, conditionColors)
      drawHCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, ispaired, designData, conditionColors, gnames)
      
      drawPCA(paste0(prefix,"_geneDE"),DEmatrix , showLabelInPCA, designData, conditionColors)
      drawHCA(paste0(prefix,"_geneDE"),DEmatrix , ispaired, designData, conditionColors, gnames)
      #drawHCA(paste0(prefix,"_gene500NotDE"), nonDEmatrix[1:min(500, nrow(nonDEmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
    }
    
    #Top 25 Significant genes barplot
    sigDiffNumber<-nrow(tbbselect)
    if (sigDiffNumber>0) {
      if (sigDiffNumber>25) {
        print(paste0("More than 25 genes were significant. Only the top 25 genes will be used in barplot"))
        diffResultSig<-tbbselect[order(tbbselect$padj)[1:25],]
      } else {
        diffResultSig<-tbbselect
      }
      if("Feature_gene_name" %in% colnames(diffResultSig)){
        diffResultSig$Name<-as.character(diffResultSig$Feature_gene_name)
      }else{
        diffResultSig$Name<-sapply(strsplit(row.names(diffResultSig),";"),function(x) x[1])
      }
      diffResultSig$Name <- factor(diffResultSig$Name, levels=diffResultSig$Name[order(diffResultSig$log2FoldChange)])
      diffResultSig<-as.data.frame(diffResultSig)
      
      png(filename=paste0(prefix, "_DESeq2_sig_barplot.png"), width=3000, height=3000, res=300)
      #	  pdf(paste0(prefix,"_DESeq2_sig_barplot.pdf"))
      p<-ggplot(diffResultSig,aes(x=Name,y=log2FoldChange,order=log2FoldChange))+geom_bar(stat="identity")+
        coord_flip()+
        #			geom_abline(slope=0,intercept=1,colour="red",linetype = 2)+
        scale_y_continuous(name=bquote(log[2]~Fold~Change))+
        theme(axis.text = element_text(colour = "black"))
      print(p)
      dev.off()
    } else {
      print(paste0("No gene with adjusted p value less than ",pvalue," and fold change larger than ",foldChange))
    }
    
    #volcano plot
    changeColours<-c(grey="grey",blue="blue",red="red")
    diffResult<-as.data.frame(tbb)
    diffResult$log10BaseMean<-log10(diffResult$baseMean)
    diffResult$colour<-"grey"
    diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange>=log2(foldChange))]<-"red"
    diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange<=-log2(foldChange))]<-"blue"
    png(filename=paste0(prefix, "_DESeq2_volcanoPlot.png"), width=3000, height=3000, res=300)
    #  pdf(paste0(prefix,"_DESeq2_volcanoPlot.pdf"))
    p<-ggplot(diffResult,aes(x=log2FoldChange,y=padj))+
      geom_point(aes(size=log10BaseMean,colour=colour))+
      scale_color_manual(values=changeColours,guide = FALSE)+
      scale_y_continuous(trans=reverselog_trans(10),name=bquote(Adjusted~p~value))+
      scale_x_continuous(name=bquote(log[2]~Fold~Change))+
      geom_hline(yintercept = 1,colour="grey",linetype = "dotted")+
      geom_vline(xintercept = 0,colour="grey",linetype = "dotted")+
      guides(size=guide_legend(title=bquote(log[10]~Base~Mean)))+
      theme_bw()+
      scale_size(range = c(3, 7))+
      theme(axis.text = element_text(colour = "black",size=30),
            axis.title = element_text(size=30),
            legend.text= element_text(size=30),
            legend.title= element_text(size=30))
    print(p)
    dev.off()
  }
  
  #write a file with all information
  write.csv(resultAllOut,paste0(comparisonName, "_DESeq2.csv"))
  
  if(length(pairedspearman) > 0){
    #draw pca graph
    filename<-ifelse(minMedianInGroup > 0, paste0("spearman_min", minMedianInGroup, ".png"), "spearman.png")
    png(filename=filename, width=1000 * length(pairedspearman), height=2000, res=300)
    boxplot(pairedspearman)
    dev.off()
  }
  
  #Venn for all significant genes
  allSigNameList<-list()
  allSigDirectionList<-list()
  sigTableAll<-NULL
  sigTableAllVar<-c("baseMean","log2FoldChange","lfcSE","stat","pvalue","padj","FoldChange")
  for(comparisonName in comparisonNames){
    if (minMedianInGroup > 0) {
      prefix<-paste0(comparisonName, "_min", minMedianInGroup)
    } else {
      prefix<-comparisonName
    }
    sigFile<-paste0(prefix, "_DESeq2_sig.csv")
    if (file.exists(sigFile)) {
      sigTable<-read.csv(sigFile,header=TRUE,as.is=TRUE,row.names=1)
      if (nrow(sigTable)>0) {
        allSigNameList[[comparisonName]]<-row.names(sigTable)
        allSigDirectionList[[comparisonName]]<-sign(sigTable$log2FoldChange)
		sigTable$comparisonName<-comparisonName
		sigTableAll<-rbind(sigTableAll,sigTable[,c("comparisonName",sigTableAllVar),drop=FALSE])
      } else {
        warning(paste0("No significant genes in ",comparisonName))
        #		allSigNameList[[comparisonName]]<-""
      }
    }
  }
  #Output all significant genes table
  write.csv(sigTableAll,paste0(inputfile,"_min", minMedianInGroup,"_DESeq2_allSig.csv"))
  
  #Do venn if length between 2-5
  if (length(allSigNameList)>=2 & length(allSigNameList)<=5) {
    venn.diagram1<-function (x, filename, height = 3000, width = 3000, resolution = 500, 
                             units = "px", compression = "lzw", na = "stop", main = NULL, 
                             sub = NULL, main.pos = c(0.5, 1.05), main.fontface = "plain", 
                             main.fontfamily = "serif", main.col = "black", main.cex = 1, 
                             main.just = c(0.5, 1), sub.pos = c(0.5, 1.05), sub.fontface = "plain", 
                             sub.fontfamily = "serif", sub.col = "black", sub.cex = 1, 
                             sub.just = c(0.5, 1), category.names = names(x), force.unique = TRUE,
                             fill=NA,
                             ...) 
    {
      if (is.na(fill[1])) {
        if (length(x)==5) {
          fill = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3")
        } else if (length(x)==4) {
          fill = c("dodgerblue", "goldenrod1",  "seagreen3", "orchid3")
        } else if (length(x)==3) {
          fill = c("dodgerblue", "goldenrod1", "seagreen3")
        } else if (length(x)==2) {
          fill = c("dodgerblue", "goldenrod1")
        }
      }
      if (force.unique) {
        for (i in 1:length(x)) {
          x[[i]] <- unique(x[[i]])
        }
      }
      if ("none" == na) {
        x <- x
      }
      else if ("stop" == na) {
        for (i in 1:length(x)) {
          if (any(is.na(x[[i]]))) {
            stop("NAs in dataset", call. = FALSE)
          }
        }
      }
      else if ("remove" == na) {
        for (i in 1:length(x)) {
          x[[i]] <- x[[i]][!is.na(x[[i]])]
        }
      }
      else {
        stop("Invalid na option: valid options are \"none\", \"stop\", and \"remove\"")
      }
      if (0 == length(x) | length(x) > 5) {
        stop("Incorrect number of elements.", call. = FALSE)
      }
      if (1 == length(x)) {
        list.names <- category.names
        if (is.null(list.names)) {
          list.names <- ""
        }
        grob.list <- VennDiagram::draw.single.venn(area = length(x[[1]]), 
                                                   category = list.names, ind = FALSE,fill=fill, ...)
      }
      else if (2 == length(x)) {
        grob.list <- VennDiagram::draw.pairwise.venn(area1 = length(x[[1]]), 
                                                     area2 = length(x[[2]]), cross.area = length(intersect(x[[1]], 
                                                                                                           x[[2]])), category = category.names, ind = FALSE, 
                                                     fill=fill,
                                                     ...)
      }
      else if (3 == length(x)) {
        A <- x[[1]]
        B <- x[[2]]
        C <- x[[3]]
        list.names <- category.names
        nab <- intersect(A, B)
        nbc <- intersect(B, C)
        nac <- intersect(A, C)
        nabc <- intersect(nab, C)
        grob.list <- VennDiagram::draw.triple.venn(area1 = length(A), 
                                                   area2 = length(B), area3 = length(C), n12 = length(nab), 
                                                   n23 = length(nbc), n13 = length(nac), n123 = length(nabc), 
                                                   category = list.names, ind = FALSE, list.order = 1:3, 
                                                   fill=fill,
                                                   ...)
      }
      else if (4 == length(x)) {
        A <- x[[1]]
        B <- x[[2]]
        C <- x[[3]]
        D <- x[[4]]
        list.names <- category.names
        n12 <- intersect(A, B)
        n13 <- intersect(A, C)
        n14 <- intersect(A, D)
        n23 <- intersect(B, C)
        n24 <- intersect(B, D)
        n34 <- intersect(C, D)
        n123 <- intersect(n12, C)
        n124 <- intersect(n12, D)
        n134 <- intersect(n13, D)
        n234 <- intersect(n23, D)
        n1234 <- intersect(n123, D)
        grob.list <- VennDiagram::draw.quad.venn(area1 = length(A), 
                                                 area2 = length(B), area3 = length(C), area4 = length(D), 
                                                 n12 = length(n12), n13 = length(n13), n14 = length(n14), 
                                                 n23 = length(n23), n24 = length(n24), n34 = length(n34), 
                                                 n123 = length(n123), n124 = length(n124), n134 = length(n134), 
                                                 n234 = length(n234), n1234 = length(n1234), category = list.names, 
                                                 ind = FALSE, fill=fill,...)
      }
      else if (5 == length(x)) {
        A <- x[[1]]
        B <- x[[2]]
        C <- x[[3]]
        D <- x[[4]]
        E <- x[[5]]
        list.names <- category.names
        n12 <- intersect(A, B)
        n13 <- intersect(A, C)
        n14 <- intersect(A, D)
        n15 <- intersect(A, E)
        n23 <- intersect(B, C)
        n24 <- intersect(B, D)
        n25 <- intersect(B, E)
        n34 <- intersect(C, D)
        n35 <- intersect(C, E)
        n45 <- intersect(D, E)
        n123 <- intersect(n12, C)
        n124 <- intersect(n12, D)
        n125 <- intersect(n12, E)
        n134 <- intersect(n13, D)
        n135 <- intersect(n13, E)
        n145 <- intersect(n14, E)
        n234 <- intersect(n23, D)
        n235 <- intersect(n23, E)
        n245 <- intersect(n24, E)
        n345 <- intersect(n34, E)
        n1234 <- intersect(n123, D)
        n1235 <- intersect(n123, E)
        n1245 <- intersect(n124, E)
        n1345 <- intersect(n134, E)
        n2345 <- intersect(n234, E)
        n12345 <- intersect(n1234, E)
        grob.list <- VennDiagram::draw.quintuple.venn(area1 = length(A), 
                                                      area2 = length(B), area3 = length(C), area4 = length(D), 
                                                      area5 = length(E), n12 = length(n12), n13 = length(n13), 
                                                      n14 = length(n14), n15 = length(n15), n23 = length(n23), 
                                                      n24 = length(n24), n25 = length(n25), n34 = length(n34), 
                                                      n35 = length(n35), n45 = length(n45), n123 = length(n123), 
                                                      n124 = length(n124), n125 = length(n125), n134 = length(n134), 
                                                      n135 = length(n135), n145 = length(n145), n234 = length(n234), 
                                                      n235 = length(n235), n245 = length(n245), n345 = length(n345), 
                                                      n1234 = length(n1234), n1235 = length(n1235), n1245 = length(n1245), 
                                                      n1345 = length(n1345), n2345 = length(n2345), n12345 = length(n12345), 
                                                      category = list.names, ind = FALSE,fill=fill, ...)
      }
      else {
        stop("Invalid size of input object")
      }
      if (!is.null(sub)) {
        grob.list <- add.title(gList = grob.list, x = sub, pos = sub.pos, 
                               fontface = sub.fontface, fontfamily = sub.fontfamily, 
                               col = sub.col, cex = sub.cex)
      }
      if (!is.null(main)) {
        grob.list <- add.title(gList = grob.list, x = main, pos = main.pos, 
                               fontface = main.fontface, fontfamily = main.fontfamily, 
                               col = main.col, cex = main.cex)
      }
      grid.newpage()
      grid.draw(grob.list)
      return(1)
      #	return(grob.list)
    }
    makeColors<-function(n,colorNames="Set1") {
      maxN<-brewer.pal.info[colorNames,"maxcolors"]
      if (n<=maxN) {
        colors<-brewer.pal(n, colorNames)
      } else {
        colors<-colorRampPalette(brewer.pal(maxN, colorNames))(n)
      }
      return(colors)
    }
    colors<-makeColors(length(allSigNameList))
    png(paste0(comparisonName,"_significantVenn.png"),res=300,height=2000,width=2000)
    venn.diagram1(allSigNameList,cex=2,cat.cex=2,cat.col=colors,fill=colors)
    dev.off()
  }
  #Do heatmap significant genes if length larger or equal than 2
  if (length(allSigNameList)>=2) {
    temp<-cbind(unlist(allSigNameList),unlist(allSigDirectionList))
    colnames(temp)<-c("Gene","Direction")
    temp<-cbind(temp,comparisonName=rep(names(allSigNameList),sapply(allSigNameList,length)))
    temp<-data.frame(temp)
    dataForFigure<-temp
    #geting dataForFigure order in figure
    temp$Direction<-as.integer(as.character(temp$Direction))
    temp<-acast(temp, Gene~comparisonName ,value.var="Direction")
    temp<-temp[do.call(order, data.frame(temp)),]
    maxNameChr<-max(nchar(row.names(temp)))
    if (maxNameChr>70) {
      row.names(temp)<-substr(row.names(temp),0,70)
      dataForFigure$Gene<-substr(dataForFigure$Gene,0,70)
      warning(paste0("The gene names were too long (",maxNameChr,"). Only first 70 letters were kept."))
    }
    dataForFigure$Gene<-factor(dataForFigure$Gene,levels=row.names(temp))
    
    width=max(2500, 60 * length(unique(dataForFigure$comparisonName)))
    height=max(2000, 40 * length(unique(dataForFigure$Gene)))
    png(paste0(comparisonName,"_significantHeatmap.png"),res=300,height=height,width=width)
    g<-ggplot(dataForFigure, aes(comparisonName, Gene))+
      geom_tile(aes(fill=Direction), color="white") +
      scale_fill_manual(values=c("light green", "red")) +
      theme(axis.text.x = element_text(angle=90, vjust=0.5, size=11, hjust=0.5, face="bold"),
            axis.text.y = element_text(size=11, face="bold")) +
      coord_equal()
    print(g)
    dev.off()
  }
}#SNOPSIS
#calculates genomic estimated breeding values (GEBVs) using rrBLUP,
#GBLUP method

#AUTHOR
# Isaak Y Tecle (iyt2@cornell.edu)

options(echo = FALSE)

library(rrBLUP)
library(plyr)
library(stringr)
library(lme4)
library(randomForest)
library(data.table)
#library(genetics)

allArgs <- commandArgs()

inputFiles  <- scan(grep("input_files", allArgs, ignore.case = TRUE, perl = TRUE, value = TRUE),
                   what = "character")

outputFiles <- scan(grep("output_files", allArgs, ignore.case = TRUE,perl = TRUE, value = TRUE),
                    what = "character")

traitsFile <- grep("traits", inputFiles, ignore.case = TRUE, value = TRUE)
traitFile  <- grep("trait_info", inputFiles, ignore.case = TRUE, value = TRUE)
traitInfo  <- scan(traitFile, what = "character",)
traitInfo  <- strsplit(traitInfo, "\t");
traitId    <- traitInfo[[1]]
trait      <- traitInfo[[2]]

datasetInfoFile <- grep("dataset_info", inputFiles, ignore.case = TRUE, value = TRUE)
datasetInfo     <- c()

if (length(datasetInfoFile) != 0 ) { 
    datasetInfo <- scan(datasetInfoFile, what = "character")    
    datasetInfo <- paste(datasetInfo, collapse = " ")   
  } else {   
    datasetInfo <- c('single population')  
  }

validationTrait <- paste("validation", trait, sep = "_")
validationFile  <- grep(validationTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(validationFile)) {
  stop("Validation output file is missing.")
}

kinshipTrait <- paste("kinship", trait, sep = "_")
blupFile     <- grep(kinshipTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(blupFile)) {
  stop("GEBVs file is missing.")
}
markerTrait <- paste("marker", trait, sep = "_")
markerFile  <- grep(markerTrait, outputFiles, ignore.case = TRUE, value = TRUE)

traitPhenoFile <- paste("phenotype_trait", trait, sep = "_")
traitPhenoFile <- grep(traitPhenoFile, outputFiles,ignore.case = TRUE, value = TRUE)

varianceComponentsFile <- grep("variance_components", outputFiles, ignore.case = TRUE, value = TRUE)
filteredGenoFile       <- grep("filtered_genotype_data", outputFiles, ignore.case = TRUE, value = TRUE)
formattedPhenoFile     <- grep("formatted_phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE)

formattedPhenoData <- c()
phenoData          <- c()
genoFile <- grep("genotype_data_", inputFiles, ignore.case = TRUE, perl=TRUE, value = TRUE)

message('geno file ', genoFile)
if (is.null(genoFile)) {
  stop("genotype data file is missing.")
}

if (file.info(genoFile)$size == 0) {
  stop("genotype data file is empty.")
}

readFilteredGenoData <- c()
filteredGenoData <- c()
if (length(filteredGenoFile) != 0 && file.info(filteredGenoFile)$size != 0) {
  filteredGenoData <- fread(filteredGenoFile, na.strings = c("NA", " ", "--", "-"),  header = TRUE)
  readFilteredGenoData <- 1
  message('read in filtered geno data')
}

genoData <- c()
if (is.null(filteredGenoData)) {
  genoData <- fread(genoFile, na.strings = c("NA", " ", "--", "-"),  header = TRUE)
  message('read in unfiltered geno data')
}

if (length(formattedPhenoFile) != 0 && file.info(formattedPhenoFile)$size != 0) {
  formattedPhenoData <- as.data.frame(fread(formattedPhenoFile,
                                            na.strings = c("NA", " ", "--", "-", ".")
                                            ))
      
  row.names(formattedPhenoData) <- formattedPhenoData[, 1]
  formattedPhenoData[, 1]       <- NULL    
} else {
  phenoFile <- grep("\\/phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE, perl = TRUE)

  if (is.null(phenoFile)) {
    stop("phenotype data file is missing.")
  }

  if (file.info(phenoFile)$size == 0) {
    stop("phenotype data file is empty.")
  }
  
  phenoData <- fread(phenoFile, na.strings = c("NA", " ", "--", "-", "."), header = TRUE) 
}

phenoData  <- as.data.frame(phenoData)
phenoTrait <- c()

if (datasetInfo == 'combined populations') {
  
   if (!is.null(formattedPhenoData)) {
      phenoTrait <- subset(formattedPhenoData, select = trait)
      phenoTrait <- na.omit(phenoTrait)
   
    } else {
      dropColumns <- grep(trait, names(phenoData), ignore.case = TRUE, value = TRUE)
      phenoTrait  <- phenoData[, !(names(phenoData) %in% dropColumns)]
   
      phenoTrait            <- as.data.frame(phenoTrait)
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1]       <- NULL
      colnames(phenoTrait)  <- trait
    }
   
} else {

  if (!is.null(formattedPhenoData)) {
    phenoTrait <- subset(formattedPhenoData, select = trait)
    phenoTrait <- na.omit(phenoTrait)
   
  } else {
    dropColumns <- c("uniquename", "stock_name")
    phenoData   <- phenoData[, !(names(phenoData) %in% dropColumns)]
    
    phenoTrait <- subset(phenoData, select = c("object_name", "object_id", "design", "block", "replicate", trait))
   
    experimentalDesign <- phenoTrait[2, 'design']
  
    if (class(phenoTrait[, trait]) != 'numeric') {
      phenoTrait[, trait] <- as.numeric(as.character(phenoTrait[, trait]))
    }
      
    if (is.na(experimentalDesign) == TRUE) {experimentalDesign <- c('No Design')}
    
    if ((experimentalDesign == 'Augmented' || experimentalDesign == 'RCBD')  &&  unique(phenoTrait$block) > 1) {

      message("GS experimental design: ", experimentalDesign)

      augData <- subset(phenoTrait, select = c("object_name", "object_id",  "block",  trait))

      colnames(augData)[1] <- "genotypes"
      colnames(augData)[4] <- "trait"

      model <- try(lmer(trait ~ 0 + genotypes + (1|block),
                        augData,
                        na.action = na.omit))

      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
        
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))  
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
      }
            
    } else if (experimentalDesign == 'Alpha') {
   
      message("Experimental desgin: ", experimentalDesign)
      
      alphaData <- subset(phenoData,
                            select = c("object_name", "object_id","block", "replicate", trait)
                            )
      
      colnames(alphaData)[1] <- "genotypes"
      colnames(alphaData)[5] <- "trait"
         
      model <- try(lmer(trait ~ 0 + genotypes + (1|replicate/block),
                        alphaData,
                        na.action = na.omit))
        
      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
      
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))     
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
        
      }
      
    } else {

      phenoTrait <- subset(phenoData,
                           select = c("object_name", "object_id",  trait))
       
      if (sum(is.na(phenoTrait)) > 0) {
        message("No. of pheno missing values: ", sum(is.na(phenoTrait)))      
        phenoTrait <- na.omit(phenoTrait)
      }

        #calculate mean of reps/plots of the same accession and
        #create new df with the accession means    
     
      phenoTrait   <- phenoTrait[order(row.names(phenoTrait)), ]
      phenoTrait   <- data.frame(phenoTrait)
      message('phenotyped lines before averaging: ', length(row.names(phenoTrait)))
   
      phenoTrait<-ddply(phenoTrait, "object_name", colwise(mean))
      message('phenotyped lines after averaging: ', length(row.names(phenoTrait)))
        
      phenoTrait <- subset(phenoTrait, select = c("object_name", trait))
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1] <- NULL
       
        #format all-traits population phenotype dataset
        ## formattedPhenoData <- phenoData
        ## dropColumns <- c("object_id", "stock_id", "design", "block", "replicate" )

        ## formattedPhenoData <- formattedPhenoData[, !(names(formattedPhenoData) %in% dropColumns)]
        ## formattedPhenoData <- ddply(formattedPhenoData,
        ##                             "object_name",
        ##                             colwise(mean)
        ##                             )

        ## row.names(formattedPhenoData) <- formattedPhenoData[, 1]
        ## formattedPhenoData[, 1] <- NULL

        ## formattedPhenoData <- round(formattedPhenoData,
        ##                             digits=3
        ##                             )     
    }
  }
}

 ### MAF calculation ###
calculateMAF <- function(x) {
  a0 <-  length(x[x==0])
  a1 <-  length(x[x==1])
  a2 <-  length(x[x==2])
  aT <- a0 + a1 + a2

  p <- ((2*a0)+a1)/(2*aT)
  q <- 1- p

  maf <- min(p, q)
  
  return (maf)

}



if (is.null(filteredGenoData)) {

  #remove markers with > 60% missing marker data
  message('no of markers before filtering out: ', ncol(genoData))
  genoData[, which(colSums(is.na(genoData)) >= nrow(genoData) * 0.6) := NULL]
  message('no of markers after filtering out 60% missing: ', ncol(genoData))

  #remove indls with > 80% missing marker data
  genoData[, noMissing := apply(.SD, 1, function(x) sum(is.na(x)))]
  genoData <- genoData[noMissing <= ncol(genoData) * 0.8]
  genoData[, noMissing := NULL]
  message('no of indls after filtering out ones with 80% missing: ', nrow(genoData))

  #remove monomorphic markers
  message('marker no before monomorphic markers cleaning ', ncol(genoData))
  genoData[, which(apply(genoData, 2,  function(x) length(unique(x))) < 2) := NULL ]
  message('marker no after monomorphic markers cleaning ', ncol(genoData))

  #remove markers with MAF < 5%
  genoData[, which(apply(genoData, 2,  calculateMAF) < 0.05) := NULL ]
  message('marker no after MAF cleaning ', ncol(genoData))

  genoData           <- as.data.frame(genoData)
  rownames(genoData) <- genoData[, 1]
  genoData[, 1]      <- NULL
  filteredGenoData   <- genoData 
} else {
  genoData           <- as.data.frame(filteredGenoData)
  rownames(genoData) <- genoData[, 1]
  genoData[, 1]      <- NULL
}

predictionTempFile <- grep("prediction_population", inputFiles, ignore.case = TRUE, value = TRUE)
predictionFile       <- c()
filteredPredGenoFile <- c()
predictionAllFiles   <- c()

message('prediction temp genotype file: ', predictionTempFile)

if (length(predictionTempFile) !=0 ) {
  predictionAllFiles <- scan(predictionTempFile, what = "character")

  predictionFile <- grep("\\/genotype_data", predictionAllFiles, ignore.case = TRUE, perl=TRUE, value = TRUE)
  message('prediction unfiltered genotype file: ', predictionFile)

  filteredPredGenoFile   <- grep("filtered_genotype_data_",  predictionAllFiles, ignore.case = TRUE, perl=TRUE, value = TRUE)
  message('prediction filtered genotype file: ', predictionFile)
}

predictionPopGEBVsFile <- grep("prediction_pop_gebvs", outputFiles, ignore.case = TRUE, value = TRUE)

message("filtered pred geno file: ", filteredPredGenoFile)
message("prediction gebv file: ",  predictionPopGEBVsFile)

predictionData <- c()
readFilteredPredGenoData <- c()

if (length(predictionFile) != 0 || length(filteredPredGenoFile) != 0 ) {
  
  if (file.info(filteredPredGenoFile)$size != 0) {
    predictionData <- fread(filteredPredGenoFile, na.strings = c("NA", " ", "--", "-"),)
    readFilteredPredGenoData <- 1
    message('read in filtered prediction genotype data')
  } else {

    predictionData <- fread(predictionFile, na.strings = c("NA", " ", "--", "-"),)
    message('selection population: no of markers before filtering out: ', ncol(predictionData))

   #remove monomorphic markers
    message('marker no before monomorphic markers cleaning ', ncol(predictionData))
    predictionData[, which(apply(predictionData, 2,  function(x) length(unique(x))) < 2) := NULL ]
    message('marker no after monomorphic markers cleaning ', ncol(predictionData))
    
    predictionData[, which(colSums(is.na(predictionData)) >= nrow(predictionData) * 0.6) := NULL]

    #remove indls with > 80% missing marker data
    predictionData[, noMissing := apply(.SD, 1, function(x) sum(is.na(x)))]
    predictionData <- predictionData[noMissing <= ncol(predictionData) * 0.8]
    predictionData[, noMissing := NULL]
 
    predictionData[, which(apply(predictionData, 2,  calculateMAF) < 0.05) := NULL ]
    message('selection pop marker no after MAF cleaning ', ncol(predictionData))
}
  predictionData           <- as.data.frame(predictionData)
  rownames(predictionData) <- predictionData[, 1]
  predictionData[, 1]      <- NULL  
}

#impute genotype values for obs with missing values,
#based on mean of neighbouring 10 (arbitrary) obs
genoDataMissing <- c()

if (sum(is.na(genoData)) > 0) {
  genoDataMissing<- c('yes')

  message("sum of geno missing values, ", sum(is.na(genoData)) )  
  genoData <- na.roughfix(genoData)
  genoData <- data.matrix(genoData)
}

genoData <- genoData[order(row.names(genoData)), ]

#create phenotype and genotype datasets with
#common stocks only
message('phenotyped lines: ', length(row.names(phenoTrait)))
message('genotyped lines: ', length(row.names(genoData)))

#extract observation lines with both
#phenotype and genotype data only.
commonObs <- intersect(row.names(phenoTrait), row.names(genoData))
commonObs <- data.frame(commonObs)
rownames(commonObs)<-commonObs[, 1]

message('lines with both genotype and phenotype data: ', length(row.names(commonObs)))

#include in the genotype dataset only observation lines
#with phenotype data
message("genotype lines before filtering for phenotyped only: ", length(row.names(genoData)))        
genoDataFilteredObs <- genoData[(rownames(genoData) %in% rownames(commonObs)), ]
message("genotype lines after filtering for phenotyped only: ", length(row.names(genoDataFilteredObs)))

#drop observation lines without genotype data
message("phenotype lines before filtering for genotyped only: ", length(row.names(phenoTrait)))        
phenoTrait <- merge(data.frame(phenoTrait), commonObs, by=0, all=FALSE)
rownames(phenoTrait) <- phenoTrait[, 1]
phenoTrait <- subset(phenoTrait, select=trait)

message("phenotype lines after filtering for genotyped only: ", length(row.names(phenoTrait)))
#a set of only observation lines with genotype data

traitPhenoData   <- data.frame(round(phenoTrait, digits = 2))           
phenoTrait       <- data.matrix(phenoTrait)
genoDataFilteredObs <- data.matrix(genoDataFilteredObs)

#impute missing data in prediction data
predictionDataMissing <- c()
if (length(predictionData) != 0) {
  #purge markers unique to both populations
  commonMarkers       <- intersect(names(data.frame(genoDataFilteredObs)), names(predictionData))
  predictionData      <- subset(predictionData, select = commonMarkers)
  genoDataFilteredObs <- subset(genoDataFilteredObs, select= commonMarkers)
  
  if (sum(is.na(predictionData)) > 0) {
    predictionDataMissing <- c('yes')
    message("sum of geno missing values, ", sum(is.na(predictionData)) )  
    predictionData <- data.matrix(na.roughfix(predictionData))
    
  }
}

relationshipMatrixFile <- grep("relationship_matrix", outputFiles, ignore.case = TRUE, value = TRUE)

message("relationship matrix file: ", relationshipMatrixFile)

relationshipMatrix <- c()
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size > 0 ) {
    relationshipDf <- as.data.frame(fread(relationshipMatrixFile))

    rownames(relationshipDf) <- relationshipDf[, 1]
    relationshipDf[, 1]      <- NULL
    relationshipMatrix       <- data.matrix(relationshipDf)
  }
}

#change genotype coding to [-1, 0, 1], to use the A.mat ) if  [0, 1, 2]
genoTrCode <- grep("2", genoDataFilteredObs[1, ], value = TRUE)
if(length(genoTrCode) != 0) {
  genoDataFilteredObs <- genoDataFilteredObs - 1
}

if (length(predictionData) != 0 ) {
  genoSlCode <- grep("2", predictionData[1, ], value = TRUE)
  if (length(genoSlCode) != 0 ) {
    predictionData <- predictionData - 1
  }
}

ordered.markerEffects <- c()
if ( length(predictionData) == 0 ) {
  markerEffects <- mixed.solve(y = phenoTrait,
                               Z = genoDataFilteredObs
                               )

  ordered.markerEffects <- data.matrix(markerEffects$u)
  ordered.markerEffects <- data.matrix(ordered.markerEffects [order (-ordered.markerEffects[, 1]), ])
  ordered.markerEffects <- round(ordered.markerEffects, digits=5)

  colnames(ordered.markerEffects) <- c("Marker Effects")

}

#additive relationship model
#calculate the inner products for
#genotypes (realized relationship matrix)
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size == 0) {
    relationshipMatrix <- tcrossprod(data.matrix(genoData))
  }
}
relationshipMatrixFiltered <- relationshipMatrix[(rownames(relationshipMatrix) %in% rownames(commonObs)),]
relationshipMatrixFiltered <- relationshipMatrixFiltered[, (colnames(relationshipMatrixFiltered) %in% rownames(commonObs))]

#construct an identity matrix for genotypes
identityMatrix <- diag(nrow(phenoTrait))

relationshipMatrixFiltered <- data.matrix(relationshipMatrixFiltered)

iGEBV  <- mixed.solve(y = phenoTrait, Z = identityMatrix, K = relationshipMatrixFiltered) 
iGEBVu <- iGEBV$u

heritability  <- c()

if ( is.null(predictionFile) == TRUE ) {
  additiveEffects <- data.frame(iGEBVu)
 
  pN <- nrow(phenoTrait)
  aN <- nrow(additiveEffects)

  if (pN <= 1 || pN != aN) {
    stop("phenoTrait and additiveEffects have different lengths: ",
         pN, " and ", aN, ".")
  }
      
  if (TRUE %in% is.na(phenoTrait) || TRUE %in% is.na(additiveEffects)) {
    stop(" Arguments phenoTrait and additiveEffects have missing values.")
  }
  
  phenoVariance <- var(phenoTrait)
  gebvVariance  <- var(additiveEffects)
  heritability  <- round((gebvVariance / phenoVariance), digits = 2)
      
  cat("\n", file = varianceComponentsFile,  append = FALSE)
  cat('Error variance', iGEBV$Ve, file = varianceComponentsFile, sep = "\t", append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Additive genetic variance',  iGEBV$Vu, file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Phenotype mean', iGEBV$beta,file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Heritability (h)', heritability, file = varianceComponentsFile, sep = '\t', append = TRUE)
}

iGEBV         <- data.matrix(iGEBVu)
ordered.iGEBV <- as.data.frame(iGEBV[order(-iGEBV[, 1]), ])
ordered.iGEBV <- round(ordered.iGEBV, digits = 3)

combinedGebvsFile <- grep('selected_traits_gebv', outputFiles, ignore.case = TRUE,value = TRUE)

allGebvs<-c()
if (length(combinedGebvsFile) != 0) {
    fileSize <- file.info(combinedGebvsFile)$size
    if (fileSize != 0 ) {
        combinedGebvs <- as.data.frame(fread(combinedGebvsFile))

        rownames(combinedGebvs) <- combinedGebvs[,1]
        combinedGebvs[,1]       <- NULL

        colnames(ordered.iGEBV) <- c(trait)
      
        traitGEBV <- as.data.frame(ordered.iGEBV)
        allGebvs <- merge(combinedGebvs, traitGEBV,
                          by = 0,
                          all = TRUE                     
                          )

        rownames(allGebvs) <- allGebvs[,1]
        allGebvs[,1] <- NULL
     }
  }

colnames(ordered.iGEBV) <- c(trait)
                  
#cross-validation
validationAll <- c()

if(is.null(predictionFile)) {
  genoNum <- nrow(phenoTrait)
if(genoNum < 20 ) {
  warning(genoNum, " is too small number of genotypes.")
}
  
reps <- round_any(genoNum, 10, f = ceiling) %/% 10

genotypeGroups <-c()

if (genoNum %% 10 == 0) {
    genotypeGroups <- rep(1:10, reps)
  } else {
    genotypeGroups <- rep(1:10, reps) [- (genoNum %% 10) ]
  }

set.seed(4567)                                   
genotypeGroups <- genotypeGroups[ order (runif(genoNum)) ]

for (i in 1:10) {
  tr <- paste("trPop", i, sep = ".")
  sl <- paste("slPop", i, sep = ".")
 
  trG <- which(genotypeGroups != i)
  slG <- which(genotypeGroups == i)
  
  assign(tr, trG)
  assign(sl, slG)

  kblup <- paste("rKblup", i, sep = ".")
  
  result <- kinship.BLUP(y = phenoTrait[trG, ],
                         G.train = genoDataFilteredObs[trG, ],
                         G.pred = genoDataFilteredObs[slG, ],                      
                         mixed.method = "REML",
                         K.method = "RR",
                         )
 
  assign(kblup, result)

#calculate cross-validation accuracy  
  valCorData <- merge(phenoTrait[slG, ], result$g.pred, by=0, all=FALSE)
  rownames(valCorData) <- valCorData[, 1]
  valCorData[, 1]      <- NULL
 
  accuracy <- try(cor(valCorData))
  validation <- paste("validation", i, sep = ".")

  cvTest <- paste("Validation test", i, sep = " ")

  if ( class(accuracy) != "try-error")
    {
      accuracy <- round(accuracy[1,2], digits = 3)
      accuracy <- data.matrix(accuracy)
    
      colnames(accuracy) <- c("correlation")
      rownames(accuracy) <- cvTest

      assign(validation, accuracy)
      
      if (!is.na(accuracy[1,1])) {
        validationAll <- rbind(validationAll, accuracy)
      }    
    }
}

validationAll <- data.matrix(validationAll[order(-validationAll[, 1]), ])
     
if (!is.null(validationAll)) {
    validationMean <- data.matrix(round(colMeans(validationAll), digits = 2))
   
    rownames(validationMean) <- c("Average")
     
    validationAll <- rbind(validationAll, validationMean)
    colnames(validationAll) <- c("Correlation")
  }
}

predictionPopResult <- c()
predictionPopGEBVs  <- c()

if (length(predictionData) != 0) {
    message("running prediction for selection candidates...marker data", ncol(predictionData), " vs. ", ncol(genoDataFilteredObs))

    predictionPopResult <- kinship.BLUP(y = phenoTrait,
                                        G.train = genoDataFilteredObs,
                                        G.pred = predictionData,
                                        mixed.method = "REML",
                                        K.method = "RR"
                                        )
 message("running prediction for selection candidates...DONE!!")

    predictionPopGEBVs <- round(data.matrix(predictionPopResult$g.pred), digits = 3)
    predictionPopGEBVs <- data.matrix(predictionPopGEBVs[order(-predictionPopGEBVs[, 1]), ])
   
    colnames(predictionPopGEBVs) <- c(trait)
  
}

if (!is.null(predictionPopGEBVs) & length(predictionPopGEBVsFile) != 0)  {
    write.table(predictionPopGEBVs,
                file = predictionPopGEBVsFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if(!is.null(validationAll)) {
    write.table(validationAll,
                file = validationFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.markerEffects)) {
    write.table(ordered.markerEffects,
                file = markerFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.iGEBV)) {
    write.table(ordered.iGEBV,
                file = blupFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (length(combinedGebvsFile) != 0 ) {
    if(file.info(combinedGebvsFile)$size == 0) {
        write.table(ordered.iGEBV,
                    file = combinedGebvsFile,
                    sep = "\t",
                    col.names = NA,
                    quote = FALSE,
                    )
      } else {
      write.table(allGebvs,
                  file = combinedGebvsFile,
                  sep = "\t",
                  quote = FALSE,
                  col.names = NA,
                  )
    }
}

if (!is.null(traitPhenoData) & length(traitPhenoFile) != 0) {
    write.table(traitPhenoData,
                file = traitPhenoFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                )
}

if (!is.null(filteredGenoData) && is.null(readFilteredGenoData)) {
  write.table(filteredGenoData,
              file = filteredGenoFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
            )

}

if (!is.null(filteredPredGenoFile) && is.null(readFilteredPredGenoData)) {
  write.table(predictionData,
              file = filteredPredGenoFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
            )
}



## if (!is.null(genoDataMissing)) {
##   write.table(genoData,
##               file = genoFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##             )

## }

## if (!is.null(predictionDataMissing)) {
##   write.table(predictionData,
##               file = predictionFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##               )
## }


if (file.info(relationshipMatrixFile)$size == 0) {
  write.table(relationshipMatrix,
              file = relationshipMatrixFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}


if (file.info(formattedPhenoFile)$size == 0 && !is.null(formattedPhenoData) ) {
  write.table(formattedPhenoData,
              file = formattedPhenoFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}

message("Done.")

q(save = "no", runLast = FALSE)
#' Function to batch download single location DAYMET data
#'
#' This function downloads DAYMET data for several single pixel
#' location.
#' @param file_location : file with several site locations and coordinates
#' in a format site, latitude, longitude
#' @param start_yr : start of the range of years over which to download data
#' @param end_yr : end of the range of years over which to download data
#' @param internal : TRUE or FALSE, load data into workspace or save to disc
#' @keywords DAYMET, climate data
#' @export
#' @examples
#' 
#' # NOT RUN
#' # batch.download("yourlocations.csv")

batch.download.daymet <- function(file_location,
                                  start_yr=1980,
                                  end_yr=as.numeric(format(Sys.time(), "%Y"))-1,
                                  internal=FALSE){
  
  # read table with sites and coordinates
  locations = read.table(file_location,sep=',')

  # loop over all lines in the file
  for (i in 1:dim(locations)[1]){
    site = as.character(locations[i,1])
    lat = as.numeric(locations[i,2])
    lon = as.numeric(locations[i,3])
    try(download.daymet(site=site,lat=lat,lon=lon,start_yr=start_yr,end_yr=end_yr,internal=internal),silent=FALSE)
  }
}#' Function to batch download gridded DAYMET data
#'
#' This function downloads DAYMET data 
#' @param lat1 : top left latitude (decimal degrees)
#' @param lon1 : top left longitude (decimal degrees)
#' @param lat2 : bottom right latitude (decimal degrees)
#' @param lon2 : bottom right longitude(decimal degrees)
#' @param start_yr : start of the range of years over which to download data
#' @param end_yr : end of the range of years over which to download data
#' @param param : climate variable you want to download vapour pressure (vp), 
#' minimum and maximum temperature (tmin,tmax), snow water equivalent (swe), 
#' solar radiation (srad), precipitation (prcp) , day length (dayl).
#' The default setting is ALL, this will download all the previously mentioned
#' climate variables.
#' @keywords DAYMET, climate data
#' @export
#' @examples
#' download.daymet.tiles(lat1=35.6737,
#'                       lon1=-86.3968,
#'                       start_yr=1980,
#'                       end_yr=1980,
#'                       param="ALL")

download.daymet.tiles = function(lat1=35.6737,
                                 lon1=-86.3968,
                                 lat2=NA,
                                 lon2=NA,
                                 start_yr=1980,
                                 end_yr=1980,
                                 param="ALL"){
  
  # determine system
  OS = Sys.info()[['sysname']]
  
  # load DAYMET grid associated with the package
  # (this is an imported shapefile)
  # I do not store any additional data in the .rdata
  # file to keep the code transparent.
  data("DAYMET_grid")
  
  # grab the projection string. This is a LCC projection.
  projection = sp::CRS(sp::proj4string(tile_outlines))
  
  # extract tile IDs (vector shape) and the DAYMET IDs associated
  # with them
  tile_nrs = tile_outlines@data[,1]
  
  # if argument 3 or 4 are the default grab only the tile
  # of the first coordinate set, if 4 arguments are given
  # extract all tile numbers within this region of interest
  if ( is.na(lat2) | is.na(lon2)){
    
        # create coordinate pairs, with original coordinate  system
        location = sp::SpatialPoints(cbind(lon1,lat1), projection)
        
        # extract tile for this location
        tiles = sp::over(location,tile_outlines)$TileID
        
        # do not continue if outside range
        if (is.na(tiles)){
          stop("Your defined range is outside DAYMET coverage,
               check your coordinate values!")
        }

      }else{
        
        # this is some juggling to define a polygon (vector format)
        # which I will convert to LCC and use as a mask to extract
        # tile numbers. As such I avoid artefacts due to resampling.
        rect_corners = cbind(c(lon1,rep(lon2,2),lon1),
                             c(rep(lat2,2),rep(lat1,2)))
        ROI = sp::SpatialPoints(cbind(rect_corners[,1],
                                      rect_corners[,2]), projection)
        
        # set original projection
        sp::proj4string(ROI) = projection
        
        # extract unique tiles overlapping the rectangular ROI
        tiles = unique(sp::over(ROI,tile_outlines)$TileID)
        
        if (is.null(tiles)){
          stop("Your defined range is outside DAYMET coverage,
               check your coordinate values!")
        }
  }
  
  # calculate the end of the range of years to download
  # conservative setting based upon the current date -1 year
  max_year = as.numeric(format(Sys.time(), "%Y"))-1
  
  # check validaty of the range of years to download
  # I'm not sure when new data is released so this might be a
  # very conservative setting, remove it if you see more recent data
  # on the website
  
  if (start_yr < 1980){
    stop("Start year preceeds valid data range!")
  }
  rect_corners = cbind(c(lon1,rep(lon2,2),lon1),c(rep(lat2,2),rep(lat1,2)))
  
  if (end_yr > max_year){
    stop("End year exceeds valid data range!")
  }
  
  # if the year range is valid, create a string of valid years
  year_range = seq(start_yr,end_yr,by=1)

  # check the parameters we want to download
  if (param == "ALL"){
    param = c('vp','tmin','tmax','swe','srad','prcp','dayl')
  }

  for ( i in year_range ){
    for ( j in tiles ){
      for ( k in param ){
        
        # create download string / url  
        download_string = sprintf("http://thredds.daac.ornl.gov/thredds/fileServer/ornldaac/1328/tiles/%s/%s_%s/%s.nc",i,j,i,k)
                
        # create filename for the output file
        daymet_file = paste(k,"_",i,"_",j,".nc",sep='')
        
        # provide some feedback
        cat(paste('Downloading DAYMET data for tile: ',j,
                  '; year: ',i,
                  '; product: ',k,
                  '\n',sep=''))
        
        # download data, force binary data mode
        try(downloader::download(download_string,
                                 daymet_file,
                                 quiet=TRUE,
                                 mode="wb"),silent=FALSE)  
      }
    }
  }
}
#' Function to batch download gridded DAYMET data
#'
#' This function downloads DAYMET data 
#' @param lat1 : top left latitude (decimal degrees)
#' @param lon1 : top left longitude (decimal degrees)
#' @param lat2 : bottom right latitude (decimal degrees)
#' @param lon2 : bottom right longitude(decimal degrees)
#' @param start_yr : start of the range of years over which to download data
#' @param end_yr : end of the range of years over which to download data
#' @param param : climate variable you want to download vapour pressure (vp), 
#' minimum and maximum temperature (tmin,tmax), snow water equivalent (swe), 
#' solar radiation (srad), precipitation (prcp) , day length (dayl).
#' The default setting is ALL, this will download all the previously mentioned
#' climate variables.
#' @keywords DAYMET, climate data
#' @export
#' @examples
#' download.daymet.tiles(lat1=35.6737,
#'                       lon1=-86.3968,
#'                       start_yr=1980,
#'                       end_yr=1980,
#'                       param="ALL")

download.daymet.tiles = function(lat1=35.6737,
                                 lon1=-86.3968,
                                 lat2=NA,
                                 lon2=NA,
                                 start_yr=1980,
                                 end_yr=1980,
                                 param="ALL"){
  
  # determine system
  OS = Sys.info()[['sysname']]
  
  # load DAYMET grid associated with the package
  # (this is an imported shapefile)
  # I do not store any additional data in the .rdata
  # file to keep the code transparent.
  #data("DAYMET_grid")
  
  # grab the projection string. This is a LCC projection.
  projection = sp::CRS(sp::proj4string(tile_outlines))
  
  # extract tile IDs (vector shape) and the DAYMET IDs associated
  # with them
  tile_nrs = tile_outlines@data[,1]
  
  # if argument 3 or 4 are the default grab only the tile
  # of the first coordinate set, if 4 arguments are given
  # extract all tile numbers within this region of interest
  if ( is.na(lat2) | is.na(lon2)){
    
        # create coordinate pairs, with original coordinate  system
        location = sp::SpatialPoints(cbind(lon1,lat1), projection)
        
        # extract tile for this location
        tiles = sp::over(location,tile_outlines)$TileID
        
        # do not continue if outside range
        if (is.na(tiles)){
          stop("Your defined range is outside DAYMET coverage,
               check your coordinate values!")
        }

      }else{
        
        # this is some juggling to define a polygon (vector format)
        # which I will convert to LCC and use as a mask to extract
        # tile numbers. As such I avoid artefacts due to resampling.
        rect_corners = cbind(c(lon1,rep(lon2,2),lon1),
                             c(rep(lat2,2),rep(lat1,2)))
        ROI = sp::SpatialPoints(cbind(rect_corners[,1],
                                      rect_corners[,2]), projection)
        
        # set original projection
        sp::proj4string(ROI) = projection
        
        # extract unique tiles overlapping the rectangular ROI
        tiles = unique(sp::over(ROI,tile_outlines)$TileID)
        
        if (is.null(tiles)){
          stop("Your defined range is outside DAYMET coverage,
               check your coordinate values!")
        }
  }
  
  # calculate the end of the range of years to download
  # conservative setting based upon the current date -1 year
  max_year = as.numeric(format(Sys.time(), "%Y"))-1
  
  # check validaty of the range of years to download
  # I'm not sure when new data is released so this might be a
  # very conservative setting, remove it if you see more recent data
  # on the website
  
  if (start_yr < 1980){
    stop("Start year preceeds valid data range!")
  }
  rect_corners = cbind(c(lon1,rep(lon2,2),lon1),c(rep(lat2,2),rep(lat1,2)))
  
  if (end_yr > max_year){
    stop("End year exceeds valid data range!")
  }
  
  # if the year range is valid, create a string of valid years
  year_range = seq(start_yr,end_yr,by=1)

  # check the parameters we want to download
  if (param == "ALL"){
    param = c('vp','tmin','tmax','swe','srad','prcp','dayl')
  }

  for ( i in year_range ){
    for ( j in tiles ){
      for ( k in param ){
        
        # create download string / url  
        download_string = sprintf("http://thredds.daac.ornl.gov/thredds/fileServer/ornldaac/1328/tiles/%s/%s_%s/%s.nc",i,j,i,k)
                
        # create filename for the output file
        daymet_file = paste(k,"_",i,"_",j,".nc",sep='')
        
        # provide some feedback
        cat(paste('Downloading DAYMET data for tile: ',j,
                  '; year: ',i,
                  '; product: ',k,
                  '\n',sep=''))
        
        # download data, force binary data mode
        try(downloader::download(download_string,
                                 daymet_file,
                                 quiet=TRUE,
                                 mode="wb"),silent=FALSE)  
      }
    }
  }
}
#Setup
# setwd("D:\\Users\\Greg Sanders\\Documents\\Development\\Lookup-Tables")
setwd("K:\\Development\\Lookup-Tables")
source("SQLimportTools.r")

#******Importing into Errorlogging.FSRSviolatesConstraint
#Match up Errorlogging.FSRSviolatesType to Errorlogging.FSRSviolatesConstraint
OriginTableType.df<-ReadCreateTable("ErrorLogging_FSRSviolatesType.txt")
DestTableType.df<-ReadCreateTable("ErrorLogging_FSRSviolatesConstraint.txt")
OriginTableType.df<-TranslateName(OriginTableType.df)
MergeType.df<-MergeSourceAndCSISnameTables(OriginTableType.df,DestTableType.df)

#Create Try Convert
TryConvertList<-Create_Try_Converts(MergeType.df,"Errorlogging","FSRSviolatesType")
write(TryConvertList,"FSRStryConvertList.txt")

#Transfer from Errorlogging.FSRSviolatesType to Errorlogging.FSRSviolatesConstraint
InsertList<-CreateInsert(MergeType.df,
             "ErrorLogging",
             "FSRSviolatesType",
             "ErrorLogging",
             "FSRSviolatesConstraint",
             DateType=101)
write(InsertList,"FSRSinsert.txt")
write(CreateCSISdates("Contract","FSRS"),"CSISdates.txt")

#******Importing into Contract.FSRS 
#Match up Errorlogging.FSRSviolatesConstraint to Contract.FSRS 
DestTableConstraint.df<-ReadCreateTable("Contract_FSRS.txt")
OriginTableConstraint.df<-ReadCreateTable("ErrorLogging_FSRSviolatesConstraint.txt")
OriginTableConstraint.df<-TranslateName(OriginTableConstraint.df)
MergeConstraint.df<-MergeSourceAndCSISnameTables(OriginTableConstraint.df,DestTableConstraint.df)


#Transfer from Errorlogging.FSRSviolatesConstraint to Contract.FSRS
ConstTable.df<-TranslateName(DestTableConstraint.df)
MergeConst<-MergeSourceAndCSISnameTables(ConstTable.df,ConstTable.df)
InsertList<-CreateInsert(MergeConst,
                         "ErrorLogging",
                         "FSRSviolatesConstraint",
                         "Contract",
                         "FSRS",
                         DateType=101)
write(InsertList,"Insert2.txt")



fkTable.df<-ReadCreateTable("Contract_FSRS.txt")

  debug(ConvertFieldToForeignKey)
  Output<-ConvertFieldToForeignKey("Contract","FSRS","[PrimeAwardPrincipalPlaceCountry]",
                           fkTable.df,
                           "FPDStypeTable","Country3lettercode")
  write(Output,"ConvertfieldToForeignKey.txt")
  
  # ConvertFieldToForeignKey("Contract","FSRS","[SubAwardeeDunsnumber]",
  #                          fkTable.df,
  #                          "Contractor","Dunsnumber")
  # 
  # ConvertFieldToForeignKey("Contract","FSRS","[SubAwardeeParentDuns]",
  #                          fkTable.df,
  #                          "Contractor","Dunsnumber")
  
  
  
  
  
  # --Decimal nullif('')
  # --prime-award_source_sub_acocunt varchar(2)?
  # --prime-award_source_account varchar(4)?
  # --prime-award_source_subaccount varchar(3)
  # --scientific notation to decimal
  
  # 
  # OriginalTable.df<-ReadCreateTable("ErrorLogging_FSRSviolatesType.csv")
  # TargetTable.df<-ReadCreateTable("Contract_FSRS.csv")
  # OriginalTable.df<-TranslateName(OriginalTable.df)
  # MergeTable.df<-MergeSourceAndCSISnameTables(OriginalTable.df,TargetTable.df)
  # 
  # # ChangeList<-ConvertAllOfType(TargetTable.df,
  # #                  "[real]",
  # #                  "[decimal](19, 4)",
  # #                  "Contract",
  # #                  "FSRS")
  # # write(ChangeList,"ChangeList.txt")
  # # 
  # # ChangeList<-ConvertAllOfType(TargetTable.df,
  # #                              "[real]",
  # #                              "[decimal](19, 4)",
  # #                              "Errorlogging",
  # #                              "FSRSviolatesConstraint")
  # # write(ChangeList,"ChangeList.txt")
  # 
  # ListProblemType(TargetTable.df)
  # debug(ConvertSwitch)
  # 
  # debug(OneSwitch)
  # TryConvertList<-Create_Try_Converts(MergeTable.df,"ErrorLogging","FSRSviolatesType")
  # write(TryConvertList,"TryConvertList.txt")
  # 
  # InsertList<-CreateInsert(MergeTable.df,
  #                          "ErrorLogging",
  #                          "FSRSviolatesType",
  #                          "ErrorLogging",
  #                          "FSRSviolatesConstraint")
  # write(InsertList,"InsertList.txt")
  # 
  # 
  # #SNOPSIS
#calculates genomic estimated breeding values (GEBVs) using rrBLUP,
#GBLUP method

#AUTHOR
# Isaak Y Tecle (iyt2@cornell.edu)

options(echo = FALSE)

library(rrBLUP)
library(plyr)
library(stringr)
library(lme4)
library(randomForest)
library(data.table)
#library(genetics)

allArgs <- commandArgs()

inputFiles  <- scan(grep("input_files", allArgs, ignore.case = TRUE, perl = TRUE, value = TRUE),
                   what = "character")

outputFiles <- scan(grep("output_files", allArgs, ignore.case = TRUE,perl = TRUE, value = TRUE),
                    what = "character")

traitsFile <- grep("traits", inputFiles, ignore.case = TRUE, value = TRUE)
traitFile  <- grep("trait_info", inputFiles, ignore.case = TRUE, value = TRUE)
traitInfo  <- scan(traitFile, what = "character",)
traitInfo  <- strsplit(traitInfo, "\t");
traitId    <- traitInfo[[1]]
trait      <- traitInfo[[2]]

datasetInfoFile <- grep("dataset_info", inputFiles, ignore.case = TRUE, value = TRUE)
datasetInfo     <- c()

if (length(datasetInfoFile) != 0 ) { 
    datasetInfo <- scan(datasetInfoFile, what = "character")    
    datasetInfo <- paste(datasetInfo, collapse = " ")   
  } else {   
    datasetInfo <- c('single population')  
  }

validationTrait <- paste("validation", trait, sep = "_")
validationFile  <- grep(validationTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(validationFile)) {
  stop("Validation output file is missing.")
}

kinshipTrait <- paste("kinship", trait, sep = "_")
blupFile     <- grep(kinshipTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(blupFile)) {
  stop("GEBVs file is missing.")
}
markerTrait <- paste("marker", trait, sep = "_")
markerFile  <- grep(markerTrait, outputFiles, ignore.case = TRUE, value = TRUE)

traitPhenoFile <- paste("phenotype_trait", trait, sep = "_")
traitPhenoFile <- grep(traitPhenoFile, outputFiles,ignore.case = TRUE, value = TRUE)

varianceComponentsFile <- grep("variance_components", outputFiles, ignore.case = TRUE, value = TRUE)
filteredGenoFile       <- grep("filtered_genotype_data", outputFiles, ignore.case = TRUE, value = TRUE)
formattedPhenoFile     <- grep("formatted_phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE)

formattedPhenoData <- c()
phenoData          <- c()

genoFile <- grep("genotype_data", inputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(genoFile)) {
  stop("genotype data file is missing.")
}

if (file.info(genoFile)$size == 0) {
  stop("genotype data file is empty.")
}

usedFilteredGenoData <- c()
filteredGenoData <- c()
if (length(filteredGenoFile) != 0 && file.info(filteredGenoFile)$size != 0) {
  filteredGenoData <- fread(filteredGenoFile, na.strings = c("NA", " ", "--", "-"),  header = TRUE)
  usedFilteredGenoData <- 1
  message('read in filtered geno data')
}

genoData <- c()
if (is.null(filteredGenoData)) {
  genoData <- fread(genoFile, na.strings = c("NA", " ", "--", "-"),  header = TRUE)
  message('read in unfiltered geno data')
}

if (length(formattedPhenoFile) != 0 && file.info(formattedPhenoFile)$size != 0) {
  formattedPhenoData <- as.data.frame(fread(formattedPhenoFile,
                                            na.strings = c("NA", " ", "--", "-", ".")
                                            ))
      
  row.names(formattedPhenoData) <- formattedPhenoData[, 1]
  formattedPhenoData[, 1]       <- NULL    
} else {
  phenoFile <- grep("\\/phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE, perl = TRUE)

  if (is.null(phenoFile)) {
    stop("phenotype data file is missing.")
  }

  if (file.info(phenoFile)$size == 0) {
    stop("phenotype data file is empty.")
  }
  
  phenoData <- fread(phenoFile, na.strings = c("NA", " ", "--", "-", "."), header = TRUE) 
}

phenoData  <- as.data.frame(phenoData)
phenoTrait <- c()

if (datasetInfo == 'combined populations') {
  
   if (!is.null(formattedPhenoData)) {
      phenoTrait <- subset(formattedPhenoData, select = trait)
      phenoTrait <- na.omit(phenoTrait)
   
    } else {
      dropColumns <- grep(trait, names(phenoData), ignore.case = TRUE, value = TRUE)
      phenoTrait  <- phenoData[, !(names(phenoData) %in% dropColumns)]
   
      phenoTrait            <- as.data.frame(phenoTrait)
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1]       <- NULL
      colnames(phenoTrait)  <- trait
    }
   
} else {

  if (!is.null(formattedPhenoData)) {
    phenoTrait <- subset(formattedPhenoData, select = trait)
    phenoTrait <- na.omit(phenoTrait)
   
  } else {
    dropColumns <- c("uniquename", "stock_name")
    phenoData   <- phenoData[, !(names(phenoData) %in% dropColumns)]
    
    phenoTrait <- subset(phenoData, select = c("object_name", "object_id", "design", "block", "replicate", trait))
   
    experimentalDesign <- phenoTrait[2, 'design']
  
    if (class(phenoTrait[, trait]) != 'numeric') {
      phenoTrait[, trait] <- as.numeric(as.character(phenoTrait[, trait]))
    }
      
    if (is.na(experimentalDesign) == TRUE) {experimentalDesign <- c('No Design')}
    
    if ((experimentalDesign == 'Augmented' || experimentalDesign == 'RCBD')  &&  unique(phenoTrait$block) > 1) {

      message("GS experimental design: ", experimentalDesign)

      augData <- subset(phenoTrait, select = c("object_name", "object_id",  "block",  trait))

      colnames(augData)[1] <- "genotypes"
      colnames(augData)[4] <- "trait"

      model <- try(lmer(trait ~ 0 + genotypes + (1|block),
                        augData,
                        na.action = na.omit))

      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
        
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))  
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
      }
            
    } else if (experimentalDesign == 'Alpha') {
   
      message("Experimental desgin: ", experimentalDesign)
      
      alphaData <- subset(phenoData,
                            select = c("object_name", "object_id","block", "replicate", trait)
                            )
      
      colnames(alphaData)[1] <- "genotypes"
      colnames(alphaData)[5] <- "trait"
         
      model <- try(lmer(trait ~ 0 + genotypes + (1|replicate/block),
                        alphaData,
                        na.action = na.omit))
        
      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
      
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))     
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
        
      }
      
    } else {

      phenoTrait <- subset(phenoData,
                           select = c("object_name", "object_id",  trait))
       
      if (sum(is.na(phenoTrait)) > 0) {
        message("No. of pheno missing values: ", sum(is.na(phenoTrait)))      
        phenoTrait <- na.omit(phenoTrait)
      }

        #calculate mean of reps/plots of the same accession and
        #create new df with the accession means    
     
      phenoTrait   <- phenoTrait[order(row.names(phenoTrait)), ]
      phenoTrait   <- data.frame(phenoTrait)
      message('phenotyped lines before averaging: ', length(row.names(phenoTrait)))
   
      phenoTrait<-ddply(phenoTrait, "object_name", colwise(mean))
      message('phenotyped lines after averaging: ', length(row.names(phenoTrait)))
        
      phenoTrait <- subset(phenoTrait, select = c("object_name", trait))
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1] <- NULL
       
        #format all-traits population phenotype dataset
        ## formattedPhenoData <- phenoData
        ## dropColumns <- c("object_id", "stock_id", "design", "block", "replicate" )

        ## formattedPhenoData <- formattedPhenoData[, !(names(formattedPhenoData) %in% dropColumns)]
        ## formattedPhenoData <- ddply(formattedPhenoData,
        ##                             "object_name",
        ##                             colwise(mean)
        ##                             )

        ## row.names(formattedPhenoData) <- formattedPhenoData[, 1]
        ## formattedPhenoData[, 1] <- NULL

        ## formattedPhenoData <- round(formattedPhenoData,
        ##                             digits=3
        ##                             )     
    }
  }
}

if (is.null(filteredGenoData)) {

  #remove markers with > 60% missing marker data
  message('no of markers before filtering out: ', ncol(genoData))
  genoData[, which(colSums(is.na(genoData)) >= nrow(genoData) * 0.6) := NULL]
  message('no of markers after filtering out 60% missing: ', ncol(genoData))

  #remove indls with > 80% missing marker data
  genoData[, noMissing := apply(.SD, 1, function(x) sum(is.na(x)))]
  genoData <- genoData[noMissing <= ncol(genoData) * 0.8]
  genoData[, noMissing := NULL]
  message('no of indls after filtering out ones with 80% missing: ', nrow(genoData))

                                        #remove monomorphic markers
  message('marker no before monomorphic markers cleaning ', ncol(genoData))
  genoData[, which(apply(genoData, 2,  function(x) length(unique(x))) < 2) := NULL ]
  message('marker no after monomorphic markers cleaning ', ncol(genoData))

  ### MAF calculation ###
  calculateMAF <- function(x) {
    a0 <-  length(x[x==0])
    a1 <-  length(x[x==1])
    a2 <-  length(x[x==2])
    aT <- a0 + a1 + a2

    p   <- ((2*a0)+a1)/(2*aT)
    q   <- 1- p
    maf <- min(p, q)
  
    return (maf)

  }

  #remove markers with MAF < 5%
  genoData[, which(apply(genoData, 2,  calculateMAF) < 0.05) := NULL ]
  message('marker no after MAF cleaning ', ncol(genoData))

  genoData           <- as.data.frame(genoData)
  rownames(genoData) <- genoData[, 1]
  genoData[, 1]      <- NULL
  filteredGenoData   <- genoData 
} else {
  genoData           <- as.data.frame(filteredGenoData)
  rownames(genoData) <- genoData[, 1]
  genoData[, 1]      <- NULL
}

predictionTempFile <- grep("prediction_population", inputFiles, ignore.case = TRUE, value = TRUE)
predictionFile     <- c()

message('prediction temp genotype file: ', predictionTempFile)

if (length(predictionTempFile) !=0 ) {
  predictionFile <- scan(predictionTempFile, what = "character")
}

message('prediction genotype file: ', predictionFile)

predictionPopGEBVsFile <- grep("prediction_pop_gebvs", outputFiles, ignore.case = TRUE, value = TRUE)
message("prediction gebv file: ",  predictionPopGEBVsFile)

predictionData <- c()

if (length(predictionFile) !=0 ) {
  
  predictionData <- fread(predictionFile, na.strings = c("NA", " ", "--", "-"),)

  predictionData[, which(apply(predictionData, 2,  function(x) length(unique(x))) < 2) := NULL ]
  
  message('selection population: no of markers before filtering out: ', ncol(genoData))
  predictionData[, which(colSums(is.na(predictionData)) >= nrow(predictionData) * 0.6) := NULL]

  #remove indls with > 80% missing marker data
  predictionData[, noMissing := apply(.SD, 1, function(x) sum(is.na(x)))]
  predictionData <- predictionData[noMissing <= ncol(predictionData) * 0.8]
  predictionData[, noMissing := NULL]
  
  predictionData[, which(apply(predictionData, 2,  calculateMAF) < 0.05) := NULL ]
  message('selection pop marker no after MAF cleaning ', ncol(preditionData))
  predictionData           <- as.data.frame(predictionData)
  rownames(predictionData) <- predictionData[, 1]
  predictionData[, 1]      <- NULL
 
}

#impute genotype values for obs with missing values,
#based on mean of neighbouring 10 (arbitrary) obs
genoDataMissing <- c()

if (sum(is.na(genoData)) > 0) {
  genoDataMissing<- c('yes')

  message("sum of geno missing values, ", sum(is.na(genoData)) )  
  genoData <- na.roughfix(genoData)
  genoData <- data.matrix(genoData)
}

genoData <- genoData[order(row.names(genoData)), ]

#create phenotype and genotype datasets with
#common stocks only
message('phenotyped lines: ', length(row.names(phenoTrait)))
message('genotyped lines: ', length(row.names(genoData)))

#extract observation lines with both
#phenotype and genotype data only.
commonObs <- intersect(row.names(phenoTrait), row.names(genoData))
commonObs <- data.frame(commonObs)
rownames(commonObs)<-commonObs[, 1]

message('lines with both genotype and phenotype data: ', length(row.names(commonObs)))

#include in the genotype dataset only observation lines
#with phenotype data
message("genotype lines before filtering for phenotyped only: ", length(row.names(genoData)))        
genoDataFilteredObs <- genoData[(rownames(genoData) %in% rownames(commonObs)), ]
message("genotype lines after filtering for phenotyped only: ", length(row.names(genoDataFilteredObs)))

#drop observation lines without genotype data
message("phenotype lines before filtering for genotyped only: ", length(row.names(phenoTrait)))        
phenoTrait <- merge(data.frame(phenoTrait), commonObs, by=0, all=FALSE)
rownames(phenoTrait) <- phenoTrait[, 1]
phenoTrait <- subset(phenoTrait, select=trait)

message("phenotype lines after filtering for genotyped only: ", length(row.names(phenoTrait)))
#a set of only observation lines with genotype data

traitPhenoData   <- data.frame(round(phenoTrait, digits = 2))           
phenoTrait       <- data.matrix(phenoTrait)
genoDataFilteredObs <- data.matrix(genoDataFilteredObs)

#impute missing data in prediction data
predictionDataMissing <- c()
if (length(predictionData) != 0) {
  #purge markers unique to both populations
  commonMarkers       <- intersect(names(data.frame(genoDataFilteredObs)), names(predictionData))
  predictionData      <- subset(predictionData, select = commonMarkers)
  genoDataFilteredObs <- subset(genoDataFilteredObs, select= commonMarkers)
  
  if (sum(is.na(predictionData)) > 0) {
    predictionDataMissing <- c('yes')
    message("sum of geno missing values, ", sum(is.na(predictionData)) )  
    predictionData <- data.matrix(na.roughfix(predictionData))
    
  }
}

relationshipMatrixFile <- grep("relationship_matrix", outputFiles, ignore.case = TRUE, value = TRUE)

message("relationship matrix file: ", relationshipMatrixFile)

relationshipMatrix <- c()
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size > 0 ) {
    relationshipDf <- as.data.frame(fread(relationshipMatrixFile))

    rownames(relationshipDf) <- relationshipDf[, 1]
    relationshipDf[, 1]      <- NULL
    relationshipMatrix       <- data.matrix(relationshipDf)
  }
}


#change genotype coding to [-1, 0, 1], to use the A.mat ) if  [0, 1, 2]
genoTrCode <- grep("2", genoDataFilteredObs[1, ], value = TRUE)
if(length(genoTrCode) != 0) {
  genoDataFilteredObs <- genoDataFilteredObs - 1
}

if (length(predictionData) != 0 ) {
  genoSlCode <- grep("2", predictionData[1, ], value = TRUE)
  if (length(genoSlCode) != 0 ) {
    predictionData <- predictionData - 1
  }
}

ordered.markerEffects <- c()
if ( length(predictionData) == 0 ) {
  markerEffects <- mixed.solve(y = phenoTrait,
                               Z = genoDataFilteredObs
                               )

  ordered.markerEffects <- data.matrix(markerEffects$u)
  ordered.markerEffects <- data.matrix(ordered.markerEffects [order (-ordered.markerEffects[, 1]), ])
  ordered.markerEffects <- round(ordered.markerEffects, digits=5)

  colnames(ordered.markerEffects) <- c("Marker Effects")

}

#additive relationship model
#calculate the inner products for
#genotypes (realized relationship matrix)
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size == 0) {
    relationshipMatrix <- tcrossprod(data.matrix(genoData))
  }
}
relationshipMatrixFiltered <- relationshipMatrix[(rownames(relationshipMatrix) %in% rownames(commonObs)),]
relationshipMatrixFiltered <- relationshipMatrixFiltered[, (colnames(relationshipMatrixFiltered) %in% rownames(commonObs))]

#construct an identity matrix for genotypes
identityMatrix <- diag(nrow(phenoTrait))

relationshipMatrixFiltered <- data.matrix(relationshipMatrixFiltered)

iGEBV  <- mixed.solve(y = phenoTrait, Z = identityMatrix, K = relationshipMatrixFiltered) 
iGEBVu <- iGEBV$u

heritability  <- c()

if ( is.null(predictionFile) == TRUE ) {
  additiveEffects <- data.frame(iGEBVu)
 
  pN <- nrow(phenoTrait)
  aN <- nrow(additiveEffects)

  if (pN <= 1 || pN != aN) {
    stop("phenoTrait and additiveEffects have different lengths: ",
         pN, " and ", aN, ".")
  }
      
  if (TRUE %in% is.na(phenoTrait) || TRUE %in% is.na(additiveEffects)) {
    stop(" Arguments phenoTrait and additiveEffects have missing values.")
  }
  
  phenoVariance <- var(phenoTrait)
  gebvVariance  <- var(additiveEffects)
  heritability  <- round((gebvVariance / phenoVariance), digits = 2)
      
  cat("\n", file = varianceComponentsFile,  append = FALSE)
  cat('Error variance', iGEBV$Ve, file = varianceComponentsFile, sep = "\t", append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Additive genetic variance',  iGEBV$Vu, file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Phenotype mean', iGEBV$beta,file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Heritability (h)', heritability, file = varianceComponentsFile, sep = '\t', append = TRUE)
}

iGEBV         <- data.matrix(iGEBVu)
ordered.iGEBV <- as.data.frame(iGEBV[order(-iGEBV[, 1]), ])
ordered.iGEBV <- round(ordered.iGEBV, digits = 3)

combinedGebvsFile <- grep('selected_traits_gebv', outputFiles, ignore.case = TRUE,value = TRUE)

allGebvs<-c()
if (length(combinedGebvsFile) != 0) {
    fileSize <- file.info(combinedGebvsFile)$size
    if (fileSize != 0 ) {
        combinedGebvs <- as.data.frame(fread(combinedGebvsFile))

        rownames(combinedGebvs) <- combinedGebvs[,1]
        combinedGebvs[,1]       <- NULL

        colnames(ordered.iGEBV) <- c(trait)
      
        traitGEBV <- as.data.frame(ordered.iGEBV)
        allGebvs <- merge(combinedGebvs, traitGEBV,
                          by = 0,
                          all = TRUE                     
                          )

        rownames(allGebvs) <- allGebvs[,1]
        allGebvs[,1] <- NULL
     }
  }

colnames(ordered.iGEBV) <- c(trait)
                  
#cross-validation
validationAll <- c()

if(is.null(predictionFile)) {
  genoNum <- nrow(phenoTrait)
if(genoNum < 20 ) {
  warning(genoNum, " is too small number of genotypes.")
}
  
reps <- round_any(genoNum, 10, f = ceiling) %/% 10

genotypeGroups <-c()

if (genoNum %% 10 == 0) {
    genotypeGroups <- rep(1:10, reps)
  } else {
    genotypeGroups <- rep(1:10, reps) [- (genoNum %% 10) ]
  }

set.seed(4567)                                   
genotypeGroups <- genotypeGroups[ order (runif(genoNum)) ]

for (i in 1:10) {
  tr <- paste("trPop", i, sep = ".")
  sl <- paste("slPop", i, sep = ".")
 
  trG <- which(genotypeGroups != i)
  slG <- which(genotypeGroups == i)
  
  assign(tr, trG)
  assign(sl, slG)

  kblup <- paste("rKblup", i, sep = ".")
  
  result <- kinship.BLUP(y = phenoTrait[trG, ],
                         G.train = genoDataFilteredObs[trG, ],
                         G.pred = genoDataFilteredObs[slG, ],                      
                         mixed.method = "REML",
                         K.method = "RR",
                         )
 
  assign(kblup, result)

#calculate cross-validation accuracy  
  valCorData <- merge(phenoTrait[slG, ], result$g.pred, by=0, all=FALSE)
  rownames(valCorData) <- valCorData[, 1]
  valCorData[, 1]      <- NULL
 
  accuracy <- try(cor(valCorData))
  validation <- paste("validation", i, sep = ".")

  cvTest <- paste("Validation test", i, sep = " ")

  if ( class(accuracy) != "try-error")
    {
      accuracy <- round(accuracy[1,2], digits = 3)
      accuracy <- data.matrix(accuracy)
    
      colnames(accuracy) <- c("correlation")
      rownames(accuracy) <- cvTest

      assign(validation, accuracy)
      
      if (!is.na(accuracy[1,1])) {
        validationAll <- rbind(validationAll, accuracy)
      }    
    }
}

validationAll <- data.matrix(validationAll[order(-validationAll[, 1]), ])
     
if (!is.null(validationAll)) {
    validationMean <- data.matrix(round(colMeans(validationAll), digits = 2))
   
    rownames(validationMean) <- c("Average")
     
    validationAll <- rbind(validationAll, validationMean)
    colnames(validationAll) <- c("Correlation")
  }
}

predictionPopResult <- c()
predictionPopGEBVs  <- c()

if (length(predictionData) != 0) {
    message("running prediction for selection candidates...marker data", ncol(predictionData), " vs. ", ncol(genoDataFilteredObs))

    predictionPopResult <- kinship.BLUP(y = phenoTrait,
                                        G.train = genoDataFilteredObs,
                                        G.pred = predictionData,
                                        mixed.method = "REML",
                                        K.method = "RR"
                                        )
 message("running prediction for selection candidates...DONE!!")

    predictionPopGEBVs <- round(data.matrix(predictionPopResult$g.pred), digits = 3)
    predictionPopGEBVs <- data.matrix(predictionPopGEBVs[order(-predictionPopGEBVs[, 1]), ])
   
    colnames(predictionPopGEBVs) <- c(trait)
  
}

if (!is.null(predictionPopGEBVs) & length(predictionPopGEBVsFile) != 0)  {
    write.table(predictionPopGEBVs,
                file = predictionPopGEBVsFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if(!is.null(validationAll)) {
    write.table(validationAll,
                file = validationFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.markerEffects)) {
    write.table(ordered.markerEffects,
                file = markerFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.iGEBV)) {
    write.table(ordered.iGEBV,
                file = blupFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (length(combinedGebvsFile) != 0 ) {
    if(file.info(combinedGebvsFile)$size == 0) {
        write.table(ordered.iGEBV,
                    file = combinedGebvsFile,
                    sep = "\t",
                    col.names = NA,
                    quote = FALSE,
                    )
      } else {
      write.table(allGebvs,
                  file = combinedGebvsFile,
                  sep = "\t",
                  quote = FALSE,
                  col.names = NA,
                  )
    }
}

if (!is.null(traitPhenoData) & length(traitPhenoFile) != 0) {
    write.table(traitPhenoData,
                file = traitPhenoFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                )
}

if (!is.null(filteredGenoData) && is.null(usedFilteredGenoData)) {
  write.table(filteredGenoData,
              file = filteredGenoFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
            )

}

## if (!is.null(genoDataMissing)) {
##   write.table(genoData,
##               file = genoFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##             )

## }

## if (!is.null(predictionDataMissing)) {
##   write.table(predictionData,
##               file = predictionFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##               )
## }


if (file.info(relationshipMatrixFile)$size == 0) {
  write.table(relationshipMatrix,
              file = relationshipMatrixFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}


if (file.info(formattedPhenoFile)$size == 0 && !is.null(formattedPhenoData) ) {
  write.table(formattedPhenoData,
              file = formattedPhenoFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}

message("Done.")

q(save = "no", runLast = FALSE)
require(plyr)

ReadCreateTable<-function(FileName){
  TargetTable.df<-read.csv(file.path("ImportAids\\",FileName),header=FALSE,sep=" ")
  
  #For now we're ignoring everything except the lines describing variable types
  CreateRow<-which(TargetTable.df$V1=="CREATE")
  TargetTable.df<-TargetTable.df[-c(1:CreateRow),]
  EndRow<-which(TargetTable.df$V1==")")
  TargetTable.df<-TargetTable.df[-c(EndRow:nrow(TargetTable.df)),]
  TargetTable.df$V1<-as.character(TargetTable.df$V1)
  #Once we have the table in, the next step is to clean up anything seperated on spaces
  #that should not have been for our purposes.
  # 
  TargetTable.df$V2<-as.character(TargetTable.df$V2)
  TargetTable.df$V2[substring(TargetTable.df$V2,1,9)=="[decimal]"]<-paste(
    TargetTable.df$V2[substring(TargetTable.df$V2,1,9)=="[decimal]"],
    TargetTable.df$V3[substring(TargetTable.df$V2,1,9)=="[decimal]"]
  )
  #Just in case the only Not NULL is a decimal
  TargetTable.df$V3<-as.character(TargetTable.df$V3)
  TargetTable.df$V3[substring(TargetTable.df$V2,1,9)=="[decimal]"]<-
    as.character(TargetTable.df$V4[substring(TargetTable.df$V2,1,9)=="[decimal]"])
  TargetTable.df$V4[substring(TargetTable.df$V2,1,9)=="[decimal]"]<-""
  
  TargetTable.df<-TargetTable.df[,c(1:3)]
  colnames(TargetTable.df)<-c("VariableName",
                              "VariableType",
                              "Nullable")
  TargetTable.df$Nullable<-gsub(",","",TargetTable.df$Nullable)
  TargetTable.df$VariableName<-gsub("\t","",TargetTable.df$VariableName)
  TargetTable.df
}

ConvertAllOfType<-function(TargetTable.df,
                           OldType,
                           NewType,
                           Schema,
                           TableName){
  #Limit it to just relevant variables
  TargetTable.df<-TargetTable.df[TargetTable.df$VariableType==OldType,]
  if(nrow(TargetTable.df)==0)
    stop("OldType not found in table")
  ChangeList<-paste(
    "Alter Table ",Schema,".",TableName,"\n",
    "Alter Column ",TargetTable.df$VariableName," ",
    NewType," ",TargetTable.df$Nullable,sep="")
  ChangeList
}

ListProblemType<-function(TargetTable.df){
  TargetTable.df[TargetTable.df$VariableType=="[varchar](max)",]
}


TranslateName<-function(TargetTable.df){
  lookup.NameConversion<-read.csv("ImportAids\\NameConversion.csv",
                                  stringsAsFactors = FALSE)
  if(!"SourceVariableName" %in% colnames(TargetTable.df)){
    colnames(TargetTable.df)[1]<-"SourceVariableName" 
  }
  TargetTable.df<-plyr::join(TargetTable.df,lookup.NameConversion)
  # TargetTable.df$VariableName<-gsub("_","",TargetTable.df$VariableName)
  
  TargetTable.df$CSISvariableName[TargetTable.df$SourceVariableName %in% 
                   lookup.NameConversion$CSISvariableName]<-
    TargetTable.df$SourceVariableName[TargetTable.df$SourceVariableName %in% 
                     lookup.NameConversion$CSISvariableName]
  
  TargetTable.df
}



MergeSourceAndCSISnameTables<-function(SourceTable.df,CSIStable.df){
  colnames(SourceTable.df)[1:3]<-c("SourceVariableName",
                                   "SourceVariableType",
                                   "SourceNullable")
  SourceTable.df$SourceVariableName<-as.character(SourceTable.df$SourceVariableName)
  colnames(CSIStable.df)[1:3]<-c("CSISvariableName",
                                 "CSISvariableType",
                                 "CSISnullable")
  CSIStable.df$CSISvariableName<-as.character(CSIStable.df$CSISvariableName)
  SourceTable.df<-plyr::join(SourceTable.df,CSIStable.df)
}



CreateCSISdates<-function(Schema,TableName){
  paste("ALTER TABLE ",Schema,".",TableName,"\n",
        "CREATE CSISmodifiedDate datetime2 NOT NULL default gettime(),\n",
        "CSIScreatedDate datetime2 NOT NULL default gettime()\n",
        sep="")
}

ConvertSwitch<-function(MergeTable.df,DateType=101,IsTryConvert=FALSE){
  #I swear I had this working, but then it broke hard and every time I tried to 
  #debug it, the crash took minutes to resolve.
  # OneSwitch<-function(VariableName,
  #                     VariableShortType,
  #                     VariableFullType){
  #   ConvertText<-ifelse(IsTryConvert,"Try_Convert","Convert")
  #   Outcome<-switch(VariableShortType,
  #                   "[decimal]"=paste(ConvertText,"(",VariableFullType,
  #                                     ", ",ConvertText,"(real,",
  #                                     VariableName,"))",
  #                                     sep=""
  #                   ),
  #                   "[date]"=paste(ConvertText,"([date], ",
  #                                  VariableName,
  #                                  ",",as.character(DateType),")",
  #                                  sep=""
  #                   ),
  #                   paste(ConvertText,"(",VariableFullType,", ",
  #                         VariableName,
  #                         ")",
  #                         sep=""
  #                   )
  #   )
  #   Outcome
  # }
  # 
  # 
  # MergeTable.df$VariableShortType<-substr(MergeTable.df$CSISvariableType,1,
  #                                         regexpr(']',MergeTable.df$CSISvariableType))
  # 
  # MergeTable.df<-
  #   ddply(MergeTable.df,
  #                      .(SourceVariableName,VariableShortType,CSISvariableType),
  #          transform,
  #                      ConvertList=OneSwitch(SourceVariableName,
  #                                            VariableShortType,
  #                                            CSISvariableType))
  # MergeTable.df
  
    ConvertText<-ifelse(IsTryConvert,"Try_Convert","Convert")
    MergeTable.df$VariableShortType<-substr(MergeTable.df$CSISvariableType,1,
                                            regexpr(']',MergeTable.df$CSISvariableType))

    MergeTable.df$ConvertList<-NA
    SwitchList<-MergeTable.df$SourceVariableType==MergeTable.df$CSISvariableType
    MergeTable.df$ConvertList[SwitchList]<-MergeTable.df$SourceVariableName[SwitchList]
    
    SwitchList<-MergeTable.df$VariableShortType %in% c("[decimal]","[smallint]","[bigint]")&
      is.na(MergeTable.df$ConvertList)
    MergeTable.df$ConvertList[SwitchList]<-
      paste(ConvertText,"(",
                                      MergeTable.df$CSISvariableType[SwitchList] ,
                                      ", ",ConvertText,"(real,",
                                      MergeTable.df$SourceVariableName[SwitchList] ,"))",
                                      sep=""
                    )
    
    SwitchList<-MergeTable.df$VariableShortType=="[bit]"&
        is.na(MergeTable.df$ConvertList)
        MergeTable.df$ConvertList[SwitchList]<-
        paste(ConvertText,"(",
              MergeTable.df$CSISvariableType[SwitchList] ,", ",
              "(SELECT ReturnBit from Errorlogging.ConvertYNtoBit(",
              MergeTable.df$SourceVariableName[SwitchList] ,
              ")))",
              sep=""
        )
    
    SwitchList<-MergeTable.df$VariableShortType=="[date]"&
      is.na(MergeTable.df$ConvertList)
    MergeTable.df$ConvertList[SwitchList]<-
      paste(ConvertText,"([date], ",
                                   MergeTable.df$SourceVariableName[SwitchList] ,
                                   ",",as.character(DateType),")",
                                   sep=""
                    )
    SwitchList<-is.na(MergeTable.df$ConvertList)
    MergeTable.df$ConvertList[SwitchList]<-
                    paste(ConvertText,"(",
                          MergeTable.df$CSISvariableType[SwitchList] ,", ",
                          MergeTable.df$SourceVariableName[SwitchList] ,
                          ")",
                          sep=""
                    )
    MergeTable.df
}


LengthCheck<-function(MergeTable.df){

    MergeTable.df$LengthCheck<-""

    MergeTable.df$VariableTypeNumber<-as.numeric(
        (substr(MergeTable.df$CSISvariableType,
                regexpr('[(]',MergeTable.df$CSISvariableType)+1,
                regexpr('[)]',MergeTable.df$CSISvariableType)-1)
        ))
        

    SwitchList<-MergeTable.df$VariableShortType=="[varchar]"&
        MergeTable.df$LengthCheck==""&
        !is.na(MergeTable.df$VariableTypeNumber)
    MergeTable.df$LengthCheck[SwitchList]<-
        paste("OR len(",MergeTable.df$SourceVariableName[SwitchList] ,")",
              ">",MergeTable.df$VariableTypeNumber[SwitchList],"\n"
        )

    MergeTable.df
}


Create_Try_Converts<-function(MergeTable.df,
                              Schema,
                              TableName,
                              DateType=101){
  #Limit it to just cases where the variable type is changing
  MergeTable.df<-subset(MergeTable.df,SourceVariableType!=MergeTable.df$CSISvariableType)
  if(nrow(MergeTable.df)==0)
    stop("No try_converts necessary")
  MergeTable.df<-ConvertSwitch(MergeTable.df,101,TRUE)
  MergeTable.df<-LengthCheck(MergeTable.df)
  
  ConvertList<-paste(
    "SELECT DISTINCT ",
    MergeTable.df$SourceVariableName,",\n",
    "len(",MergeTable.df$SourceVariableName,") as Length,\n",
    "'",MergeTable.df$CSISvariableType,"' as DestinationType","\n",
    "FROM ",Schema,".",TableName,"\n",
    "WHERE (",
    MergeTable.df$ConvertList,
    " IS NULL AND\n",
    "NULLIF(",MergeTable.df$SourceVariableName,",'') IS NOT NULL)\n",
    MergeTable.df$LengthCheck,
    sep="")
  ConvertList
}


CreateInsert<-function(MergeTable.df,
                       SourceSchema,
                       SourceTableName,
                       TargetSchema,
                       TargetTableName,
                       DateType=101){
  MergeTable.df<-ConvertSwitch(MergeTable.df,101,FALSE)
  
  InsertList<-paste("INSERT INTO ",TargetSchema,".",TargetTableName,"\n",
                    "(",sep="")
  InsertList<-c(InsertList,paste(MergeTable.df$CSISvariableName,",",sep=""))
  #Remove the comma from the last insert list column
  InsertList[length(InsertList)]<-gsub(",","",InsertList[length(InsertList)])
  InsertList<-c(InsertList,")\n SELECT ")
  InsertList<-c(InsertList,paste(MergeTable.df$ConvertList,",",sep=""))
  #Remove the comma from the select list column
  InsertList[length(InsertList)]<-substr(InsertList[length(InsertList)],
                                       1,
                                       nchar(InsertList[length(InsertList)])-1)
  
  InsertList<-c(InsertList,
                    paste("FROM ",SourceSchema,".",SourceTableName,sep="")
  )
  InsertList
}



ConvertFieldToForeignKey<-function(FKschema,
                                   FKtable,
                                   FKcolumn,
                                   TargetTable.df,
                                   PKschema,
                                   PKtable,
                                   PKname=PKtable){

  TargetTable.df<-read.csv(file.path("ImportAids",FileName),header=FALSE,sep=" ")
  #Test if the field can be converted to the primary keys typed.

}require(plyr)

ReadCreateTable<-function(FileName){
  TargetTable.df<-read.csv(file.path("ImportAids\\",FileName),header=FALSE,sep=" ")
  
  #For now we're ignoring everything except the lines describing variable types
  CreateRow<-which(TargetTable.df$V1=="CREATE")
  TargetTable.df<-TargetTable.df[-c(1:CreateRow),]
  EndRow<-which(TargetTable.df$V1==")")
  TargetTable.df<-TargetTable.df[-c(EndRow:nrow(TargetTable.df)),]
  TargetTable.df$V1<-as.character(TargetTable.df$V1)
  #Once we have the table in, the next step is to clean up anything seperated on spaces
  #that should not have been for our purposes.
  # 
  TargetTable.df$V2<-as.character(TargetTable.df$V2)
  TargetTable.df$V2[substring(TargetTable.df$V2,1,9)=="[decimal]"]<-paste(
    TargetTable.df$V2[substring(TargetTable.df$V2,1,9)=="[decimal]"],
    TargetTable.df$V3[substring(TargetTable.df$V2,1,9)=="[decimal]"]
  )
  #Just in case the only Not NULL is a decimal
  TargetTable.df$V3<-as.character(TargetTable.df$V3)
  TargetTable.df$V3[substring(TargetTable.df$V2,1,9)=="[decimal]"]<-
    as.character(TargetTable.df$V4[substring(TargetTable.df$V2,1,9)=="[decimal]"])
  TargetTable.df$V4[substring(TargetTable.df$V2,1,9)=="[decimal]"]<-""
  
  TargetTable.df<-TargetTable.df[,c(1:3)]
  colnames(TargetTable.df)<-c("VariableName",
                              "VariableType",
                              "Nullable")
  TargetTable.df$Nullable<-gsub(",","",TargetTable.df$Nullable)
  TargetTable.df$VariableName<-gsub("\t","",TargetTable.df$VariableName)
  TargetTable.df
}

ConvertAllOfType<-function(TargetTable.df,
                           OldType,
                           NewType,
                           Schema,
                           TableName){
  #Limit it to just relevant variables
  TargetTable.df<-TargetTable.df[TargetTable.df$VariableType==OldType,]
  if(nrow(TargetTable.df)==0)
    stop("OldType not found in table")
  ChangeList<-paste(
    "Alter Table ",Schema,".",TableName,"\n",
    "Alter Column ",TargetTable.df$VariableName," ",
    NewType," ",TargetTable.df$Nullable,sep="")
  ChangeList
}

ListProblemType<-function(TargetTable.df){
  TargetTable.df[TargetTable.df$VariableType=="[varchar](max)",]
}


TranslateName<-function(TargetTable.df){
  lookup.NameConversion<-read.csv("ImportAids\\NameConversion.csv",
                                  stringsAsFactors = FALSE)
  if(!"SourceVariableName" %in% colnames(TargetTable.df)){
    colnames(TargetTable.df)[1]<-"SourceVariableName" 
  }
  TargetTable.df<-plyr::join(TargetTable.df,lookup.NameConversion)
  # TargetTable.df$VariableName<-gsub("_","",TargetTable.df$VariableName)
  
  TargetTable.df$CSISvariableName[TargetTable.df$SourceVariableName %in% 
                   lookup.NameConversion$CSISvariableName]<-
    TargetTable.df$SourceVariableName[TargetTable.df$SourceVariableName %in% 
                     lookup.NameConversion$CSISvariableName]
  
  TargetTable.df
}



MergeSourceAndCSISnameTables<-function(SourceTable.df,CSIStable.df){
  colnames(SourceTable.df)[1:3]<-c("SourceVariableName",
                                   "SourceVariableType",
                                   "SourceNullable")
  SourceTable.df$SourceVariableName<-as.character(SourceTable.df$SourceVariableName)
  colnames(CSIStable.df)[1:3]<-c("CSISvariableName",
                                 "CSISvariableType",
                                 "CSISnullable")
  CSIStable.df$CSISvariableName<-as.character(CSIStable.df$CSISvariableName)
  SourceTable.df<-plyr::join(SourceTable.df,CSIStable.df)
}



CreateCSISdates<-function(Schema,TableName){
  paste("ALTER TABLE ",Schema,".",TableName,"\n",
        "CREATE CSISmodifiedDate datetime2 NOT NULL default gettime(),\n",
        "CSIScreatedDate datetime2 NOT NULL default gettime()\n",
        sep="")
}

ConvertSwitch<-function(MergeTable.df,DateType=101,IsTryConvert=FALSE){
  #I swear I had this working, but then it broke hard and every time I tried to 
  #debug it, the crash took minutes to resolve.
  # OneSwitch<-function(VariableName,
  #                     VariableShortType,
  #                     VariableFullType){
  #   ConvertText<-ifelse(IsTryConvert,"Try_Convert","Convert")
  #   Outcome<-switch(VariableShortType,
  #                   "[decimal]"=paste(ConvertText,"(",VariableFullType,
  #                                     ", ",ConvertText,"(real,",
  #                                     VariableName,"))",
  #                                     sep=""
  #                   ),
  #                   "[date]"=paste(ConvertText,"([date], ",
  #                                  VariableName,
  #                                  ",",as.character(DateType),")",
  #                                  sep=""
  #                   ),
  #                   paste(ConvertText,"(",VariableFullType,", ",
  #                         VariableName,
  #                         ")",
  #                         sep=""
  #                   )
  #   )
  #   Outcome
  # }
  # 
  # 
  # MergeTable.df$VariableShortType<-substr(MergeTable.df$CSISvariableType,1,
  #                                         regexpr(']',MergeTable.df$CSISvariableType))
  # 
  # MergeTable.df<-
  #   ddply(MergeTable.df,
  #                      .(SourceVariableName,VariableShortType,CSISvariableType),
  #          transform,
  #                      ConvertList=OneSwitch(SourceVariableName,
  #                                            VariableShortType,
  #                                            CSISvariableType))
  # MergeTable.df
  
    ConvertText<-ifelse(IsTryConvert,"Try_Convert","Convert")
    MergeTable.df$VariableShortType<-substr(MergeTable.df$CSISvariableType,1,
                                            regexpr(']',MergeTable.df$CSISvariableType))

    MergeTable.df$ConvertList<-NA
    SwitchList<-MergeTable.df$SourceVariableType==MergeTable.df$CSISvariableType
    MergeTable.df$ConvertList[SwitchList]<-MergeTable.df$SourceVariableName[SwitchList]
    
    SwitchList<-MergeTable.df$VariableShortType %in% c("[decimal]","[smallint]","[bigint]")&
      is.na(MergeTable.df$ConvertList)
    MergeTable.df$ConvertList[SwitchList]<-
      paste(ConvertText,"(",
                                      MergeTable.df$CSISvariableType[SwitchList] ,
                                      ", ",ConvertText,"(real,",
                                      MergeTable.df$SourceVariableName[SwitchList] ,"))",
                                      sep=""
                    )
    
    SwitchList<-MergeTable.df$VariableShortType=="[bit]"&
        is.na(MergeTable.df$ConvertList)
        MergeTable.df$ConvertList[SwitchList]<-
        paste(ConvertText,"(",
              MergeTable.df$CSISvariableType[SwitchList] ,", ",
              "(SELECT ReturnBit from Errorlogging.ConvertYNtoBit(",
              MergeTable.df$SourceVariableName[SwitchList] ,
              ")))",
              sep=""
        )
    
    SwitchList<-MergeTable.df$VariableShortType=="[date]"&
      is.na(MergeTable.df$ConvertList)
    MergeTable.df$ConvertList[SwitchList]<-
      paste(ConvertText,"([date], ",
                                   MergeTable.df$SourceVariableName[SwitchList] ,
                                   ",",as.character(DateType),")",
                                   sep=""
                    )
    SwitchList<-is.na(MergeTable.df$ConvertList)
    MergeTable.df$ConvertList[SwitchList]<-
                    paste(ConvertText,"(",
                          MergeTable.df$CSISvariableType[SwitchList] ,", ",
                          MergeTable.df$SourceVariableName[SwitchList] ,
                          ")",
                          sep=""
                    )
    MergeTable.df
}


LengthCheck<-function(MergeTable.df){

    MergeTable.df$LengthCheck<-""

    MergeTable.df$VariableTypeNumber<-as.numeric(
        (substr(MergeTable.df$CSISvariableType,
                regexpr('[(]',MergeTable.df$CSISvariableType)+1,
                regexpr('[)]',MergeTable.df$CSISvariableType)-1)
        ))
        

    SwitchList<-MergeTable.df$VariableShortType=="[varchar]"&
        MergeTable.df$LengthCheck==""&
        !is.na(MergeTable.df$VariableTypeNumber)
    MergeTable.df$LengthCheck[SwitchList]<-
        paste("OR len(",MergeTable.df$SourceVariableName[SwitchList] ,")",
              ">",MergeTable.df$VariableTypeNumber[SwitchList],"\n"
        )

    MergeTable.df
}


Create_Try_Converts<-function(MergeTable.df,
                              Schema,
                              TableName,
                              DateType=101){
  #Limit it to just cases where the variable type is changing
  MergeTable.df<-subset(MergeTable.df,SourceVariableType!=MergeTable.df$CSISvariableType)
  if(nrow(MergeTable.df)==0)
    stop("No try_converts necessary")
  MergeTable.df<-ConvertSwitch(MergeTable.df,101,TRUE)
  MergeTable.df<-LengthCheck(MergeTable.df)
  
  ConvertList<-paste(
    "SELECT DISTINCT ",
    MergeTable.df$SourceVariableName,",\n",
    "len(",MergeTable.df$SourceVariableName,") as Length,\n",
    "'",MergeTable.df$CSISvariableType,"' as DestinationType","\n",
    "FROM ",Schema,".",TableName,"\n",
    "WHERE (",
    MergeTable.df$ConvertList,
    " IS NULL AND\n",
    "NULLIF(",MergeTable.df$SourceVariableName,",'') IS NOT NULL)\n",
    MergeTable.df$LengthCheck,
    sep="")
  ConvertList
}


CreateInsert<-function(MergeTable.df,
                       SourceSchema,
                       SourceTableName,
                       TargetSchema,
                       TargetTableName,
                       DateType=101){
  MergeTable.df<-ConvertSwitch(MergeTable.df,101,FALSE)
  
  InsertList<-paste("INSERT INTO ",TargetSchema,".",TargetTableName,"\n",
                    "(",sep="")
  InsertList<-c(InsertList,paste(MergeTable.df$CSISvariableName,",",sep=""))
  #Remove the comma from the last insert list column
  InsertList[length(InsertList)]<-gsub(",","",InsertList[length(InsertList)])
  InsertList<-c(InsertList,")\n SELECT ")
  InsertList<-c(InsertList,paste(MergeTable.df$ConvertList,",",sep=""))
  #Remove the comma from the select list column
  InsertList[length(InsertList)]<-substr(InsertList[length(InsertList)],
                                       1,
                                       nchar(InsertList[length(InsertList)])-1)
  
  InsertList<-c(InsertList,
                    paste("FROM ",SourceSchema,".",SourceTableName,sep="")
  )
  InsertList
}



ConvertFieldToForeignKey<-function(PKschema,
                                   PKname){

  TargetTable.df<-read.csv(file.path("ImportAids",FileName),header=FALSE,sep=" ")
  #Test if the field can be converted to the primary keys typed.

}###########################################
# process_cfsv2_ts_ncdc.r
# processes grib2 files from ncdc cfsv2 archive
# aggregates 6-hrly forecasts to 24hr and 5-day accumulations
# regrids and maps to river basins using correspondence file
# saves data in csv format
###########################################

## load libraries
library(data.table)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(tidyr)
library(tools)
library(akima)

## user inputs
dir_scratch = ''
dir_dom = ''
dir_dom_proc = ''

# define sub-domain of raw forecast
lat_dom = c(1, 16)
lon_dom = c(32, 49)

# new 0.1º grid
xp1 = seq(from = 33.05, by = 0.1, length.out = 150)
yp1 = seq(from = 2.05, by = 0.1, length.out = 130)

# correspondence file 
c_file = fread('correspondence_ethiopiabasins.csv')

# extension for outfile
fileout_dom = '_ethiopia_24hraccum.csv'

## set up
setwd(dir_scratch)

dom_file_list = list.files(dir_dom, pattern = '*.grb2')
nfiles_dom = length(dom_file_list)
# 21600 sec / 6hr
weight_tbl = data.table(fcst_hour = c(0, 6, 12, 18, 24), weight = c(0.5, 1, 1, 1, 0.5))

## process files
for(i in 1:nfiles_dom){
	dom_file_sel = paste0(dir_dom, dom_file_list[i])
	file_out = paste0(dir_dom_proc, file_path_sans_ext(dom_file_list[i]), fileout_dom)
	if(file.exists(file_out) == F){
		system(paste0("wgrib2 ", dom_file_sel, " -csv temp3.csv"))
		tryCatch({
			fcst_dat = fread('temp3.csv') %>% setnames(c('date_init', 'date_fcst', 'var', 'level', 'lon', 'lat', 'value')) %>% select(-var, -level)
			fcst_dat = fcst_dat %>% filter(lon >= lon_dom[1], lon <= lon_dom[2], lat >= lat_dom[1], lat <= lat_dom[2]) %>% mutate(date_init = as.POSIXct(date_init), date_fcst = as.POSIXct(date_fcst), value = value * 21600) %>% mutate(fcst_hour = hour(date_fcst), init_hour = hour(date_init)) %>% mutate(date_init = as.Date(date_init), date_fcst = as.Date(date_fcst)) 

			fcst_dat_24z = fcst_dat %>% filter(fcst_hour == 0) %>% mutate(date_fcst = date_fcst - days(1), fcst_hour = 24)

			fcst_dat = bind_rows(fcst_dat, fcst_dat_24z) %>% group_by(lon, lat, date_fcst) %>% mutate(nfcst = n()) %>% filter(nfcst == 5)

			fcst_dat_24hraccum = fcst_dat %>% left_join(weight_tbl) %>% mutate(value = value * weight, date_fcst = date_fcst + days(1)) %>% group_by(date_init, init_hour, date_fcst, lon, lat) %>% dplyr::summarise(value = sum(value)) 
			date_init_temp = unique(fcst_dat_24hraccum$date_init)
			init_hour_temp = unique(fcst_dat_24hraccum$init_hour)
			date_fcst_list = sort(unique(fcst_dat_24hraccum$date_fcst))
			nfcst = length(date_fcst_list)
			fcst_dat_24hraccum_interp = NULL
			for(j in 1:nfcst){
				date_fcst_temp = date_fcst_list[j]
				fcst_dat_24hraccum_fl = filter(fcst_dat_24hraccum, date_fcst == date_fcst_temp)
				x_temp = fcst_dat_24hraccum_fl$lon
				y_temp = fcst_dat_24hraccum_fl$lat
				z_temp = fcst_dat_24hraccum_fl$value
				interp_raw = interp(x_temp, y_temp, z_temp, xo = xp1, yo = yp1)
				fcst_dat_24hraccum_interp_temp = data.table(date_init = date_init_temp, hour_init = init_hour_temp, date_fcst = date_fcst_temp, lon = interp_raw$x, lat = rep(interp_raw$y, each = length(interp_raw$x)), value = as.numeric(interp_raw$z)) %>% mutate(value = ifelse(value < 0, 0, value))%>% filter(!is.na(value))
				fcst_dat_24hraccum_interp = bind_rows(fcst_dat_24hraccum_interp, fcst_dat_24hraccum_interp_temp)
			}
			fcst_dat_24hraccum_basin = left_join(fcst_dat_24hraccum_interp, c_file) %>% filter(!is.na(name)) %>% group_by(date_init, hour_init, date_fcst, ethbasin, ethbasin_I, name) %>% summarise(value = mean(value))
			write.csv(fcst_dat_24hraccum_basin, file_out)
		})
	}
}
require(knitr)
render_caption <- 
function(caption) {
  paste('<p class="caption">', caption, "</p>", sep="")
}
 
knit_hooks$set(html.cap <- function(before, options, envir) {
    if(!before) {
      render_caption(options$html.cap)
    } else {
      # Do nothing (or set isTable flag to render_caption at the top?
    }
  }
)

require(R6)
Caption =
R6Class("Caption",
  public <- list(
    label_=c(),
    text_=c(),
    type_=NA,
    initialize=function(type="Figure") {
      self$type_ <- type
    },
    label=function(l, t=NULL) {
        index <- length(self$label_) + 1
        if (l %in% self$label_) {
            index <- which(self$label_ == l)
        } else {
            self$label_[index] <- l
        }
        if (!is.null(t)) {
            self$text_[index] <- t
        }
        which(l == self$label_)
    },
    text=function(l, t=NULL) {
        if (!l %in% self$label_) stop("No such label")
        index <- which(l == self$label_)
        if (!is.null(t)) {
            self$text_[index] <- t
        }
        paste(self$type_, " ", which(l == self$label_), ". ", self$text_[index], sep="")
    }
  )
)

Footnote =
R6Class("Footnote",
  public <- list(
    label_=c(),
    text_=c(),
    label=function(l, t=NULL) {
      self$update(l, t)
      writeLines(paste('<a href="#', l, '">',
        '<span id="', l, '_back"><sup>',
        which(l == self$label_), '</sup></span></a>', sep=""))
    },
    update=function(l, t=NULL) {
        index <- length(self$label_) + 1
        if (l %in% self$label_) {
            index <- which(self$label_ == l)
        } else {
            self$label_[index] <- l
        }
        if (!is.null(t)) {
            self$text_[index] <- t
        }
    },
    render=function(head="Notes") {
        writeLines('<div class="footnotes">')
        writeLines(head)
        writeLines('<ol>')
        items <- paste('<li id="', self$label_, '">', self$text_,
                      ' <a href="#', self$label_,'_back">&#8617;</a>', '</li>', sep="")
        writeLines(items)
        writeLines('</ol></div>')
    }
  )
)

numericToString = function(numbers, digits=2) {
    strings <- sprintf(paste("%.", digits, "f", sep=""), 
            round(numbers, digits=digits))
    return(strings)
}

markdownTableStrings = function(data, header=NULL, digits=2) {
    tableLines <- c()

    if (is.null(header)) {
        header <- names(data)
    }
    head <- paste("|",
                  paste(header, collapse="|"),
                  "|", sep="")

    format <- "|"
    for (col in 1:length(names(data))) {
        if (is.numeric(data[1, col])) {
            format <- paste(format, "----:|", sep="")
        } else {
            format <- paste(format, ":----|", sep="")
        }
    }

    row = c()
    for (r in 1:nrow(data)) {
        dataStr = c()
        for (col in 1:length(names(data))) {
            elem <- data[r, col]
            if (is.numeric(elem)) {
                dataStr = c(dataStr, numericToString(elem))
            } else if (is.factor(elem)) {
                dataStr = c(dataStr, as.character(elem))
            } else {
                dataStr = c(dataStr, elem)
            }
        }
        row[r] <- paste("|",
                        paste(dataStr, collapse="|"),
                        "|", sep="")
    }
    return (c(head, format, row))
}

pkgs <- c(
	"alabama",
	"base64enc",
	"caret",
	"cubature",
	"data.table",
	"DEoptim",
	"devtools",
	"doParallel",
	"doSNOW",
	"dplyr",
	"dyn",
	"dynlm",
	"extrafont",
	"feather",
	"fAsianOptions",
	"fAssets",
	"fBasics",
	"fBonds",
	"fCopulae",
	"fExoticOptions",
	"fExtremes",
	"fGarch",
	"fImport",
	"fMultivar",
	"fNonlinear",
	"fOptions",
	"fPortfolio",
	"fRegression",
	"fTrading",
	"fUnitRoots",
	"foreach",
	"forecast",
	"glmnet",
	"gmailr",
	"ggfortify",
	"ggplot2",
	"ggthemes",
	"gmp",
	"Hmisc",
	"knitr",
	"leaps",
	"linprog",
	"lubridate",
	"lpSolve",
	"lpSolveAPI",
	"mail",
	"mapproj",
	"maptools",
	"microbenchmark",
	"mongolite",
	"NMOF",
	"openxlsx",
	"parcor",
	"party",
	"pbivnorm",
	"plm",
	"plotly",
	"PythonInR",
	"quantmod",
	"R.cache",
	"randomForest",
	"Rcpp",
	"RCurl",
	"rJava",
	"readr",
	"reshape",
	"rmarkdown",
	"Rmpfr",
	"rjson",
	"roxygen2",
	"RQuantLib",
	"RSelenium",
	"RSQLite",
	"rvest",
	"scales",
	"sqldf",
	"stringr",
	"Synth",
	"plyr",
	"TSA",
	"tikzDevice",
	"x12",
	"xlsx",
	"XML",
	"xml2",
	"xts",
	"zoo"
	)

install.packages(pkgs)

# rjulia
devtools::install_github("armgong/rjulia", ref="julia0.5")

# http://bioconductor.org/packages/release/bioc/html/rhdf5.html
source("https://bioconductor.org/biocLite.R")
biocLite("rhdf5", ask=F) # HDF5 interface to R
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        cancel = function(job_ids, user = private$user, host = private$host) {
            job_ids <- paste(job_ids, collapse = ",")

            stain_ssh(user, host, paste("scancel", job_ids))
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host, submit_dir = "~/stain") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir = "~/stain") {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        view_submission_history = function() {
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                View(history)
                invisible(history)
            }
        },
        view_statuses = function(user = private$user, host = private$host, should_view = TRUE) {
            job_ids <- stain_sub_history(self$dir)$job_id

            tryCatch({
                status_table <- stain_ssh_squeue(user, host, job_ids)
            }, warning = function(w) {
                message(paste("No statuses found for job ids:", job_ids))
                invisible()
            })


            if (nrow(status_table) > 0) {
                if (should_view) { View(status_table) }
            } else {
                job_ids <- paste(job_ids, collapse = ", ")
                message(paste("No statuses found for job ids:", job_ids))
            }

            invisible(status_table)
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        cancel = function(job_ids, user = private$user, host = private$host) {
            job_ids <- paste(job_ids, collapse = ",")

            stain_ssh(user, host, paste("scancel", job_ids))
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host, submit_dir = "~/stain") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        view_submission_history = function() {
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                View(history)
                invisible(history)
            }
        },
        view_statuses = function(user = private$user, host = private$host, should_view = TRUE) {
            job_ids <- stain_sub_history(self$dir)$job_id

            tryCatch({
                status_table <- stain_ssh_squeue(user, host, job_ids)
            }, warning = function(w) {
                message(paste("No statuses found for job ids:", job_ids))
                invisible()
            })


            if (nrow(status_table) > 0) {
                if (should_view) { View(status_table) }
            } else {
                job_ids <- paste(job_ids, collapse = ", ")
                message(paste("No statuses found for job ids:", job_ids))
            }

            invisible(status_table)
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
###########################################
# get_cfsv2_ts_ncdc.r
# pulls cfsv2 forecasts from NCDC timeseries archive
# subsets to gbm and africa domains
# pulls out specified forecast variables
###########################################

start_time()
## load libraries 
library(data.table)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(tidyr)
library(doParallel)
library(foreach)

## user inputs
dir_scratch = ''
dir_gbm = ''
dir_africa = ''

lims_lon_gbm = c(73, 98)
lims_lat_gbm = c(22, 32)
lims_lon_africa = c(-20, 55)
lims_lat_africa = c(-40, 40)

fcst_lead_sel = 1440
time_sel_start = as.POSIXct('2011-04-01', tz = 'utc')
time_sel_end = as.POSIXct('2016-09-15 18:00', tz = 'utc')

var_sel = 'prate'

ncores_sel = 6

## setup
setwd(dir_scratch)

time_list = seq(from = time_sel_start, to = time_sel_end, by = '6 hour')
ntimes = length(time_list)

tempvar_list = rep(letters, ceiling(ntimes / 26))

## download function
get_cfs_ts_grb = function(var, time_init_sel, fcst_lead = 1440, tempvar){
	require(data.table)
	require(dplyr)
	require(lubridate)
	require(stringr)
	require(tidyr)
	
	urlhead = 'http://nomads.ncdc.noaa.gov/modeldata/cfsv2_forecast_ts_9mon/'
	
	yearinit = year(time_init_sel)
	monthinit = str_pad(month(time_init_sel), 2, pad = "0")
	dayinit = str_pad(day(time_init_sel), 2, pad = "0")
	hourinit = str_pad(hour(time_init_sel), 2, pad = "0")

	initdatefilestr = paste0(yearinit, monthinit, dayinit)
	initdatestr = paste0(yearinit, monthinit, dayinit, hourinit)
	inityrmon = paste0(yearinit, monthinit)
	
	fcst_lead_list = seq(from = 6, to = fcst_lead, by = 6)
	fcst_match_list = paste(paste0(':', fcst_lead_list, ' hour fcst:'), collapse = '|')
	
	url = paste0(urlhead, yearinit, '/', inityrmon, '/', initdatefilestr, '/', initdatestr, '/', var, '.', '01', '.', initdatestr, '.daily.grb2') 
	
	destfile_gbm = paste0(dir_gbm, var, '.', initdatestr, '.', '01', '.grb2') 
	destfile_africa = paste0(dir_africa, var, '.', initdatestr, '.', '01', '.grb2') 
	
	#checks forecast lead against selected and removes file if too small
	if(file.exists(destfile_gbm) == T){
		file_meta = data.table(raw = system(paste('wgrib2', destfile_gbm, '-ftime'), intern = T)) %>% separate(raw, sep = c(':'), into = c('id', 'ref', 'hour')) %>% separate(hour, sep = ' ', into = c('hour', 'lab1', 'lab2'))
		file_max_hour = max(as.numeric(file_meta$hour))
		if(file_max_hour < fcst_lead){
			system(paste("rm", destfile_gbm))
		}
	}
	if(file.exists(destfile_africa) == T){
		file_meta = data.table(raw = system(paste('wgrib2', destfile_africa, '-ftime'), intern = T)) %>% separate(raw, sep = c(':'), into = c('id', 'ref', 'hour')) %>% separate(hour, sep = ' ', into = c('hour', 'lab1', 'lab2'))
		file_max_hour = max(as.numeric(file_meta$hour))
		if(file_max_hour < fcst_lead){
			system(paste("rm", destfile_africa))
		}
	}

	#downloads and subsets (if needed)
	if(file.exists(destfile_gbm) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match '", fcst_match_list, "' -g2clib 0 -small_grib ", paste(lims_lon_gbm, collapse = ':'), " ", paste(lims_lat_gbm, collapse = ':'), " ", destfile_gbm), ignore.stdout = T, ignore.stderr = T)
		if(file.exists(destfile_africa) == F){
			system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match '", fcst_match_list, "' -g2clib 0 -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
		}
	}
	if(file.exists(destfile_africa) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match '", fcst_match_list, "' -g2clib 0 -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
	}
}

## call function 
cl = makeCluster(ncores_sel)
registerDoParallel(cl)
foreach (i = 1:ntimes) %dopar% {
	time_init_sel = time_list[i]
	tempvar_sel = tempvar_list[i]
	try(get_cfs_ts_grb(var_sel, time_init_sel, fcst_lead_sel, tempvar_sel))
}
stopCluster(cl)
Sys.time() - start_time
system(paste("find", dir_gbm, "-size -1k -delete"))
system(paste("find", dir_africa, "-size -1k -delete"))
###########################################
# get_cfsv2_ncdc.r
# pulls cfsv2 forecasts from NCDC archive
# subsets to gbm and africa domains
# pulls out precip. surface temp, winds, and latent
# heat flux
###########################################

start_time = Sys.time()

## load libraries
library(stringr)
library(dplyr)
library(data.table)
library(lubridate)

date2str = function(dte){
	#dte - POSIXct date 
	year_str = year(dte)
	month_str = str_pad(month(dte), 2, pad = '0')
	day_str = str_pad(day(dte), 2, pad = '0')
	hour_str = str_pad(hour(dte), 2, pad = '0')

	paste0(year_str, month_str, day_str, hour_str)
}

## user inputs
dir_scratch = ''
dir_gbm = ''
dir_africa = ''

lims_lon_gbm = c(73, 98)
lims_lat_gbm = c(22, 32)
lims_lon_africa = c(-20, 55)
lims_lat_africa = c(-40, 40)

fcst_lead_sel = 1440
time_sel_start = as.POSIXct('2011-04-01', tz = 'utc')
time_sel_end = as.POSIXct('2011-12-31 18:00', tz = 'utc')

ncores_sel = 6

## setup
setwd(dir_scratch)

time_init_list = seq(from = time_sel_start, to = time_sel_end, by = '6 hour')
fcst_lead_list = seq(from = 6, to = fcst_lead_sel, by = 6)
nfcstlead = length(fcst_lead_list)
time_dt = data.table(time_init = rep(time_init_list, each = nfcstlead), fcst_lead = fcst_lead_list) %>% mutate(time_fcst = time_init + hours(fcst_lead))
ntimes = nrow(time_dt)

tempvar_list = rep(letters, ceiling(ntimes / 26))

## download function
get_cfs_grb = function(time_init_sel, time_fcst_sel, tempvar){
	require(data.table)
	require(dplyr)
	require(lubridate)
	require(stringr)
	require(tidyr)
	
	urlhead = 'http://nomads.ncdc.noaa.gov/modeldata/cfsv2_forecast_6-hourly_9mon_flxf/'
	
	yearinit = year(time_init_sel)
	monthinit = str_pad(month(time_init_sel), 2, pad = "0")
	dayinit = str_pad(day(time_init_sel), 2, pad = "0")
	hourinit = str_pad(hour(time_init_sel), 2, pad = "0")

	initdatefilestr = paste0(yearinit, monthinit, dayinit)
	initdatestr = paste0(yearinit, monthinit, dayinit, hourinit)
	inityrmon = paste0(yearinit, monthinit)
	
	yearfcst = year(time_fcst_sel)
	monthfcst = str_pad(month(time_fcst_sel), 2, pad = "0")
	dayfcst = str_pad(day(time_fcst_sel), 2, pad = "0")
	hourfcst = str_pad(hour(time_fcst_sel), 2, pad = "0")
	
	fcstdatestr = paste0(yearfcst, monthfcst, dayfcst, hourfcst)

	url = paste0(urlhead, yearinit, '/', inityrmon, '/', initdatefilestr, '/', initdatestr, '/flxf', fcstdatestr, '.01.', initdatestr, '.grb2')
	
	destfile_gbm = paste0(dir_gbm, initdatestr, '.', '01', '.', fcstdatestr, '.grb2') 
	destfile_africa = paste0(dir_africa, initdatestr, '.', '01', '.', fcstdatestr, '.grb2') 
	
	#downloads and subsets (if needed)
	if(file.exists(destfile_gbm) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		
		system(paste0("wgrib2 ", "temp_", tempvar, ".grb2", " -g2clib 0 -match ':(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):' -small_grib ", paste(lims_lon_gbm, collapse = ':'), " ", paste(lims_lat_gbm, collapse = ':'), " ", destfile_gbm), ignore.stdout = T, ignore.stderr = T)
		
		if(file.exists(destfile_africa) == F){
			system(paste0("wgrib2 ", "temp_", tempvar, ".grb2", " -g2clib 0 -match ':(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):' -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
		}
	}
	if(file.exists(destfile_africa) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		system(paste0("wgrib2 ", "temp_", tempvar, ".grb2", " -g2clib 0 -match ':(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):' -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
	}
}

## call function
cl = makeCluster(ncores_sel)
registerDoParallel(cl)
foreach (i = 1:ntimes) %dopar% {
	time_init_sel = time_dt$time_init[i]
	time_fcst_sel = time_dt$time_fcst[i]
	tempvar_sel = tempvar_list[i]
	try(get_cfs_grb(time_init_sel, time_fcst_sel, tempvar_sel))
}
stopCluster(cl)
Sys.time() - start_time
system(paste("find", dir_gbm, "-size -1k -delete"))
system(paste("find", dir_africa, "-size -1k -delete"))
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host, submit_dir = "~/stain") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        view_submission_history = function() {
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                View(history)
                invisible(history)
            }
        },
        view_statuses = function(user = private$user, host = private$host, should_view = TRUE) {
            job_ids <- stain_sub_history(self$dir)$job_id

            tryCatch({
                status_table <- stain_ssh_squeue(user, host, job_ids)
            }, warning = function(w) {
                message(paste("No statuses found for job ids:", job_ids))
                invisible()
            })


            if (nrow(status_table) > 0) {
                if (should_view) { View(status_table) }
            } else {
                job_ids <- paste(job_ids, collapse = ", ")
                message(paste("No statuses found for job ids:", job_ids))
            }

            invisible(status_table)
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        view_submission_history = function() {
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                View(history)
                invisible(history)
            }
        },
        view_statuses = function(user, host, should_view = TRUE) {
            job_ids <- stain_sub_history(self$dir)$job_id

            tryCatch({
                status_table <- stain_ssh_squeue(user, host, job_ids)
            }, warning = function(w) {
                message(paste("No statuses found for job ids:", job_ids))
                invisible()
            })


            if (nrow(status_table) > 0) {
                if (should_view) { View(status_table) }
            } else {
                job_ids <- paste(job_ids, collapse = ", ")
                message(paste("No statuses found for job ids:", job_ids))
            }

            invisible(status_table)
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        view_statuses = function(user, host, should_view = TRUE) {
            job_ids <- stain_sub_history(self$dir)$job_id

            tryCatch({
                status_table <- stain_ssh_squeue(user, host, job_ids)
            }, warning = function(w) {
                message(paste("No statuses found for job ids:", job_ids))
                invisible()
            })


            if (nrow(status_table) > 0) {
                if (should_view) { View(status_table) }
            } else {
                job_ids <- paste(job_ids, collapse = ", ")
                message(paste("No statuses found for job ids:", job_ids))
            }

            invisible(status_table)
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        view_statuses = function(user, host, should_view = TRUE) {
            job_ids <- stain_sub_history(self$dir)$job_id
            status_table <- stain_ssh_squeue(user, host, job_ids)

            if (nrow(status_table) > 0) {
                if (should_view) { View(status_table) }
            } else {
                job_ids <- paste(job_ids, collapse = ", ")
                message(paste("No statuses found for job ids:", job_ids))
            }

            invisible(status_table)
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
######################################################################
######################################################################
## ROUTINE ZUM EINLESEN UND VERARBEITEN DER ZEITLICHEN MITTELWERTE
## DES U- ,V- ,W-WINDFELDES AUS ERA-DATEN IM NCDF-FORMAT
## source('~/Master_Thesis/r-code-git/process_mean_uvw.r')
######################################################################
######################################################################


######################################################################
## AUFRUF WICHTIGER BIBLIOTHEKEN UND PAKETE
######################################################################
##

library(ncdf4)
library(parallel)
library(chron)

library(fields)
library(clim.pact)

setwd("~/Master_Thesis/02-r-code-git/")
path <- "data/"
# path <- "/home/skiefer/era/raw/"
file <- "era-t63-mean_uvw_13z.nh-trop-inv.nc"  # Nordhemisphäre + Südhemisphäre



######################################################################
## EINLESEN DER DATEN
## ERA40 / ERA-INTERIM
## T63 - GRID - GAUSSIAN
## NORDHEMISPHÄRE & TROPEN
## 192 (lat) * 64 (lon)
######################################################################
##

nc <- nc_open(paste(path, file, sep = ""))
# print(nc)
u.mean <- ncvar_get(nc, "var131") # U-Wind-Komponente
v.mean <- ncvar_get(nc, "var132") # V-Wind-Komponente
w.mean <- ncvar_get(nc, "var135") # W-Wind-Komponente

lon <- ncvar_get(nc, "lon") # Längengrad
lat <- ncvar_get(nc, "lat") # Breitengrad
lev <- ncvar_get(nc, "lev") # Drucklevel
date.help <- ncvar_get(nc, "time")

nc_close(nc)
rm(nc)

uvw.mean <- sqrt( u.mean ** 2 + v.mean **2 + w.mean ** 2 )


#################################################
## ZONAL MEAN
u.zon.mean <- apply(u.mean[,,], c(2,3), mean)
v.zon.mean <- apply(v.mean[,,], c(2,3), mean)
uvw.zon.mean <- apply(uvw.mean[,,], c(2,3), mean)

## ZONAL-WIND U
filled.contour(lat, 1:13, u.zon.mean, 
               xlab = "Breitengrad in (deg)", 
               ylab = "Druckniveaus in (hPa)",
               main = "Zonal gemittelter Zonal-Wind in (m/s)",
               plot.axes = {
                 axis(1, at = seq(-90, 90, 10))
                 axis(2, at = seq(1,13,2), labels = c('1000', '850', '700', '500',  '300',  '200', '100'))
                 contour(lat, 1:13, u.zon.mean, nlevels = 16,
                         drawlabels = TRUE, axes = FALSE, 
                         frame.plot = FALSE, add = TRUE,
                         col = "grey0", lty = 3, lwd = 1)
               },
               color.palette = tim.colors, nlevels = 16
)

## MERIDIONAL-WIND V
filled.contour(lat, 1:13, v.zon.mean, 
               xlab = "Breitengrad in (deg)", 
               ylab = "Druckniveaus in (hPa)",
               main = "Zonal gemittelter Meridional-Wind in (m/s)",
               plot.axes = {
                 axis(1, at = seq(-90, 90, 10))
                 axis(2, at = seq(1,13,2), labels = c('1000', '850', '700', '500',  '300',  '200', '100'))
                 contour(lat, 1:13, v.zon.mean, nlevels = 16,
                         drawlabels = TRUE, axes = FALSE, 
                         frame.plot = FALSE, add = TRUE,
                         col = "grey0", lty = 3, lwd = 1)
               },
               color.palette = tim.colors, nlevels = 16
)

## BETRAG DES WINDFELDES
filled.contour(lat, 1:13, uvw.zon.mean, 
               xlab = "Breitengrad in (deg)", 
               ylab = "Druckniveaus in (hPa)",
               main = "Zonal gemittelter Wind in (m/s)",
               plot.axes = {
                 axis(1, at = seq(-90, 90, 10))
                 axis(2, at = seq(1,13,2), labels = c('1000', '850', '700', '500',  '300',  '200', '100'))
                 contour(lat, 1:13, uvw.zon.mean, nlevels = 16,
                         drawlabels = TRUE, axes = FALSE, 
                         frame.plot = FALSE, add = TRUE,
                         col = "grey0", lty = 3, lwd = 1)
               },
               color.palette = tim.colors, nlevels = 16
)



#################################################
## MERIDIONAL MEAN
u.mer.mean <- apply(u.mean[,,], c(1,3), mean)
v.mer.mean <- apply(v.mean[,,], c(1,3), mean)
uvw.mer.mean <- apply(uvw.mean[,,], c(1,3), mean)

## ZONAL-WIND U
filled.contour(lon, 1:13, u.mer.mean, 
               xlab = "Längengrad in (deg)", 
               ylab = "Druckniveaus in (hPa)",
               main = "Meridional gemittelter Zonal-Wind in (m/s)",
               plot.axes = {
                 axis(1, at = seq(0, 360, 40))
                 axis(2, at = seq(1,13,2), labels = c('1000', '850', '700', '500',  '300',  '200', '100'))
                 contour(lon, 1:13, u.mer.mean, nlevels = 16,
                         drawlabels = TRUE, axes = FALSE, 
                         frame.plot = FALSE, add = TRUE,
                         col = "grey0", lty = 3, lwd = 1)
               },
               color.palette = tim.colors, nlevels = 16
)

## MERIDIONAL-WIND V
filled.contour(lon, 1:13, v.mer.mean, 
               xlab = "Längengrad in (deg)", 
               ylab = "Druckniveaus in (hPa)",
               main = "Meridional gemittelter Meridional-Wind in (m/s)",
               plot.axes = {
                 axis(1, at = seq(0, 360, 40))
                 axis(2, at = seq(1,13,2), labels = c('1000', '850', '700', '500',  '300',  '200', '100'))
                 contour(lon, 1:13, v.mer.mean, nlevels = 16,
                         drawlabels = TRUE, axes = FALSE, 
                         frame.plot = FALSE, add = TRUE,
                         col = "grey0", lty = 3, lwd = 1)
               },
               color.palette = tim.colors, nlevels = 16
)

## BETRAG DES WINDFELDES
filled.contour(lon, 1:13, uvw.mer.mean, 
               xlab = "Längengrad in (deg)", 
               ylab = "Druckniveaus in (hPa)",
               main = "Meridional gemittelter Wind in (m/s)",
               plot.axes = {
                 axis(1, at = seq(0, 360, 40))
                 axis(2, at = seq(1,13,2), labels = c('1000', '850', '700', '500',  '300',  '200', '100'))
                 contour(lon, 1:13, uvw.mer.mean, nlevels = 16,
                         drawlabels = TRUE, axes = FALSE, 
                         frame.plot = FALSE, add = TRUE,
                         col = "grey0", lty = 3, lwd = 1)
               },
               color.palette = tim.colors, nlevels = 16
)






#################################################
##
filled.contour(lon, lat, u.mean[,,11], 
               xlab = "Längengrad in (deg)", 
               ylab = "Breitengrad in (deg)",
               main = "Meridional gemittelter Zonal-Wind in (m/s)",
               plot.axes = {
                 axis(1, at = seq(0, 360, 40))
                 axis(2, at = seq(-90, 90, 10))
                 contour(lon, lat, u.mean[,,11], nlevels = 16,
                         drawlabels = TRUE, axes = FALSE, 
                         frame.plot = FALSE, add = TRUE,
                         col = "grey0", lty = 3, lwd = 1)
               },
               color.palette = tim.colors, nlevels = 16
)

###########################################
# process_cfsv2_ts_ncdc.r
# processes grib2 files from ncdc cfsv2 archive
# aggregates 6-hrly forecasts to 24hr and 5-day accumulations
# regrids and maps to river basins using correspondence file
# saves data in csv format
###########################################

## load libraries
library(data.table)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(tidyr)
library(tools)
library(akima)

## user inputs
dir_scratch = '/d1/dbroman/projects/cfsv2/scratch/'
dir_dom = '/d1/dbroman/projects/cfsv2/grib2/africa/'
dir_dom_proc = '/d1/dbroman/projects/cfsv2/rdata/africa/'

# define sub-domain of raw forecast
lat_dom = c(1, 16)
lon_dom = c(32, 49)

# new 0.1º grid
xp1 = seq(from = 33.05, by = 0.1, length.out = 150)
yp1 = seq(from = 2.05, by = 0.1, length.out = 130)

# correspondence file 
c_file = fread('/d1/dbroman/projects/cfsv2/src/correspondence_ethiopiabasins.csv')

# extension for outfile
fileout_dom = '_ethiopia_24hraccum.csv'

## set up
setwd(dir_scratch)

dom_file_list = list.files(dir_dom, pattern = '*.grb2')
nfiles_dom = length(dom_file_list)
# 21600 sec / 6hr
weight_tbl = data.table(fcst_hour = c(0, 6, 12, 18, 24), weight = c(0.5, 1, 1, 1, 0.5))

## process files
for(i in 1:nfiles_dom){
	dom_file_sel = paste0(dir_dom, dom_file_list[i])
	file_out = paste0(dir_dom_proc, file_path_sans_ext(dom_file_list[i]), fileout_dom)
	if(file.exists(file_out) == F){
		system(paste0("wgrib2 ", dom_file_sel, " -csv temp.csv"))
		tryCatch({
			fcst_dat = fread('temp.csv') %>% setnames(c('date_init', 'date_fcst', 'var', 'level', 'lon', 'lat', 'value')) %>% select(-var, -level)
			fcst_dat = fcst_dat %>% filter(lon >= lon_dom[1], lon <= lon_dom[2], lat >= lat_dom[1], lat <= lat_dom[2]) %>% mutate(date_init = as.POSIXct(date_init), date_fcst = as.POSIXct(date_fcst), value = value * 21600) %>% mutate(fcst_hour = hour(date_fcst)) %>% mutate(date_init = as.Date(date_init), date_fcst = as.Date(date_fcst))

			fcst_dat_24z = fcst_dat %>% filter(fcst_hour == 0) %>% mutate(date_fcst = date_fcst - days(1), fcst_hour = 24)

			fcst_dat = bind_rows(fcst_dat, fcst_dat_24z)
			fcst_dat_24hraccum = fcst_dat %>% left_join(weight_tbl) %>% mutate(value = value * weight, date_fcst = date_fcst + days(1)) %>% group_by(date_init, date_fcst, lon, lat) %>% dplyr::summarise(value = sum(value)) 
			date_init_temp = unique(fcst_dat_24hraccum $date_init)
			date_fcst_list = sort(unique(fcst_dat_24hraccum$date_fcst))
			nfcst = length(date_fcst_list)
			fcst_dat_24hraccum_interp = NULL
			for(j in 1:nfcst){
				date_fcst_temp = date_fcst_list[j]
				fcst_dat_24hraccum_fl = filter(fcst_dat_24hraccum, date_fcst == date_fcst_temp)

				x_temp = fcst_dat_24hraccum_fl$lon
				y_temp = fcst_dat_24hraccum_fl$lat
				z_temp = fcst_dat_24hraccum_fl$value
				interp_raw = interp(x_temp, y_temp, z_temp, xo = xp1, yo = yp1)
				fcst_dat_24hraccum_interp_temp = data.table(date_init = date_init_temp, date_fcst = date_fcst_temp, lon = interp_raw$x, lat = rep(interp_raw$y, each = length(interp_raw$x)), value = as.numeric(interp_raw$z)) %>% mutate(value = ifelse(value < 0, 0, value))%>% filter(!is.na(value))
				fcst_dat_24hraccum_interp = bind_rows(fcst_dat_24hraccum_interp, fcst_dat_24hraccum_interp_temp)
			}
			fcst_dat_24hraccum_basin = left_join(fcst_dat_24hraccum_interp, c_file) %>% filter(!is.na(name)) %>% group_by(date_init, date_fcst, ethbasin, ethbasin_I, name) %>% summarise(value = mean(value))
			write.csv(fcst_dat_24hraccum_basin, file_out)
		})
	}
}
###########################################
# process_cfsv2_ts_ncdc.r
# processes grib2 files from ncdc cfsv2 archive
# aggregates 6-hrly forecasts to 24hr accumulations
# saves data in csv format
###########################################

## load libraries
library(data.table)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(tidyr)
library(tools)

## user inputs
dir_scratch = ''
dir_dom = ''
dir_dom_proc = '/d1/dbroman/projects/cfsv2/rdata/africa/'

# define domain
lat_dom = c(2, 16)
lon_dom = c(31, 49)
fileout_dom = '_ethiopia_24hraccum.csv'

## setup
setwd(dir_scratch)

dom_file_list = list.files(dir_dom, pattern = '*.grb2')
nfiles_dom = length(dom_file_list)
# 21600 sec / 6hr
weight_tbl = data.table(fcst_hour = c(0, 6, 12, 18, 24), weight = c(0.5, 1, 1, 1, 0.5))

## process files
for(i in 1:nfiles_dom){
	dom_file_sel = paste0(dir_dom, dom_file_list[i])
	file_out = paste0(dir_dom_proc, file_path_sans_ext(dom_file_list[i]), fileout_dom)
	if(file.exists(file_out) == F){
		system(paste0("wgrib2 ", dom_file_sel, " -csv temp.csv"))
		tryCatch({
			fcst_dat = fread('temp.csv') %>% setnames(c('date_init', 'date_fcst', 'var', 'level', 'lon', 'lat', 'value')) %>% select(-var, -level)
			fcst_dat = fcst_dat %>% filter(lon >= lon_dom[1], lon <= lon_dom[2], lat >= lat_dom[1], lat <= lat_dom[2]) %>% mutate(date_init = as.POSIXct(date_init), date_fcst = as.POSIXct(date_fcst), value = value * 21600) %>% mutate(fcst_hour = hour(date_fcst)) %>% mutate(date_init = as.Date(date_init), date_fcst = as.Date(date_fcst))

			fcst_dat_24z = fcst_dat %>% filter(fcst_hour == 0) %>% mutate(date_fcst = date_fcst - days(1), fcst_hour = 24)

			fcst_dat = bind_rows(fcst_dat, fcst_dat_24z)
			fcst_dat_24hraccum = fcst_dat %>% left_join(weight_tbl) %>% mutate(value = value * weight, date_fcst = date_fcst + days(1)) %>% group_by(date_init, date_fcst, lon, lat) %>% dplyr::summarise(value = sum(value)) 
			write.csv(fcst_dat_24hraccum, file_out)
		})
	}
}
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                stain_ssh(user, host, submit_cmd)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' Number of control matrix principal components
#'
#' Fits probe intensities to principal components of the microarray control matrix
#' and calculates the resulting mean squared residuals for different
#' numbers of principal components.
#' 
#' @param qc.objects A list of outputs from \code{\link{meffil.create.qc.object}()}.
#' @param number.pcs Number of principal components to include in the design matrix (Default: all).
#' @param fixed.effects Names of columns in samplesheet that should be included as fixed effects
#' along with control matrix principal components (Default: NULL).
#' @param random.effects Names of columns in samplesheet that should be included as random effects
#' (Default: NULL).
#' @return A list containing a data frame with the mean squared residuals for different numbers of principal components
#' and a plot of these residuals.
#'
#' @export
meffil.plot.pc.fit <- function(qc.objects, fixed.effects=NULL, random.effects=NULL, n.cross=10, name="autosomal.ii") {
    stopifnot(is.valid.site.subset(name))    
    stopifnot(all(sapply(qc.objects, is.qc.object)))
    
    if (2*n.cross > length(qc.objects)) 
        n.cross <- floor(length(qc.objects)/2)
    
    n.quantiles <- length(qc.objects[[1]]$quantiles[[1]]$M)
    max.pcs <- min(ncol(meffil.control.matrix(qc.objects)),
                   length(qc.objects) - ceiling(length(qc.objects)/n.cross))
    
    stats <- mclapply(1:max.pcs, function(number.pcs) {
        residuals <- list(M=matrix(NA,nrow=n.quantiles,ncol=length(qc.objects)),
                          U=matrix(NA,nrow=n.quantiles,ncol=length(qc.objects)))
        group <- sample(rep(1:n.cross, length.out=length(qc.objects)), length(qc.objects), replace=F)
        
        for (test.group in unique(group)) {
            msg("pcs", number.pcs, "group", test.group)
            test.idx <- which(group == test.group)
            design.matrix <- predict.design.matrix(qc.objects, number.pcs, test.idx,
                                                   fixed.effects=fixed.effects,
                                                   random.effects=random.effects)

            intensity.R <- sapply(qc.objects, function(object) object$intensity.R)
            intensity.G <- sapply(qc.objects, function(object) object$intensity.G)
            valid.idx <- which(intensity.R + intensity.G > 200)
            if(length(valid.idx) == 0) {
                valid.idx <- 1:length(intensity.R)
                warning("Most or all of the microarrays have very low intensity.")
            }
            reference.idx <- valid.idx[which.min(abs(intensity.R/intensity.G-1)[valid.idx])]
            dye.intensity <- (intensity.R + intensity.G)[reference.idx]/2
            for (target in c("M","U")) {
                original <- sapply(qc.objects[test.idx], function(object) {
                    object$quantiles[[name]][[target]] * dye.intensity/object$dye.intensity
                })
                residuals[[target]][,test.idx] <- (normalize.quantiles(original, design.matrix)
                                                   - rowMeans(original))
            }
        }
        
        c(n=number.pcs,M=mean((residuals$M[,-1])^2), U=mean((residuals$U[,-1])^2))
    })

    stats <- as.data.frame(do.call(rbind, stats))

    list(data=stats,
         plot=(ggplot(stats, aes(x=n)) +
               geom_line(aes(y=M, colour="M")) +
               geom_line(aes(y=U, colour="U")) +
               ggtitle("Fit residuals for different numbers of PCs") +
               labs(x="number of PCs", y="Mean squared residuals") +
               scale_x_continuous(breaks=seq(0,max(stats$n),by=5 )) +
               theme(legend.title=element_blank())))
}
#coverage/inst/shiny/covmob1/ui.r
#* deprecated version, replaced by coverage1
#andy south 12/5/16

library(shiny)


shinyUI(fluidPage(

  #can add CSS controls in here
  #http://shiny.rstudio.com/articles/css.html
  #http://www.w3schools.com/css/css_rwd_mediaqueries.asp

  #trying to put the @media bit in to make it responsive
  #i think i must have made another change later when i modified from pc to mobile

  tags$head(
    tags$style(HTML("

                    @media only screen and (max-width: 768px) {

                      /* For mobile phones: */

                      [class*='col-'] {
                      padding: 10px;
                      border: 1px;
                      position: relative;
                      min-height: 1px;
                      }

                      .container {
                      margin-right: 0;
                      margin-left: 0;
                      float: left;
                      }
                      .col-sm-1 {width: 8.33%; float: left;}
                      .col-sm-2 {width: 16.66%; float: left;}
                      .col-sm-3 {width: 25%; float: left;}
                      .col-sm-4 {width: 33.33%; float: left;}
                      .col-sm-5 {width: 41.66%; float: left;}
                      .col-sm-6 {width: 50%;  float: left;}
                      .col-sm-7 {width: 58.33%; float: left;}
                      .col-sm-8 {width: 66.66%; float: left; padding: 5px;} !to make more space for plots
                      .col-sm-9 {width: 75%; float: left;}
                      .col-sm-10 {width: 83.33%; float: left;}
                      .col-sm-11 {width: 91.66%; float: left;}
                      .col-sm-12 {width: 100%; float: left;}
                    }
                    "))
    ),

  title = "coverage of vector control interventions",

  h5("Vector control demonstrator prototype. Gerry Killeen & Andy South."),
  h5("OLD version replaced by coverage1"),
  #h5("Vectors feed indoors and outdoors, on humans and cattle. Interventions target a subset of these behaviours."),
  #h5("Change inputs below to see implications."),

  # fluidRow(
  #   column(8, plotOutput('plot_feed')),
  #   # column(2, h5("Vector feeding"), plotOutput('plot_pie_feed') ),
  #   # column(2, h5("Human exposure"), plotOutput('plot_pie_expose') )
  #   column(2, plotOutput('plot_pie_feed') ),
  #   column(2, plotOutput('plot_pie_expose') )
  # ), #end fluid row

  fluidRow(

    #column(12, plotOutput('plot_feed'))

    column(12, HTML("<div style='height: 320px;'>"), plotOutput('plot_feed'), HTML("</div>"))

  ), #end fluid row

  fluidRow(
    #column(2,NULL),

    #column(4, plotOutput('plot_pie_feed') ),
    #column(4, plotOutput('plot_pie_expose') )

    column(6, HTML("<div style='height: 150px;'>"), plotOutput('plot_pie_feed'), HTML("</div>")),
    column(6, HTML("<div style='height: 150px;'>"), plotOutput('plot_pie_expose'), HTML("</div>"))

    #column(4, plotOutput('plot_pie_expose') )
  ), #end fluid row

  #hr(),

  fluidRow(
    column(3,
           #h4("Vector feeding"),
           sliderInput("feed_man", "vectors feeding on man", 0.7, min = 0, max = 1, step = 0.1, ticks=FALSE)
           #numericInput("feed_cow", "cattle", 0.3, min = 0, max = 1, step = 0.1),
           #sliderInput("feed_in","indoor", 0.6, min = 0, max = 1, step = 0.1)
           #numericInput("feed_out","outdoor", 0.4, min = 0, max = 1, step = 0.1)
    ),
    column(3,
           sliderInput("feed_in","vectors feeding indoors", 0.6, min = 0, max = 1, step = 0.1, ticks=FALSE)
    ),
    column(3, offset = 0,
           #h4("Intervention"),
           radioButtons("intervention","intervention",choices=c("bed nets","vet insecticide"))
           #sliderInput("target_coverage", "coverage", 0.7, min = 0, max = 1, step = 0.1)
    ),
    column(3, offset = 0,
           sliderInput("target_coverage", "intervention coverage", 0, min = 0, max = 1, step = 0.1, ticks=FALSE)
    )
           # h4("Intervention target"),
           # numericInput("target_man", "human", 0.7, min = 0, max = 1, step = 0.1),
           # numericInput("target_cow", "cattle", 0.3, min = 0, max = 1, step = 0.1),
           # numericInput("target_in","indoor", 0.6, min = 0, max = 1, step = 0.1),
           # numericInput("target_out","outdoor", 0.4, min = 0, max = 1, step = 0.1)


  ) #end fluid row

))
#' Function to batch download gridded DAYMET data
#'
#' This function downloads DAYMET data 
#' @param lat1 : top left latitude (decimal degrees)
#' @param lon1 : top left longitude (decimal degrees)
#' @param lat2 : bottom right latitude (decimal degrees)
#' @param lon2 : bottom right longitude(decimal degrees)
#' @param start_yr : start of the range of years over which to download data
#' @param end_yr : end of the range of years over which to download data
#' @param param : climate variable you want to download vapour pressure (vp), 
#' minimum and maximum temperature (tmin,tmax), snow water equivalent (swe), 
#' solar radiation (srad), precipitation (prcp) , day length (dayl).
#' The default setting is ALL, this will download all the previously mentioned
#' climate variables.
#' @keywords DAYMET, climate data
#' @export
#' @examples
#' download.daymet.tiles(lat1=36.0133,
#'                       lon1=-84.2625,
#'                       start_yr=1980,
#'                       end_yr=2000,
#'                       param="ALL")

download.daymet.tiles = function(lat1=36.0133,
                                 lon1=-84.2625,
                                 lat2=NA,
                                 lon2=NA,
                                 start_yr=1980,
                                 end_yr=1980,
                                 param="ALL"){
  
  # determine system
  OS = Sys.info()[['sysname']]
  
  # load DAYMET grid associated with the package
  # (this is an imported shapefile)
  # I do not store any additional data in the .rdata
  # file to keep the code transparent.
  data("DAYMET_grid")
  
  # grab the projection string. This is a LCC projection.
  projection = sp::CRS(sp::proj4string(tile_outlines))
  
  # extract tile IDs (vector shape) and the DAYMET IDs associated
  # with them
  tile_nrs = tile_outlines@data[,1]
  
  # if argument 3 or 4 are the default grab only the tile
  # of the first coordinate set, if 4 arguments are given
  # extract all tile numbers within this region of interest
  if ( is.na(lat2) | is.na(lon2)){
    
        # create coordinate pairs, with original coordinate  system
        location = sp::SpatialPoints(cbind(lon1,lat1), projection)
        
        # extract tile for this location
        tiles = sp::over(location,tile_outlines)$TileID
        
        # do not continue if outside range
        if (is.na(tiles)){
          stop("Your defined range is outside DAYMET coverage,
               check your coordinate values!")
        }

      }else{
      
        # create coordinate pairs, with original coordinate system
        topleft = sp::SpatialPoints(cbind(lon1,lat1), projection)
        bottomright = sp::SpatialPoints(cbind(lon2,lat2), projection)

        # this is some juggling to define a polygon (vector format)
        # which I will convert to LCC and use as a mask to extract
        # tile numbers. As such I avoid artefacts due to resampling.
        poly_corners = matrix(NA,5,2)
        poly_corners[1,] = c(lon1,lat2)
        poly_corners[2,] = c(lon2,lat2)
        poly_corners[3,] = c(lon2,lat1)
        poly_corners[4,] = c(lon1,lat1)
        poly_corners[5,] = c(lon1,lat2)
        
        # make into a polygon object
        ROI = sp::SpatialPolygons(list(sp::Polygons(list(sp::Polygon(poly_corners)),1)))
        
        # set original projection
        sp::proj4string(ROI) = projection
        
        # extract pixels within the ROI
        r = rgeos::gIntersection(ROI,tile_outlines,byid=TRUE)
        
        if (is.null(r)){
          stop("Your defined range is outside DAYMET coverage,
               check your coordinate values!")
        }
        
        # extract tile IDs and match to DAYMET grid IDs
        polygon_nr = as.numeric(sapply(r@polygons,function(x)unlist(strsplit(x@ID,split=' '))[2])) + 1
        tiles = tile_nrs[polygon_nr]
  }
  
  # calculate the end of the range of years to download
  # conservative setting based upon the current date
  # -1 year
  max_year = as.numeric(format(Sys.time(), "%Y"))-1
  
  # check validaty of the range of years to download
  # I'm not sure when new data is released so this might be a
  # very conservative setting, remove it if you see more recent data
  # on the website
  
  if (start_yr < 1980){
    stop("Start year preceeds valid data range!")
  }
  
  if (end_yr > max_year){
    stop("End year exceeds valid data range!")
  }
  
  # if the year range is valid, create a string of valid years
  year_range = seq(start_yr,end_yr,by=1)

  # check the parameters we want to download
  if (param == "ALL"){
    param = c('vp','tmin','tmax','swe','srad','prcp','dayl')
  }

  for ( i in year_range ){
    for ( j in tiles ){
      for ( k in param ){
        
        # create download string / url  
        download_string = sprintf("http://thredds.daac.ornl.gov/thredds/catalog/ornldaac/1328/tiles/%s/%s_%s/%s.nc",i,j,i,k)
                
        # create filename for the output file
        daymet_file = paste(k,"_",i,"_",j,".nc",sep='')
        
        # provide some feedback
        cat(paste('Downloading DAYMET data for tile: ',j,
                  '; year: ',i,
                  '; product: ',k,
                  '\n',sep=''))
        
        # download data, force binary data mode
        try(downloader::download(download_string,
                                 daymet_file,
                                 quiet=TRUE,
                                 mode="wb"),silent=FALSE)  
      }
    }
  }
}
###########################################
# cfsv2_ts_ncdc_sqlite.r
# processes grib2 files from ncdc cfsv2 archive
# saves data to sqlite database
# saves data in rdata format
###########################################

library(data.table)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(tidyr)
library(RSQLite)
library(sqldf)

dir_scratch = '/d1/dbroman/projects/cfsv2/scratch/'
dir_gbm = '/d1/dbroman/projects/cfsv2/grib2/gbm/'
dir_gbm_proc = '/d1/dbroman/projects/cfsv2/rdata/gbm/'

setwd(dir_gbm_proc)
db = dbConnect(SQLite(), dbname = 'gbm_cfsv2.sqlite')

gbm_file_list = list.files(dir_gbm, pattern = '*.grb2')
nfiles_gbm = length(gbm_file_list)

for(i in 1:nfiles_gbm){
  gbm_file_sel = paste0(dir_gbm, gbm_file_list[i])
	system(paste0("wgrib2 ", gbm_file_sel, " -csv temp.csv"))
	tryCatch({
		fcst_dt_temp = fread('temp.csv') %>% setnames(c('datetime_init', 'datetime_fcst', 'var', 'level', 'lon', 'lat', 'value'))
		fcst_dt_temp = fcst_dt_temp %>% mutate(datetime_init = as.POSIXct(datetime_init), datetime_fcst = as.POSIXct(datetime_fcst)) %>% mutate(hour_fcst = hour(datetime_fcst), hour_init = hour(datetime_init)) %>% mutate(date_init = as.Date(datetime_init), date_fcst = as.Date(datetime_fcst))
		fcst_dt_temp_24z = fcst_dt_temp %>% filter(hour_fcst == 0) %>% mutate(date_fcst = date_fcst - days(1), hour_fcst = 24)
		fcst_dt_temp = bind_rows(fcst_dt_temp, fcst_dt_temp_24z) %>% mutate(date_init = as.character(date_init), date_fcst = as.character(date_fcst)) %>% mutate(datetime_init = as.character(datetime_init), datetime_fcst = as.character(datetime_fcst)) %>% select(datetime_init, date_init, hour_init, datetime_fcst, date_fcst, hour_fcst, var, level, lon, lat, value) %>% data.table()
		var_temp = unique(fcst_dt_temp$var)
  		dbWriteTable(conn = db, name = var_temp, value = fcst_dt_temp, row.names = F, append = T)
	})
}


dir_scratch = '/d1/dbroman/projects/cfsv2/scratch/'
dir_africa = '/d1/dbroman/projects/cfsv2/grib2/africa/'
dir_africa_proc = '/d1/dbroman/projects/cfsv2/rdata/africa/'

setwd(dir_africa_proc)
db = dbConnect(SQLite(), dbname = 'africa_cfsv2.sqlite')

africa_file_list = list.files(dir_africa, pattern = '*.grb2')
nfiles_africa = length(africa_file_list)

for(i in 1:nfiles_africa){
  africa_file_sel = paste0(dir_africa, africa_file_list[i])
	system(paste0("wgrib2 ", africa_file_sel, " -csv temp.csv"))
	tryCatch({
		fcst_dt_temp = fread('temp.csv') %>% setnames(c('datetime_init', 'datetime_fcst', 'var', 'level', 'lon', 'lat', 'value'))
		fcst_dt_temp = fcst_dt_temp %>% mutate(datetime_init = as.POSIXct(datetime_init), datetime_fcst = as.POSIXct(datetime_fcst)) %>% mutate(hour_fcst = hour(datetime_fcst), hour_init = hour(datetime_init)) %>% mutate(date_init = as.Date(datetime_init), date_fcst = as.Date(datetime_fcst))
		fcst_dt_temp_24z = fcst_dt_temp %>% filter(hour_fcst == 0) %>% mutate(date_fcst = date_fcst - days(1), hour_fcst = 24)
		fcst_dt_temp = bind_rows(fcst_dt_temp, fcst_dt_temp_24z) %>% mutate(date_init = as.character(date_init), date_fcst = as.character(date_fcst)) %>% mutate(datetime_init = as.character(datetime_init), datetime_fcst = as.character(datetime_fcst)) %>% select(datetime_init, date_init, hour_init, datetime_fcst, date_fcst, hour_fcst, var, level, lon, lat, value) %>% data.table()
		var_temp = unique(fcst_dt_temp$var)
  		dbWriteTable(conn = db, name = var_temp, value = fcst_dt_temp, row.names = F, append = T)
	})
}
###########################################
# cfsv2_ts_ncdc_sqlite.r
# processes grib2 files from ncdc cfsv2 archive
# saves data to sqlite database
# saves data in rdata format
###########################################

library(data.table)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(tidyr)
library(RSQLite)
library(sqldf)

dir_scratch = '/d1/dbroman/projects/cfsv2/scratch/'
dir_gbm = '/d1/dbroman/projects/cfsv2/grib2/gbm/'
dir_gbm_proc = '/d1/dbroman/projects/cfsv2/rdata/gbm/'

setwd(dir_gbm_proc)
db = dbConnect(SQLite(), dbname = 'gbm_cfsv2.sqlite')

gbm_file_list = list.files(dir_gbm, pattern = '*.grb2')
nfiles_gbm = length(gbm_file_list)

for(i in 1:nfiles_gbm){
  gbm_file_sel = paste0(dir_gbm, gbm_file_list[i])
	system(paste0("wgrib2 ", gbm_file_sel, " -csv temp.csv"))
	tryCatch({
	fcst_dt_temp = fread('temp.csv') %>% setnames(c('date_init', 'date_fcst', 'var', 'level', 'lon', 'lat', 'value'))
	})
	var_temp = unique(fcst_dt_temp$var)
  dbWriteTable(conn = db, name = var_temp, value = fcst_dt_temp, row.names = F, append = T)
}


dir_scratch = '/d1/dbroman/projects/cfsv2/scratch/'
dir_africa = '/d1/dbroman/projects/cfsv2/grib2/africa/'
dir_africa_proc = '/d1/dbroman/projects/cfsv2/rdata/africa/'

setwd(dir_africa_proc)
db = dbConnect(SQLite(), dbname = 'africa_cfsv2.sqlite')

africa_file_list = list.files(dir_africa, pattern = '*.grb2')
nfiles_africa = length(africa_file_list)

for(i in 1:nfiles_africa){
  africa_file_sel = paste0(dir_africa, africa_file_list[i])
	system(paste0("wgrib2 ", africa_file_sel, " -csv temp.csv"))
	tryCatch({
	fcst_dt_temp = fread('temp.csv') %>% setnames(c('date_init', 'date_fcst', 'var', 'level', 'lon', 'lat', 'value'))
	})
	var_temp = unique(fcst_dt_temp$var)
  dbWriteTable(conn = db, name = var_temp, value = fcst_dt_temp, row.names = F, append = T)
}
# download:
https://yale.box.com/s/icu69vs2m7ygww38lor7d3laoibpfk6x

#Create a new project in the folder that has the JSTOR data.

install.packages("devtools")
library(devtools)
install_github("agoldst/dfrtopics")
install.packages("dplyr")
install.packages("ggplot2")
install.packages("lubridate")
install.packages("stringr")
install.packages("rJava")
install.packages("mallet")




options(java.parameters="-Xmx4g")
library(dfrtopics)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(rJava)
library(mallet)


data_dir <- file.path("/Users/[YOUR USERNAME HERE]/Desktop/slavic")

# First we load metadata: 

metadata_file <- file.path(data_dir, "citations.tsv")
meta <- read_dfr_metadata(metadata_file)
# 
# "The word counts can be loaded into memory all at once with read_wordcounts, 
# which takes a vector of file names."
counts <- read_wordcounts(list.files(file.path(data_dir, "wordcounts"), full.names=T))


# "Here’s how we might tabulate how many words stoplisting will remove from each document:"
stoplist_file <- file.path("stoplist-russian.txt")
stoplist <- readLines(stoplist_file)
counts <- counts %>% wordcounts_remove_stopwords(stoplist)




# "Filter infrequent words. OCR’d text in particular is littered with hapax legomena.
# The long tail of one-off features means a lot of noise for the modeling process, 
# and you’ll likely want to get rid of these.
# For example, to eliminate all but roughly the 20,000 most frequent features:"
counts <- counts %>%
  wordcounts_remove_rare(20000)
  
  
  
  
  
# "MALLET cannot accept our counts data frame from R as is. 
# Instead, it wants a data frame with one row per document, 
# which it will then tokenize once again. This is silly, but easily handled:"
docs <- wordcounts_texts(counts)



# "To create the MALLET-ready input, which is called an InstanceList, we use:"
ilist <- make_instances(docs)



#
# "Now we launch the LDA algorithm"
#
# we ran 20, 50, 100, and 150, and agreed on 100
topic_model <- train_model(ilist, n_topics=50,
                 n_iters=300,
                 seed=1,
                 threads=4,
                 metadata=meta
)
#this can take quite a long time...
write_mallet_model(topic_model, "modeling_results")




# create folder for topic browsing. note that folder name is 'browser-'+number of topics+formatted datetime
dfr_browser(topic_model, "slavic-review-browser", internalize=F)

# Type this in a terminal, not rStudio:
cd slavic-review-browser
bin/server


# to get a readout of the top N words by weight and first N topic labels, use these
# top_words(topic_model, n=10)
# topic_labels(topic_model, n=8)
# download:
https://yale.box.com/s/icu69vs2m7ygww38lor7d3laoibpfk6x

#Create a new project in the folder that has the JSTOR data.

install.packages("devtools")
install_github("agoldst/dfrtopics")
install.packages("dplyr")
install.packages("ggplot2")
install.packages("lubridate")
install.packages("stringr")
install.packages("rJava")
install.packages("mallet")



library(devtools)
options(java.parameters="-Xmx4g")
library(dfrtopics)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(rJava)
library(mallet)


data_dir <- file.path("/Users/[YOUR USERNAME HERE]/Desktop/slavic")

# First we load metadata: 

metadata_file <- file.path(data_dir, "citations.tsv")
meta <- read_dfr_metadata(metadata_file)
# 
# "The word counts can be loaded into memory all at once with read_wordcounts, 
# which takes a vector of file names."
counts <- read_wordcounts(list.files(file.path(data_dir, "wordcounts"), full.names=T))


# "Here’s how we might tabulate how many words stoplisting will remove from each document:"
stoplist_file <- file.path("stoplist-russian.txt")
stoplist <- readLines(stoplist_file)
counts <- counts %>% wordcounts_remove_stopwords(stoplist)




# "Filter infrequent words. OCR’d text in particular is littered with hapax legomena.
# The long tail of one-off features means a lot of noise for the modeling process, 
# and you’ll likely want to get rid of these.
# For example, to eliminate all but roughly the 20,000 most frequent features:"
counts <- counts %>%
  wordcounts_remove_rare(20000)
  
  
  
  
  
# "MALLET cannot accept our counts data frame from R as is. 
# Instead, it wants a data frame with one row per document, 
# which it will then tokenize once again. This is silly, but easily handled:"
docs <- wordcounts_texts(counts)



# "To create the MALLET-ready input, which is called an InstanceList, we use:"
ilist <- make_instances(docs)



#
# "Now we launch the LDA algorithm"
#
# we ran 20, 50, 100, and 150, and agreed on 100
topic_model <- train_model(ilist, n_topics=50,
                 n_iters=300,
                 seed=1,
                 threads=4,
                 metadata=meta
)
#this can take quite a long time...
write_mallet_model(topic_model, "modeling_results")




# create folder for topic browsing. note that folder name is 'browser-'+number of topics+formatted datetime
dfr_browser(topic_model, "slavic-review-browser", internalize=F)

# Type this in a terminal, not rStudio:
cd slavic-review-browser
bin/server


# to get a readout of the top N words by weight and first N topic labels, use these
# top_words(topic_model, n=10)
# topic_labels(topic_model, n=8)
#Create a new project in the folder that has the JSTOR data.

install.packages("devtools")
install_github("agoldst/dfrtopics")
install.packages("dplyr")
install.packages("ggplot2")
install.packages("lubridate")
install.packages("stringr")
install.packages("rJava")
install.packages("mallet")



library(devtools)
options(java.parameters="-Xmx4g")
library(dfrtopics)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(rJava)
library(mallet)


data_dir <- file.path("/Users/[YOUR USERNAME HERE]/Desktop/slavic")

# First we load metadata: 

metadata_file <- file.path(data_dir, "citations.tsv")
meta <- read_dfr_metadata(metadata_file)
# 
# "The word counts can be loaded into memory all at once with read_wordcounts, 
# which takes a vector of file names."
counts <- read_wordcounts(list.files(file.path(data_dir, "wordcounts"), full.names=T))


# "Here’s how we might tabulate how many words stoplisting will remove from each document:"
stoplist_file <- file.path("stoplist-russian.txt")
stoplist <- readLines(stoplist_file)
counts <- counts %>% wordcounts_remove_stopwords(stoplist)




# "Filter infrequent words. OCR’d text in particular is littered with hapax legomena.
# The long tail of one-off features means a lot of noise for the modeling process, 
# and you’ll likely want to get rid of these.
# For example, to eliminate all but roughly the 20,000 most frequent features:"
counts <- counts %>%
  wordcounts_remove_rare(20000)
  
  
  
  
  
# "MALLET cannot accept our counts data frame from R as is. 
# Instead, it wants a data frame with one row per document, 
# which it will then tokenize once again. This is silly, but easily handled:"
docs <- wordcounts_texts(counts)



# "To create the MALLET-ready input, which is called an InstanceList, we use:"
ilist <- make_instances(docs)



#
# "Now we launch the LDA algorithm"
#
# we ran 20, 50, 100, and 150, and agreed on 100
topic_model <- train_model(ilist, n_topics=50,
                 n_iters=300,
                 seed=1,
                 threads=4,
                 metadata=meta
)
#this can take quite a long time...
write_mallet_model(topic_model, "modeling_results")




# create folder for topic browsing. note that folder name is 'browser-'+number of topics+formatted datetime
dfr_browser(topic_model, "slavic-review-browser", internalize=F)

# Type this in a terminal, not rStudio:
cd slavic-review-browser
bin/server


# to get a readout of the top N words by weight and first N topic labels, use these
# top_words(topic_model, n=10)
# topic_labels(topic_model, n=8)
#Create a new project in the folder that has the JSTOR data.

install.packages("devtools")
install_github("agoldst/dfrtopics")
install.packages("dplyr")
install.packages("ggplot2")
install.packages("lubridate")
install.packages("stringr")
install.packages("rJava")
install.packages("mallet")



library(devtools)
options(java.parameters="-Xmx4g")
library(dfrtopics)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(rJava)
library(mallet)


data_dir <- file.path("/Users/[YOUR USERNAME HERE]/Desktop/slavic")

# First we load metadata: 

metadata_file <- file.path(data_dir, "citations.tsv")
meta <- read_dfr_metadata(metadata_file)
# 
# "The word counts can be loaded into memory all at once with read_wordcounts, 
# which takes a vector of file names."
counts <- read_wordcounts(list.files(file.path(data_dir, "wordcounts"), full.names=T))


# "Here’s how we might tabulate how many words stoplisting will remove from each document:"
stoplist_file <- file.path("stoplist-russian.txt")
stoplist <- readLines(stoplist_file)
counts <- counts %>% wordcounts_remove_stopwords(stoplist)




# "Filter infrequent words. OCR’d text in particular is littered with hapax legomena.
# The long tail of one-off features means a lot of noise for the modeling process, 
# and you’ll likely want to get rid of these.
# For example, to eliminate all but roughly the 20,000 most frequent features:"
counts <- counts %>%
  wordcounts_remove_rare(20000)
  
  
  
  
  
# "MALLET cannot accept our counts data frame from R as is. 
# Instead, it wants a data frame with one row per document, 
# which it will then tokenize once again. This is silly, but easily handled:"
docs <- wordcounts_texts(counts)



# "To create the MALLET-ready input, which is called an InstanceList, we use:"
ilist <- make_instances(docs)



#
# "Now we launch the LDA algorithm"
#
# we ran 20, 50, 100, and 150, and agreed on 100
topic_model <- train_model(ilist, n_topics=50,
                 n_iters=300,
                 seed=1,
                 threads=4,
                 metadata=meta
)
#this can take quite a long time...
write_mallet_model(topic_model, "modeling_results")




summary(topic_model)
# create folder for topic browsing. note that folder name is 'browser-'+number of topics+formatted datetime
dfr_browser(topic_model, "slavic-review-browser", internalize=F)

# Type this in a terminal, not rStudio:
cd slavic-review-browser
bin/server


# to get a readout of the top N words by weight and first N topic labels, use these
# top_words(topic_model, n=10)
# topic_labels(topic_model, n=8)
#Create a new project in the folder that has the JSTOR data.

install.packages("devtools")
install_github("agoldst/dfrtopics")
install.packages("dplyr")
install.packages("ggplot2")
install.packages("lubridate")
install.packages("stringr")
install.packages("rJava")
install.packages("mallet")



library(devtools)
options(java.parameters="-Xmx4g")
library(dfrtopics)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(rJava)
library(mallet)


data_dir <- file.path("/Users/[YOUR USERNAME HERE]/Desktop/slavic")

# First we load metadata: 

metadata_file <- file.path(data_dir, "citations.tsv")
meta <- read_dfr_metadata(metadata_file)
# 
# "The word counts can be loaded into memory all at once with read_wordcounts, 
# which takes a vector of file names."
counts <- read_wordcounts(list.files(file.path(data_dir, "wordcounts"), full.names=T))


# "Here’s how we might tabulate how many words stoplisting will remove from each document:"
stoplist_file <- file.path("stoplist-russian.txt")
stoplist <- readLines(stoplist_file)
counts <- counts %>% wordcounts_remove_stopwords(stoplist)




# "Filter infrequent words. OCR’d text in particular is littered with hapax legomena.
# The long tail of one-off features means a lot of noise for the modeling process, 
# and you’ll likely want to get rid of these.
# For example, to eliminate all but roughly the 20,000 most frequent features:"
counts <- counts %>%
  wordcounts_remove_rare(20000)
  
  
  
  
  
# "MALLET cannot accept our counts data frame from R as is. 
# Instead, it wants a data frame with one row per document, 
# which it will then tokenize once again. This is silly, but easily handled:"
docs <- wordcounts_texts(counts)



# "To create the MALLET-ready input, which is called an InstanceList, we use:"
ilist <- make_instances(docs)



#
# "Now we launch the LDA algorithm"
#
# we ran 20, 50, 100, and 150, and agreed on 100
topic_model <- train_model(ilist, n_topics=50,
                 n_iters=300,
                 seed=1,
                 threads=4,
                 metadata=meta
)
write_mallet_model(topic_model, "modeling_results")
summary(topic_model)
# create folder for topic browsing. note that folder name is 'browser-'+number of topics+formatted datetime
dfr_browser(topic_model, "slavic-review-browser", internalize=F)

# Type this in a terminal, not rStudio:
cd slavic-review-browser
bin/server


# to get a readout of the top N words by weight and first N topic labels, use these
# top_words(topic_model, n=10)
# topic_labels(topic_model, n=8)
#' Message for globals.
#'
#' Prompt the user to set globals if they have not already been
#' specified.
#'
#' @param globals The list of globals for a stain.
#'
#' @param is_submitting Is a slurm job being submitted? Default
#' value is FALSE to avoid any fatal errors.
stain_message_globals <- function(globals, is_submitting = FALSE) {
    na_globals <- globals[sapply(globals, is.na)]
    n_globals <- length(na_globals)

    if (n_globals > 0) {
        if (n_globals == 1) {
            plurality <- "global"
            demonstrative <- paste("this", plurality)
        } else {
            plurality <- "globals"
            demonstrative <- paste("these", plurality)
        }

        message(paste(length(na_globals), plurality, "to specify:"))

        for (global in names(na_globals)) {
            message(paste("\n    -", global), appendLF = FALSE)
        }

        message(paste("\n\nSet", demonstrative, "in the `globals` property of your `Stain` instance.\n"))

        if (is_submitting) {
            stop("Aborting submission.")
        }
    }
}


#' Message for source files.
#'
#' One of the source files must contain a \code{main} function and this
#' message will notify the user if none of his or her source files
#' contain a \code{main} function.
#'
#' @param source_files The list of R source files.
#'
#' @param is_submitting Is a slurm job being submitted? Default
#' value is FALSE to avoid any fatal errors.
stain_message_source_files <- function(source_files, is_submitting = FALSE) {
    file_count <- length(source_files)

    if (file_count > 0) {
        e <- new.env()

        for (file in source_files) {
            testthat::source_file(file, e)
        }

        if (is.null(e$main)) {
            if (file_count == 1) {
                plurality = paste("Your R source file doesn't")
            } else {
                plurality = paste("None of your", file_count, "R source files")
            }

            m <- paste(plurality, "contain a `main()` function.")

            if (is_submitting) {
                stop(paste(m, "Aborting submission."), call. = FALSE)
            } else {
                message(m)
            }
        }
    } else {
        message("A `Stain` object must contain at least one source file.")

        if (is_submitting) {
            stop(paste(m, "Aborting submission."), call. = FALSE)
        } else {
            message(m)
        }
    }
}


#' Message for ssh.
#'
#' Notify the user about remote host ssh requirements.
stain_message_ssh <- function() {
    packageStartupMessage("If your cluster is remote, add the .ssh/stain_rsa.pub key to your remote host. ")
    packageStartupMessage("To autogenerate the bash code, see ?stain_ssh_setup.")
}
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        get_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$get_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                stain_ssh(user, host, submit_cmd)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        get_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/"),
                                     full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$get_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                stain_ssh(user, host, submit_cmd)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        get_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/"),
                                     full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$get_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                stain_ssh(user, host, submit_cmd)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' Reciprocal function of base::log10
#' 
#' @param x numeric vector
#' @export
#' @keywords internal light
exp10 <- function(x) exp(x * log(10))

#' Convert Wildlife Computers light values from/to linear W/cm^2 units
#' 
#' Use the equation provided by the manufacturer, Wildlife Computers.
#' 
#' @param x raw sensor readings
#' @export
#' @keywords light
SI_light <- function(x) {
  10^((x - 250) / 20)
}

#' @rdname SI_light
#' @param x transformed sensor readings
#' @export
#' @keywords light
WC_light <- function(x) {
  20 * log10(x) + 250
}

#' BioPIC QR decomposition on a TDR sample
#' @param x A data subset of fixed width of 11 seconds/lines.
#' @param lightSI.nm The name of the TDR column with light values in W/cm^2.
#' @references 
#' Vacquié-Garcia, J., Royer, F., Dragon, A.-C., Viviant, M., Bailleul, F. 
#' & Guinet, C. (2012) Foraging in the Darkness of the Southern Ocean: 
#' Influence of Bioluminescence on a Deep Diving Predator. PLoS ONE, 7, e43565.
#' @keywords internal
#' @export
biopic.qr <- function(x, lightSI.nm = "light_si") {
  # A = QR. We use qr.solve() to find R given A and Q.
  Amat <- log10(x[ , lightSI.nm])
  # Build the Q matrix (w rows X length(R) columns)
  Qmat <- matrix(c(
    0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,  # log(It) = log(Ia)
    1, 0, 1,                                      # log(It) = log(alpha) + log(Ia)
    1, 1, 1, 1, 2, 1, 1, 3, 1, 1, 4, 1, 1, 5, 1), # log(It) = log(alpha) -K*t + log(Ia)
    nrow = 11, byrow = TRUE)
  Rmat <- try(qr.solve(Qmat, Amat), silent = TRUE)
  if (is.error(Rmat)) {
    Rmat <-rep(NA, 3)
  } else {
    Rmat[c(1, 3)] <- exp10(Rmat[c(1, 3)])
  }
  Rmat # alpha, lessK & Ia
}

#' BioPIC: bioluminescent event detection tool
#' 
#' Adaptation of BioPIC method with 1 Hz sampling frequency datasets and 
#' of post-peak attenuation (related to sensor and not depth)
#' 
#' @param x a TDR data sample
#' @param nms The names of the output variables.
#' @inheritParams biopic.qr
#' @export
#' @keywords light
#' @references 
#' Vacquié-Garcia, J., Royer, F., Dragon, A.-C., Viviant, M., Bailleul, F. 
#' & Guinet, C. (2012) Foraging in the Darkness of the Southern Ocean: 
#' Influence of Bioluminescence on a Deep Diving Predator. PLoS ONE, 7, e43565.
#' @examples 
#' data(exses)
#' dv <- tdrply(identity, no = 100, obj = exses)[[1]]
#' dv$light_si <- SI_light(dv$light)
#' biolum_tbl <- BioPIC(dv)
BioPIC <- function(x, lightSI.nm = "light_si", nms = c("alpha", "lessK", "Ia")) {
  x[ , nms] <-  NA
  nr <- nrow(x)
  for (ii in seq(6, nr - 5)) {
    x[ii, nms] <- biopic.qr(x[seq(ii - 5, ii + 5), ], lightSI.nm)
  }
  attr(x, "biopic") <- list("lightSI.nm" = lightSI.nm, "bioPIC.nms" = nms)
  x
}

#' Identify potential bioluminescence emission events
#' 
#' @param x a data.frame such as returned by \code{\link{BioPIC}} output
#' @param sensitivity A threshold to decide if a signal peak is high enought. See 
#' details.
#' @param max_light Max light level (W/cm^2) where a event can be detected. Set to 
#' NULL to disable.
#' @details Sensor sensitivity threshold: The minimum ratio between two measures 
#' to be considered significantly different. In laboratory experiments, the 
#' sensors measured light intensity +- 2 units while submitted to a constant 
#' light intensity. Translating the sensor log-scale units to SI linear scale 
#' units this accuracy measure translates into a minimum ratio of 1.26
#' @export
#' @keywords light
#' @examples 
#' \dontrun{
#' data(exses)
#' exses$tdr$light_si <- SI_light(exses$tdr$light)
#' biolum_tbl <- tdrply(BioPIC, obj = exses)
#' ble_tbl <- Reduce(rbind, lapply(biolum_tbl, biolum_events))
#' }
biolum_events <- function(x, sensitivity = 1.26, max_light = exp(-20)) {
  # Retrieve info
  alpha <- attr(x, "biopic")$bioPIC.nms[1]
  light <- attr(x, "biopic")$lightSI.nm[1]
  
  # Increasing light periods
  is_potble <- is.finite(x[ , alpha]) & x[ , alpha] > 1 # Alpha is valid and > 1
  potble <- per(is_potble)
  potble <- potble[potble$value %in% TRUE, ]
  
  # Compute peak light ratio
  potble$st_idx <- potble$st_idx
  potble$start_time  <- x[potble$st_idx, 1]
  potble$end_time    <- x[potble$ed_idx, 1]
  potble$start_light <- x[potble$st_idx, light]
  peakmax_idx <- mapply(function(st, ed) which.max(x[st:ed, light]), potble$st_idx, potble$ed_idx)
  peakmax_idx <- peakmax_idx + potble$st_idx - 1
  potble$peakmax_time  <- x[peakmax_idx, 1]
  potble$peakmax_light <- x[peakmax_idx, light]
  potble$peak_ratio <- potble$peakmax_light / potble$start_light
  
  # Filter
  cnd <- potble$peak_ratio >= sensitivity
  cnd <- "if"(is.null(max_light), cnd, cnd  & potble$peakmax_light <= max_light)
  potble[cnd, -(1:4)]
}
#SNOPSIS
#calculates genomic estimated breeding values (GEBVs) using rrBLUP,
#GBLUP method

#AUTHOR
# Isaak Y Tecle (iyt2@cornell.edu)

options(echo = FALSE)

library(rrBLUP)
library(plyr)
library(stringr)
library(lme4)
library(randomForest)
library(data.table)
#library(genetics)

allArgs <- commandArgs()

inputFiles  <- scan(grep("input_files", allArgs, ignore.case = TRUE, perl = TRUE, value = TRUE),
                   what = "character")

outputFiles <- scan(grep("output_files", allArgs, ignore.case = TRUE,perl = TRUE, value = TRUE),
                    what = "character")

traitsFile <- grep("traits", inputFiles, ignore.case = TRUE, value = TRUE)
traitFile  <- grep("trait_info", inputFiles, ignore.case = TRUE, value = TRUE)
traitInfo  <- scan(traitFile, what = "character",)
traitInfo  <- strsplit(traitInfo, "\t");
traitId    <- traitInfo[[1]]
trait      <- traitInfo[[2]]

datasetInfoFile <- grep("dataset_info", inputFiles, ignore.case = TRUE, value = TRUE)
datasetInfo     <- c()

if (length(datasetInfoFile) != 0 ) { 
    datasetInfo <- scan(datasetInfoFile, what = "character")    
    datasetInfo <- paste(datasetInfo, collapse = " ")   
  } else {   
    datasetInfo <- c('single population')  
  }

validationTrait <- paste("validation", trait, sep = "_")
validationFile  <- grep(validationTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(validationFile)) {
  stop("Validation output file is missing.")
}

kinshipTrait <- paste("kinship", trait, sep = "_")
blupFile     <- grep(kinshipTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(blupFile)) {
  stop("GEBVs file is missing.")
}
markerTrait <- paste("marker", trait, sep = "_")
markerFile  <- grep(markerTrait, outputFiles, ignore.case = TRUE, value = TRUE)

traitPhenoFile <- paste("phenotype_trait", trait, sep = "_")
traitPhenoFile <- grep(traitPhenoFile, outputFiles,ignore.case = TRUE, value = TRUE)

varianceComponentsFile <- grep("variance_components", outputFiles, ignore.case = TRUE, value = TRUE)

formattedPhenoFile <- grep("formatted_phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE)

formattedPhenoData <- c()
phenoData          <- c()

genoFile <- grep("genotype_data", inputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(genoFile)) {
  stop("genotype data file is missing.")
}

if (file.info(genoFile)$size == 0) {
  stop("genotype data file is empty.")
}

genoData <- fread(genoFile, na.strings = c("NA", " ", "--", "-"),  header = TRUE)

if (length(formattedPhenoFile) != 0 && file.info(formattedPhenoFile)$size != 0) {
  formattedPhenoData <- as.data.frame(fread(formattedPhenoFile,
                                            na.strings = c("NA", " ", "--", "-", ".")
                                            ))
      
  row.names(formattedPhenoData) <- formattedPhenoData[, 1]
  formattedPhenoData[, 1]       <- NULL    
} else {
  phenoFile <- grep("\\/phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE, perl = TRUE)

  if (is.null(phenoFile)) {
    stop("phenotype data file is missing.")
  }

  if (file.info(phenoFile)$size == 0) {
    stop("phenotype data file is empty.")
  }
  
  phenoData <- fread(phenoFile, na.strings = c("NA", " ", "--", "-", "."), header = TRUE) 
}

phenoData  <- as.data.frame(phenoData)
phenoTrait <- c()

if (datasetInfo == 'combined populations') {
  
   if (!is.null(formattedPhenoData)) {
      phenoTrait <- subset(formattedPhenoData, select = trait)
      phenoTrait <- na.omit(phenoTrait)
   
    } else {
      dropColumns <- grep(trait, names(phenoData), ignore.case = TRUE, value = TRUE)
      phenoTrait  <- phenoData[, !(names(phenoData) %in% dropColumns)]
   
      phenoTrait            <- as.data.frame(phenoTrait)
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1]       <- NULL
      colnames(phenoTrait)  <- trait
    }
   
} else {

  if (!is.null(formattedPhenoData)) {
    phenoTrait <- subset(formattedPhenoData, select = trait)
    phenoTrait <- na.omit(phenoTrait)
   
  } else {
    dropColumns <- c("uniquename", "stock_name")
    phenoData   <- phenoData[, !(names(phenoData) %in% dropColumns)]
    
    phenoTrait <- subset(phenoData, select = c("object_name", "object_id", "design", "block", "replicate", trait))
   
    experimentalDesign <- phenoTrait[2, 'design']
  
    if (class(phenoTrait[, trait]) != 'numeric') {
      phenoTrait[, trait] <- as.numeric(as.character(phenoTrait[, trait]))
    }
      
    if (is.na(experimentalDesign) == TRUE) {experimentalDesign <- c('No Design')}
    
    if ((experimentalDesign == 'Augmented' || experimentalDesign == 'RCBD')  &&  unique(phenoTrait$block) > 1) {

      message("GS experimental design: ", experimentalDesign)

      augData <- subset(phenoTrait, select = c("object_name", "object_id",  "block",  trait))

      colnames(augData)[1] <- "genotypes"
      colnames(augData)[4] <- "trait"

      model <- try(lmer(trait ~ 0 + genotypes + (1|block),
                        augData,
                        na.action = na.omit))

      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
        
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))  
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
      }
            
    } else if (experimentalDesign == 'Alpha') {
   
      message("Experimental desgin: ", experimentalDesign)
      
      alphaData <- subset(phenoData,
                            select = c("object_name", "object_id","block", "replicate", trait)
                            )
      
      colnames(alphaData)[1] <- "genotypes"
      colnames(alphaData)[5] <- "trait"
         
      model <- try(lmer(trait ~ 0 + genotypes + (1|replicate/block),
                        alphaData,
                        na.action = na.omit))
        
      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
      
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))     
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
        
      }
      
    } else {

      phenoTrait <- subset(phenoData,
                           select = c("object_name", "object_id",  trait))
       
      if (sum(is.na(phenoTrait)) > 0) {
        message("No. of pheno missing values: ", sum(is.na(phenoTrait)))      
        phenoTrait <- na.omit(phenoTrait)
      }

        #calculate mean of reps/plots of the same accession and
        #create new df with the accession means    
     
      phenoTrait   <- phenoTrait[order(row.names(phenoTrait)), ]
      phenoTrait   <- data.frame(phenoTrait)
      message('phenotyped lines before averaging: ', length(row.names(phenoTrait)))
   
      phenoTrait<-ddply(phenoTrait, "object_name", colwise(mean))
      message('phenotyped lines after averaging: ', length(row.names(phenoTrait)))
        
      phenoTrait <- subset(phenoTrait, select = c("object_name", trait))
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1] <- NULL
       
        #format all-traits population phenotype dataset
        ## formattedPhenoData <- phenoData
        ## dropColumns <- c("object_id", "stock_id", "design", "block", "replicate" )

        ## formattedPhenoData <- formattedPhenoData[, !(names(formattedPhenoData) %in% dropColumns)]
        ## formattedPhenoData <- ddply(formattedPhenoData,
        ##                             "object_name",
        ##                             colwise(mean)
        ##                             )

        ## row.names(formattedPhenoData) <- formattedPhenoData[, 1]
        ## formattedPhenoData[, 1] <- NULL

        ## formattedPhenoData <- round(formattedPhenoData,
        ##                             digits=3
        ##                             )     
    }
  }
}

#remove monomorphic markers
message('marker no before monomorphic markers cleaning ', ncol(genoData))
genoData[, which(apply(genoData, 2,  function(x) length(unique(x))) < 2) := NULL ]
message('marker no after monomorphic markers cleaning ', ncol(genoData))

#remove markers with > 60% missing marker data
message('no of markers before filtering out: ', ncol(genoData))
genoData[, which(colSums(is.na(genoData)) >= nrow(genoData) * 0.6) := NULL]
message('no of markers after filtering out 60% missing: ', ncol(genoData))

#remove indls with > 80% missing marker data
genoData[, noMissing := apply(.SD, 1, function(x) sum(is.na(x)))]
genoData <- genoData[noMissing <= ncol(genoData) * 0.8]
genoData[, noMissing := NULL]
message('no of indls after filtering out ones with 80% missing: ', nrow(genoData))

### MAF calculation ###
calculateMAF <- function(x) {
  a0 <-  length(x[x==0])
  a1 <-  length(x[x==1])
  a2 <-  length(x[x==2])
  aT <- a0 + a1 + a2

  message('a0: ', a0, ' a1: ', a1, ' a2:', a2, ' aT: ', aT)
  p   <- ((2*a0)+a1)/(2*aT)
  q   <- 1- p
  maf <- min(p, q)
  
  return (maf)

}


#remove markers with MAF < 5%
genoData[, which(apply(genoData, 2,  calculateMAF) < 0.05) := NULL ]
message('marker no after MAF cleaning ', ncol(genoData))

genoData           <- as.data.frame(genoData)
rownames(genoData) <- genoData[, 1]
genoData[, 1]      <- NULL

predictionTempFile <- grep("prediction_population", inputFiles, ignore.case = TRUE, value = TRUE)
predictionFile     <- c()

message('prediction temp genotype file: ', predictionTempFile)

if (length(predictionTempFile) !=0 ) {
  predictionFile <- scan(predictionTempFile, what = "character")
}

message('prediction genotype file: ', predictionFile)

predictionPopGEBVsFile <- grep("prediction_pop_gebvs", outputFiles, ignore.case = TRUE, value = TRUE)
message("prediction gebv file: ",  predictionPopGEBVsFile)

predictionData <- c()

if (length(predictionFile) !=0 ) {
  
  predictionData <- fread(predictionFile, na.strings = c("NA", " ", "--", "-"),)

  predictionData[, which(apply(predictionData, 2,  function(x) length(unique(x))) < 2) := NULL ]
  
  message('selection population: no of markers before filtering out: ', ncol(genoData))
  predictionData[, which(colSums(is.na(predictionData)) >= nrow(predictionData) * 0.6) := NULL]

  #remove indls with > 80% missing marker data
  predictionData[, noMissing := apply(.SD, 1, function(x) sum(is.na(x)))]
  predictionData <- predictionData[noMissing <= ncol(predictionData) * 0.8]
  predictionData[, noMissing := NULL]
  
  predictionData[, which(apply(predictionData, 2,  calculateMAF) < 0.05) := NULL ]
  message('selection pop marker no after MAF cleaning ', ncol(preditionData))
  predictionData           <- as.data.frame(predictionData)
  rownames(predictionData) <- predictionData[, 1]
  predictionData[, 1]      <- NULL
 
}

#impute genotype values for obs with missing values,
#based on mean of neighbouring 10 (arbitrary) obs
genoDataMissing <- c()

if (sum(is.na(genoData)) > 0) {
  genoDataMissing<- c('yes')

  message("sum of geno missing values, ", sum(is.na(genoData)) )  
  genoData <- na.roughfix(genoData)
  genoData <- data.matrix(genoData)
}

genoData <- genoData[order(row.names(genoData)), ]

#create phenotype and genotype datasets with
#common stocks only
message('phenotyped lines: ', length(row.names(phenoTrait)))
message('genotyped lines: ', length(row.names(genoData)))

#extract observation lines with both
#phenotype and genotype data only.
commonObs <- intersect(row.names(phenoTrait), row.names(genoData))
commonObs <- data.frame(commonObs)
rownames(commonObs)<-commonObs[, 1]

message('lines with both genotype and phenotype data: ', length(row.names(commonObs)))

#include in the genotype dataset only observation lines
#with phenotype data
message("genotype lines before filtering for phenotyped only: ", length(row.names(genoData)))        
genoDataFiltered <- genoData[(rownames(genoData) %in% rownames(commonObs)), ]
message("genotype lines after filtering for phenotyped only: ", length(row.names(genoDataFiltered)))

#drop observation lines without genotype data
message("phenotype lines before filtering for genotyped only: ", length(row.names(phenoTrait)))        
phenoTrait <- merge(data.frame(phenoTrait), commonObs, by=0, all=FALSE)
rownames(phenoTrait) <- phenoTrait[, 1]
phenoTrait <- subset(phenoTrait, select=trait)

message("phenotype lines after filtering for genotyped only: ", length(row.names(phenoTrait)))
#a set of only observation lines with genotype data

traitPhenoData   <- data.frame(round(phenoTrait, digits = 2))           
phenoTrait       <- data.matrix(phenoTrait)
genoDataFiltered <- data.matrix(genoDataFiltered)

#impute missing data in prediction data
predictionDataMissing <- c()
if (length(predictionData) != 0) {
  #purge markers unique to both populations
  commonMarkers    <- intersect(names(data.frame(genoDataFiltered)), names(predictionData))
  predictionData   <- subset(predictionData, select = commonMarkers)
  genoDataFiltered <- subset(genoDataFiltered, select= commonMarkers)
  
 # predictionData <- data.matrix(predictionData)
 
  if (sum(is.na(predictionData)) > 0) {
    predictionDataMissing <- c('yes')
    message("sum of geno missing values, ", sum(is.na(predictionData)) )  
    predictionData <- data.matrix(na.roughfix(predictionData))
    
  }
}

relationshipMatrixFile <- grep("relationship_matrix", outputFiles, ignore.case = TRUE, value = TRUE)

message("relationship matrix file: ", relationshipMatrixFile)

relationshipMatrix <- c()
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size > 0 ) {
    relationshipDf <- as.data.frame(fread(relationshipMatrixFile))

    rownames(relationshipDf) <- relationshipDf[, 1]
    relationshipDf[, 1]      <- NULL
    relationshipMatrix       <- data.matrix(relationshipDf)
  }
}


#change genotype coding to [-1, 0, 1], to use the A.mat ) if  [0, 1, 2]
genoTrCode <- grep("2", genoDataFiltered[1, ], value = TRUE)
if(length(genoTrCode) != 0) {
  genoDataFiltered <- genoDataFiltered - 1
}

if (length(predictionData) != 0 ) {
  genoSlCode <- grep("2", predictionData[1, ], value = TRUE)
  if (length(genoSlCode) != 0 ) {
    predictionData <- predictionData - 1
  }
}

ordered.markerEffects <- c()
if ( length(predictionData) == 0 ) {
  markerEffects <- mixed.solve(y = phenoTrait,
                               Z = genoDataFiltered
                               )

  ordered.markerEffects <- data.matrix(markerEffects$u)
  ordered.markerEffects <- data.matrix(ordered.markerEffects [order (-ordered.markerEffects[, 1]), ])
  ordered.markerEffects <- round(ordered.markerEffects, digits=5)

  colnames(ordered.markerEffects) <- c("Marker Effects")

}

#additive relationship model
#calculate the inner products for
#genotypes (realized relationship matrix)
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size == 0) {
    relationshipMatrix <- tcrossprod(data.matrix(genoData))
  }
}
relationshipMatrixFiltered <- relationshipMatrix[(rownames(relationshipMatrix) %in% rownames(commonObs)),]
relationshipMatrixFiltered <- relationshipMatrixFiltered[, (colnames(relationshipMatrixFiltered) %in% rownames(commonObs))]

#construct an identity matrix for genotypes
identityMatrix <- diag(nrow(phenoTrait))

relationshipMatrixFiltered <- data.matrix(relationshipMatrixFiltered)

iGEBV  <- mixed.solve(y = phenoTrait, Z = identityMatrix, K = relationshipMatrixFiltered) 
iGEBVu <- iGEBV$u

heritability  <- c()

if ( is.null(predictionFile) == TRUE ) {
  additiveEffects <- data.frame(iGEBVu)
 
  pN <- nrow(phenoTrait)
  aN <- nrow(additiveEffects)

  if (pN <= 1 || pN != aN) {
    stop("phenoTrait and additiveEffects have different lengths: ",
         pN, " and ", aN, ".")
  }
      
  if (TRUE %in% is.na(phenoTrait) || TRUE %in% is.na(additiveEffects)) {
    stop(" Arguments phenoTrait and additiveEffects have missing values.")
  }
  
  phenoVariance <- var(phenoTrait)
  gebvVariance  <- var(additiveEffects)
  heritability  <- round((gebvVariance / phenoVariance), digits = 2)
      
  cat("\n", file = varianceComponentsFile,  append = FALSE)
  cat('Error variance', iGEBV$Ve, file = varianceComponentsFile, sep = "\t", append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Additive genetic variance',  iGEBV$Vu, file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Phenotype mean', iGEBV$beta,file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Heritability (h)', heritability, file = varianceComponentsFile, sep = '\t', append = TRUE)
}

iGEBV         <- data.matrix(iGEBVu)
ordered.iGEBV <- as.data.frame(iGEBV[order(-iGEBV[, 1]), ])
ordered.iGEBV <- round(ordered.iGEBV, digits = 3)

combinedGebvsFile <- grep('selected_traits_gebv', outputFiles, ignore.case = TRUE,value = TRUE)

allGebvs<-c()
if (length(combinedGebvsFile) != 0) {
    fileSize <- file.info(combinedGebvsFile)$size
    if (fileSize != 0 ) {
        combinedGebvs <- as.data.frame(fread(combinedGebvsFile))

        rownames(combinedGebvs) <- combinedGebvs[,1]
        combinedGebvs[,1]       <- NULL

        colnames(ordered.iGEBV) <- c(trait)
      
        traitGEBV <- as.data.frame(ordered.iGEBV)
        allGebvs <- merge(combinedGebvs, traitGEBV,
                          by = 0,
                          all = TRUE                     
                          )

        rownames(allGebvs) <- allGebvs[,1]
        allGebvs[,1] <- NULL
     }
  }

colnames(ordered.iGEBV) <- c(trait)
                  
#cross-validation
validationAll <- c()

if(is.null(predictionFile)) {
  genoNum <- nrow(phenoTrait)
if(genoNum < 20 ) {
  warning(genoNum, " is too small number of genotypes.")
}
  
reps <- round_any(genoNum, 10, f = ceiling) %/% 10

genotypeGroups <-c()

if (genoNum %% 10 == 0) {
    genotypeGroups <- rep(1:10, reps)
  } else {
    genotypeGroups <- rep(1:10, reps) [- (genoNum %% 10) ]
  }

set.seed(4567)                                   
genotypeGroups <- genotypeGroups[ order (runif(genoNum)) ]

for (i in 1:10) {
  tr <- paste("trPop", i, sep = ".")
  sl <- paste("slPop", i, sep = ".")
 
  trG <- which(genotypeGroups != i)
  slG <- which(genotypeGroups == i)
  
  assign(tr, trG)
  assign(sl, slG)

  kblup <- paste("rKblup", i, sep = ".")
  
  result <- kinship.BLUP(y = phenoTrait[trG, ],
                         G.train = genoDataFiltered[trG, ],
                         G.pred = genoDataFiltered[slG, ],                      
                         mixed.method = "REML",
                         K.method = "RR",
                         )
 
  assign(kblup, result)

#calculate cross-validation accuracy  
  valCorData <- merge(phenoTrait[slG, ], result$g.pred, by=0, all=FALSE)
  rownames(valCorData) <- valCorData[, 1]
  valCorData[, 1]      <- NULL
 
  accuracy <- try(cor(valCorData))
  validation <- paste("validation", i, sep = ".")

  cvTest <- paste("Validation test", i, sep = " ")

  if ( class(accuracy) != "try-error")
    {
      accuracy <- round(accuracy[1,2], digits = 3)
      accuracy <- data.matrix(accuracy)
    
      colnames(accuracy) <- c("correlation")
      rownames(accuracy) <- cvTest

      assign(validation, accuracy)
      
      if (!is.na(accuracy[1,1])) {
        validationAll <- rbind(validationAll, accuracy)
      }    
    }
}

validationAll <- data.matrix(validationAll[order(-validationAll[, 1]), ])
     
if (!is.null(validationAll)) {
    validationMean <- data.matrix(round(colMeans(validationAll), digits = 2))
   
    rownames(validationMean) <- c("Average")
     
    validationAll <- rbind(validationAll, validationMean)
    colnames(validationAll) <- c("Correlation")
  }
}

predictionPopResult <- c()
predictionPopGEBVs  <- c()

if (length(predictionData) != 0) {
    message("running prediction for selection candidates...marker data", ncol(predictionData), " vs. ", ncol(genoDataFiltered))

    predictionPopResult <- kinship.BLUP(y = phenoTrait,
                                        G.train = genoDataFiltered,
                                        G.pred = predictionData,
                                        mixed.method = "REML",
                                        K.method = "RR"
                                        )
 message("running prediction for selection candidates...DONE!!")

    predictionPopGEBVs <- round(data.matrix(predictionPopResult$g.pred), digits = 3)
    predictionPopGEBVs <- data.matrix(predictionPopGEBVs[order(-predictionPopGEBVs[, 1]), ])
   
    colnames(predictionPopGEBVs) <- c(trait)
  
}

if (!is.null(predictionPopGEBVs) & length(predictionPopGEBVsFile) != 0)  {
    write.table(predictionPopGEBVs,
                file = predictionPopGEBVsFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if(!is.null(validationAll)) {
    write.table(validationAll,
                file = validationFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.markerEffects)) {
    write.table(ordered.markerEffects,
                file = markerFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.iGEBV)) {
    write.table(ordered.iGEBV,
                file = blupFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (length(combinedGebvsFile) != 0 ) {
    if(file.info(combinedGebvsFile)$size == 0) {
        write.table(ordered.iGEBV,
                    file = combinedGebvsFile,
                    sep = "\t",
                    col.names = NA,
                    quote = FALSE,
                    )
      } else {
      write.table(allGebvs,
                  file = combinedGebvsFile,
                  sep = "\t",
                  quote = FALSE,
                  col.names = NA,
                  )
    }
}

if (!is.null(traitPhenoData) & length(traitPhenoFile) != 0) {
    write.table(traitPhenoData,
                file = traitPhenoFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                )
}



## if (!is.null(genoDataMissing)) {
##   write.table(genoData,
##               file = genoFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##             )

## }

## if (!is.null(predictionDataMissing)) {
##   write.table(predictionData,
##               file = predictionFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##               )
## }


if (file.info(relationshipMatrixFile)$size == 0) {
  write.table(relationshipMatrix,
              file = relationshipMatrixFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}


if (file.info(formattedPhenoFile)$size == 0 && !is.null(formattedPhenoData) ) {
  write.table(formattedPhenoData,
              file = formattedPhenoFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}

message("Done.")

q(save = "no", runLast = FALSE)
###########################################
# get_cfsv2_ncdc.r
# pulls cfsv2 forecasts from NCDC archive
# subsets to gbm and africa domains
# pulls out precip. surface temp, winds, and latent
# heat flux
###########################################

start_time = Sys.time()

## load libraries
library(stringr)
library(dplyr)
library(data.table)
library(lubridate)

date2str = function(dte){
	#dte - POSIXct date 
	year_str = year(dte)
	month_str = str_pad(month(dte), 2, pad = '0')
	day_str = str_pad(day(dte), 2, pad = '0')
	hour_str = str_pad(hour(dte), 2, pad = '0')

	paste0(year_str, month_str, day_str, hour_str)
}

## user inputs
dir_scratch = ''
dir_gbm = ''
dir_africa = ''

lims_lon_gbm = c(73, 98)
lims_lat_gbm = c(22, 32)
lims_lon_africa = c(-20, 55)
lims_lat_africa = c(-40, 40)

fcst_lead_sel = 1440
time_sel_start = as.POSIXct('2011-04-01', tz = 'utc')
time_sel_end = as.POSIXct('2011-12-31 18:00', tz = 'utc')

ncores_sel = 6

## setup
setwd(dir_scratch)

time_init_list = seq(from = time_sel_start, to = time_sel_end, by = '6 hour')
fcst_lead_list = seq(from = 6, to = fcst_lead_sel, by = 6)
nfcstlead = length(fcst_lead_list)
time_dt = data.table(time_init = rep(time_init_list, each = nfcstlead), fcst_lead = fcst_lead_list) %>% mutate(time_fcst = time_init + hours(fcst_lead))
ntimes = nrow(time_dt)

tempvar_list = rep(letters, ceiling(ntimes / 26))

## download function
get_cfs_grb = function(time_init_sel, time_fcst_sel, tempvar){
	require(data.table)
	require(dplyr)
	require(lubridate)
	require(stringr)
	require(tidyr)
	
	urlhead = 'http://nomads.ncdc.noaa.gov/modeldata/cfsv2_forecast_6-hourly_9mon_flxf/'
	
	yearinit = year(time_init_sel)
	monthinit = str_pad(month(time_init_sel), 2, pad = "0")
	dayinit = str_pad(day(time_init_sel), 2, pad = "0")
	hourinit = str_pad(hour(time_init_sel), 2, pad = "0")

	initdatefilestr = paste0(yearinit, monthinit, dayinit)
	initdatestr = paste0(yearinit, monthinit, dayinit, hourinit)
	inityrmon = paste0(yearinit, monthinit)
	
	yearfcst = year(time_fcst_sel)
	monthfcst = str_pad(month(time_fcst_sel), 2, pad = "0")
	dayfcst = str_pad(day(time_fcst_sel), 2, pad = "0")
	hourfcst = str_pad(hour(time_fcst_sel), 2, pad = "0")
	
	fcstdatestr = paste0(yearfcst, monthfcst, dayfcst, hourfcst)

	url = paste0(urlhead, yearinit, '/', inityrmon, '/', initdatefilestr, '/', initdatestr, '/flxf', fcstdatestr, '.01.', initdatestr, '.grb2')
	
	destfile_gbm = paste0(dir_gbm, initdatestr, '.', '01', '.', fcstdatestr, '.grb2') 
	destfile_africa = paste0(dir_africa, initdatestr, '.', '01', '.', fcstdatestr, '.grb2') 
	
	#downloads and subsets (if needed)
	if(file.exists(destfile_gbm) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		
		system(paste0("wgrib2 ", "temp_", tempvar, ".grb2", " -g2clib 0 -match ':(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):' -small_grib ", paste(lims_lon_gbm, collapse = ':'), " ", paste(lims_lat_gbm, collapse = ':'), " ", destfile_gbm), ignore.stdout = T, ignore.stderr = T)
		
		if(file.exists(destfile_africa) == F){
			system(paste0("wgrib2 ", "temp_", tempvar, ".grb2", " -g2clib 0 -match ':(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):' -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
		}
	}
	if(file.exists(destfile_africa) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		system(paste0("wgrib2 ", "temp_", tempvar, ".grb2", " -g2clib 0 -match ':(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):' -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
	}
}

## call function
cl = makeCluster(ncores_sel)
registerDoParallel(cl)
foreach (i = 1:ntimes) %dopar% {
	time_init_sel = time_dt$time_init[i]
	time_fcst_sel = time_dt$time_fcst[i]
	tempvar_sel = tempvar_list[i]
	try(get_cfs_grb(time_init_sel, time_fcst_sel, tempvar_sel))
}
stopCluster(cl)
Sys.time() - start_time
###########################################
# get_cfsv2_ts_ncdc.r
# pulls cfsv2 forecasts from NCDC timeseries archive
# subsets to gbm and africa domains
# pulls out specified forecast variables
###########################################

start_time()
## load libraries 
library(data.table)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(tidyr)
library(doParallel)
library(foreach)

## user inputs
dir_scratch = ''
dir_gbm = ''
dir_africa = ''

lims_lon_gbm = c(73, 98)
lims_lat_gbm = c(22, 32)
lims_lon_africa = c(-20, 55)
lims_lat_africa = c(-40, 40)

fcst_lead_sel = 1440
time_sel_start = as.POSIXct('2011-04-01', tz = 'utc')
time_sel_end = as.POSIXct('2016-09-15 18:00', tz = 'utc')

var_sel = 'prate'

ncores_sel = 6

## setup
setwd(dir_scratch)

time_list = seq(from = time_sel_start, to = time_sel_end, by = '6 hour')
ntimes = length(time_list)

tempvar_list = rep(letters, ceiling(ntimes / 26))

## download function
get_cfs_ts_grb = function(var, time_init_sel, fcst_lead = 1440, tempvar){
	require(data.table)
	require(dplyr)
	require(lubridate)
	require(stringr)
	require(tidyr)
	
	urlhead = 'http://nomads.ncdc.noaa.gov/modeldata/cfsv2_forecast_ts_9mon/'
	
	yearinit = year(time_init_sel)
	monthinit = str_pad(month(time_init_sel), 2, pad = "0")
	dayinit = str_pad(day(time_init_sel), 2, pad = "0")
	hourinit = str_pad(hour(time_init_sel), 2, pad = "0")

	initdatefilestr = paste0(yearinit, monthinit, dayinit)
	initdatestr = paste0(yearinit, monthinit, dayinit, hourinit)
	inityrmon = paste0(yearinit, monthinit)
	
	yearfcst = year(time_fcst_sel)
	monthfcst = str_pad(month(time_fcst_sel), 2, pad = "0")
	dayfcst = str_pad(day(time_fcst_sel), 2, pad = "0")
	hourfcst = str_pad(hour(time_fcst_sel), 2, pad = "0")
	
	fcstdatestr = paste0(yearfcst, monthfcst, dayfcst, hourfcst)

	fcst_lead_list = seq(from = 6, to = fcst_lead, by = 6)
	fcst_match_list = paste(paste0(':', fcst_lead_list, ' hour fcst:'), collapse = '|')
	
	url = paste0(urlhead, yearinit, '/', inityrmon, '/', initdatefilestr, '/', initdatestr, '/', var, '.', '01', '.', initdatestr, '.daily.grb2') 
	
	destfile_gbm = paste0(dir_gbm, var, '.', initdatestr, '.', '01', '.grb2') 
	destfile_africa = paste0(dir_africa, var, '.', initdatestr, '.', '01', '.grb2') 
	
	#checks forecast lead against selected and removes file if too small
	if(file.exists(destfile_gbm) == T){
		file_meta = data.table(raw = system(paste('wgrib2', destfile_gbm, '-ftime'), intern = T)) %>% separate(raw, sep = c(':'), into = c('id', 'ref', 'hour')) %>% separate(hour, sep = ' ', into = c('hour', 'lab1', 'lab2'))
		file_max_hour = max(as.numeric(file_meta$hour))
		if(file_max_hour < fcst_lead){
			system(paste("rm", destfile_gbm))
		}
	}
	if(file.exists(destfile_africa) == T){
		file_meta = data.table(raw = system(paste('wgrib2', destfile_africa, '-ftime'), intern = T)) %>% separate(raw, sep = c(':'), into = c('id', 'ref', 'hour')) %>% separate(hour, sep = ' ', into = c('hour', 'lab1', 'lab2'))
		file_max_hour = max(as.numeric(file_meta$hour))
		if(file_max_hour < fcst_lead){
			system(paste("rm", destfile_africa))
		}
	}

	#downloads and subsets (if needed)
	if(file.exists(destfile_gbm) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match '", fcst_match_list, "' -g2clib 0 -small_grib ", paste(lims_lon_gbm, collapse = ':'), " ", paste(lims_lat_gbm, collapse = ':'), " ", destfile_gbm), ignore.stdout = T, ignore.stderr = T)
		if(file.exists(destfile_africa) == F){
			system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match '", fcst_match_list, "' -g2clib 0 -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
		}
	}
	if(file.exists(destfile_africa) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match '", fcst_match_list, "' -g2clib 0 -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
	}
}

## call function 
cl = makeCluster(ncores_sel)
registerDoParallel(cl)
foreach (i = 1:ntimes) %dopar% {
	time_init_sel = time_list[i]
	tempvar_sel = tempvar_list[i]
	try(get_cfs_ts_grb(var_sel, time_init_sel, fcst_lead_sel, tempvar_sel))
}
stopCluster(cl)
Sys.time() - start_time
###########################################
# get_cfsv2_ncdc.r
# pulls cfsv2 forecasts from NCDC archive
# subsets to gbm and africa domains
# pulls out precip. surface temp, winds, and latent
# heat flux
###########################################

start_time = Sys.time()

## load libraries
library(stringr)
library(dplyr)
library(data.table)
library(lubridate)

date2str = function(dte){
	#dte - POSIXct date 
	year_str = year(dte)
	month_str = str_pad(month(dte), 2, pad = '0')
	day_str = str_pad(day(dte), 2, pad = '0')
	hour_str = str_pad(hour(dte), 2, pad = '0')

	paste0(year_str, month_str, day_str, hour_str)
}

## user inputs
dir_scratch = ''
dir_gbm = ''
dir_africa = ''

lims_lon_gbm = c(73, 98)
lims_lat_gbm = c(22, 32)
lims_lon_africa = c(-20, 55)
lims_lat_africa = c(-40, 40)

fcst_lead_sel = 1440
time_sel_start = as.POSIXct('2011-04-01', tz = 'utc')
time_sel_end = as.POSIXct('2011-12-31 18:00', tz = 'utc')

ncores_sel = 6

## setup
setwd(dir_scratch)

time_init_list = seq(from = time_sel_start, to = time_sel_end, by = '6 hour')
fcst_lead_list = seq(from = 6, to = fcst_lead_sel, by = 6)
nfcstlead = length(fcst_lead_list)
time_dt = data.table(time_init = rep(time_init_list, each = nfcstlead), fcst_lead = fcst_lead_list) %>% mutate(time_fcst = time_init + hours(fcst_lead))
ntimes = nrow(time_dt)

tempvar_list = rep(letters, ceiling(ntimes / 26))

## download function
get_cfs_grb = function(time_init_sel, time_fcst_sel, tempvar){
	require(data.table)
	require(dplyr)
	require(lubridate)
	require(stringr)
	require(tidyr)
	
	urlhead = 'http://nomads.ncdc.noaa.gov/modeldata/cfsv2_forecast_6-hourly_9mon_flxf/'
	
	yearinit = year(time_init_sel)
	monthinit = str_pad(month(time_init_sel), 2, pad = "0")
	dayinit = str_pad(day(time_init_sel), 2, pad = "0")
	hourinit = str_pad(hour(time_init_sel), 2, pad = "0")

	initdatefilestr = paste0(yearinit, monthinit, dayinit)
	initdatestr = paste0(yearinit, monthinit, dayinit, hourinit)
	inityrmon = paste0(yearinit, monthinit)
	
	yearfcst = year(time_fcst_sel)
	monthfcst = str_pad(month(time_fcst_sel), 2, pad = "0")
	dayfcst = str_pad(day(time_fcst_sel), 2, pad = "0")
	hourfcst = str_pad(hour(time_fcst_sel), 2, pad = "0")
	
	fcstdatestr = paste0(yearfcst, monthfcst, dayfcst, hourfcst)

	url = paste0(urlhead, yearinit, '/', inityrmon, '/', initdatefilestr, '/', initdatestr, '/flxf', fcstdatestr, '.01.', initdatestr, '.grb2')
	
	destfile_gbm = paste0(dir_gbm, fcstdatestr, '_', '01', '_', initdatestr ,'.grb2') 
	destfile_africa = paste0(dir_africa, fcstdatestr, '_', '01', '_', initdatestr ,'.grb2') 
	
	#downloads and subsets (if needed)
	if(file.exists(destfile_gbm) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		
		system(paste0("wgrib2 ", "temp_", tempvar, ".grb2", " -g2clib 0 -match ':(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):' -small_grib ", paste(lims_lon_gbm, collapse = ':'), " ", paste(lims_lat_gbm, collapse = ':'), " ", destfile_gbm), ignore.stdout = T, ignore.stderr = T)
		
		if(file.exists(destfile_africa) == F){
			system(paste0("wgrib2 ", "temp_", tempvar, ".grb2", " -g2clib 0 -match ':(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):' -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
		}
	}
	if(file.exists(destfile_africa) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		system(paste0("wgrib2 ", "temp_", tempvar, ".grb2", " -g2clib 0 -match ':(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):' -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
	}
}

## call function
cl = makeCluster(ncores_sel)
registerDoParallel(cl)
foreach (i = 1:ntimes) %dopar% {
	time_init_sel = time_dt$time_init[i]
	time_fcst_sel = time_dt$time_fcst[i]
	tempvar_sel = tempvar_list[i]
	try(get_cfs_grb(time_init_sel, time_fcst_sel, tempvar_sel))
}
stopCluster(cl)
Sys.time() - start_time
#' Message for globals.
#'
#' Prompt the user to set globals if they have not already been
#' specified.
#'
#' @param globals The list of globals for a stain.
#'
#' @param is_submitting Is a slurm job being submitted? Default
#' value is FALSE to avoid any fatal errors.
stain_message_globals <- function(globals, is_submitting = FALSE) {
    na_globals <- globals[sapply(globals, is.na)]
    n_globals <- length(na_globals)

    if (n_globals > 0) {
        if (n_globals == 1) {
            plurality <- "global"
            demonstrative <- paste("this", plurality)
        } else {
            plurality <- "globals"
            demonstrative <- paste("these", plurality)
        }

        message(paste(length(na_globals), plurality, "to specify:"))

        for (global in names(na_globals)) {
            message(paste("\n    -", global), appendLF = FALSE)
        }

        message(paste("\n\nSet", demonstrative, "in the `globals` property of your `Stain` instance.\n"))

        if (is_submitting) {
            stop("Aborting submission.")
        }
    }
}


#' Message for source files.
#'
#' One of the source files must contain a \code{main} function and this
#' message will notify the user if none of his or her source files
#' contain a \code{main} function.
#'
#' @param source_files The list of R source files.
#'
#' @param is_submitting Is a slurm job being submitted? Default
#' value is FALSE to avoid any fatal errors.
stain_message_source_files <- function(source_files, is_submitting = FALSE) {
    file_count <- length(source_files)

    if (file_count > 0) {
        e <- new.env()

        for (file in source_files) {
            testthat::source_file(file, e)
        }

        if (is.null(e$main)) {
            if (file_count == 1) {
                plurality = paste("Your R source file doesn't")
            } else {
                plurality = paste("None of your", file_count, "R source files")
            }

            m <- paste(plurality, "contain a `main()` function.")

            if (is_submitting) {
                stop(paste(m, "Aborting submission."), call. = FALSE)
            } else {
                message(m)
            }
        }
    } else {
        message("A `Stain` object must contain at least one source file.")

        if (is_submitting) {
            stop(paste(m, "Aborting submission."), call. = FALSE)
        } else {
            message(m)
        }
    }
}


#' Message for ssh.
#'
#' Notify the user about remote host ssh requirements.
stain_message_ssh <- function() {
    cat("If your cluster is remote, add the .ssh/stain_rsa.pub key to your remote host. ")
    cat("To autogenerate the bash code, see ?stain_ssh_setup.")
}
#' Message for globals.
#'
#' Prompt the user to set globals if they have not already been
#' specified.
#'
#' @param globals The list of globals for a stain.
#'
#' @param is_submitting Is a slurm job being submitted? Default
#' value is FALSE to avoid any fatal errors.
stain_message_globals <- function(globals, is_submitting = FALSE) {
    na_globals <- globals[sapply(globals, is.na)]
    n_globals <- length(na_globals)

    if (n_globals > 0) {
        if (n_globals == 1) {
            plurality <- "global"
            demonstrative <- paste("this", plurality)
        } else {
            plurality <- "globals"
            demonstrative <- paste("these", plurality)
        }

        message(paste(length(na_globals), plurality, "to specify:"))

        for (global in names(na_globals)) {
            message(paste("\n    -", global))
        }

        message(paste("\nSet", demonstrative, "in the `globals` property of your `Stain` instance.\n"))

        if (is_submitting) {
            stop("Aborting submission.")
        }
    }
}


#' Message for source files.
#'
#' One of the source files must contain a \code{main} function and this
#' message will notify the user if none of his or her source files
#' contain a \code{main} function.
#'
#' @param source_files The list of R source files.
#'
#' @param is_submitting Is a slurm job being submitted? Default
#' value is FALSE to avoid any fatal errors.
stain_message_source_files <- function(source_files, is_submitting = FALSE) {
    file_count <- length(source_files)

    if (file_count > 0) {
        e <- new.env()

        for (file in source_files) {
            testthat::source_file(file, e)
        }

        if (is.null(e$main)) {
            if (file_count == 1) {
                plurality = paste("Your R source file doesn't")
            } else {
                plurality = paste("None of your", file_count, "R source files")
            }

            message(paste(plurality, "contain a `main()` function."))

            if (is_submitting) {
                stop("Aborting submission.")
            }
        }
    } else {
        message("A `Stain` object must contain at least one source file.")

        if (is_submitting) {
            stop("Aborting submission.")
        }
    }
}


#' Message for ssh.
#'
#' Notify the user about remote host ssh requirements.
stain_message_ssh <- function() {
    cat("If your cluster is remote, add the .ssh/stain_rsa.pub key to your remote host. ")
    cat("To autogenerate the bash code, see ?stain_ssh_setup.")
}
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        get_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/"),
                                     full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$get_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("Aborting submission.", call. = FALSE)
            })

            tryCatch({
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission", call. = FALSE)
            })

            tryCatch({
                stain_scp(user, host, self$dir, submit_dir)

                job_dir <- paste(submit_dir, self$dir, sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                stain_ssh(user, host, submit_cmd)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' Message for globals.
#'
#' Prompt the user to set globals if they have not already been
#' specified.
#'
#' @param globals The list of globals for a stain.
stain_message_globals <- function(globals) {
    na_globals <- globals[sapply(globals, is.na)]
    n_globals <- length(na_globals)

    if (n_globals > 0) {
        if (n_globals == 1) {
            plurality <- "global"
            demonstrative <- paste("this", plurality)
        } else {
            plurality <- "globals"
            demonstrative <- paste("these", plurality)
        }

        cat(paste(length(na_globals), plurality, "to specify:"))

        for (global in names(na_globals)) {
            cat(paste("\n    -", global))
        }

        cat(paste("\n\nSet", demonstrative, "in the `globals` property of your `Stain` instance."))
    }
}


#' Message for source files.
#'
#' One of the source files must contain a \code{main} function and this
#' message will notify the user if none of his or her source files
#' contain a \code{main} function.
#'
#' @param source_files The list of R source files.
stain_message_source_files <- function(source_files) {
    file_count <- length(source_files)

    if (file_count > 0) {
        e <- new.env()

        for (file in source_files) {
            testthat::source_file(file, e)
        }

        if (is.null(e$main)) {
            if (file_count == 1) {
                plurality = paste("Your R source file doesn't")
            } else {
                plurality = paste("None of your", file_count, "R source files")
            }

            cat(paste(plurality, "contain a `main()` function."))
        }
    } else {
        cat("A `Stain` object must contain at least one source file.")
    }
}


#' Message for ssh.
#'
#' Notify the user about remote host ssh requirements.
stain_message_ssh <- function() {
    cat("If your cluster is remote, add the .ssh/stain_rsa.pub key to your remote host. ")
    cat("To autogenerate the bash code, see ?stain_ssh_setup.")
}
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename1 = 'catalog_predictions2'
filename2 = 'catalog_predictions3'
filename3 = 'catalog_predictions4'


catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions2 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename1)

catalog_predictions3 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(30,50,70),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename2)

catalog_predictions4 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(60,80,90),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename3)



# Catalog vs predictions
load("./Analyses/catalog_predictions0.RData")
catalog_predictions0 <- Tanimoto_analysis
load("./Analyses/catalog_predictions1.RData")
catalog_predictions1 <- Tanimoto_analysis
load("./Analyses/catalog_predictions2.RData")
catalog_predictions2 <- Tanimoto_analysis
load("./Analyses/catalog_predictions3.RData")
catalog_predictions3 <- Tanimoto_analysis
load("./Analyses/catalog_predictions4.RData")
catalog_predictions4 <- Tanimoto_analysis

accuracy <- accuracy0 <- accuracy1 <- accuracy2 <- accuracy3 <- vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) <- names(accuracy2) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy2[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, empirical.only = TRUE)
accuracy2[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, predict.only = TRUE)
accuracy2[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3)

accuracy3[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions4, empirical.only = TRUE)
accuracy3[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions4, predict.only = TRUE)
accuracy3[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions4)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]], accuracy2[[1]], accuracy3[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]], accuracy2[[2]], accuracy3[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]], accuracy2[[3]], accuracy3[[3]])

percent_remove = c(0,10,20,30,40,50,60,70,80,90,100)
nb_iter = 50
K.values = 8
MW = 1
WT =  c(0.5,1)
minimum_threshold = 0.3

nb.pts <- length(percent_remove)

#Figure version 1
pdf(paste('./Article/','catalog_predictions','.pdf',sep=''),width=6,height=8)
j = 14 #'Score'[y]
        eplot(xmin = -1, xmax = 100 + 1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        col <- c("#FF8822",'#5ED275','#9CCBFF')
        col2 <- c("#FF8822",'#275A31','#0077FF')
        col3 <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.05)
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.05 + 2.5)
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)
            mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            mtext(text = expression(paste("Percent of taxa removed from ", italic(S0), ' (%)')), side = 1, line = 2, at = 50, font = 2, cex = 1)
            mtext(text = seq(0, 100, by = 10), side = 1, line = 0, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            mtext(text = seq(0, 100, by = 10), side = 3, line = -0.5, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            text(x = 5, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col3[1], adj = 0)
            text(x = 5, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col3[2], adj = 0)
            text(x = 5, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col3[3], adj = 0)


        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            points(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it, cex = 0.5, pch = 1, col = col[i])
            points(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it, cex = 0.5, pch = 1, col = col2[i])

            lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it), col = col[i])
            lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it), col = col2[i])

            if(i == 2 || i == 3) {
                text(x = 90, y = 0.9 + it, labels = expression(paste(italic('w'[t]), ' = 0.5')), col = col[i], font = 1, cex = 0.75)
                text(x = 90, y = 0.8 + it, labels = expression(paste(italic('w'[t]), ' = 1')), col = col2[i], font = 1, cex = 0.75)
            }

            it <- it + 1.25
        } #i
dev.off()

#Figure version 2
pdf(paste('./Article/','catalog_predictions2','.pdf',sep=''),width=6,height=8)
j = 14 #'Score'[y]
        eplot(xmin = -1, xmax = 100 + 1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        col <- c("#FF8822",'#5ED275','#9CCBFF')
        col2 <- c("#FF8822",'#275A31','#0077FF')
        col3 <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.05)
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.05 + 2.5)
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)
            mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            mtext(text = expression(paste("Percent of taxa removed from ", italic(N[0]), ' (%)')), side = 1, line = 2, at = 50, font = 2, cex = 1)
            mtext(text = expression(paste("Percent of ",italic(N[1])," taxa in ", italic(N[0]), ' (%)')), side = 3, line = 1, at = 50, font = 2, cex = 1)
            mtext(text = seq(0, 100, by = 10), side = 1, line = 0, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            mtext(text = seq(100, 0, by = -10), side = 3, line = -0.5, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            text(x = 5, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col3[1], adj = 0)
            text(x = 5, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col3[2], adj = 0)
            text(x = 5, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col3[3], adj = 0)


        it <- 0
        for(i in 1:length(accuracy)) {
            if(i == 2 || i == 3) {
                accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'pc_rm']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
                # hack: we draw arrows but with very special "arrowheads" for error bars

                arrows(seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][,1] - accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 2]+it, seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 1] + accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
                points(x = seq(0,100,by=10), y = accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])

                arrows(seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][,1] - accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 2]+it, seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 1] + accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 2]+it, length=0.025, angle=90, code=3, col = col2[i])
                points(x = seq(0,100,by=10), y = accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 1]+it, cex = 0.75, pch = 22, col = col2[i])

                lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it), col = col[i])
                lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it), col = col2[i])

                text(x = 90, y = 0.9 + it, labels = expression(paste(italic('w'[t]), ' = 0.5')), col = col[i], font = 1, cex = 0.75)
                text(x = 90, y = 0.8 + it, labels = expression(paste(italic('w'[t]), ' = 1')), col = col2[i], font = 1, cex = 0.75)
                } else {
                    accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'pc_rm']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                    accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
                    # hack: we draw arrows but with very special "arrowheads" for error bars

                    arrows(seq(0,100,by=10), accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2]+it, seq(0,100,by=10), accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2]+it, length=0.025, angle=90, code=3, col = col3[i])
                    points(x = seq(0,100,by=10), y = accuracy_mean[, 2][, 1]+it, cex = 0.75, pch = 22, col = col3[i])

                    lines(lowess(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it), col = col3[i])
                }

            it <- it + 1.25
        } #i
dev.off()
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename1 = 'catalog_predictions2'
filename2 = 'catalog_predictions3'
filename3 = 'catalog_predictions4'


catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions2 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename1)

catalog_predictions3 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(30,50,70),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename2)

catalog_predictions4 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(60,80,90),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename3)



# Catalog vs predictions
load("./Analyses/catalog_predictions0.RData")
catalog_predictions0 <- Tanimoto_analysis
load("./Analyses/catalog_predictions1.RData")
catalog_predictions1 <- Tanimoto_analysis
load("./Analyses/catalog_predictions2.RData")
catalog_predictions2 <- Tanimoto_analysis
load("./Analyses/catalog_predictions3.RData")
catalog_predictions3 <- Tanimoto_analysis
load("./Analyses/catalog_predictions4.RData")
catalog_predictions4 <- Tanimoto_analysis

accuracy <- accuracy0 <- accuracy1 <- accuracy2 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) <- names(accuracy2) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy2[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, empirical.only = TRUE)
accuracy2[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, predict.only = TRUE)
accuracy2[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3)

accuracy3[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions4, empirical.only = TRUE)
accuracy3[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions4, predict.only = TRUE)
accuracy3[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions4)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]], accuracy2[[1]], accuracy3[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]], accuracy2[[2]], accuracy3[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]], accuracy2[[3]], accuracy3[[3]])

percent_remove = c(0,10,20,30,40,50,60,70,80,90,100)
nb_iter = 50
K.values = 8
MW = 1
WT =  c(0.5,1)
minimum_threshold = 0.3

nb.pts <- length(percent_remove)

#Figure version 1
pdf(paste('./Article/','catalog_predictions','.pdf',sep=''),width=6,height=8)
j = 14 #'Score'[y]
        eplot(xmin = -1, xmax = 100 + 1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        col <- c("#FF8822",'#5ED275','#9CCBFF')
        col2 <- c("#FF8822",'#275A31','#0077FF')
        col3 <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.05)
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.05 + 2.5)
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)
            mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            mtext(text = expression(paste("Percent of taxa removed from ", italic(S0), ' (%)')), side = 1, line = 2, at = 50, font = 2, cex = 1)
            mtext(text = seq(0, 100, by = 10), side = 1, line = 0, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            mtext(text = seq(0, 100, by = 10), side = 3, line = -0.5, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            text(x = 5, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col3[1], adj = 0)
            text(x = 5, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col3[2], adj = 0)
            text(x = 5, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col3[3], adj = 0)


        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            points(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it, cex = 0.5, pch = 1, col = col[i])
            points(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it, cex = 0.5, pch = 1, col = col2[i])

            lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it), col = col[i])
            lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it), col = col2[i])

            if(i == 2 || i == 3) {
                text(x = 90, y = 0.9 + it, labels = expression(paste(italic('w'[t]), ' = 0.5')), col = col[i], font = 1, cex = 0.75)
                text(x = 90, y = 0.8 + it, labels = expression(paste(italic('w'[t]), ' = 1')), col = col2[i], font = 1, cex = 0.75)
            }

            it <- it + 1.25
        } #i
dev.off()

#Figure version 2
pdf(paste('./Article/','catalog_predictions2','.pdf',sep=''),width=6,height=8)
j = 14 #'Score'[y]
        eplot(xmin = -1, xmax = 100 + 1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        col <- c("#FF8822",'#5ED275','#9CCBFF')
        col2 <- c("#FF8822",'#275A31','#0077FF')
        col3 <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.05)
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.05 + 2.5)
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)
            mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            mtext(text = expression(paste("Percent of taxa removed from ", italic(S0), ' (%)')), side = 1, line = 2, at = 50, font = 2, cex = 1)
            mtext(text = expression(paste("Percent of ",italic(S1)," taxa in ", italic(S0), ' (%)')), side = 3, line = 1, at = 50, font = 2, cex = 1)
            mtext(text = seq(0, 100, by = 10), side = 1, line = 0, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            mtext(text = seq(100, 0, by = -10), side = 3, line = -0.5, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            text(x = 5, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col3[1], adj = 0)
            text(x = 5, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col3[2], adj = 0)
            text(x = 5, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col3[3], adj = 0)


        it <- 0
        for(i in 1:length(accuracy)) {
            if(i == 2 || i == 3) {
                accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'pc_rm']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
                # hack: we draw arrows but with very special "arrowheads" for error bars

                arrows(seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][,1] - accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 2]+it, seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 1] + accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
                points(x = seq(0,100,by=10), y = accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])

                arrows(seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][,1] - accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 2]+it, seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 1] + accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 2]+it, length=0.025, angle=90, code=3, col = col2[i])
                points(x = seq(0,100,by=10), y = accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 1]+it, cex = 0.75, pch = 22, col = col2[i])

                lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it), col = col[i])
                lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it), col = col2[i])

                text(x = 90, y = 0.9 + it, labels = expression(paste(italic('w'[t]), ' = 0.5')), col = col[i], font = 1, cex = 0.75)
                text(x = 90, y = 0.8 + it, labels = expression(paste(italic('w'[t]), ' = 1')), col = col2[i], font = 1, cex = 0.75)
                } else {
                    accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'pc_rm']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                    accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
                    # hack: we draw arrows but with very special "arrowheads" for error bars

                    arrows(seq(0,100,by=10), accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2]+it, seq(0,100,by=10), accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2]+it, length=0.025, angle=90, code=3, col = col3[i])
                    points(x = seq(0,100,by=10), y = accuracy_mean[, 2][, 1]+it, cex = 0.75, pch = 22, col = col3[i])

                    lines(lowess(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it), col = col3[i])
                }

            it <- it + 1.25
        } #i
dev.off()
#Solve for optimal lobby effort under DGH97-style model with obj fcn W + e

#reserve space for loop output
tau = seq(0.001,.166,0.001) #this will be counter variable in loop
PSx = matrix(NA,length(tau),1)
CSx = matrix(NA,length(tau),1)
TR = matrix(NA,length(tau),1)
PSy = matrix(NA,length(tau),1)
CSy = matrix(NA,length(tau),1)

#calculate producer surplus, consumer surplus, tariff revenue for each possible
#value of the tariff on the grid (just above zero to prohibitive tariff 1/6)
for (j in 1:length(tau)) {
  t = tau[j]

  PSx[j] = ((2 +2*t)^2)/49
  CSx[j] = .5*((3 -4*t)^2)/49
  TR[j] = (t - 6*t^2)/7
  CSy[j] = ((3 +3*t)^2)/98
  PSy[j] = ((4 -3*t)^2)/98
}

#Calculations for when lobby has all the bargaining power

#calculate government welfare when tau = 0 (baseline)
b = ((2 +2*0)^2)/49 + .5*((3 -4*0)^2)/49 + (0 - 6*0^2)/7 + ((3 +3*0)^2)/98 + ((4 -3*0)^2)/98
W = PSx + CSx + TR + CSy + PSy  #social welfare
e = ((b - W)/PSx)^5             #gov't indifference condition when WG = W + e
pi = PSx - e                    #net profits

value = max(pi) #the value at which profits are maximized (over non-negative values)
ind = which.max(pi) #the location at which profits are maximized
RC = arrayInd(ind,c(dim(pi),dim(pi))) #row/column version of maximand location


#Calculations for when government has all the bargaining power
bl = ((2 +2*0)^2)/49           #baseline for lobby: profits when tau = 0
e = PSx - bl                   #effort level giving all excess profits over tau=0 to gov't

g = e^1.2                       #little g(e) function to add to social welfare
G = W + g                      #gov't welfare a la DGH97
plot(G)

value = max(G) #the value at which profits are maximized (over non-negative values)
ind = which.max(G) #the location at which profits are maximized
RC = arrayInd(ind,c(dim(G),dim(G))) #row/column version of maximand locationlibrary(DiagrammeR)
grViz("

digraph boxes_and_circles{

    node [shape = box
            # fixedsize = TRUE
            # width = 2.5
            ]
            1 [label = <<B>S1) </B>I(<I>T<sub><font point-size='8'>C</font></sub>,T<sub><font point-size='8'>R</font></sub></I>) in <I>N<sub><font point-size='8'>0</font></sub></I>?>]
            2 [label = <<B>S2) </B><I>T<sub><font point-size='8'>R </font></sub></I> in <I>N<sub><font point-size='8'>1</font></sub></I>?>]
            3 [label = <<B>S3) </B>Add <I>T<sub><font point-size='8'>R </font></sub></I> to<br/>predictions>]
            4 [label = <<B>S4) </B><I>K </I> most similar<br/>resource <I>T<sub><font point-size='8'>R&apos;</font></sub></I> in <I>N<sub><font point-size='8'>1</font></sub></I>>]
            5 [label = <<B>S5) </B><I>T<sub><font point-size='8'>R&apos; </font></sub></I> in <I>C<SUB><font point-size='8'>R</font></SUB></I>?>]
            6 [label = <<B>S6) </B>Add weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I><br/>to <I>T<sub><font point-size='8'>R&apos; </font></sub></I>in <I>C<SUB><font point-size='8'>R </font></SUB></I> if<br/><I>t </I> &gt; minimum threshold>]
            7 [label = <<B>S7) </B>Add <I>T<sub><font point-size='8'>R&apos; </font></sub></I>to <I>C<SUB><font point-size='8'>R </font></SUB></I> with<br/>weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I> if<br/><I>t </I> &gt; minimum threshold>]
            8 [label = <<B>S8) </B><I>K </I> most similar<br/>consumer <I>T<sub><font point-size='8'>C&apos;</font></sub></I>>]
            9 [label = <<B>S9) </B><I>T<sub><font point-size='8'>R </font></sub></I>in <I>N<sub><font point-size='8'>1</font></sub></I>?>]
            10 [label = <<B>S10) </B><I>T<sub><font point-size='8'>R </font></sub></I>in <I>C<SUB><font point-size='8'>R</font></SUB></I>?>]
            11 [label = <<B>S11) </B>Add 1 to <I>T<sub><font point-size='8'>R </font></sub></I><br/>weight in <I>C<SUB><font point-size='8'>R</font></SUB></I>>]
            12 [label = <<B>S12) </B>Add <I>T<sub><font point-size='8'>R </font></sub></I>to <I>C<SUB><font point-size='8'>R </font></SUB></I><br/>with weight = 1>]
            13 [label = <<B>S13) </B><I>K </I> most similar<br/>resource <I>T<sub><font point-size='8'>R&apos; </font></sub></I>in <I>N<sub><font point-size='8'>1</font></sub></I>>]
            14 [label = <<B>S14) </B><I>T<sub><font point-size='8'>R&apos; </font></sub></I>in <I>C<SUB><font point-size='8'>R</font></SUB></I>?>]
            15 [label = <<B>S15) </B>Add weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I><br/>to <I>T<sub><font point-size='8'>R&apos; </font></sub></I>in <I>C<SUB><font point-size='8'>R </font></SUB></I>if<br/><I>t </I> &gt; minimum threshold>]
            16 [label = <<B>S16) </B>Add <I>T<sub><font point-size='8'>R&apos; </font></sub></I>to <I>C<SUB><font point-size='8'>R </font></SUB></I>with<br/> weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I> if<br/><I>t </I> &gt; minimum threshold>]
            17 [label = <<B>S17) </B>Add <I>T<sub><font point-size='8'>R </font></sub></I>or <I>T<sub><font point-size='8'>R&apos; </font></sub></I>to predictions if weight &gt; minimum weight>]

1 -> 2 [label = 'Yes', headport = 'n', tailport = 'w']
1 -> 3 [color = 'transparent']
1 -> 4 [color = 'transparent']
1 -> 5 [color = 'transparent']
1 -> 6 [color = 'transparent']
1 -> 7 [color = 'transparent']
1 -> 8 [color = 'transparent']
2 -> 3 [label = 'Yes']
2 -> 4 [label = 'No']
4 -> 5
5 -> 6 [label = 'Yes']
5 -> 7 [label = 'No']
6 -> 17
7 -> 17
1 -> 8 [tailport = 'e']
8 -> 9
9 -> 10 [label = 'Yes']
10 -> 11 [label = 'Yes']
10 -> 12 [label = 'No']
11 -> 17
12 -> 17
9 -> 13 [label = 'No']
13 -> 14
14 -> 15 [label = 'Yes']
14 -> 16 [label = 'No']
15 -> 17
16 -> 17

graph [ranksep = 0.15
        rank = sink
        # rankdir = LR
        # splines = ortho
        ]


}
")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2.8 Example with southern St. Lawrence EwE model for mid-1980s
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "./RawData/South_St_Lawrence_EwE.RData"
#   Script  <- file = "Script/2-8_St_Lawrence_ex.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REFERENCE:
#   Savenkoff, to add
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
library(stringr)
load("./RawData/South_St_Lawrence_EwE.RData")
SSL <- South_St_Lawrence

SSL[[2]][which(SSL[[2]] > 0)] <- 1
rownames(SSL[[2]]) <- colnames(SSL[[2]]) <- SSL[[3]]

sp_SSL <- matrix(ncol = 3, nrow = 29, data = NA, dimnames = list(c(), c('ACCR','SP','FG')))

sp_SSL[,1] <- c('WHA','HAS','HOS','GRS','HSE','SEA','LCO','SCO','LGH','SAP','LAP','FLO','SKA','RED','LDF','SDF','CAP','LPF','PISF','PLSF','SHR','LCRU','ECH','MOL','POL','OBI','LZOO','SZOO','PHY')

sp_SSL[,3] <- c('Cetaceans',
'Harp seals',
'Hooded seals',
'Grey seals',
'Harbour seals',
'Seabirds',
'Atlantic cod',
'Atlantic cod',
'Greenland halibut',
'American plaice',
'American plaice',
'Flounders',
'Skates',
'Redfish',
'Large demersal feeders',
'Small demersal feeders',
'Capelin',
'Large pelagic feeders',
'Piscivorous small pelagic feeders',
'Planktivorous small pelagic feeders',
'Shrimp',
'Large crustaceans',
'Echinoderms',
'Molluscs',
'Polychates',
'Other benthic invertebrates',
'Large zooplankton',
'Small zooplankton',
'Phytoplankton')



sp_SSL[,2] <- c('Balaenoptera physalus - Balaenoptera acutorostrata - Megaptera novaeangliae - Phocoena phocoena - Lagenorhynchus acutus - Lagenorhynchus albirostris',
'Pagophilus groenlandicus',
'Cystophora cristata',
'Halichoerus grypus',
'Phoca vitulina',
'Phalacrocorax carbo - Phalacrocorax auritus - Larus delawarensis - Larus argentatus - Larus marinus - Sterna hirundo - Sterna paradisaea - Cepphus grylle - Oceanodroma leucorhoa - Morus bassanus - Rissa tridactyla - Uria aalge - Alca torda - Fratercula arctica',
'Gadus morhua',
'Gadus morhua',
'Reinhardtius hippoglossoides',
'Hippoglossoides platessoides',
'Hippoglossoides platessoides',
'Limanda ferruginea - Glyptocephalus cynoglossus - Pseudopleuronectes americanus',
'Amblyraja radiata - Malacoraja senta - Leucoraja ocellata',
'Sebastes mentella - Sebastes fasciatus',
'Urophycis tenuis - Melanogrammus aeglefinus - Centroscyllium fabricii - Anarhichas - Cyclopterus lumpus - Lycodes - Macrouridae - Zoarcidae - Lophius americanus - Hippoglossus hippoglossus',
'Myoxocephalus - Tautogolabrus adspersus - Zoarces americanus',
'Mallotus villosus',
'Squalus acanthias - Pollachius virens - Merluccius bilinearis - Cetorhinus maximus',
'Scomber scombrus - Illex illecebrosus',
'Clupea harengus - Scomberesox saurus - Gonatus',
'Argis dentata - Eualus macilentus - Eualus gaimardi - Pandalus montagui',
'Chionoecetes opilio - Hyas',
'Echinarachnius parma - Stronglyocentrotus pallidus - Ophiura robusta',
'Mesodesma deauratum - Cyrtodaria siliqua',
'Parexogone hebes',
'Miscellaneous crustaceans', #to remove OBI
'Euphausiids - chaetognaths', # to remove LZOO
'Oithona similis - Temora longicornis - Pseudocalanus - Calanus finmarchicus',
'Chaetoceros affinis - Chaetoceros - Leptocylindrus minimus - Thalassiiosira nordenskioldii - Thalassiiosira - Fragilariopsis')

# Removing portions of the web for which there is no taxa usable for the analysis, 'OBI' & 'LZOO'
SSL[[2]] <- SSL[[2]][-which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO'), -which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO')]
sp_SSL <- sp_SSL[-which(sp_SSL[,1] == 'OBI' | sp_SSL[,1] == 'LZOO'), ]

S1 <- unique(unlist(str_split(sp_SSL[,2], ' - ')))

load("./RData/S0_catalog.RData")
S0 <- S0_catalog


# Have to extract taxonomy for speies that are not found in S0
S1_missing <- which(!S1 %in% S0[,1])

S1_add_S0 <- matrix(ncol = 6, nrow = length(S1_missing), data = "", dimnames = list(c(), c("taxon", "taxonomy", "resource", "non-resource", "consumer", "non-consumer")))

S1_add_S0[, 'taxon'] <- S1[S1_missing]

S1_add_S0[, 'taxonomy'] <- c('Animalia | Chordata | Mammalia | Cetartiodactyla | Delphinidae | Lagenorhynchus | Lagenorhynchus acutus',
'Animalia | Chordata | Mammalia | Carnivora | Phocidae | Halichoerus | Halichoerus grypus',
'Animalia | Chordata | Procellariiformes | Hydrobatidae | Oceanodroma | Oceanodroma leucorhoa',
'Animalia | Chordata | Aves | Pelecaniformes | Sulidae | Morus | Morus bassanus',
'Animalia | Chordata | Aves | Charadriiformes | Alcidae | Alca | Alca torda',
'Animalia | Chordata | Elasmobranchii | Rajiformes | Rajidae | Malacoraja | Malacoraja senta',
'Animalia | Chordata | Elasmobranchii | Squaliformes | Etmopteridae | Centroscyllium | Centroscyllium fabricii',
'Animalia | Arthropoda | Malacostraca | Decapoda | Crangonidae | Argis | Argis dentata',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus macilentus',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus gaimardii',
'Animalia | Echinodermata | Echinoidea | Camarodonta | Strongylocentrotidae | Strongylocentrotus | Strongylocentrotus pallidus',
'Animalia | Mollusca | Bivalvia | Imparidentia | Mesodesmatidae | Mesodesma | Mesodesma deauratum',
'Animalia | Mollusca | Bivalvia | Adapedonta | Hiatellidae | Cyrtodaria | Cyrtodaria siliqua',
'Animalia | Annelida | Polychaeta | Phyllodocida | Syllidae | Parexogone | Parexogone hebes',
'Chromista | Ochrophyta | Bacillariophyceae | Chaetocerotanae | Chaetocerotaceae | Chaetoceros | Chaetoceros affinis',
'Chromista | Ochrophyta | Bacillariophyceae | Leptocylindrales | Leptocylindraceae | Leptocylindrus | Leptocylindrus minimus',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | Thalassiosira nordenskioeldii',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | NA')

 S0 <- rbind(S0, S1_add_S0) #binding missing taxonomies
 rownames(S0) <- S0[, 'taxon']


# #Thinning down catalogue
# S02 <- S0[unique(c(which(S0[, 'resource'] != ""), which(S0[, 'consumer'] != ""))), ]
#
# S1_missing2 <- which(!S1 %in% S02[,1]) #after culling
# S1_missing3 <- S1_missing2[which(!S1_missing2 %in% S1_missing)] #taxo to keep
# S1_add_S0 <- rbind(S1_add_S0, S0[which(S0[, 'taxon'] %in% S1[S1_missing3]), ])
# rownames(S1_add_S0) <- NULL
# S0 <- rbind(S02, S1_add_S0)
# remove(S02,S1_missing3,S1_missing2,S1_missing)

# Predicting interactions
SSL_predict <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.3)

# SSL_predict2 <- full_algorithm(Kc = 4,
#                             Kr = 4,
#                             S0 = S0,
#                             S1 = S1,
#                             MW = 1,
#                             wt = 0.5,
#                             minimum_threshold = 0.2)

SSL_predict_mat <- prediction_matrix(S1 = S1, predictions = SSL_predict)
# SSL_predict_mat2 <- prediction_matrix(S1 = S1, predictions = SSL_predict2)
x <- SSL_predict_mat

for(i in 1:nrow(sp_SSL)) {
    Sx <- unique(unlist(str_split(sp_SSL[i,2], ' - ')))
    for(j in 1:length(Sx)){
        for(k in 1:length(S1))
        if(S1[k] %in% Sx == TRUE) {
            colnames(SSL_predict_mat)[k] <- rownames(SSL_predict_mat)[k] <- sp_SSL[i, 2]
            # colnames(SSL_predict_mat2)[k] <- rownames(SSL_predict_mat2)[k] <- sp_SSL[i, 2]
        }
    }
}

SSL_predict_mat_combine <- dupl_sp(SSL_predict_mat)
# SSL_predict_mat_combine2 <- dupl_sp(SSL_predict_mat2)

SSL_emp <- SSL[[2]]
colnames(SSL_emp) <- rownames(SSL_emp) <- sp_SSL[,2]
SSL_emp <-  dupl_sp(SSL_emp)

accuracy_SSL <- prediction_accuracy_id(predicted = SSL_predict_mat_combine, empirical = SSL_emp)
# accuracy_SSL2 <- prediction_accuracy_id(predicted = SSL_predict_mat_combine2, empirical = SSL_emp)
accuracy_SSL
# accuracy_SSL2

# for(i in 2:nrow(accuracy_SSL[[4]])) {
#     print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]))
# }
#
# for(i in 2:nrow(accuracy_SSL[[3]])) {
#     print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]))
# }


SSL_bin_inter <- bin_inter(SSL_predict_mat_combine)
# SSL_bin_inter2 <- bin_inter(SSL_predict_mat_combine2)
SSL_emp_bin <- bin_inter(SSL_emp)
SSL_bin_inter <- SSL_bin_inter[which(SSL_bin_inter[, 'FeedInter'] == '1'), ]
# SSL_bin_inter2 <- SSL_bin_inter2[which(SSL_bin_inter2[, 'FeedInter'] == '1'), ]
SSL_emp_bin <- SSL_emp_bin[which(SSL_emp_bin[, 'FeedInter'] == '1'), ]

# SSL species with interactions noted in catalogue
x <- which(S0[, 'taxon'] %in% S1)
length(which(S0[x,'resource'] != "" | S0[x,'consumer'] != ""))

id_c <- matrix(nrow = nrow(accuracy_SSL[[4]]), ncol = 2, data = NA, dimnames = list(c(), c('consumer','resource')))
for(i in 2:nrow(accuracy_SSL[[4]])) {
    id_c[i,1] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]
    id_c[i,2] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]]
}

id_b <- matrix(nrow = nrow(accuracy_SSL[[3]]), ncol = 2, data = NA, dimnames = list(c(), c('consumer','resource')))
for(i in 2:nrow(accuracy_SSL[[3]])) {
    id_b[i,1] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]
    id_b[i,2] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]]
}
for(i in 1:nrow(sp_SSL)){
    id_c[which(id_c[, 'consumer'] == sp_SSL[i,2]), 'consumer'] <- sp_SSL[i,3]
    id_c[which(id_c[, 'resource'] == sp_SSL[i,2]), 'resource'] <- sp_SSL[i,3]
    id_b[which(id_b[, 'consumer'] == sp_SSL[i,2]), 'consumer'] <- sp_SSL[i,3]
    id_b[which(id_b[, 'resource'] == sp_SSL[i,2]), 'resource'] <- sp_SSL[i,3]
}



pp <- which(SSL_emp_bin[,'Predator'] == "Scomber scombrus - Illex illecebrosus" | SSL_emp_bin[,'Prey'] == "Scomber scombrus - Illex illecebrosus")
cap <- which(SSL_emp_bin[,'Predator'] == "Mallotus villosus" | SSL_emp_bin[,'Prey'] == "Mallotus villosus")
SSL_emp_part <- SSL_emp_bin[unique(c(pp,cap)), ]


pp <- which(SSL_bin_inter[,'Predator'] == "Scomber scombrus - Illex illecebrosus" | SSL_bin_inter[,'Prey'] == "Scomber scombrus - Illex illecebrosus")

cap <- which(SSL_bin_inter[,'Predator'] == "Mallotus villosus" | SSL_bin_inter[,'Prey'] == "Mallotus villosus")
SSL_pred_part <- SSL_bin_inter[unique(c(pp,cap)), ]

for(i in 1:nrow(sp_SSL)){
    SSL_emp_part[which(SSL_emp_part[, 'Predator'] == sp_SSL[i,2]), 'Predator'] <- sp_SSL[i,3]
    SSL_emp_part[which(SSL_emp_part[, 'Prey'] == sp_SSL[i,2]), 'Prey'] <- sp_SSL[i,3]
    SSL_pred_part[which(SSL_pred_part[, 'Predator'] == sp_SSL[i,2]), 'Predator'] <- sp_SSL[i,3]
    SSL_pred_part[which(SSL_pred_part[, 'Prey'] == sp_SSL[i,2]), 'Prey'] <- sp_SSL[i,3]
}

unique(c(SSL_emp_part,SSL_pred_part))

SSL_pred_part <- gsub("1", "->",SSL_pred_part)
SSL_pred_part <- gsub("Skates", "1",SSL_pred_part)
SSL_pred_part <- gsub("Cetaceans", "2",SSL_pred_part)
SSL_pred_part <- gsub("Hooded seals", "3",SSL_pred_part)
SSL_pred_part <- gsub("Atlantic cod", "4",SSL_pred_part)
SSL_pred_part <- gsub("Grey seals", "5",SSL_pred_part)
SSL_pred_part <- gsub("Harp seals", "6",SSL_pred_part)
SSL_pred_part <- gsub("Seabirds", "7",SSL_pred_part)
SSL_pred_part <- gsub("Harbour seals", "8",SSL_pred_part)
SSL_pred_part <- gsub("Greenland halibut", "9",SSL_pred_part)
SSL_pred_part <- gsub("Piscivorous small pelagic feeders", "10",SSL_pred_part)
SSL_pred_part <- gsub("Redfish", "11",SSL_pred_part)
SSL_pred_part <- gsub("Large pelagic feeders", "12",SSL_pred_part)
SSL_pred_part <- gsub("Large demersal feeders", "13",SSL_pred_part)
SSL_pred_part <- gsub("Capelin", "14",SSL_pred_part)
SSL_pred_part <- gsub("Small demersal feeders","15",SSL_pred_part)
SSL_pred_part <- gsub("Planktivorous small pelagic feeders", "16",SSL_pred_part)
SSL_pred_part <- gsub("Small zooplankton", "17",SSL_pred_part)
SSL_pred_part <- gsub("Flounders", "18",SSL_pred_part)
SSL_pred_part <- gsub("Large crustaceans", "19",SSL_pred_part)
SSL_pred_part <- gsub("American plaice", "20",SSL_pred_part)
SSL_pred_part <- gsub("Shrimp", "21",SSL_pred_part)

SSL_emp_part <- gsub("1", "->",SSL_emp_part)
SSL_emp_part <- gsub("Skates", "1",SSL_emp_part)
SSL_emp_part <- gsub("Cetaceans", "2",SSL_emp_part)
SSL_emp_part <- gsub("Hooded seals", "3",SSL_emp_part)
SSL_emp_part <- gsub("Atlantic cod", "4",SSL_emp_part)
SSL_emp_part <- gsub("Grey seals", "5",SSL_emp_part)
SSL_emp_part <- gsub("Harp seals", "6",SSL_emp_part)
SSL_emp_part <- gsub("Seabirds", "7",SSL_emp_part)
SSL_emp_part <- gsub("Harbour seals", "8",SSL_emp_part)
SSL_emp_part <- gsub("Greenland halibut", "9",SSL_emp_part)
SSL_emp_part <- gsub("Piscivorous small pelagic feeders", "10",SSL_emp_part)
SSL_emp_part <- gsub("Redfish", "11",SSL_emp_part)
SSL_emp_part <- gsub("Large pelagic feeders", "12",SSL_emp_part)
SSL_emp_part <- gsub("Large demersal feeders", "13",SSL_emp_part)
SSL_emp_part <- gsub("Capelin", "14",SSL_emp_part)
SSL_emp_part <- gsub("Small demersal feeders", "15",SSL_emp_part)
SSL_emp_part <- gsub("Planktivorous small pelagic feeders", "16",SSL_emp_part)
SSL_emp_part <- gsub("Small zooplankton", "17",SSL_emp_part)
SSL_emp_part <- gsub("Flounders", "18",SSL_emp_part)
SSL_emp_part <- gsub("Large crustaceans", "19",SSL_emp_part)
SSL_emp_part <- gsub("American plaice", "20",SSL_emp_part)
SSL_emp_part <- gsub("Shrimp", "21",SSL_emp_part)

SSL_emp_part
SSL_pred_part

library(DiagrammeR)
grViz("

digraph boxes_and_circles{

    node [shape = box
            # fixedsize = TRUE
            # width = 2.5
            ]
            1 [label =  <Skates>]
            2 [label =  <Cetaceans>]
            3 [label =  <Hooded seals>]
            4 [label =  <Atlantic cod>]
            5 [label =  <Grey seals>]
            6 [label =  <Harp seals>]
            7 [label =  <Seabirds>]
            8 [label =  <Harbour seals>]
            9 [label =  <Greenland halibut>]
            10 [label =  <Piscivorous small<br/>pelagic feeders>]
            11 [label =  <Redfish>]
            12 [label =  <Large pelagic<br/>feeders>]
            13 [label =  <Large demersal<br/>feeders>]
            14 [label =  <Capelin>]
            15 [label =  <Small demersal<br/>feeders>]
            16 [label =  <Planktivorous small<br/>pelagic feeders>]
            17 [label =  <Small zooplankton>]
            18 [label =  <Flounders>]
            19 [label =  <Large crustaceans>]
            20 [label =  <American plaice>]
            21 [label =  <Shrimp>]

    edge [dir = back]
            12 -> 15 [color = 'transparent']
            12 -> 16 [color = 'transparent']
            13 -> 15 [color = 'transparent']
            13 -> 16 [color = 'transparent']
            20 -> 15 [color = 'transparent']
            20 -> 16 [color = 'transparent']
            18 -> 15 [color = 'transparent']
            18 -> 16 [color = 'transparent']
            4 -> 15 [color = 'transparent']
            4 -> 16 [color = 'transparent']
            15 -> 21 [color = 'transparent']
            15 -> 19 [color = 'transparent']
            16 -> 21 [color = 'transparent']
            16 -> 19 [color = 'transparent']

            2 -> 11 [color = 'transparent']
            2 -> 1 [color = 'transparent']
            2 -> 9 [color = 'transparent']
            3 -> 11 [color = 'transparent']
            3 -> 1 [color = 'transparent']
            3 -> 9 [color = 'transparent']
            5 -> 11 [color = 'transparent']
            5 -> 1 [color = 'transparent']
            5 -> 9 [color = 'transparent']
            6 -> 11 [color = 'transparent']
            6 -> 1 [color = 'transparent']
            6 -> 9 [color = 'transparent']

            #Empirical & predictions
            1 -> 10 [color = 'green']
            2 -> 10 [color = 'green']
            3 -> 10 [color = 'green']
            4 -> 10 [color = 'green']
            6 -> 10 [color = 'green']
            7 -> 10 [color = 'green']
            8 -> 10 [color = 'green']
            10 -> 16 [color = 'green']
            10 -> 14 [color = 'green']
            10 -> 17 [color = 'green']
            12 -> 10 [color = 'green']
            13 -> 10 [color = 'green']
            1 -> 14 [color = 'green']
            2 -> 14 [color = 'green']
            3 -> 14 [color = 'green']
            4 -> 14 [color = 'green']
            5 -> 14 [color = 'green']
            14 -> 17 [color = 'green']
            15 -> 14 [color = 'green']
            6 -> 14 [color = 'green']
            7 -> 14 [color = 'green']
            8 -> 14 [color = 'green']
            9 -> 14 [color = 'green']
            11 -> 14 [color = 'green']
            12 -> 14 [color = 'green']
            13 -> 14 [color = 'green']

            # Empirical only
            5 -> 10 [color = 'black']
            9 -> 10 [color = 'black']
            11 -> 10 [color = 'black']

            # Predictions only
            18 -> 10 [color = 'blue']
            15 -> 10 [color = 'blue']
            10 -> 21 [color = 'blue']
            10 -> 4 [color = 'blue']
            10 -> 18 [color = 'blue']
            10 -> 15 [color = 'blue']
            10 -> 10 [color = 'blue']
            10 -> 12 [color = 'blue']
            10 -> 13 [color = 'blue']
            19 -> 14 [color = 'blue']
            16 -> 14 [color = 'blue']
            20 -> 14 [color = 'blue']
            18 -> 14 [color = 'blue']
            14 -> 14 [color = 'blue']
            16 -> 10 [color = 'blue']
            20 -> 10 [color = 'blue']
            10 -> 19 [color = 'blue']
            10 -> 20 [color = 'blue']
            10 -> 9 [color = 'blue']
}
")

# Load package
library(networkD3)
# Plot
simpleNetwork(as.data.frame(SSL_bin_inter[, c(1,3)]))
simpleNetwork(as.data.frame(SSL_emp_bin[, c(1,3)]))
create_dtm <- function( path ) {

  library(tm)
  library(slam)

  a <- Corpus( DirSource( path, encoding = "UTF-8" ) )

  stop <- scan('stop.txt', what = list(""), sep = '\n' )
  stop <- c( stopwords("finnish") , stop , recursive=T )

  ## bunch of cleanup and transformations
  a <- tm_map(a, removeNumbers, mc.cores=1 )
  a <- tm_map(a, stripWhitespace, mc.cores=1 )
  a <- tm_map(a, removePunctuation, mc.cores=1 )
  a <- tm_map(a, content_transformer(tolower), mc.cores=1 )
  a <- tm_map(a, removeWords, stop )

  ## compute word frequencies
  dtm <-DocumentTermMatrix(a)

  frequency <- col_sums( dtm , na.rm = T )
  frequency <- sort(frequency, decreasing=TRUE)

  ## choose removal boundaries for further data analysis

  upper = Inf ## floor( length( frequency ) * .005 )
  lower = floor( length( frequency) * .95 )
  ## upper = frequency[ upper ]
  lower = frequency[ lower ]
  ## upper = as.integer( upper )
  lower = as.integer( lower ) + 1

  dtm2 = DocumentTermMatrix( a , control = list( bounds = list( global = c( lower, upper ) ) ) )

  ## throw away columns with 0 indicators
  dtm3 <- dtm2[ row_sums( dtm2 ) > 0, ]

  return( dtm3 )

}

create_model <- function( dtm, k ) {

   library(topicmodels)

   burnin = 1000
   iter = 1000
   keep = 50

   model <- LDA( dtm , k = k, method = "Gibbs", control =  list(burnin = burnin, iter = iter, keep = keep) )

   return( model )

}

check_fitness <- function( dtm , k ) {

  library(topicmodels)
  library(Rmpfr)

  burnin = 1000
  iter = 1000
  keep = 50

  model <- create_model( dtm , k )
  ll <- model@logLiks[ -c(1:(burnin/keep)) ]

  precision = 2000L
  llMed <- median( ll )
  ll = as.double( llMed - log( mean( exp( -mpfr(ll , prec = precision) + llMed ) ) ) )

  return( ll )

}


## from http://www.r-bloggers.com/a-link-between-topicmodels-lda-and-ldavis/

visualize_topicmodel <- function(fitted, corpus, doc_term){
    # Required packages
    library(topicmodels)
    library(dplyr)
    library(stringi)
    library(tm)
    library(LDAvis)

    # Find required quantities
    phi <- posterior(fitted)$terms %>% as.matrix
    theta <- posterior(fitted)$topics %>% as.matrix
    vocab <- colnames(phi)
    doc_length <- vector()
    for (i in 1:length(corpus)) {
        temp <- paste(corpus[[i]]$content, collapse = ' ')
        doc_length <- c(doc_length, stri_count(temp, regex = '\\S+'))
    }
    temp_frequency <- inspect(doc_term)
    freq_matrix <- data.frame(ST = colnames(temp_frequency),
                              Freq = colSums(temp_frequency))
    rm(temp_frequency)

    # Convert to json
    json_lda <- LDAvis::createJSON(phi = phi, theta = theta,
                            vocab = vocab,
                            doc.length = doc_length,
                            term.frequency = freq_matrix$Freq)

    return(json_lda)
}
source('topics.r')

args <- commandArgs(trailingOnly = TRUE)

print( args[1] )

load( paste( args[1] , 'dtm.rdata', sep='' ) )
k <- as.integer( args[2] )

model <- create_model( dtm , k )

path <- paste( args[1] , '/topic-', args[2], '.rdata' , sep = '' )
save( model , file = path )
create_dtm <- function( path ) {

  library(tm)

  a <- Corpus( DirSource( path, encoding = "UTF-8" ) )

  stop <- scan('stop.txt', what = list(""), sep = '\n' )
  stop <- c( stopwords("finnish") , stop , recursive=T )

  ## bunch of cleanup and transformations
  a <- tm_map(a, removeNumbers, mc.cores=1 )
  a <- tm_map(a, stripWhitespace, mc.cores=1 )
  a <- tm_map(a, removePunctuation, mc.cores=1 )
  a <- tm_map(a, tolower, mc.cores=1 )
  a <- tm_map(a, function(x) iconv(x, to='UTF-8', sub='byte'), mc.cores=1 )
  a <- tm_map(a, removeWords, stop, mc.cores=1 )

  ## compute word frequencies
  dtm <-DocumentTermMatrix(a)

  frequency <- col_sums( dtm , na.rm = T )
  frequency <- sort(frequency, decreasing=TRUE)

  ## choose removal boundaries for further data analysis

  upper = Inf ## floor( length( frequency ) * .005 )
  lower = floor( length( frequency) * .95 )
  ## upper = frequency[ upper ]
  lower = frequency[ lower ]
  ## upper = as.integer( upper )
  lower = as.integer( lower ) + 1

  dtm2 = DocumentTermMatrix( a , control = list( bounds = list( global = c( lower, upper ) ) ) )

  ## throw away columns with 0 indicators
  dtm3 <- dtm2[ row_sums( dtm2 ) > 0, ]

  return( dtm3 )

}

create_model <- function( dtm, k ) {

   library(topicmodels)

   burnin = 1000
   iter = 1000
   keep = 50

   model <- LDA( dtm , k = k, method = "Gibbs", control =  list(burnin = burnin, iter = iter, keep = keep) )

   return( model )

}

check_fitness <- function( dtm , k ) {

  library(topicmodels)
  library(Rmpfr)

  burnin = 1000
  iter = 1000
  keep = 50

  model <- create_model( dtm , k )
  ll <- model@logLiks[ -c(1:(burnin/keep)) ]

  precision = 2000L
  llMed <- median( ll )
  ll = as.double( llMed - log( mean( exp( -mpfr(ll , prec = precision) + llMed ) ) ) )

  return( ll )

}


## from http://www.r-bloggers.com/a-link-between-topicmodels-lda-and-ldavis/

visualize_topicmodel <- function(fitted, corpus, doc_term){
    # Required packages
    library(topicmodels)
    library(dplyr)
    library(stringi)
    library(tm)
    library(LDAvis)

    # Find required quantities
    phi <- posterior(fitted)$terms %>% as.matrix
    theta <- posterior(fitted)$topics %>% as.matrix
    vocab <- colnames(phi)
    doc_length <- vector()
    for (i in 1:length(corpus)) {
        temp <- paste(corpus[[i]]$content, collapse = ' ')
        doc_length <- c(doc_length, stri_count(temp, regex = '\\S+'))
    }
    temp_frequency <- inspect(doc_term)
    freq_matrix <- data.frame(ST = colnames(temp_frequency),
                              Freq = colSums(temp_frequency))
    rm(temp_frequency)

    # Convert to json
    json_lda <- LDAvis::createJSON(phi = phi, theta = theta,
                            vocab = vocab,
                            doc.length = doc_length,
                            term.frequency = freq_matrix$Freq)

    return(json_lda)
}
create_dtm <- function( path ) {

  library(tm)

  a <- Corpus( DirSource( path, encoding = "UTF-8" ) )


  stop <- scan('stop.txt', what = list(""), sep = '\n' )
  stop <- c( stopwords("finnish") , stop , recursive=T )

  ## bunch of cleanup and transformations
  a <- tm_map(a, removeNumbers, mc.cores=1 )
  a <- tm_map(a, stripWhitespace, mc.cores=1 )
  a <- tm_map(a, removePunctuation, mc.cores=1 )
  a <- tm_map(a, tolower, mc.cores=1 )
  a <- tm_map(a, function(x) iconv(x, to='UTF-8', sub='byte'), mc.cores=1 )
  a <- tm_map(a, removeWords, stop, mc.cores=1 )

  ## compute word frequencies
  dtm <-DocumentTermMatrix(a) ## , control = list( bounds = list( global = c( minDocFreq, maxDocFreq ) ) ) )

  frequency <- col_sums( dtm , na.rm = T )
  frequency <- sort(frequency, decreasing=TRUE)

  upper = Inf ## floor( length( frequency ) * .005 )
  lower = floor( length( frequency) * .80 )
  ## upper = frequency[ upper ]
  lower = frequency[ lower ]
  ## upper = as.integer( upper )
  lower = as.integer( lower ) + 1

  dtm2 = DocumentTermMatrix( a , control = list( bounds = list( global = c( lower, upper ) ) ) )

  ## throw away columns with 0 indicators
  dtm3 <- dtm2[ row_sums( dtm2 ) > 0, ]

  return( dtm3 )

}

create_model <- function( dtm, k ) {

   library(topicmodels)

   burnin = 1000
   iter = 1000
   keep = 50

   model <- LDA( dtm , k = k, method = "Gibbs", control =  list(burnin = burnin, iter = iter, keep = keep) )

   return( model )

}

check_fitness <- function( dtm , k ) {

  library(topicmodels)
  library(Rmpfr)

  burnin = 1000
  iter = 1000
  keep = 50

  model <- create_model( dtm , k )
  ll <- model@logLiks[ -c(1:(burnin/keep)) ]

  precision = 2000L
  llMed <- median( ll )
  ll = as.double( llMed - log( mean( exp( -mpfr(ll , prec = precision) + llMed ) ) ) )

  return( ll )

}


## from http://www.r-bloggers.com/a-link-between-topicmodels-lda-and-ldavis/

visualize_topicmodel <- function(fitted, corpus, doc_term){
    # Required packages
    library(topicmodels)
    library(dplyr)
    library(stringi)
    library(tm)
    library(LDAvis)

    # Find required quantities
    phi <- posterior(fitted)$terms %>% as.matrix
    theta <- posterior(fitted)$topics %>% as.matrix
    vocab <- colnames(phi)
    doc_length <- vector()
    for (i in 1:length(corpus)) {
        temp <- paste(corpus[[i]]$content, collapse = ' ')
        doc_length <- c(doc_length, stri_count(temp, regex = '\\S+'))
    }
    temp_frequency <- inspect(doc_term)
    freq_matrix <- data.frame(ST = colnames(temp_frequency),
                              Freq = colSums(temp_frequency))
    rm(temp_frequency)

    # Convert to json
    json_lda <- LDAvis::createJSON(phi = phi, theta = theta,
                            vocab = vocab,
                            doc.length = doc_length,
                            term.frequency = freq_matrix$Freq)

    return(json_lda)
}
source('topics.r')

for( path in commandArgs(trailingOnly=TRUE) ) {

   print( paste( "Working on" , path ) )

   unlink( paste( path , '*.rdata*', sep = '' ) ) ## remove all existing rdata in the folder

   dtm <- create_dtm( path )
   save( dtm , file = paste( path, 'dtm.rdata' , sep = '' ) )

}
# Run init.r before other scripts
rm(list=ls())
 # for use in R console.
 # set own relevant directory if working in R console, otherwise ignore if in terminal
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "./Script/0-1-Tanimoto_data.r
#           RData <- file = './RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "./Script/0-1-Interactions_sources.r
#           RData <- file = "./RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = './Script/1-Similarity_matrix.r'
#       RData <- file = './RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = './Script/2-1-Tanimoto_analysis.r'
#           RData <- file = './RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = './Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = './RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("./Script/tanimoto.r") # basic tanimoto similarity
source("./Script/tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("./Script/similarity_taxon.r") # similarity matrix for set of taxa
source("./Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("./Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("./Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/consumer_set_of_resource.r")
source("./Script/resource_set_of_consumer.r")
source("./Script/prediction_accuracy.r") #
source("./Script/prediction_accuracy_id.r") #
source("./Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("./Script/serialNext.r") # function to avoid overwriting existing files in temporary analyses folder
source("./Script/eplot.r") # empty plot for figure generation
source("./Script/tanimoto_analysis.r")
source("./Script/catalog_predictions.r") # computing prediction accuracy ~ # taxa in catalog
source("./Script/catalog_predictions_accuracy.r") # accuracy of predictions for accuracy ~ # taxa in catalog
source("./Script/full_algorithm.r") # full algorithm with similarity measurements included
source("./Script/similarity_full_algorithm.r") # similarity measurements for full algorithm
source("./Script/duplicate_row_col.r") # function to combine duplicated row and column names
source("./Script/bin_inter.r") # function to extract binary interaction from diet matrix


# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PSEUDOCODE:
# Parameters:
#   Kc                    Integer, how many consumer neighbors to select
#   Kr                    Integer, how many resource neighbors to select
#   S0                    Interction catalogue w/ 'taxa', 'taxonomy', 'resource set', 'non-resource set', 'consumer set', 'non-consumer set'
#   S1                    Set of taxa for which we wish to predict pairwise interactions
#   MW                    Mimimum weight to accept a candidate as a prey
#   Minimum_threshold     Minimum similarity threshold used to accept candidate species. Arbitrary at this point.
#
# Output
#   A matrix 'predictions' with columns
#     1. S1 taxa
#     2. empirical resource of S1 taxa
#     3. predicted resources of S1 taxa
#
# ------------
#
# predictions <- empty vector
#
#
# for consumers in S1
#     candidate_list <- empty vector
#
#     # 1. Empirical information in catalogue
#     resources_S1 = set of resources found in S0
#     empirical_resource <- empty vector
#
#     if length(resources_S1) > 0:
#         for resources in resources_S1
#             if resources in S1:
#                 add resources to empirical_resource
#             else:
#                 similar_resource <- pick K most similar resources in S1 based on taxonomy and set of consumers
#                     if similarity K + 1 = similarity K:
#                         random sample of similar resources with similarity K
#
#                 for resources' in similar_resource
#                     if all K similarity = 0:
#                         break out of loop
#                     else if resources' similarity = 0:
#                         NULL
#                     else if resources' similarity < minimum similarity threshold:
#                         NULL
#                     else if resources' in candidate_list:
#                         add weight = similarity between resources and resources' to resources' in candidate_list
#                     else: (not in candidate_list)
#                         add resources' to candidate_list w/ weight = similarity between resources and resources'
#
#         add empirical_resource to predictions matrix
#
#     # 2. Similar consumers information
#     similar_consumers <- pick K most similar consumers in S0 based on taxonomy and set of resources
#         if similarity K + 1 = similarity K:
#             random sample of similar consumers with similarity K
#
#     for consumers' in similar_consumers
#         if all K similarity = 0:
#             break out of loop
#         else if consumers' similarity = 0:
#             NULL
#
#         candidate_resources = resources' of consumers' in S0
#
#         for resources' in candidate_resources
#             if length(candidate_resources) == 0:
#                 break out of loop
#             else if candidate_resources == "":
#                 break out of loop
#             else if resources' = consumers: (does not allow for cannibalism. Should verify this at some point and allow for it, there are multiple instances of cannibalism in food webs)
#                 break out of loop
#             else if resources' in S1:
#                 if resources' in candidate_list:
#                     add weight = 1 to resources' in candidate_list
#                 else:
#                     add resources' w/ weight = 1 to candidate_list
#
#             else: (resources' not in S1)
#                 similar_resource <- pick K most similar resources in S1 based on taxonomy and set of consumers
#                     if similarity K + 1 = similarity K:
#                         random sample of similar resources with similarity K
#
#                 for resources' in similar_resource
#                     if all K similarity = 0:
#                         break out of loop
#                     else if resources' similarity = 0:
#                         NULL
#                     else if resources' similarity < minimum similarity threshold:
#                         NULL
#                     else if resources' in candidate_list:
#                         add weight = similarity between resources' and candidate_resources to resources' in candidate_list
#                     else: (not in candidate_list)
#                         add resources' to candidate_list w/ weight = similarity between resources' and candidate_resources
#
#     candidate_list <- choose candidate resources with weight >= MW
#     predictions <- add candidate_list to predictions
#
# return(predictions matrix)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/"),
                                     full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            stain_scp(user, host, self$dir, submit_dir)

            job_dir <- paste(submit_dir, self$dir, sep = "/")
            submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
            stain_ssh(user, host, submit_cmd)
        }
    ),
    private = list(
        options = NULL,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            stain_message_globals(globals)

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' ssh with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param cmds A sting of one or more commands to run on the remote host.
stain_ssh <- function(user, host, cmds = "") {
    if (!stain_ssh_key_exists()) {
        invisible(stain_ssh_key_gen())
    }

    remote_host <- paste(user, host, sep = "@")
    system(paste("ssh", remote_host, "-t -t -i ~/.ssh/stain_rsa",
                 paste0("\"", cmds, "\"")))
}


#' scp with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param from The local files or directory to copy from.
#'
#' @param to The directory in \code{<user>@<host>} to copy into.
stain_scp <- function(user, host, from, to) {
    if (!dir.exists(from) & !file.exists(from)) {
        stop(paste(from, "is an invalid path."))
    }

    recursive <- ifelse(dir.exists(from), "-r", "")
    to <- paste0(user, "@", host, ":", to)

    system(paste("scp -i ~/.ssh/stain_rsa", recursive, normalizePath(from), to))
}


#' Check for a Stain ssh key.
#'
#' @return If a public/private key pair exists in \code{~/.ssh/} with the name
#' \code{stain_rsa}, return TRUE, otherwise return FALSE.
stain_ssh_key_exists <- function() {
    return("stain_rsa" %in% list.files("~/.ssh/"))
}


#' Generate a Stain ssh key.
#'
#' A 4096 bit key will be generated and stored in \code{~/.ssh/} with the name
#' \code{stain_rsa}.
#'
#' @param overwrite Should an existing Stain ssh key be overwritten. Default
#' value is FALSE.
stain_ssh_key_gen <- function(overwrite = FALSE) {
    if (overwrite | !(overwrite | stain_ssh_key_exists())) {
        system("ssh-keygen -b 4096 -f ~/.ssh/stain_rsa -N ''")
    }
}


#' Create bash code for ssh setup.
#'
#' In order for a remote submission to work, an ssh public key for Stain must
#' be present in the remote host's \code{~/.ssh/authorized_keys} list. This
#' process requires two steps. 1) To \code{scp} the public key and 2) to add
#' the key to \code{~/.ssh/authorized_keys}. This function will autogenerate
#' the necessary bash code to complete these steps.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @return A single bash command to run.
#'
#' @export
stain_ssh_setup <- function(user, host) {
    remote_host <- paste(user, host, sep = "@")
    scp <- paste0("scp ~/.ssh/stain_rsa.pub", remote_host, ":~/.ssh/stain_rsa.pub")
    ssh <- paste0("ssh ", scp, " 'echo `cat ~/.ssh/stain_rsa.pub` >> ~/.ssh/authorized_keys'")
    cmd <- paste0(scp, " && ", ssh)

    if (Sys.info()["sysname"] == "Darwin") {
        cat("The bash command to setup remote submission has been copied to your clipboard. Run it in your terminal.")
        write.table(cmd, file = pipe("pbcopy"), sep = "\t",
                    col.names = F, row.names = F , quote = F)
    } else {
        cat("Run the following bash command in your terminal to setup remote submission:")
        cat(cmd)
    }
}
#' ssh with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param cmds A sting of one or more commands to run on the remote host.
stain_ssh <- function(user, host, cmds = "") {
    if (!stain_ssh_key_exists()) {
        invisible(stain_ssh_key_gen())
    }

    remote_host <- paste(user, host, sep = "@")
    system(paste("ssh -i ~/.ssh/stain_rsa", cmds))
}


#' scp with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param from The local files or directory to copy from.
#'
#' @param to The directory in \code{<user>@<host>} to copy into.
stain_scp <- function(user, host, from, to) {
    if (!dir.exists(from) & !file.exists(from)) {
        stop(paste(from, "is an invalid path."))
    }

    recursive <- ifelse(dir.exists(from), "-r", "")
    to <- paste0(user, "@", host, ":", to)

    system(paste("scp -i ~/.ssh/stain_rsa", recursive, normalizePath(from), to))
}


#' Check for a Stain ssh key.
#'
#' @return If a public/private key pair exists in \code{~/.ssh/} with the name
#' \code{stain_rsa}, return TRUE, otherwise return FALSE.
stain_ssh_key_exists <- function() {
    return("stain_rsa" %in% list.files("~/.ssh/"))
}


#' Generate a Stain ssh key.
#'
#' A 4096 bit key will be generated and stored in \code{~/.ssh/} with the name
#' \code{stain_rsa}.
#'
#' @param overwrite Should an existing Stain ssh key be overwritten. Default
#' value is FALSE.
stain_ssh_key_gen <- function(overwrite = FALSE) {
    if (overwrite | !(overwrite | stain_ssh_key_exists())) {
        system("ssh-keygen -b 4096 -f ~/.ssh/stain_rsa -N ''")
    }
}


#' Create bash code for ssh setup.
#'
#' In order for a remote submission to work, an ssh public key for Stain must
#' be present in the remote host's \code{~/.ssh/authorized_keys} list. This
#' process requires two steps. 1) To \code{scp} the public key and 2) to add
#' the key to \code{~/.ssh/authorized_keys}. This function will autogenerate
#' the necessary bash code to complete these steps.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @return A single bash command to run.
#'
#' @export
stain_ssh_setup <- function(user, host) {
    remote_host <- paste(user, host, sep = "@")
    scp <- paste0("scp ~/.ssh/stain_rsa.pub", remote_host, ":~/.ssh/stain_rsa.pub")
    ssh <- paste0("ssh ", scp, " 'echo `cat ~/.ssh/stain_rsa.pub` >> ~/.ssh/authorized_keys'")
    cmd <- paste0(scp, " && ", ssh)

    if (Sys.info()["sysname"] == "Darwin") {
        cat("The bash command to setup remote submission has been copied to your clipboard. Run it in your terminal.")
        write.table(cmd, file = pipe("pbcopy"), sep = "\t",
                    col.names = F, row.names = F , quote = F)
    } else {
        cat("Run the following bash command in your terminal to setup remote submission:")
        cat(cmd)
    }
}
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#    1. Evaluating similarity of consumers and resources
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
# // TODO: Evaluate similarity based on set of consumers for resources
# // TODO: Look into proximity graphs for better performance
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# LIBRARIES:
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/S0_catalog.RData")
# Weight values for 2-way similarity measurements
    wt <- seq(0, 1, by = 0.1)

# 1st is for similarity measured from set of resources and taxonomy, for consumers
    similarity.consumers <- vector('list',11)
    names(similarity.consumers) <- wt
    for(i in 1:length(wt)) {
        similarity.consumers[[i]] <- similarity_taxon(S0 = S0_catalog, wt = wt[i], taxa = 'consumer')
        save(x = similarity.consumers, file = "./RData/Similarity_consumers.RData")
    }
    save(x = similarity.consumers, file = "./RData/Similarity_consumers.RData")

# 2nd is for similarity measured from set of consumers and taxonomy, for resources
    similarity.resources <- vector('list',11)
    names(similarity.resources) <- wt
    for(i in 1:length(wt)) {
        similarity.resources[[i]] <- similarity_taxon(S0 = S0_catalog, wt = wt[i], taxa = 'resource')
        save(x = similarity.resources, file = "./RData/Similarity_resources.RData")
    }
    save(x = similarity.resources, file = "./RData/Similarity_resources.RData")
###############################################
### COMMONLY USED PACKAGES IN AIM R SCRIPTS ###
###############################################

#### THE CORE ####
install.packages("tidyverse")
## The tidyverse package includes a number of packages also listed below. It's a quick way to bootstrap up a new install of R.
## They include:
## broom, DBI, dplyr, forcats, ggplot2, haven, httr, hms, jsonlite, lubridate, magrittr, modelr, purrr, readr, readxl, stringr,
## tibble, rvest, tidyr, and xml2

#### DATA WRANGLING ####
install.packages(
  c(
    "dplyr", ## Notably useful for data frame manipulation with group_by(), summarize(), and mutate() and the piping operator %>%. Do you have a moment to hear the good news of our savior, piping?
    "tidyr", ## Lots of useful things, but specifically gather() and spread() for converting wide data frames into long ones and vice versa
    "broom", ## Get stats objects into tidy data frames. Not as common
    "stringr", ## All about character strings. Great for str_split() in particular, but the whole str_ family of functions are A+
    "RODBC", ## Allows R to pass SQL queries to Access databases and pull out the results
    "XLSX" ## Read in modern Excel workbooks and spreadsheets
  )
)

#### SPATIAL DATA ####
install.packages(
  c(
    "sp", ## Functions for manipulating spatial objects. If you want a Spatial _____ Data Frame, this is part of the deal
    "spsurvey", ## Contains plenty, but the most important to AIM is the GRTS function
    "rgeos", ## Additional spatial object functions
    "rgdal", ## Contains the mission critical readOGR() function that we read shapefiles in with
    "raster" ## Everything you didn't know you needed for dealing with rasters
  )
)

#### DATA VISUALIZATION ####
install.packages(
  c(
    "ggplot2", ## The go-to for figure generation. Most R-using scientists AND Nate Silver use it, so you should too
    "ggthemes", ## Quick themes to painlessly apply to figures from ggplot
    "ggmap", ## Mapping support for ggplot
    "RColorBrewer" ## All about making beautiful color palettes for maps and figures
  )
)

#### MISCELLANEOUS PACKAGES ####
## These are more ala carte. Pick and choose as you need them
install.packages("markdown") ## Generates documents with figures and everything based on your script, which means that if you change the data, the document changes to reflect it. POWERFUL.
install.packages("rJava") ## Chances are really good that this is already installed as a dependency for another package, but just to be safe, here it is
install.packages("devtools") ## For more granular control of the R environment when you need it, which may not be very often at all
install.packages("git2r") ## If you're going to use Git, this is important because it lets you use git from within R. It's a dependency of devtools though, so it may already be installed
install.packages("arcgisbinding") ## Young and finicky, but once you have it all installed (an ordeal) you should be able to read from and write to file geodatabases from R
install.packages("gridExtra") ## Lets you make grid objects that you can place ggplot figures into. May occasionally be preferable to faceting in ggplot, but rarely
install.packages("shiny") ## Required for working with Shiny tools in any form. Can be maddening
install.packages("purrr") ## Really, really useful for writing functions, particularly those that fail gracefully
install.packages("gstat") ## For spatial and spatio-temporal geostatistical modelling and simulation
install.packages("foreach") ## Parallel looping structures. Sarah McCord's thesis work required this
install.packages("snow") ## If you're doing distributed computing across multiple machines, grab this
install.packages("vegan") ## Multivariate analysis of things like vegetation communities
tanimoto_analysis <- function(min.tx, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, blind = FALSE) {
    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    load("./RData/S0_catalog.RData")

    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon
                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog

                        if(similarity == 'both') { # For similarity matrices already evaluated
                            similarity.consumer <- similarity.consumers[[i]]
                            similarity.resource <- similarity.resources[[i]]
                        } else if(similarity == 'consumer') {
                            similarity.consumer <- similarity.consumers[[i]]
                        } else if (similarity == 'resource') {
                            similarity.resource <- similarity.resources[[i]]
                        }

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                              S0[S1[k], 'consumer'] <- ""
                              S0[S1[k], 'non-consumer'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                                consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                        resource = interactions[, 'resource'],
                                                                        inter_type = interactions[, 'inter'])


                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                }
                                for(k in 1:nrow(consumer_set)) {
                                  S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                  S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.consumer,
                                                                                taxa = 'consumer')

                            similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.resource,
                                                                                taxa = 'resource')

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.consumer = similarity.consumer,
                                                                                    similarity.resource = similarity.resource,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.consumer, similarity.resource)
                        iteration <- iteration + 1
                        setTxtProgressBar(pb, iteration)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values

        }#m
    }#n
    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
catalog_predictions <- function(min.tx = 45, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, percent_remove = 0, nb_iter = 1, comm_id = FALSE, community) {

    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    load("./RData/S0_catalog.RData")

    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        if(comm_id == FALSE) {
            to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        } else { # comm_id = TRUE
            to.delete <- which(!Cm %in% community)
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        }

    # Setting up lists to store the results
    # weights
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        #Minimum weight
        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

        #Number of iterations
        iter <- vector('list', nb_iter)
            for(i in 1:nb_iter) {
                iter[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- iter
        names(Tanimoto_analysis) <- seq(1,nb_iter)
        remove(iter)


        # Percent remove in communities
        pc_rm <- vector('list', length(percent_remove))
            for(i in 1:length(percent_remove)) {
                pc_rm[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- pc_rm
        names(Tanimoto_analysis) <- percent_remove
        remove(pc_rm)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(percent_remove) * nb_iter * length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(p in 1:length(percent_remove)){
        percent_rm <- percent_remove[p]
        for(o in 1:nb_iter){
            for(n in 1:length(MW)) {
                mw <- MW[n]
                for(m in 1:length(K.values)) {

                    # Tanimoto analysis with different weights for different communities
                        # Parameters:
                            Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                            Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                            # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                        #   wt  Weight of traits in similarity measurement
                        #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                        #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                        # Output:
                        #   A vector of sets of resources for each taxon
                        for(i in 1:length(WT)){ #1st loop for all types of wt values
                            wt <- WT[i]
                            for(j in 1:length(Cm)) { #2nd loop for all C[i]
                                S1 <- communities[[j]]
                                S0 <- S0_catalog

                                if(similarity == 'both') { # For similarity matrices already evaluated
                                    similarity.consumer <- similarity.consumers[[i]]
                                    similarity.resource <- similarity.resources[[i]]
                                } else if(similarity == 'consumer') {
                                    similarity.consumer <- similarity.consumers[[i]]
                                } else if (similarity == 'resource') {
                                    similarity.resource <- similarity.resources[[i]]
                                }

                                # setting up the iterative process to evaluate the accuracy ~ # taxa in catalog
                                # removing a certain percentage of the # of species for which there are interactions as consumers described in the original food web.

                                # inter_Cm <- unique(subset(interactions_sources[, 'consumer'], interactions_sources[, 'source'] == Cm[j] & interactions_sources[, 'inter'] == "1")) # Species for which there are interactions as consumer in Cm[j]

                                interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3] # interaction catalog without interactions coming from Cm[j]

                                # inter_Cm2 <- unique(interactions[which(interactions[, 'consumer'] %in% inter_Cm), 'consumer']) # consumers in Cm[j] for which information is still available in catalog after deletion of Cm[j] from catalog

                                #Removing a percentage of consumers described in catalog
                                    # sample_iter <- sample(x = inter_Cm2, size = round((percent_rm / 100) * length(inter_Cm2)), replace = FALSE)
                                    sample_iter <- sample(x = S1, size = round((percent_rm / 100) * length(S1)), replace = FALSE) # To use if removing a percent of all taxa in original web

                                    if(length(sample_iter) == 0) {
                                        S1_no_mod <- seq(1,length(S1))
                                    } else {
                                        for(k in 1:length(sample_iter)) {
                                          S0[sample_iter[k], 'resource'] <- ""
                                          S0[sample_iter[k], 'non-resource'] <- ""
                                          S0[sample_iter[k], 'consumer'] <- ""
                                          S0[sample_iter[k], 'non-consumer'] <- ""
                                        }
                                        S1_no_mod <- which(!S1 %in% sample_iter)
                                    }

                                # 2. Preexisting information kept to inform algorithm
                                    if(length(S1_no_mod) == 0) {
                                        NULL
                                    } else {
                                    # Only modifying those that are loosing data from the catalogue, less time
                                        to.change <- numeric()
                                        for(k in 1:length(S1_no_mod)) {
                                            to.change <- c(to.change, which(interactions[, 'consumer'] == S1[S1_no_mod[k]]), which(interactions[, 'resource'] == S1[S1_no_mod[k]]))
                                        }
                                        to.change <- unique(to.change)

                                    # Modifying sets of resources and non-resources for taxa in S1_no_mod
                                        interactions <- interactions[to.change, ]
                                        rownames(interactions) <- seq(1,nrow(interactions))
                                        resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                                  resource = interactions[, 'resource'],
                                                                                  inter_type = interactions[, 'inter'])

                                        consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                                resource = interactions[, 'resource'],
                                                                                inter_type = interactions[, 'inter'])


                                    # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                        for(k in 1:nrow(resource_set)) {
                                          S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                          S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                        }
                                        for(k in 1:nrow(consumer_set)) {
                                          S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                          S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                        }
                                    remove(interactions, resource_set, to.change)
                                    }#if

                                # Recalculate similarity
                                    similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.consumer,
                                                                                        taxa = 'consumer')

                                    similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.resource,
                                                                                        taxa = 'resource')

                                # Predicting interactions
                                    Tanimoto_analysis[[p]][[o]][[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                            Kr = Kr,
                                                                                            S0 = S0,
                                                                                            S1 = S1,
                                                                                            MW = mw,
                                                                                            similarity.consumer = similarity.consumer,
                                                                                            similarity.resource = similarity.resource,
                                                                                            minimum_threshold = minimum_threshold)

                                save(x = Tanimoto_analysis, file = file.to.save)
                                remove(S0, S1, similarity.consumer, similarity.resource)
                                iteration <- iteration + 1
                                setTxtProgressBar(pb, iteration)
                            }#2nd loop for all C[i]

                            save(x = Tanimoto_analysis, file = file.to.save)
                            remove(wt)

                        }#1st loop for all types of wt values
                }#m
            }#n
        }#o
    }#p
    #Saving number of species in original web vs catalog once web removed
    # percent_original <- length(inter_Cm2) / length(inter_Cm)
    # x <- c(percent_original, length(inter_Cm), length(inter_Cm2))
    # file.to.save2 <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis_pc_tx.RData")
    # save(x = x, file = file.to.save2)

    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2.8 Example with southern St. Lawrence EwE model for mid-1980s
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "./RawData/South_St_Lawrence_EwE.RData"
#   Script  <- file = "Script/2-8_St_Lawrence_ex.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REFERENCE:
#   Savenkoff, to add
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
library(stringr)
load("./RawData/South_St_Lawrence_EwE.RData")
SSL <- South_St_Lawrence

SSL[[2]][which(SSL[[2]] > 0)] <- 1
rownames(SSL[[2]]) <- colnames(SSL[[2]]) <- SSL[[3]]

sp_SSL <- matrix(ncol = 3, nrow = 29, data = NA, dimnames = list(c(), c('ACCR','SP','FG')))

sp_SSL[,1] <- c('WHA','HAS','HOS','GRS','HSE','SEA','LCO','SCO','LGH','SAP','LAP','FLO','SKA','RED','LDF','SDF','CAP','LPF','PISF','PLSF','SHR','LCRU','ECH','MOL','POL','OBI','LZOO','SZOO','PHY')

sp_SSL[,3] <- c('Cetaceans',
'Harp seals',
'Hooded seals',
'Grey seals',
'Harbour seals',
'Seabirds',
'Atlantic cod',
'Atlantic cod',
'Greenland halibut',
'American plaice',
'American plaice',
'Flounders',
'Skates',
'Redfish',
'Large demersal feeders',
'Small demersal feeders',
'Capelin',
'Large pelagic feeders',
'Piscivorous small pelagic feeders',
'Planktivorous small pelagic feeders',
'Shrimp',
'Large crustaceans',
'Echinoderms',
'Molluscs',
'Polychates',
'Other benthic invertebrates',
'Large zooplankton',
'Small zooplankton',
'Phytoplankton')



sp_SSL[,2] <- c('Balaenoptera physalus - Balaenoptera acutorostrata - Megaptera novaeangliae - Phocoena phocoena - Lagenorhynchus acutus - Lagenorhynchus albirostris',
'Pagophilus groenlandicus',
'Cystophora cristata',
'Halichoerus grypus',
'Phoca vitulina',
'Phalacrocorax carbo - Phalacrocorax auritus - Larus delawarensis - Larus argentatus - Larus marinus - Sterna hirundo - Sterna paradisaea - Cepphus grylle - Oceanodroma leucorhoa - Morus bassanus - Rissa tridactyla - Uria aalge - Alca torda - Fratercula arctica',
'Gadus morhua',
'Gadus morhua',
'Reinhardtius hippoglossoides',
'Hippoglossoides platessoides',
'Hippoglossoides platessoides',
'Limanda ferruginea - Glyptocephalus cynoglossus - Pseudopleuronectes americanus',
'Amblyraja radiata - Malacoraja senta - Leucoraja ocellata',
'Sebastes mentella - Sebastes fasciatus',
'Urophycis tenuis - Melanogrammus aeglefinus - Centroscyllium fabricii - Anarhichas - Cyclopterus lumpus - Lycodes - Macrouridae - Zoarcidae - Lophius americanus - Hippoglossus hippoglossus',
'Myoxocephalus - Tautogolabrus adspersus - Zoarces americanus',
'Mallotus villosus',
'Squalus acanthias - Pollachius virens - Merluccius bilinearis - Cetorhinus maximus',
'Scomber scombrus - Illex illecebrosus',
'Clupea harengus - Scomberesox saurus - Gonatus',
'Argis dentata - Eualus macilentus - Eualus gaimardi - Pandalus montagui',
'Chionoecetes opilio - Hyas',
'Echinarachnius parma - Stronglyocentrotus pallidus - Ophiura robusta',
'Mesodesma deauratum - Cyrtodaria siliqua',
'Parexogone hebes',
'Miscellaneous crustaceans', #to remove OBI
'Euphausiids - chaetognaths', # to remove LZOO
'Oithona similis - Temora longicornis - Pseudocalanus - Calanus finmarchicus',
'Chaetoceros affinis - Chaetoceros - Leptocylindrus minimus - Thalassiiosira nordenskioldii - Thalassiiosira - Fragilariopsis')

# Removing portions of the web for which there is no taxa usable for the analysis, 'OBI' & 'LZOO'
SSL[[2]] <- SSL[[2]][-which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO'), -which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO')]
sp_SSL <- sp_SSL[-which(sp_SSL[,1] == 'OBI' | sp_SSL[,1] == 'LZOO'), ]

S1 <- unique(unlist(str_split(sp_SSL[,2], ' - ')))

load("./RData/S0_catalog.RData")
S0 <- S0_catalog


# Have to extract taxonomy for speies that are not found in S0
S1_missing <- which(!S1 %in% S0[,1])

S1_add_S0 <- matrix(ncol = 6, nrow = length(S1_missing), data = "", dimnames = list(c(), c("taxon", "taxonomy", "resource", "non-resource", "consumer", "non-consumer")))

S1_add_S0[, 'taxon'] <- S1[S1_missing]

S1_add_S0[, 'taxonomy'] <- c('Animalia | Chordata | Mammalia | Cetartiodactyla | Delphinidae | Lagenorhynchus | Lagenorhynchus acutus',
'Animalia | Chordata | Mammalia | Carnivora | Phocidae | Halichoerus | Halichoerus grypus',
'Animalia | Chordata | Procellariiformes | Hydrobatidae | Oceanodroma | Oceanodroma leucorhoa',
'Animalia | Chordata | Aves | Pelecaniformes | Sulidae | Morus | Morus bassanus',
'Animalia | Chordata | Aves | Charadriiformes | Alcidae | Alca | Alca torda',
'Animalia | Chordata | Elasmobranchii | Rajiformes | Rajidae | Malacoraja | Malacoraja senta',
'Animalia | Chordata | Elasmobranchii | Squaliformes | Etmopteridae | Centroscyllium | Centroscyllium fabricii',
'Animalia | Arthropoda | Malacostraca | Decapoda | Crangonidae | Argis | Argis dentata',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus macilentus',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus gaimardii',
'Animalia | Echinodermata | Echinoidea | Camarodonta | Strongylocentrotidae | Strongylocentrotus | Strongylocentrotus pallidus',
'Animalia | Mollusca | Bivalvia | Imparidentia | Mesodesmatidae | Mesodesma | Mesodesma deauratum',
'Animalia | Mollusca | Bivalvia | Adapedonta | Hiatellidae | Cyrtodaria | Cyrtodaria siliqua',
'Animalia | Annelida | Polychaeta | Phyllodocida | Syllidae | Parexogone | Parexogone hebes',
'Chromista | Ochrophyta | Bacillariophyceae | Chaetocerotanae | Chaetocerotaceae | Chaetoceros | Chaetoceros affinis',
'Chromista | Ochrophyta | Bacillariophyceae | Leptocylindrales | Leptocylindraceae | Leptocylindrus | Leptocylindrus minimus',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | Thalassiosira nordenskioeldii',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | NA')

 S0 <- rbind(S0, S1_add_S0) #binding missing taxonomies
 rownames(S0) <- S0[, 'taxon']


# #Thinning down catalogue
# S02 <- S0[unique(c(which(S0[, 'resource'] != ""), which(S0[, 'consumer'] != ""))), ]
#
# S1_missing2 <- which(!S1 %in% S02[,1]) #after culling
# S1_missing3 <- S1_missing2[which(!S1_missing2 %in% S1_missing)] #taxo to keep
# S1_add_S0 <- rbind(S1_add_S0, S0[which(S0[, 'taxon'] %in% S1[S1_missing3]), ])
# rownames(S1_add_S0) <- NULL
# S0 <- rbind(S02, S1_add_S0)
# remove(S02,S1_missing3,S1_missing2,S1_missing)

# Predicting interactions
SSL_predict <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.3)

# SSL_predict2 <- full_algorithm(Kc = 4,
#                             Kr = 4,
#                             S0 = S0,
#                             S1 = S1,
#                             MW = 1,
#                             wt = 0.5,
#                             minimum_threshold = 0.2)

SSL_predict_mat <- prediction_matrix(S1 = S1, predictions = SSL_predict)
# SSL_predict_mat2 <- prediction_matrix(S1 = S1, predictions = SSL_predict2)
x <- SSL_predict_mat

for(i in 1:nrow(sp_SSL)) {
    Sx <- unique(unlist(str_split(sp_SSL[i,2], ' - ')))
    for(j in 1:length(Sx)){
        for(k in 1:length(S1))
        if(S1[k] %in% Sx == TRUE) {
            colnames(SSL_predict_mat)[k] <- rownames(SSL_predict_mat)[k] <- sp_SSL[i, 2]
            # colnames(SSL_predict_mat2)[k] <- rownames(SSL_predict_mat2)[k] <- sp_SSL[i, 2]
        }
    }
}

SSL_predict_mat_combine <- dupl_sp(SSL_predict_mat)
# SSL_predict_mat_combine2 <- dupl_sp(SSL_predict_mat2)

SSL_emp <- SSL[[2]]
colnames(SSL_emp) <- rownames(SSL_emp) <- sp_SSL[,2]
SSL_emp <-  dupl_sp(SSL_emp)

accuracy_SSL <- prediction_accuracy_id(predicted = SSL_predict_mat_combine, empirical = SSL_emp)
# accuracy_SSL2 <- prediction_accuracy_id(predicted = SSL_predict_mat_combine2, empirical = SSL_emp)
accuracy_SSL
# accuracy_SSL2

# for(i in 2:nrow(accuracy_SSL[[4]])) {
#     print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]))
# }
#
# for(i in 2:nrow(accuracy_SSL[[3]])) {
#     print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]))
# }


SSL_bin_inter <- bin_inter(SSL_predict_mat_combine)
# SSL_bin_inter2 <- bin_inter(SSL_predict_mat_combine2)
SSL_emp_bin <- bin_inter(SSL_emp)
SSL_bin_inter <- SSL_bin_inter[which(SSL_bin_inter[, 'FeedInter'] == '1'), ]
# SSL_bin_inter2 <- SSL_bin_inter2[which(SSL_bin_inter2[, 'FeedInter'] == '1'), ]
SSL_emp_bin <- SSL_emp_bin[which(SSL_emp_bin[, 'FeedInter'] == '1'), ]

# SSL species with interactions noted in catalogue
x <- which(S0[, 'taxon'] %in% S1)
length(which(S0[x,'resource'] != "" | S0[x,'consumer'] != ""))

id_c <- matrix(nrow = nrow(accuracy_SSL[[4]]), ncol = 2, data = NA, dimnames = list(c(), c('consumer','resource')))
for(i in 2:nrow(accuracy_SSL[[4]])) {
    id_c[i,1] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]
    id_c[i,2] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]]
}

id_b <- matrix(nrow = nrow(accuracy_SSL[[3]]), ncol = 2, data = NA, dimnames = list(c(), c('consumer','resource')))
for(i in 2:nrow(accuracy_SSL[[3]])) {
    id_b[i,1] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]
    id_b[i,2] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]]
}


pp <- which(SSL_emp_bin[,'Predator'] == "Scomber scombrus - Illex illecebrosus" | SSL_emp_bin[,'Prey'] == "Scomber scombrus - Illex illecebrosus")
cap <- which(SSL_emp_bin[,'Predator'] == "Mallotus villosus" | SSL_emp_bin[,'Prey'] == "Mallotus villosus")
SSL_emp_part <- SSL_emp_bin[unique(c(pp,cap)), ]


pp <- which(SSL_bin_inter[,'Predator'] == "Scomber scombrus - Illex illecebrosus" | SSL_bin_inter[,'Prey'] == "Scomber scombrus - Illex illecebrosus")

cap <- which(SSL_bin_inter[,'Predator'] == "Mallotus villosus" | SSL_bin_inter[,'Prey'] == "Mallotus villosus")
SSL_pred_part <- SSL_bin_inter[unique(c(pp,cap)), ]

for(i in 1:nrow(sp_SSL)){
    SSL_emp_part[which(SSL_emp_part[, 'Predator'] == sp_SSL[i,2]), 'Predator'] <- sp_SSL[i,3]
    SSL_emp_part[which(SSL_emp_part[, 'Prey'] == sp_SSL[i,2]), 'Prey'] <- sp_SSL[i,3]
    SSL_pred_part[which(SSL_pred_part[, 'Predator'] == sp_SSL[i,2]), 'Predator'] <- sp_SSL[i,3]
    SSL_pred_part[which(SSL_pred_part[, 'Prey'] == sp_SSL[i,2]), 'Prey'] <- sp_SSL[i,3]
}

unique(c(SSL_emp_part,SSL_pred_part))

SSL_pred_part <- gsub("1", "->",SSL_pred_part)
SSL_pred_part <- gsub("Skates", "1",SSL_pred_part)
SSL_pred_part <- gsub("Cetaceans", "2",SSL_pred_part)
SSL_pred_part <- gsub("Hooded seals", "3",SSL_pred_part)
SSL_pred_part <- gsub("Atlantic cod", "4",SSL_pred_part)
SSL_pred_part <- gsub("Grey seals", "5",SSL_pred_part)
SSL_pred_part <- gsub("Harp seals", "6",SSL_pred_part)
SSL_pred_part <- gsub("Seabirds", "7",SSL_pred_part)
SSL_pred_part <- gsub("Harbour seals", "8",SSL_pred_part)
SSL_pred_part <- gsub("Greenland halibut", "9",SSL_pred_part)
SSL_pred_part <- gsub("Piscivorous small pelagic feeders", "10",SSL_pred_part)
SSL_pred_part <- gsub("Redfish", "11",SSL_pred_part)
SSL_pred_part <- gsub("Large pelagic feeders", "12",SSL_pred_part)
SSL_pred_part <- gsub("Large demersal feeders", "13",SSL_pred_part)
SSL_pred_part <- gsub("Capelin", "14",SSL_pred_part)
SSL_pred_part <- gsub("Small demersal feeders","15",SSL_pred_part)
SSL_pred_part <- gsub("Planktivorous small pelagic feeders", "16",SSL_pred_part)
SSL_pred_part <- gsub("Small zooplankton", "17",SSL_pred_part)
SSL_pred_part <- gsub("Flounders", "18",SSL_pred_part)
SSL_pred_part <- gsub("Large crustaceans", "19",SSL_pred_part)
SSL_pred_part <- gsub("American plaice", "20",SSL_pred_part)
SSL_pred_part <- gsub("Shrimp", "21",SSL_pred_part)

SSL_emp_part <- gsub("1", "->",SSL_emp_part)
SSL_emp_part <- gsub("Skates", "1",SSL_emp_part)
SSL_emp_part <- gsub("Cetaceans", "2",SSL_emp_part)
SSL_emp_part <- gsub("Hooded seals", "3",SSL_emp_part)
SSL_emp_part <- gsub("Atlantic cod", "4",SSL_emp_part)
SSL_emp_part <- gsub("Grey seals", "5",SSL_emp_part)
SSL_emp_part <- gsub("Harp seals", "6",SSL_emp_part)
SSL_emp_part <- gsub("Seabirds", "7",SSL_emp_part)
SSL_emp_part <- gsub("Harbour seals", "8",SSL_emp_part)
SSL_emp_part <- gsub("Greenland halibut", "9",SSL_emp_part)
SSL_emp_part <- gsub("Piscivorous small pelagic feeders", "10",SSL_emp_part)
SSL_emp_part <- gsub("Redfish", "11",SSL_emp_part)
SSL_emp_part <- gsub("Large pelagic feeders", "12",SSL_emp_part)
SSL_emp_part <- gsub("Large demersal feeders", "13",SSL_emp_part)
SSL_emp_part <- gsub("Capelin", "14",SSL_emp_part)
SSL_emp_part <- gsub("Small demersal feeders", "15",SSL_emp_part)
SSL_emp_part <- gsub("Planktivorous small pelagic feeders", "16",SSL_emp_part)
SSL_emp_part <- gsub("Small zooplankton", "17",SSL_emp_part)
SSL_emp_part <- gsub("Flounders", "18",SSL_emp_part)
SSL_emp_part <- gsub("Large crustaceans", "19",SSL_emp_part)
SSL_emp_part <- gsub("American plaice", "20",SSL_emp_part)
SSL_emp_part <- gsub("Shrimp", "21",SSL_emp_part)

SSL_emp_part
SSL_pred_part

library(DiagrammeR)
grViz("

digraph boxes_and_circles{

    node [shape = box
            # fixedsize = TRUE
            # width = 2.5
            ]
            1 [label =  <Skates>]
            2 [label =  <Cetaceans>]
            3 [label =  <Hooded seals>]
            4 [label =  <Atlantic cod>]
            5 [label =  <Grey seals>]
            6 [label =  <Harp seals>]
            7 [label =  <Seabirds>]
            8 [label =  <Harbour seals>]
            9 [label =  <Greenland halibut>]
            10 [label =  <Piscivorous small<br/>pelagic feeders>]
            11 [label =  <Redfish>]
            12 [label =  <Large pelagic<br/>feeders>]
            13 [label =  <Large demersal<br/>feeders>]
            14 [label =  <Capelin>]
            15 [label =  <Small demersal<br/>feeders>]
            16 [label =  <Planktivorous small<br/>pelagic feeders>]
            17 [label =  <Small zooplankton>]
            18 [label =  <Flounders>]
            19 [label =  <Large crustaceans>]
            20 [label =  <American plaice>]
            21 [label =  <Shrimp>]

    edge [dir = back]
            7 -> 12 [color = 'transparent']
            7 -> 13 [color = 'transparent']
            7 -> 20 [color = 'transparent']
            7 -> 18 [color = 'transparent']
            7 -> 4 [color = 'transparent']
            8 -> 12 [color = 'transparent']
            8 -> 13 [color = 'transparent']
            8 -> 20 [color = 'transparent']
            8 -> 18 [color = 'transparent']
            8 -> 4 [color = 'transparent']
            12 -> 15 [color = 'transparent']
            12 -> 16 [color = 'transparent']
            13 -> 15 [color = 'transparent']
            13 -> 16 [color = 'transparent']
            20 -> 15 [color = 'transparent']
            20 -> 16 [color = 'transparent']
            18 -> 15 [color = 'transparent']
            18 -> 16 [color = 'transparent']
            4 -> 15 [color = 'transparent']
            4 -> 16 [color = 'transparent']
            15 -> 21 [color = 'transparent']
            15 -> 19 [color = 'transparent']
            16 -> 21 [color = 'transparent']
            16 -> 19 [color = 'transparent']

            2 -> 11 [color = 'transparent']
            2 -> 1 [color = 'transparent']
            2 -> 9 [color = 'transparent']
            3 -> 11 [color = 'transparent']
            3 -> 1 [color = 'transparent']
            3 -> 9 [color = 'transparent']
            5 -> 11 [color = 'transparent']
            5 -> 1 [color = 'transparent']
            5 -> 9 [color = 'transparent']
            6 -> 11 [color = 'transparent']
            6 -> 1 [color = 'transparent']
            6 -> 9 [color = 'transparent']

            #Empirical
            1 -> 10 [color = 'green']
            2 -> 10 [color = 'green']
            3 -> 10 [color = 'black']
            4 -> 10 [color = 'green']
            5 -> 10 [color = 'black']
            6 -> 10 [color = 'black']
            7 -> 10 [color = 'black']
            8 -> 10 [color = 'green']
            9 -> 10 [color = 'black']
            10 -> 16 [color = 'green']
            10 -> 14 [color = 'green']
            10 -> 17 [color = 'green']
            11 -> 10 [color = 'black']
            12 -> 10 [color = 'green']
            13 -> 10 [color = 'green']
            1 -> 14 [color = 'green']
            2 -> 14 [color = 'green']
            3 -> 14 [color = 'green']
            4 -> 14 [color = 'green']
            5 -> 14 [color = 'green']
            14 -> 17 [color = 'green']
            15 -> 14 [color = 'green']
            6 -> 14 [color = 'green']
            7 -> 14 [color = 'green']
            8 -> 14 [color = 'green']
            9 -> 14 [color = 'green']
            11 -> 14 [color = 'green']
            12 -> 14 [color = 'green']
            13 -> 14 [color = 'green']

            # #Predictions

            18 -> 10 [color = 'blue']
            15 -> 10 [color = 'blue']
            10 -> 1 [color = 'blue']
            10 -> 21 [color = 'blue']
            10 -> 4 [color = 'blue']
            10 -> 18 [color = 'blue']
            10 -> 15 [color = 'blue']
            10 -> 7 [color = 'blue']
            10 -> 8 [color = 'blue']
            10 -> 10 [color = 'blue']
            10 -> 12 [color = 'blue']
            10 -> 13 [color = 'blue']
            19 -> 14 [color = 'blue']
            16 -> 14 [color = 'blue']
            20 -> 14 [color = 'blue']
            18 -> 14 [color = 'blue']
            14 -> 14 [color = 'blue']
}
")


# #Empirical
# 1 -> 10 [color = 'blue']
# 2 -> 10 [color = 'blue']
# 3 -> 10 [color = '']
# 4 -> 10 [color = 'blue']
# 5 -> 10 [color = '']
# 6 -> 10 [color = '']
# 7 -> 10 [color = '']
# 8 -> 10 [color = '']
# 9 -> 10 [color = '']
# 10 -> 16 [color = '']
# 10 -> 14 [color = '']
# 10 -> 17 [color = '']
# 11 -> 10 [color = '']
# 12 -> 10 [color = '']
# 13 -> 10 [color = '']
# 1 -> 14 [color = '']
# 2 -> 14 [color = '']
# 3 -> 14 [color = '']
# 4 -> 14 [color = '']
# 5 -> 14 [color = '']
# 14 -> 17 [color = '']
# 15 -> 14 [color = '']
# 6 -> 14 [color = '']
# 7 -> 14 [color = '']
# 8 -> 14 [color = '']
# 9 -> 14 [color = '']
# 11 -> 14 [color = '']
# 12 -> 14 [color = '']
# 13 -> 14 [color = '']

# #Predictions
# 1 -> 10
# 2 -> 10
# 4 -> 10
# 18 -> 10
# 15 -> 10
# 8 -> 10
# 10 -> 1
# 10 -> 21
# 10 -> 16
# 10 -> 4
# 10 -> 18
# 10 -> 14
# 10 -> 15
# 10 -> 17
# 10 -> 7
# 10 -> 8
# 10 -> 10
# 10 -> 12
# 10 -> 13
# 12 -> 10
# 13 -> 10
# 1 -> 14
# 2 -> 14
# 19 -> 14
# 16 -> 14
# 3 -> 14
# 4 -> 14
# 5 -> 14
# 20 -> 14
# 18 -> 14
# 14 -> 14
# 14 -> 17
# 15 -> 14
# 6 -> 14
# 7 -> 14
# 8 -> 14
# 9 -> 14
# 11 -> 14
# 12 -> 14
# 13 -> 14

# Load package
library(networkD3)
# Plot
simpleNetwork(as.data.frame(SSL_bin_inter[, c(1,3)]))
simpleNetwork(as.data.frame(SSL_emp_bin[, c(1,3)]))
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:
    filename <- 'Multiple_parameters'
    min.tx = 45
    K.values = c(2,4,6,8)
    MW = c(1,3,5)
    WT = c(0,0.3,0.6,1)
    blind = FALSE
    minimum_threshold = 0.3
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/Tanimoto_data.RData")
load("./RData/interactions_source.RData")
load("./RData/S0_catalog.RData")
suppressMessages(load("./RData/Similarity.matrices.RData")) # For similarity matrices already evaluated

# setting up the analyses for multiple communities
# Data for communities on which to test the algorithm
    Cm <- unique(interactions_sources[, 'source'])
    communities <- vector("list", length(Cm))
    names(communities) <- Cm

    # Taxa list per community to predict
        for(i in 1:length(communities)) {
            Ci <- which(interactions_sources[, 'source'] == Cm[i])
            S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

            if(length(which(!S1 %in% S0_catalog)) > 0) {
                print('Taxa in C[i] are not all included in taxa list S0')
                break
            }

            communities[[i]] <- S1
        }

# Substracting GloBI interactions for this portion
    Cm.lg <- numeric()
    for(i in 1:length(communities)) {
        Cm.lg <- c(Cm.lg,length(communities[[i]]))
    }

    to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

    Cm <- Cm[-to.delete]
    for(i in rev(to.delete)) {
        communities[[i]] <- NULL
    }
    names(communities) <- Cm

# Setting up lists to store the results
    wt.init <- wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
    wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
    for(i in rev(wt.remove)) {
        similarity.matrices[[i]] <- NULL
    }

    sim.wt <- names(similarity.matrices)
    Tanimoto_analysis <- vector("list",length(sim.wt))
    names(Tanimoto_analysis) <- sim.wt
    for(i in 1:length(sim.wt)) {
        Tanimoto_analysis[[i]] <- vector("list", length(Cm))
        names(Tanimoto_analysis[[i]]) <- Cm
    }

# List to store results of multiple K values
K <- vector("list", length(K.values))
for(i in 1:length(K.values)) {
    K[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- K
names(Tanimoto_analysis) <- K.values
remove(K)

min.wt <- vector("list", length(MW))
for(i in 1:length(MW)) {
    min.wt[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- min.wt
names(Tanimoto_analysis) <- MW
remove(min.wt)

file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
save(x = Tanimoto_analysis, file = file.to.save)

init.time <- Sys.time()
for(n in 1:length(MW)) {
    mw <- MW[n]
    for(m in 1:length(K.values)) {

        # Tanimoto analysis with different weights for different communities
            # Parameters:
                Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
            #   wt  Weight of traits in similarity measurement
            #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
            #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

            # Output:
            #   A vector of sets of resources for each taxon

            for(i in 1:length(WT)){ #1st loop for all types of wt values
                wt <- WT[i]
                pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                for(j in 1:length(Cm)) { #2nd loop for all C[i]
                    S1 <- communities[[j]]
                    S0 <- S0_catalog
                    similarity.matrix <- similarity.matrices[[i]]

                    # Two choices here:
                    #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                    #   2. The analysis takes into account preexisting information already contained in the catalogue

                    # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                    if(blind == TRUE) {
                        for(k in 1:length(S1)) {
                          S0[S1[k], 'resource'] <- ""
                          S0[S1[k], 'non-resource'] <- ""
                        }

                    # 2. Preexisting information kept to inform algorithm
                    } else { # blind == FALSE

                        interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                        # Only modifying those that are loosing data from the catalogue, less time
                            to.change <- numeric()
                            for(k in 1:length(S1)) {
                                to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                            }
                            to.change <- unique(to.change)

                        # Modifying sets of resources and non-resources for taxa in S1
                            interactions <- interactions[to.change, ]
                            rownames(interactions) <- seq(1,nrow(interactions))
                            resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                      resource = interactions[, 'resource'],
                                                                      inter_type = interactions[, 'inter'])

                        # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                            for(k in 1:nrow(resource_set)) {
                              S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                              S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                            }
                        remove(interactions, resource_set, to.change)
                    } #if blind or not blind

                    # Recalculate similarity
                        similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                            S1 = S1,
                                                                            wt = wt,
                                                                            similarity.matrix = similarity.matrix)

                    # Predicting interactions
                        Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                Kr = Kr,
                                                                                S0 = S0,
                                                                                S1 = S1,
                                                                                MW = mw,
                                                                                similarity.matrix = similarity.matrix,
                                                                                minimum_threshold = minimum_threshold)

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(S0, S1, similarity.matrix)
                    setTxtProgressBar(pb, j)
                }#2nd loop for all C[i]

                save(x = Tanimoto_analysis, file = file.to.save)
                remove(wt)

            }#1st loop for all types of wt values
            close(pb)
    }#m
}#n
print(Sys.time() - init.time)
save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))


# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 50, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(WT) * length(K.values)) + 0.5, labels = FALSE, las = 1, pos = -0.02) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, nb.pts, by = length(WT)) + 0.5, labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)

            abline(v = seq(length(WT)+0.5,nb.pts-length(WT)+0.5,by = length(WT)), col = "grey", lty = 2)
            abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
            abline(h = c(1.125,2.375), col = "black", lty = 2)


            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'MW']) + as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,48), accuracy_mean[, 4][,1] - accuracy_mean[, 4][, 2]+it, seq(1,48), accuracy_mean[, 4][, 1] + accuracy_mean[, 4][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,48), y = accuracy_mean[, 4][, 1]+it, cex = 0.75, pch = 22, col = col[i])
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
#Solve for optimal lobby effort under DGH97-style model with obj fcn W + e

#reserve space for loop output
tau = seq(0.001,.166,0.001) #this will be counter variable in loop
PSx = matrix(NA,length(tau),1)
CSx = matrix(NA,length(tau),1)
TR = matrix(NA,length(tau),1)
PSy = matrix(NA,length(tau),1)
CSy = matrix(NA,length(tau),1)

#calculate producer surplus, consumer surplus, tariff revenue for each possible
#value of the tariff on the grid (just above zero to prohibitive tariff 1/6)
for (j in 1:length(tau)) {
  t = tau[j]

  PSx[j] = ((2 +2*t)^2)/49
  CSx[j] = .5*((3 -4*t)^2)/49
  TR[j] = (t - 6*t^2)/7
  CSy[j] = ((3 +3*t)^2)/98
  PSy[j] = ((4 -3*t)^2)/98
}

#Calculations for when lobby has all the bargaining power

#calculate government welfare when tau = 0 (baseline)
b = ((2 +2*0)^2)/49 + .5*((3 -4*0)^2)/49 + (0 - 6*0^2)/7 + ((3 +3*0)^2)/98 + ((4 -3*0)^2)/98
W = PSx + CSx + TR + CSy + PSy  #social welfare
e = ((b - W)/PSx)^5             #gov't indifference condition when WG = W + e
pi = PSx - e                    #net profits

value = max(pi) #the value at which profits are maximized (over non-negative values)
ind = which.max(pi) #the location at which profits are maximized
RC = arrayInd(ind,c(dim(pi),dim(pi))) #row/column version of maximand location


#Calculations for when government has all the bargaining power
bl = ((2 +2*0)^2)/49           #baseline for lobby: profits when tau = 0
e = PSx - bl                   #effort level giving all excess profits over tau=0 to gov't

g = e^.9*PSx                   #little g(e) function to add to social welfare
G = W + e^.9*PSx               #gov't welfare a la DGH97
plot(G)

value = max(G) #the value at which profits are maximized (over non-negative values)
ind = which.max(G) #the location at which profits are maximized
RC = arrayInd(ind,c(dim(G),dim(G))) #row/column version of maximand locationfull_algorithm <- function(Kc, Kr, S0, S1, MW, wt, minimum_threshold) {
    # Two-way Tanimoto Algorithm
    # ===========================

    # Parameters:
    #   Kc  Integer, how many neighbors to select for consumers
    #   Kr  Integer, how many neighbors to select for resources
    #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
    #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name
    #   MW  Mimimum weight to accept a candidate as a prey

    # Output
    #   A vector of sets (the preys for each species)

    predictions <- matrix(nrow = length(S1), ncol = 3, data = "", dimnames = list(c(S1), c('consumer','resource_empirical','resource_predictions'))) # empty object for resource predictions
    predictions[, 'consumer'] <- S1

    pb <- txtProgressBar(min = 0,max = length(S1), style = 3)
    for(i in 1:length(S1)) { # loop through each taxon in S1
        candidates <- matrix(nrow = 0, ncol = 2, dimnames = list(c(), c('resource', 'weight')), data = NA) # empty matrix for resource candidate list for S1[i], with taxon name and weight
        resources.S1 <- unlist(strsplit(S0[S1[i], 'resource'], " \\|\\ ")) # resources of S1[i]

        # Add resources that are already listed as resources for S1[i] in predictions[, 'resource_empirical'] or
        # Find similar resources to resources for S1[i] in S1
        if(length(resources.S1) > 0) {
            empirical <- character()
            for(j in 1:length(resources.S1)) { #loop through empirical resources for S1
                if(resources.S1[j] %in% S1) {
                    empirical <- c(empirical, resources.S1[j]) # observed resource found in S1 are automatically added to the column resource_empirical
                } else { # selecting Kr most similar resources in S1
                    # Let's assume for this part that we are not compiling a different similarity measure for predators and preys.

                    similarity.resources <- similarity_full_algorithm(S0 = unique(S0[which(S0[, 'taxon'] %in% S1 | S0[, 'taxon'] == resources.S1[j]), ]), # S1 in S0 + resource for which similarity has to be measured
                                                                    S1 = resources.S1[j], # resource for which similarity has to be measured
                                                                    wt = wt,
                                                                    taxa = 'resource')

                    similar.resource <- matrix(nrow = nrow(similarity.resources), ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources
                    similar.resource[, 'resource'] <- names(similarity.resources[order(similarity.resources, decreasing = TRUE), ])
                    similar.resource[, 'similarity'] <- similarity.resources[order(similarity.resources, decreasing = TRUE)]
                    to.remove <- which(similar.resource[,'resource'] == resources.S1[j])
                    if(length(to.remove) > 0){ #remove resoures.S1[j] in case it gets through (just keeping it consistant with other similarity evaluation further down in the catalogue, even though it is not necessary in this portion)
                        similar.resource <- similar.resource[-which(similar.resource[,'resource'] == resources.S1[j]), ]
                    }

                    # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
                    if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {
                        same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])
                        similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]
                        similar.resource <- similar.resource[1:Kr, ]
                    } else {
                        similar.resource <- similar.resource[1:Kr, ]
                    }# if for random draw

                    for(l in 1:Kr) { # extracting resource candidates
                        if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break
                            break
                        } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                            NULL
                            # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed
                        } else if(similar.resource[l, 'similarity'] < minimum_threshold) {
                            NULL
                        } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add resource' with wt to its weight
                          candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])
                        } else {
                              candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it resource' with wt to its weight
                        }#if3
                    }#l
                }#if
            }#j
            predictions[S1[i], 'resource_empirical'] <- paste(empirical, collapse = ' | ')
        }#if1

        # Identify similar consumers to S1[i]

        similarity.consumers <- similarity_full_algorithm(S0 = S0,
                                                        S1 = S1[i],
                                                        wt = wt,
                                                        taxa = 'consumer')

        similar.consumer <- matrix(nrow = nrow(similarity.consumers), ncol = 2, dimnames = list(c(), c('consumer','similarity')), data = NA) # importing K nearest neighbors consumers
        similar.consumer[, 'consumer'] <- names(similarity.consumers[order(similarity.consumers, decreasing = TRUE), ])
        similar.consumer[, 'similarity'] <- similarity.consumers[order(similarity.consumers, decreasing = TRUE)]
        to.remove <- which(similar.consumer[,'consumer'] == S1[i])
        if(length(to.remove) > 0){ #remove resoures.S1[j] in case it gets through (just keeping it consistant with other similarity evaluation further down in the catalogue, even though it is not necessary in this portion)
            similar.consumer <- similar.consumer[-which(similar.consumer[,'consumer'] == S1[i]), ]
        }

        # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
        if(similar.consumer[Kc+1, 'similarity'] == similar.consumer[Kc, 'similarity']) {
            same.similarity <- which(similar.consumer[, 'similarity'] == similar.consumer[Kc, 'similarity'])
            similar.consumer[same.similarity, ] <- similar.consumer[sample(same.similarity), ]
            similar.consumer <- similar.consumer[1:Kc, ]
        } else {
            similar.consumer <- similar.consumer[1:Kc, ]
        }# if for random draw


        # Est-ce que la valeur de similarité a de l'importance pour l'attribution des proies?
        # If yes, we could add an argument call wt_predator.
          # if(wt_predator == FALSE) {
          #   resources <- unique of all prey species of all similar predators
          # } else {}

        for(j in 1:Kc) { #loop through consumers

            if(all.equal(similar.consumer[, 'similarity'], rep('0',Kc)) == TRUE) { # if similarities all == 0, break
                break
            } else if(similar.consumer[j, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                NULL
            } else if(similar.consumer[j, 'similarity'] < minimum_threshold) {
                NULL
            } else {

                # It's possible that consumers in the list have high taxonomic similarity, but no recorded resource
                candidate.resource <- unlist(strsplit(S0[similar.consumer[j, 'consumer'], 'resource'], " \\|\\ ")) # list of resources for consumer j
                # candidate.resource <- candidate.resource[(candidate.resource %in% resources.S1) == FALSE] # substracting candidate resources that are already listed as resources for S1[i] and hence considered in the preceding code segment

                for(k in 1:length(candidate.resource)) { # loop through resources of consumer j
                    if(length(candidate.resource) == 0) { # if candidate resource list is empty, break
                        break
                    } else if(candidate.resource[1] == "") { # if candidate list is an empty vector "", break
                        break
                    } else if(candidate.resource[k] == S1[i]) {
                    #   #// FIXME: if candidate resource is taxon for which predictions are being made, break (unless we want to allow CANIBALISM). Add argument for cannibalism allowed or not
                         NULL
                    } else if((candidate.resource[k] %in% S1) == TRUE) {
                        if((candidate.resource[k] %in% candidates[, 'resource']) == TRUE) {# if candidate is already in candidate list, add 1 to its weight
                            candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight']) + 1
                        } else {
                            candidates <- rbind(candidates, c(candidate.resource[k], 1)) # if candidate is not in the list, add it with 1 to its weight
                        }#if2

                    } else {
                        similarity.resources <- similarity_full_algorithm(S0 = unique(S0[which(S0[, 'taxon'] %in% S1 | S0[, 'taxon'] == candidate.resource[k]), ]), # S1 in S0 + resource for which similarity has to be measured
                                                                        S1 = candidate.resource[k], # resource for which similarity has to be measured
                                                                        wt = wt,
                                                                        taxa = 'resource')

                        similar.resource <- matrix(nrow = nrow(similarity.resources), ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources
                        similar.resource[, 'resource'] <- names(similarity.resources[order(similarity.resources, decreasing = TRUE), ])
                        similar.resource[, 'similarity'] <- similarity.resources[order(similarity.resources, decreasing = TRUE)]
                        to.remove <- which(similar.resource[,'resource'] == candidate.resource[k])
                        if(length(to.remove) > 0){ #remove resoures.S1[j] in case it gets through (just keeping it consistant with other similarity evaluation further down in the catalogue, even though it is not necessary in this portion)
                            similar.resource <- similar.resource[-which(similar.resource[,'resource'] == candidate.resource[k]), ]
                        }

                        # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
                        if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {
                            same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])
                            similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]
                            similar.resource <- similar.resource[1:Kr, ]
                        } else {
                            similar.resource <- similar.resource[1:Kr, ]
                        }# if for random draw

                        for(l in 1:Kr) { # extracting resource candidates
                            if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break
                                break
                            } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                                NULL
                                # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed
                            } else if(similar.resource[l, 'similarity'] < minimum_threshold) {
                                NULL
                            } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add 1 to its weight
                              candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])
                            } else {
                                  candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it with its weight = similarity
                            }#if3
                        }#l
                    } #if1
                }#k
            }#if
        }#j

        candidates <- candidates[which(candidates[, 'weight'] >= MW), ] # remove candidates with a weight below MW
        if(is.matrix(candidates) == TRUE) { #if it's a vector, there's only one predicted resource, no need to order
            candidates[order(candidates[, 'weight']), ] # sorts candidates according to their weight
            predictions[S1[i], 'resource_predictions'] <- paste(candidates[, 'resource'], collapse = ' | ')
        } else {
          predictions[S1[i], 'resource_predictions'] <- paste(candidates['resource'], collapse = ' | ')
        }#if
    setTxtProgressBar(pb, i)
    }#i
    close(pb)
    return(predictions)
}#full algorithm function
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2.8 Example with southern St. Lawrence EwE model for mid-1980s
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "./RawData/South_St_Lawrence_EwE.RData"
#   Script  <- file = "Script/2-8_St_Lawrence_ex.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REFERENCE:
#   Savenkoff, to add
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
library(stringr)
load("./RawData/South_St_Lawrence_EwE.RData")
SSL <- South_St_Lawrence

SSL[[2]][which(SSL[[2]] > 0)] <- 1
rownames(SSL[[2]]) <- colnames(SSL[[2]]) <- SSL[[3]]

sp_SSL <- matrix(ncol = 3, nrow = 29, data = NA, dimnames = list(c(), c('ACCR','SP','FG')))

sp_SSL[,1] <- c('WHA','HAS','HOS','GRS','HSE','SEA','LCO','SCO','LGH','SAP','LAP','FLO','SKA','RED','LDF','SDF','CAP','LPF','PISF','PLSF','SHR','LCRU','ECH','MOL','POL','OBI','LZOO','SZOO','PHY')

sp_SSL[,3] <- c('Cetaceans',
'Harp seals',
'Hooded seals',
'Grey seals',
'Harbour seals',
'Seabirds',
'Atlantic cod',
'Atlantic cod',
'Greenland halibut',
'American plaice',
'American plaice',
'Flounders',
'Skates',
'Redfish',
'Large demersal feeders',
'Small demersal feeders',
'Capelin',
'Large pelagic feeders',
'Piscivorous small pelagic feeders',
'Planktivorous small pelagic feeders',
'Shrimp',
'Large crustaceans',
'Echinoderms',
'Molluscs',
'Polychates',
'Other benthic invertebrates',
'Large zooplankton',
'Small zooplankton',
'Phytoplankton')



sp_SSL[,2] <- c('Balaenoptera physalus - Balaenoptera acutorostrata - Megaptera novaeangliae - Phocoena phocoena - Lagenorhynchus acutus - Lagenorhynchus albirostris',
'Pagophilus groenlandicus',
'Cystophora cristata',
'Halichoerus grypus',
'Phoca vitulina',
'Phalacrocorax carbo - Phalacrocorax auritus - Larus delawarensis - Larus argentatus - Larus marinus - Sterna hirundo - Sterna paradisaea - Cepphus grylle - Oceanodroma leucorhoa - Morus bassanus - Rissa tridactyla - Uria aalge - Alca torda - Fratercula arctica',
'Gadus morhua',
'Gadus morhua',
'Reinhardtius hippoglossoides',
'Hippoglossoides platessoides',
'Hippoglossoides platessoides',
'Limanda ferruginea - Glyptocephalus cynoglossus - Pseudopleuronectes americanus',
'Amblyraja radiata - Malacoraja senta - Leucoraja ocellata',
'Sebastes mentella - Sebastes fasciatus',
'Urophycis tenuis - Melanogrammus aeglefinus - Centroscyllium fabricii - Anarhichas - Cyclopterus lumpus - Lycodes - Macrouridae - Zoarcidae - Lophius americanus - Hippoglossus hippoglossus',
'Myoxocephalus - Tautogolabrus adspersus - Zoarces americanus',
'Mallotus villosus',
'Squalus acanthias - Pollachius virens - Merluccius bilinearis - Cetorhinus maximus',
'Scomber scombrus - Illex illecebrosus',
'Clupea harengus - Scomberesox saurus - Gonatus',
'Argis dentata - Eualus macilentus - Eualus gaimardi - Pandalus montagui',
'Chionoecetes opilio - Hyas',
'Echinarachnius parma - Stronglyocentrotus pallidus - Ophiura robusta',
'Mesodesma deauratum - Cyrtodaria siliqua',
'Parexogone hebes',
'Miscellaneous crustaceans', #to remove OBI
'Euphausiids - chaetognaths', # to remove LZOO
'Oithona similis - Temora longicornis - Pseudocalanus - Calanus finmarchicus',
'Chaetoceros affinis - Chaetoceros - Leptocylindrus minimus - Thalassiiosira nordenskioldii - Thalassiiosira - Fragilariopsis')

# Removing portions of the web for which there is no taxa usable for the analysis, 'OBI' & 'LZOO'
SSL[[2]] <- SSL[[2]][-which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO'), -which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO')]
sp_SSL <- sp_SSL[-which(sp_SSL[,1] == 'OBI' | sp_SSL[,1] == 'LZOO'), ]

S1 <- unique(unlist(str_split(sp_SSL[,2], ' - ')))

load("./RData/Tanimoto_data.RData")
# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
# Format interaction catalogue to fit this table format
    S0 <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
    S0[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
        S0[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
    }


# Have to extract taxonomy for speies that are not found in S0
S1_missing <- which(!S1 %in% S0[,1])

S1_add_S0 <- matrix(ncol = 6, nrow = length(S1_missing), data = "", dimnames = list(c(), c("taxon", "taxonomy", "resource", "non-resource", "consumer", "non-consumer")))

S1_add_S0[, 'taxon'] <- S1[S1_missing]

S1_add_S0[, 'taxonomy'] <- c('Animalia | Chordata | Mammalia | Cetartiodactyla | Delphinidae | Lagenorhynchus | Lagenorhynchus acutus',
'Animalia | Chordata | Mammalia | Carnivora | Phocidae | Halichoerus | Halichoerus grypus',
'Animalia | Chordata | Procellariiformes | Hydrobatidae | Oceanodroma | Oceanodroma leucorhoa',
'Animalia | Chordata | Aves | Pelecaniformes | Sulidae | Morus | Morus bassanus',
'Animalia | Chordata | Aves | Charadriiformes | Alcidae | Alca | Alca torda',
'Animalia | Chordata | Elasmobranchii | Rajiformes | Rajidae | Malacoraja | Malacoraja senta',
'Animalia | Chordata | Elasmobranchii | Squaliformes | Etmopteridae | Centroscyllium | Centroscyllium fabricii',
'Animalia | Arthropoda | Malacostraca | Decapoda | Crangonidae | Argis | Argis dentata',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus macilentus',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus gaimardii',
'Animalia | Echinodermata | Echinoidea | Camarodonta | Strongylocentrotidae | Strongylocentrotus | Strongylocentrotus pallidus',
'Animalia | Mollusca | Bivalvia | Imparidentia | Mesodesmatidae | Mesodesma | Mesodesma deauratum',
'Animalia | Mollusca | Bivalvia | Adapedonta | Hiatellidae | Cyrtodaria | Cyrtodaria siliqua',
'Animalia | Annelida | Polychaeta | Phyllodocida | Syllidae | Parexogone | Parexogone hebes',
'Chromista | Ochrophyta | Bacillariophyceae | Chaetocerotanae | Chaetocerotaceae | Chaetoceros | Chaetoceros affinis',
'Chromista | Ochrophyta | Bacillariophyceae | Leptocylindrales | Leptocylindraceae | Leptocylindrus | Leptocylindrus minimus',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | Thalassiosira nordenskioeldii',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | NA')

 S0 <- rbind(S0, S1_add_S0) #binding missing taxonomies
 rownames(S0) <- S0[, 'taxon']


# #Thinning down catalogue
# S02 <- S0[unique(c(which(S0[, 'resource'] != ""), which(S0[, 'consumer'] != ""))), ]
#
# S1_missing2 <- which(!S1 %in% S02[,1]) #after culling
# S1_missing3 <- S1_missing2[which(!S1_missing2 %in% S1_missing)] #taxo to keep
# S1_add_S0 <- rbind(S1_add_S0, S0[which(S0[, 'taxon'] %in% S1[S1_missing3]), ])
# rownames(S1_add_S0) <- NULL
# S0 <- rbind(S02, S1_add_S0)
# remove(S02,S1_missing3,S1_missing2,S1_missing)

# Predicting interactions
SSL_predict <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.3)

SSL_predict2 <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.2)

SSL_predict_mat <- prediction_matrix(S1 = S1, predictions = SSL_predict)
SSL_predict_mat2 <- prediction_matrix(S1 = S1, predictions = SSL_predict2)
x <- SSL_predict_mat

for(i in 1:nrow(sp_SSL)) {
    Sx <- unique(unlist(str_split(sp_SSL[i,2], ' - ')))
    for(j in 1:length(Sx)){
        for(k in 1:length(S1))
        if(S1[k] %in% Sx == TRUE) {
            colnames(SSL_predict_mat)[k] <- rownames(SSL_predict_mat)[k] <- sp_SSL[i, 2]
            colnames(SSL_predict_mat2)[k] <- rownames(SSL_predict_mat2)[k] <- sp_SSL[i, 2]
        }
    }
}

SSL_predict_mat_combine <- dupl_sp(SSL_predict_mat)
SSL_predict_mat_combine2 <- dupl_sp(SSL_predict_mat2)

SSL_emp <- SSL[[2]]
colnames(SSL_emp) <- rownames(SSL_emp) <- sp_SSL[,2]
SSL_emp <-  dupl_sp(SSL_emp)

accuracy_SSL <- prediction_accuracy_id(predicted = SSL_predict_mat_combine, empirical = SSL_emp)
accuracy_SSL2 <- prediction_accuracy_id(predicted = SSL_predict_mat_combine2, empirical = SSL_emp)
accuracy_SSL
accuracy_SSL2

# for(i in 2:nrow(accuracy_SSL[[4]])) {
#     print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]))
# }
#
# for(i in 2:nrow(accuracy_SSL[[3]])) {
#     print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]))
# }


SSL_bin_inter <- bin_inter(SSL_predict_mat_combine)
SSL_bin_inter2 <- bin_inter(SSL_predict_mat_combine2)
SSL_emp_bin <- bin_inter(SSL_emp)
SSL_bin_inter <- SSL_bin_inter[which(SSL_bin_inter[, 'FeedInter'] == '1'), ]
SSL_bin_inter2 <- SSL_bin_inter2[which(SSL_bin_inter2[, 'FeedInter'] == '1'), ]
SSL_emp_bin <- SSL_emp_bin[which(SSL_emp_bin[, 'FeedInter'] == '1'), ]

# SSL species with interactions noted in catalogue
x <- which(S0[, 'taxon'] %in% S1)
length(which(S0[x,'resource'] != "" | S0[x,'consumer'] != ""))

id_c <- matrix(nrow = nrow(accuracy_SSL[[4]]), ncol = 2, data = NA, dimnames = list(c(), c('consumer','resource')))
for(i in 2:nrow(accuracy_SSL[[4]])) {
    id_c[i,1] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]
    id_c[i,2] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]]
}

id_b <- matrix(nrow = nrow(accuracy_SSL[[3]]), ncol = 2, data = NA, dimnames = list(c(), c('consumer','resource')))
for(i in 2:nrow(accuracy_SSL[[3]])) {
    id_b[i,1] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]
    id_b[i,2] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]]
}



# Load package
library(networkD3)
# Plot
simpleNetwork(as.data.frame(SSL_bin_inter[, c(1,3)]))
simpleNetwork(as.data.frame(SSL_emp_bin[, c(1,3)]))





# remplace , par ' - '
# remplacer les noms de colonnes et lignes
# combiner duplicatas
# rouler fonction du catalogue pour séparer les lignes et colonnes qui ont plusieurs entrées?
# faire l'analyse en séparant toutes les espèces listées, puis comparer l'analyse divisée, compartimenter les résultats (combiner les interactions des espèces qui sont dans un compartiment), et la réseau présenté dans l'article à partir de la matrice de diète.


pp <- which(SSL_emp_bin[,'Predator'] == "Scomber scombrus - Illex illecebrosus" | SSL_emp_bin[,'Prey'] == "Scomber scombrus - Illex illecebrosus")
cap <- which(SSL_emp_bin[,'Predator'] == "Mallotus villosus" | SSL_emp_bin[,'Prey'] == "Mallotus villosus")
SSL_emp_part <- SSL_emp_bin[unique(c(pp,cap)), ]


pp <- which(SSL_bin_inter[,'Predator'] == "Scomber scombrus - Illex illecebrosus" | SSL_bin_inter[,'Prey'] == "Scomber scombrus - Illex illecebrosus")

cap <- which(SSL_bin_inter[,'Predator'] == "Mallotus villosus" | SSL_bin_inter[,'Prey'] == "Mallotus villosus")
SSL_pred_part <- SSL_bin_inter[unique(c(pp,cap)), ]

for(i in 1:nrow(sp_SSL)){
    SSL_emp_part[which(SSL_emp_part[, 'Predator'] == sp_SSL[i,2]), 'Predator'] <- sp_SSL[i,3]
    SSL_emp_part[which(SSL_emp_part[, 'Prey'] == sp_SSL[i,2]), 'Prey'] <- sp_SSL[i,3]
    SSL_pred_part[which(SSL_pred_part[, 'Predator'] == sp_SSL[i,2]), 'Predator'] <- sp_SSL[i,3]
    SSL_pred_part[which(SSL_pred_part[, 'Prey'] == sp_SSL[i,2]), 'Prey'] <- sp_SSL[i,3]
}

unique(c(SSL_emp_part,SSL_pred_part))

SSL_pred_part <- gsub("1", "->",SSL_pred_part)
SSL_pred_part <- gsub("Skates", "1",SSL_pred_part)
SSL_pred_part <- gsub("Cetaceans", "2",SSL_pred_part)
SSL_pred_part <- gsub("Hooded seals", "3",SSL_pred_part)
SSL_pred_part <- gsub("Atlantic cod", "4",SSL_pred_part)
SSL_pred_part <- gsub("Grey seals", "5",SSL_pred_part)
SSL_pred_part <- gsub("Harp seals", "6",SSL_pred_part)
SSL_pred_part <- gsub("Seabirds", "7",SSL_pred_part)
SSL_pred_part <- gsub("Harbour seals", "8",SSL_pred_part)
SSL_pred_part <- gsub("Greenland halibut", "9",SSL_pred_part)
SSL_pred_part <- gsub("Piscivorous small pelagic feeders", "10",SSL_pred_part)
SSL_pred_part <- gsub("Redfish", "11",SSL_pred_part)
SSL_pred_part <- gsub("Large pelagic feeders", "12",SSL_pred_part)
SSL_pred_part <- gsub("Large demersal feeders", "13",SSL_pred_part)
SSL_pred_part <- gsub("Capelin", "14",SSL_pred_part)
SSL_pred_part <- gsub("Small demersal feeders","15",SSL_pred_part)
SSL_pred_part <- gsub("Planktivorous small pelagic feeders", "16",SSL_pred_part)
SSL_pred_part <- gsub("Small zooplankton", "17",SSL_pred_part)
SSL_pred_part <- gsub("Flounders", "18",SSL_pred_part)
SSL_pred_part <- gsub("Large crustaceans", "19",SSL_pred_part)
SSL_pred_part <- gsub("American plaice", "20",SSL_pred_part)
SSL_pred_part <- gsub("Shrimp", "21",SSL_pred_part)

SSL_emp_part <- gsub("1", "->",SSL_emp_part)
SSL_emp_part <- gsub("Skates", "1",SSL_emp_part)
SSL_emp_part <- gsub("Cetaceans", "2",SSL_emp_part)
SSL_emp_part <- gsub("Hooded seals", "3",SSL_emp_part)
SSL_emp_part <- gsub("Atlantic cod", "4",SSL_emp_part)
SSL_emp_part <- gsub("Grey seals", "5",SSL_emp_part)
SSL_emp_part <- gsub("Harp seals", "6",SSL_emp_part)
SSL_emp_part <- gsub("Seabirds", "7",SSL_emp_part)
SSL_emp_part <- gsub("Harbour seals", "8",SSL_emp_part)
SSL_emp_part <- gsub("Greenland halibut", "9",SSL_emp_part)
SSL_emp_part <- gsub("Piscivorous small pelagic feeders", "10",SSL_emp_part)
SSL_emp_part <- gsub("Redfish", "11",SSL_emp_part)
SSL_emp_part <- gsub("Large pelagic feeders", "12",SSL_emp_part)
SSL_emp_part <- gsub("Large demersal feeders", "13",SSL_emp_part)
SSL_emp_part <- gsub("Capelin", "14",SSL_emp_part)
SSL_emp_part <- gsub("Small demersal feeders", "15",SSL_emp_part)
SSL_emp_part <- gsub("Planktivorous small pelagic feeders", "16",SSL_emp_part)
SSL_emp_part <- gsub("Small zooplankton", "17",SSL_emp_part)
SSL_emp_part <- gsub("Flounders", "18",SSL_emp_part)
SSL_emp_part <- gsub("Large crustaceans", "19",SSL_emp_part)
SSL_emp_part <- gsub("American plaice", "20",SSL_emp_part)
SSL_emp_part <- gsub("Shrimp", "21",SSL_emp_part)

SSL_emp_part
SSL_pred_part

library(DiagrammeR)
grViz("

digraph boxes_and_circles{

    node [shape = box
            # fixedsize = TRUE
            # width = 2.5
            ]
            1 [label =  <Skates>]
            2 [label =  <Cetaceans>]
            3 [label =  <Hooded seals>]
            4 [label =  <Atlantic cod>]
            5 [label =  <Grey seals>]
            6 [label =  <Harp seals>]
            7 [label =  <Seabirds>]
            8 [label =  <Harbour seals>]
            9 [label =  <Greenland halibut>]
            10 [label =  <Piscivorous small<br/>pelagic feeders>]
            11 [label =  <Redfish>]
            12 [label =  <Large pelagic<br/>feeders>]
            13 [label =  <Large demersal<br/>feeders>]
            14 [label =  <Capelin>]
            15 [label =  <Small demersal<br/>feeders>]
            16 [label =  <Planktivorous small<br/>pelagic feeders>]
            17 [label =  <Small zooplankton>]
            18 [label =  <Flounders>]
            19 [label =  <Large crustaceans>]
            20 [label =  <American plaice>]
            21 [label =  <Shrimp>]

    edge [dir = back]
            7 -> 12 [color = 'transparent']
            7 -> 13 [color = 'transparent']
            7 -> 20 [color = 'transparent']
            7 -> 18 [color = 'transparent']
            7 -> 4 [color = 'transparent']
            8 -> 12 [color = 'transparent']
            8 -> 13 [color = 'transparent']
            8 -> 20 [color = 'transparent']
            8 -> 18 [color = 'transparent']
            8 -> 4 [color = 'transparent']
            12 -> 15 [color = 'transparent']
            12 -> 16 [color = 'transparent']
            13 -> 15 [color = 'transparent']
            13 -> 16 [color = 'transparent']
            20 -> 15 [color = 'transparent']
            20 -> 16 [color = 'transparent']
            18 -> 15 [color = 'transparent']
            18 -> 16 [color = 'transparent']
            4 -> 15 [color = 'transparent']
            4 -> 16 [color = 'transparent']
            15 -> 21 [color = 'transparent']
            15 -> 19 [color = 'transparent']
            16 -> 21 [color = 'transparent']
            16 -> 19 [color = 'transparent']

            2 -> 11 [color = 'transparent']
            2 -> 1 [color = 'transparent']
            2 -> 9 [color = 'transparent']
            3 -> 11 [color = 'transparent']
            3 -> 1 [color = 'transparent']
            3 -> 9 [color = 'transparent']
            5 -> 11 [color = 'transparent']
            5 -> 1 [color = 'transparent']
            5 -> 9 [color = 'transparent']
            6 -> 11 [color = 'transparent']
            6 -> 1 [color = 'transparent']
            6 -> 9 [color = 'transparent']

            #Empirical
            1 -> 10 [color = 'green']
            2 -> 10 [color = 'green']
            3 -> 10 [color = 'black']
            4 -> 10 [color = 'green']
            5 -> 10 [color = 'black']
            6 -> 10 [color = 'black']
            7 -> 10 [color = 'black']
            8 -> 10 [color = 'green']
            9 -> 10 [color = 'black']
            10 -> 16 [color = 'green']
            10 -> 14 [color = 'green']
            10 -> 17 [color = 'green']
            11 -> 10 [color = 'black']
            12 -> 10 [color = 'green']
            13 -> 10 [color = 'green']
            1 -> 14 [color = 'green']
            2 -> 14 [color = 'green']
            3 -> 14 [color = 'green']
            4 -> 14 [color = 'green']
            5 -> 14 [color = 'green']
            14 -> 17 [color = 'green']
            15 -> 14 [color = 'green']
            6 -> 14 [color = 'green']
            7 -> 14 [color = 'green']
            8 -> 14 [color = 'green']
            9 -> 14 [color = 'green']
            11 -> 14 [color = 'green']
            12 -> 14 [color = 'green']
            13 -> 14 [color = 'green']

            # #Predictions

            18 -> 10 [color = 'blue']
            15 -> 10 [color = 'blue']
            10 -> 1 [color = 'blue']
            10 -> 21 [color = 'blue']
            10 -> 4 [color = 'blue']
            10 -> 18 [color = 'blue']
            10 -> 15 [color = 'blue']
            10 -> 7 [color = 'blue']
            10 -> 8 [color = 'blue']
            10 -> 10 [color = 'blue']
            10 -> 12 [color = 'blue']
            10 -> 13 [color = 'blue']
            19 -> 14 [color = 'blue']
            16 -> 14 [color = 'blue']
            20 -> 14 [color = 'blue']
            18 -> 14 [color = 'blue']
            14 -> 14 [color = 'blue']
}
")


# #Empirical
# 1 -> 10 [color = 'blue']
# 2 -> 10 [color = 'blue']
# 3 -> 10 [color = '']
# 4 -> 10 [color = 'blue']
# 5 -> 10 [color = '']
# 6 -> 10 [color = '']
# 7 -> 10 [color = '']
# 8 -> 10 [color = '']
# 9 -> 10 [color = '']
# 10 -> 16 [color = '']
# 10 -> 14 [color = '']
# 10 -> 17 [color = '']
# 11 -> 10 [color = '']
# 12 -> 10 [color = '']
# 13 -> 10 [color = '']
# 1 -> 14 [color = '']
# 2 -> 14 [color = '']
# 3 -> 14 [color = '']
# 4 -> 14 [color = '']
# 5 -> 14 [color = '']
# 14 -> 17 [color = '']
# 15 -> 14 [color = '']
# 6 -> 14 [color = '']
# 7 -> 14 [color = '']
# 8 -> 14 [color = '']
# 9 -> 14 [color = '']
# 11 -> 14 [color = '']
# 12 -> 14 [color = '']
# 13 -> 14 [color = '']

# #Predictions
# 1 -> 10
# 2 -> 10
# 4 -> 10
# 18 -> 10
# 15 -> 10
# 8 -> 10
# 10 -> 1
# 10 -> 21
# 10 -> 16
# 10 -> 4
# 10 -> 18
# 10 -> 14
# 10 -> 15
# 10 -> 17
# 10 -> 7
# 10 -> 8
# 10 -> 10
# 10 -> 12
# 10 -> 13
# 12 -> 10
# 13 -> 10
# 1 -> 14
# 2 -> 14
# 19 -> 14
# 16 -> 14
# 3 -> 14
# 4 -> 14
# 5 -> 14
# 20 -> 14
# 18 -> 14
# 14 -> 14
# 14 -> 17
# 15 -> 14
# 6 -> 14
# 7 -> 14
# 8 -> 14
# 9 -> 14
# 11 -> 14
# 12 -> 14
# 13 -> 14
S0 <- matrix(nrow = 12, ncol = 4, data = NA, dimnames = list(c(),c('taxon','taxonomy','resource','consumer')))
S0[1, ] <- c('1', 'a | b | c', '2 | 3 | 12', '4')
S0[2, ] <- c('2', 'e | f | g', '', '1 | 5')
S0[3, ] <- c('3', 'i | j | k', '', '5')
S0[4, ] <- c('4', 'm | n | o', '1 | 5', '')
S0[5, ] <- c('5', 'a | b | d', '8 | 9', '4')
S0[6, ] <- c('6', 'i | q | r', '2 | 8', '4')
S0[7, ] <- c('7', 'e | f | h', '', '1 | 6')
S0[8, ] <- c('8', 's | t | u', '', '5 | 6')
S0[9, ] <- c('9', 's | t | v', '', '5')
S0[10, ] <- c('10', 'i | j | l', '', '')
S0[11, ] <- c('11', 'm | n | p', '', '')
S0[12, ] <- c('12', 'q | r | s', '', '1')
rownames(S0) <- S0[,'taxon']

S1 <- c('1','9','10','11','12')

example0 <- full_algorithm(Kc = 2, Kr = 2, S0 = S0, S1 = S1, MW = 0, wt = 0, minimum_threshold = 0)
example05 <- full_algorithm(Kc = 2, Kr = 2, S0 = S0, S1 = S1, MW = 0, wt = 0.5, minimum_threshold = 0)
example1 <- full_algorithm(Kc = 2, Kr = 2, S0 = S0, S1 = S1, MW = 0, wt = 1, minimum_threshold = 0)

example0
example05
example1

cons0 <- similarity_taxon(S0 = S0, wt = 0, taxa = 'consumer')
res0 <- similarity_taxon(S0 = S0, wt = 0, taxa = 'resource')
taxo <- similarity_taxon(S0 = S0, wt = 1, taxa = 'consumer')

sim.example <- matrix(nrow = nrow(cons0), ncol = ncol(cons0))
sim.example[upper.tri(sim.example)] <- cons0[upper.tri(cons0)]
sim.example[lower.tri(sim.example)] <- taxo[lower.tri(taxo)]
diag(sim.example) <- S0[, 'taxon']


library(DiagrammeR)
grViz("

digraph boxes_and_circles{

    node [shape = box
            fixedsize = TRUE
            width = 2]
    1 [label = <<I>T<SUB>1</SUB></I>>]
    2 [label = <<I>T<SUB>9</SUB></I>>]
    3 [label = <<I>T<SUB>10</SUB></I>>]
    4 [label = <<I>T<SUB>11</SUB></I>>]
    5 [label = <<I>T<SUB>12</SUB></I>>]

1 -> 2
1 -> 5

}
")

grViz("
digraph boxes_and_circles{

    node [shape = box
            fixedsize = TRUE
            width = 0.2
            fontsize = 9
            color = white]
    6 [label = <<I>T<SUB>1</SUB></I>>]
    7 [label = <<I>T<SUB>9</SUB></I>>]
    8 [label = <<I>T<SUB>10</SUB></I>>]
    9 [label = <<I>T<SUB>11</SUB></I>>]
    10 [label = <<I>T<SUB>12</SUB></I>>]

    1 [label = <<I>T<SUB>1</SUB></I>>]
    2 [label = <<I>T<SUB>9</SUB></I>>]
    3 [label = <<I>T<SUB>10</SUB></I>>]
    4 [label = <<I>T<SUB>11</SUB></I>>]
    5 [label = <<I>T<SUB>12</SUB></I>>]

    edge [dir = back]
    1 -> 2 [arrowsize = 0.5]
    1 -> 3 [arrowsize = 0.5]
    1 -> 5 [arrowsize = 0.5]
    3 -> 2 [arrowsize = 0.5]
    3 -> 5 [arrowsize = 0.5]
    4 -> 1 [arrowsize = 0.5]
    5 -> 2 [arrowsize = 0.5]

    6 -> 7 [arrowsize = 0.5]
    6 -> 8 [color = 'white'; arrowsize = 0]
    6 -> 10 [arrowsize = 0.5]
    8 -> 7 [color = 'white'; arrowsize = 0]
    8 -> 10 [color = 'white'; arrowsize = 0]
    9 -> 6 [color = 'white'; arrowsize = 0]
    10 -> 7 [color = 'white'; arrowsize = 0]


    graph [ranksep = 0.15
            rank = source
            # rankdir = LR
            ]
}
")
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/"),
                                     full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        }
    ),
    private = list(
        options = NULL,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            stain_message_globals(globals)

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
library(staticdocs)

sd_section(
  "Connecting to Spark",
  "Functions for installing Spark components and managing connections to Spark.",
  c(
    "spark_config",
    "spark_connect",
    "spark_disconnect",
    "spark_install",
    "spark_log",
    "spark_web"
  )
)

sd_section(
  "Reading and Writing Data",
  "Functions for reading and writing Spark DataFrames.",
  c(
    "spark_read_csv",
    "spark_read_json",
    "spark_read_parquet",
    "spark_write_csv",
    "spark_write_json",
    "spark_write_parquet",
    "sdf-saveload"
  )
)

sd_section(
  "dplyr Interface",
  "Functions implementing a dplyr backend for Spark DataFrames.",
  c(
    "copy_to",
    "tbl_cache",
    "tbl_uncache"
  )
)

sd_section(
  "Spark DataFrames",
  "Functions for maniplulating Spark DataFrames.",
  c(
    "na.replace",
    "sdf_copy_to",
    "sdf_mutate",
    "sdf_partition",
    "sdf_predict",
    "sdf_read_column",
    "sdf_register",
    "sdf_sample",
    "sdf_sort",
    "sdf_with_unique_id"
  )
)

sd_section(
  "Machine Learning Algorithms",
  "Functions for invoking machine learning algorithms.",
  c(
    "ml_als_factorization",
    "ml_decision_tree",
    "ml_generalized_linear_regression",
    "ml_gradient_boosted_trees",
    "ml_kmeans",
    "ml_lda",
    "ml_linear_regression",
    "ml_logistic_regression",
    "ml_multilayer_perceptron",
    "ml_naive_bayes",
    "ml_one_vs_rest",
    "ml_pca",
    "ml_random_forest",
    "ml_survival_regression"
  )
)

sd_section(
  "Machine Learning Transformers",
  "Functions for transforming features in Spark DataFrames.",
  c(
    "ft_binarizer",
    "ft_bucketizer",
    "ft_discrete_cosine_transform",
    "ft_elementwise_product",
    "ft_index_to_string",
    "ft_one_hot_encoder",
    "ft_quantile_discretizer",
    "ft_sql_transformer",
    "ft_string_indexer",
    "ft_vector_assembler"
  )
)

sd_section(
  "Machine Learning Utilities",
  "Functions for interacting with Spark ML model fits.",
  c(
    "ml_binary_classification_eval",
    "ml_classification_eval",
    "ml_tree_feature_importance",
    "ml_saveload"
  )
)

sd_section(
  "Machine Learning Extensions",
  "Functions for creating custom wrappers to other Spark ML algorithms.",
  c(
    "ensure",
    "ml_create_dummy_variables",
    "ml_model",
    "ml_options",
    "ml_prepare_dataframe",
    "ml_prepare_response_features_intercept"
  )
)

sd_section(
  "Extensions API",
  "Functions for creating extensions to the sparklyr package.",
  c(
    "compile_package_jars",
    "connection_config",
    "find_scalac",
    "hive_context",
    "invoke",
    "java_context",
    "register_extension",
    "spark_compilation_spec",
    "spark_default_compilation_spec",
    "spark_connection",
    "spark_context",
    "spark_dataframe",
    "spark_dependency",
    "spark_jobj",
    "spark_session",
    "spark_version"
  )
)
###############################################
### COMMONLY USED PACKAGES IN AIM R SCRIPTS ###
###############################################

#### THE CORE ####
install.packages("tidyverse")
## The tidyverse package includes a number of packages also listed below. It's a quick way to bootstrap up a new install of R.
## They include:
## broom, DBI, dplyr, forcats, ggplot2, haven, httr, hms, jsonlite, lubridate, magrittr, modelr, purrr, readr, readxl, stringr,
## tibble, rvest, tidyr, and xml2

#### DATA WRANGLING ####
install.packages(
  c(
    "dplyr", ## Notably useful for data frame manipulation with group_by(), summarize(), and mutate() and the piping operator %>%. Do you have a moment to hear the good news of our savior, piping?
    "tidyr", ## Lots of useful things, but specifically gather() and spread() for converting wide data frames into long ones and vice versa
    "broom", ## Get stats objects into tidy data frames. Not as common
    "stringr", ## All about character strings. Great for str_split() in particular, but the whole str_ family of functions are A+
    "RODBC", ## Allows R to pass SQL queries to Access databases and pull out the results
    "XLSX" ## Read in modern Excel workbooks and spreadsheets
  )
)

#### SPATIAL DATA ####
install.packages(
  c(
    "sp", ## Functions for manipulating spatial objects. If you want a Spatial _____ Data Frame, this is part of the deal
    "spsurvey", ## Contains plenty, but the most important to AIM is the GRTS function
    "rgeos", ## Additional spatial object functions
    "rgdal", ## Contains the mission critical readOGR() function that we read shapefiles in with
    "raster" ## Everything you didn't know you needed for dealing with rasters
  )
)

#### DATA VISUALIZATION ####
install.packages(
  c(
    "ggplot2", ## The go-to for figure generation. Most R-using scientists AND Nate Silver use it, so you should too
    "ggthemes", ## Quick themes to painlessly apply to figures from ggplot
    "ggmap", ## Mapping support for ggplot
    "RColorBrewer" ## All about making beautiful color palettes for maps and figures
  )
)

#### MISCELLANEOUS PACKAGES ####
## These are more ala carte. Pick and choose as you need them
install.packages("markdown") ## Generates documents with figures and everything based on your script, which means that if you change the data, the document changes to reflect it. POWERFUL.
install.packages("rJava") ## Chances are really good that this is already installed as a dependency for another package, but just to be safe, here it is
install.packages("devtools") ## For more granular control of the R environment when you need it, which may not be very often at all
install.packages("git2r") ## If you're going to use Git, this is important because it lets you use git from within R. It's a dependency of devtools though, so it may already be installed
install.packages("arcgisbinding") ## Young and finicky, but once you have it all installed (an ordeal) you should be able to read from and write to file geodatabases from R
install.packages("gridExtra") ## Lets you make grid objects that you can place ggplot figures into. May occasionally be preferable to faceting in ggplot, but rarely
install.packages("shiny") ## Required for working with Shiny tools in any form. Can be maddening
install.packages("purrr") ## Really, really useful for writing functions, particularly those that fail gracefully
install.packages("gstat") ## For spatial and spatio-temporal geostatistical modelling and simulation
install.packages("foreach") ## Parallel looping structures. Sarah McCord's thesis work required this
install.packages("snow") ## If you're doing distributed computing across multiple machines, grab thislibrary(staticdocs)

sd_section(
  "Connecting to Spark",
  "Functions for installing Spark components and managing connections to Spark.",
  c(
    "spark_config",
    "spark_connect",
    "spark_disconnect",
    "spark_install",
    "spark_log",
    "spark_web"
  )
)

sd_section(
  "Reading and Writing Data",
  "Functions for reading and writing Spark DataFrames.",
  c(
    "spark_read_csv",
    "spark_read_json",
    "spark_read_parquet",
    "spark_write_csv",
    "spark_write_json",
    "spark_write_parquet",
    "sdf-saveload"
  )
)

sd_section(
  "dplyr Interface",
  "Functions implementing a dplyr backend for Spark DataFrames.",
  c(
    "copy_to",
    "tbl_cache",
    "tbl_uncache"
  )
)

sd_section(
  "Spark DataFrames",
  "Functions for maniplulating Spark DataFrames.",
  c(
    "na.replace",
    "sdf_copy_to",
    "sdf_mutate",
    "sdf_partition",
    "sdf_predict",
    "sdf_read_column",
    "sdf_register",
    "sdf_sample",
    "sdf_sort",
    "sdf_with_unique_id"
  )
)

sd_section(
  "Machine Learning Algorithms",
  "Functions for invoking machine learning algorithms.",
  c(
    "ml_als_factorization",
    "ml_decision_tree",
    "ml_generalized_linear_regression",
    "ml_gradient_boosted_trees",
    "ml_kmeans",
    "ml_lda",
    "ml_linear_regression",
    "ml_logistic_regression",
    "ml_multilayer_perceptron",
    "ml_naive_bayes",
    "ml_one_vs_rest",
    "ml_pca",
    "ml_random_forest",
    "ml_survival_regression"
  )
)

sd_section(
  "Machine Learning Transformers",
  "Functions for transforming features in Spark DataFrames.",
  c(
    "ft_binarizer",
    "ft_bucketizer",
    "ft_discrete_cosine_transform",
    "ft_elementwise_product",
    "ft_index_to_string",
    "ft_one_hot_encoder",
    "ft_quantile_discretizer",
    "ft_sql_transformer",
    "ft_string_indexer",
    "ft_vector_assembler"
  )
)

sd_section(
  "Machine Learning Utilities",
  "Functions for interacting with Spark ML model fits.",
  c(
    "ml_binary_classification_eval",
    "ml_classification_eval",
    "ml_tree_feature_importance",
    "ml_saveload"
  )
)

sd_section(
  "Machine Learning Extensions",
  "Functions for creating custom wrappers to other Spark ML algorithms.",
  c(
    "ensure",
    "ml_create_dummy_variables",
    "ml_model",
    "ml_options",
    "ml_prepare_dataframe",
    "ml_prepare_response_features_intercept"
  )
)

sd_section(
  "Extensions API",
  "Functions for creating extensions to the sparklyr package",
  c(
    "compile_package_jars",
    "connection_config",
    "find_scalac",
    "hive_context",
    "invoke",
    "java_context",
    "register_extension",
    "spark_compilation_spec",
    "spark_default_compilation_spec",
    "spark_connection",
    "spark_context",
    "spark_dataframe",
    "spark_dependency",
    "spark_jobj",
    "spark_session",
    "spark_version"
  )
)
library(staticdocs)

sd_section(
  "Connecting to Spark",
  "Functions for installing Spark components and managing connections to Spark",
  c(
    "spark_config",
    "spark_connect",
    "spark_disconnect",
    "spark_install",
    "spark_log",
    "spark_web"
  )
)

sd_section(
  "Reading and Writing Data",
  "Functions for reading and writing Spark DataFrames",
  c(
    "spark_read_csv",
    "spark_read_json",
    "spark_read_parquet",
    "spark_write_csv",
    "spark_write_json",
    "spark_write_parquet",
    "sdf-saveload"
  )
)

sd_section(
  "dplyr Interface",
  "Functions implementing a dplyr backend for Spark DataFrames",
  c(
    "copy_to",
    "tbl_cache",
    "tbl_uncache"
  )
)

sd_section(
  "Spark DataFrames",
  "Functions for maniplulating Spark DataFrames",
  c(
    "na.replace",
    "sdf_copy_to",
    "sdf_mutate",
    "sdf_partition",
    "sdf_predict",
    "sdf_read_column",
    "sdf_register",
    "sdf_sample",
    "sdf_sort",
    "sdf_with_unique_id"
  )
)

sd_section(
  "Machine Learning Algorithms",
  "Functions for invoking machine learning algorithms",
  c(
    "ml_als_factorization",
    "ml_decision_tree",
    "ml_generalized_linear_regression",
    "ml_gradient_boosted_trees",
    "ml_kmeans",
    "ml_lda",
    "ml_linear_regression",
    "ml_logistic_regression",
    "ml_multilayer_perceptron",
    "ml_naive_bayes",
    "ml_one_vs_rest",
    "ml_pca",
    "ml_random_forest",
    "ml_survival_regression"
  )
)

sd_section(
  "Machine Learning Transformers",
  "Functions for transforming features in Spark DataFrames",
  c(
    "ft_binarizer",
    "ft_bucketizer",
    "ft_discrete_cosine_transform",
    "ft_elementwise_product",
    "ft_index_to_string",
    "ft_one_hot_encoder",
    "ft_quantile_discretizer",
    "ft_sql_transformer",
    "ft_string_indexer",
    "ft_vector_assembler"
  )
)

sd_section(
  "Machine Learning Utilities",
  "Functions for interacting with Spark ML model fits",
  c(
    "ml_binary_classification_eval",
    "ml_classification_eval",
    "ml_tree_feature_importance",
    "ml_saveload"
  )
)

sd_section(
  "Machine Learning Extensions",
  "Functions for creating custom wrappers to other Spark ML algorithms",
  c(
    "ensure",
    "ml_create_dummy_variables",
    "ml_model",
    "ml_options",
    "ml_prepare_dataframe",
    "ml_prepare_response_features_intercept"
  )
)

sd_section(
  "Extensions API",
  "Functions for creating extensions to the sparklyr package",
  c(
    "compile_package_jars",
    "connection_config",
    "find_scalac",
    "hive_context",
    "invoke",
    "java_context",
    "register_extension",
    "spark_compilation_spec",
    "spark_default_compilation_spec",
    "spark_connection",
    "spark_context",
    "spark_dataframe",
    "spark_dependency",
    "spark_jobj",
    "spark_session",
    "spark_version"
  )
)
library(staticdocs)

sd_section(
  "Connecting to Spark",
  "Functions for installing Spark components and managing connections to Spark",
  c(
    "spark_config",
    "spark_connect",
    "spark_disconnect",
    "spark_install",
    "spark_log",
    "spark_web"
  )
)

sd_section(
  "Reading and Writing Data",
  "Functions for reading and writing Spark DataFrames",
  c(
    "spark_read_csv",
    "spark_read_json",
    "spark_read_parquet",
    "spark_write_csv",
    "spark_write_json",
    "spark_write_parquet"
  )
)

sd_section(
  "dplyr Interface",
  "Functions implementing a dplyr backend for Spark DataFrames",
  c(
    "copy_to",
    "tbl_cache",
    "tbl_uncache"
  )
)

sd_section(
  "Spark DataFrames",
  "Functions for maniplulating Spark DataFrames",
  c(
    "sdf_copy_to",
    "sdf_mutate",
    "sdf_partition",
    "sdf_predict",
    "sdf_read_column",
    "sdf_register",
    "sdf_sample",
    "sdf_sort",
    "sdf_with_unique_id"
  )
)

sd_section(
  "Machine Learning Algorithms",
  "Functions for invoking machine learning algorithms",
  c(
    "ml_als_factorization",
    "ml_decision_tree",
    "ml_generalized_linear_regression",
    "ml_gradient_boosted_trees",
    "ml_kmeans",
    "ml_lda",
    "ml_linear_regression",
    "ml_logistic_regression",
    "ml_multilayer_perceptron",
    "ml_naive_bayes",
    "ml_one_vs_rest",
    "ml_pca",
    "ml_random_forest",
    "ml_survival_regression"
  )
)

sd_section(
  "Machine Learning Utilities",
  "Functions for interacting with Spark ML model fits",
  c(
    "ml_binary_classification_eval",
    "ml_classification_eval",
    "ml_tree_feature_importance"
  )
)

sd_section(
  "Machine Learning Transformers",
  "Functions for transforming features in Spark DataFrames",
  c(
    "ft_binarizer",
    "ft_bucketizer",
    "ft_discrete_cosine_transform",
    "ft_elementwise_product",
    "ft_index_to_string",
    "ft_one_hot_encoder",
    "ft_quantile_discretizer",
    "ft_sql_transformer",
    "ft_string_indexer",
    "ft_vector_assembler"
  )
)

sd_section(
  "Machine Learning Utility Functions",
  "Functions for creating custom wrappers to other Spark ML algorithms",
  c(
    "ensure",
    "ml_create_dummy_variables",
    "ml_model",
    "ml_options",
    "ml_prepare_dataframe",
    "ml_prepare_response_features_intercept"
  )
)

sd_section(
  "Extensions API",
  "Functions for creating extensions to the sparklyr package",
  c(
    "compile_package_jars",
    "connection_config",
    "find_scalac",
    "hive_context",
    "invoke",
    "java_context",
    "register_extension",
    "spark_compilation_spec",
    "spark_default_compilation_spec",
    "spark_connection",
    "spark_context",
    "spark_dataframe",
    "spark_dependency",
    "spark_jobj",
    "spark_session",
    "spark_version"
  )
)
library(staticdocs)

sd_section(
  "Connecting to Spark",
  "Functions for installing Spark components and managing connections to Spark",
  c(
    "spark_config",
    "spark_connect",
    "spark_disconnect",
    "spark_install",
    "spark_log",
    "spark_web"
  )
)

sd_section(
  "Reading and Writing Data",
  "Functions for reading and writing Spark DataFrames",
  c(
    "spark_read_csv",
    "spark_read_json",
    "spark_read_parquet",
    "spark_write_csv",
    "spark_write_json",
    "spark_write_parquet"
  )
)

sd_section(
  "dplyr Interface",
  "Functions implementing a dplyr backend for Spark DataFrames",
  c(
    "copy_to",
    "tbl_cache",
    "tbl_uncache"
  )
)

sd_section(
  "Spark DataFrames",
  "Functions for maniplulating Spark DataFrames",
  c(
    "sdf_copy_to",
    "sdf_import",
    "sdf_mutate",
    "sdf_partition",
    "sdf_predict",
    "sdf_read_column",
    "sdf_register",
    "sdf_sample",
    "sdf_sort",
    "sdf_with_unique_id"
  )
)

sd_section(
  "Machine Learning Algorithms",
  "Functions for invoking machine learning algorithms",
  c(
    "ml_als_factorization",
    "ml_decision_tree",
    "ml_generalized_linear_regression",
    "ml_gradient_boosted_trees",
    "ml_kmeans",
    "ml_lda",
    "ml_linear_regression",
    "ml_logistic_regression",
    "ml_multilayer_perceptron",
    "ml_naive_bayes",
    "ml_one_vs_rest",
    "ml_pca",
    "ml_random_forest",
    "ml_survival_regression"
  )
)

sd_section(
  "Machine Learning Utilities",
  "Functions for interacting with Spark ML model fits",
  c(
    "ml_binary_classification_eval",
    "ml_classification_eval",
    "ml_tree_feature_importance"
  )
)

sd_section(
  "Machine Learning Transformers",
  "Functions for transforming features in Spark DataFrames",
  c(
    "ft_binarizer",
    "ft_bucketizer",
    "ft_discrete_cosine_transform",
    "ft_elementwise_product",
    "ft_index_to_string",
    "ft_one_hot_encoder",
    "ft_quantile_discretizer",
    "ft_sql_transformer",
    "ft_string_indexer",
    "ft_vector_assembler"
  )
)

sd_section(
  "Machine Learning Utility Functions",
  "Functions for creating custom wrappers to other Spark ML algorithms",
  c(
    "ensure_scalar_boolean",
    "ensure_scalar_character",
    "ensure_scalar_double",
    "ensure_scalar_integer",
    "ml_create_dummy_variables",
    "ml_model",
    "ml_options",
    "ml_prepare_dataframe",
    "ml_prepare_response_features_intercept"
  )
)

sd_section(
  "Extensions API",
  "Functions for creating extensions to the sparklyr package",
  c(
    "compile_package_jars",
    "connection_config",
    "find_scalac",
    "hive_context",
    "invoke",
    "invoke_new",
    "invoke_static",
    "java_context",
    "register_extension",
    "spark_compilation_spec",
    "spark_default_compilation_spec",
    "spark_connection",
    "spark_context",
    "spark_dataframe",
    "spark_dependency",
    "spark_jobj",
    "spark_session",
    "spark_version"
  )
)
library(DiagrammeR)
grViz("

digraph boxes_and_circles{

    node [shape = box
            # fixedsize = TRUE
            # width = 2.5
            ]
            1 [label = <<B>S1) </B>I(<I>T<sub><font point-size='8'>C</font></sub>,T<sub><font point-size='8'>R</font></sub></I>) in <I>S0</I>?>]
            2 [label = <<B>S2) </B><I>T<sub><font point-size='8'>R </font></sub></I> in <I>S1</I>?>]
            3 [label = <<B>S3) </B>Add <I>T<sub><font point-size='8'>R </font></sub></I> to<br/>predictions>]
            4 [label = <<B>S4) </B><I>K </I> most similar<br/>resource <I>T<sub><font point-size='8'>R&apos;</font></sub></I> in <I>S1</I>>]
            5 [label = <<B>S5) </B><I>T<sub><font point-size='8'>R&apos; </font></sub></I> in <I>C<SUB><font point-size='8'>R</font></SUB></I>?>]
            6 [label = <<B>S6) </B>Add weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I><br/>to <I>T<sub><font point-size='8'>R&apos; </font></sub></I>in <I>C<SUB><font point-size='8'>R </font></SUB></I> if<br/><I>t </I> &gt; minimum threshold>]
            7 [label = <<B>S7) </B>Add <I>T<sub><font point-size='8'>R&apos; </font></sub></I>to <I>C<SUB><font point-size='8'>R </font></SUB></I> with<br/>weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I> if<br/><I>t </I> &gt; minimum threshold>]
            8 [label = <<B>S8) </B><I>K </I> most similar<br/>consumer <I>T<sub><font point-size='8'>C&apos;</font></sub></I>>]
            9 [label = <<B>S9) </B><I>T<sub><font point-size='8'>R </font></sub></I>in <I>S1</I>?>]
            10 [label = <<B>S10) </B><I>T<sub><font point-size='8'>R </font></sub></I>in <I>C<SUB><font point-size='8'>R</font></SUB></I>?>]
            11 [label = <<B>S11) </B>Add 1 to <I>T<sub><font point-size='8'>R </font></sub></I><br/>weight in <I>C<SUB><font point-size='8'>R</font></SUB></I>>]
            12 [label = <<B>S12) </B>Add <I>T<sub><font point-size='8'>R </font></sub></I>to <I>C<SUB><font point-size='8'>R </font></SUB></I><br/>with weight = 1>]
            13 [label = <<B>S13) </B><I>K </I> most similar<br/>resource <I>T<sub><font point-size='8'>R&apos; </font></sub></I>in <I>S1</I>>]
            14 [label = <<B>S14) </B><I>T<sub><font point-size='8'>R&apos; </font></sub></I>in <I>C<SUB><font point-size='8'>R</font></SUB></I>?>]
            15 [label = <<B>S15) </B>Add weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I><br/>to <I>T<sub><font point-size='8'>R&apos; </font></sub></I>in <I>C<SUB><font point-size='8'>R </font></SUB></I>if<br/><I>t </I> &gt; minimum threshold>]
            16 [label = <<B>S16) </B>Add <I>T<sub><font point-size='8'>R&apos; </font></sub></I>to <I>C<SUB><font point-size='8'>R </font></SUB></I>with<br/> weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I> if<br/><I>t </I> &gt; minimum threshold>]
            17 [label = <<B>S17) </B>Add <I>T<sub><font point-size='8'>R </font></sub></I>or <I>T<sub><font point-size='8'>R&apos; </font></sub></I>to predictions if weight &gt; minimum weight>]

1 -> 2 [label = 'Yes', headport = 'n', tailport = 'w']
1 -> 3 [color = 'transparent']
1 -> 4 [color = 'transparent']
1 -> 5 [color = 'transparent']
1 -> 6 [color = 'transparent']
1 -> 7 [color = 'transparent']
1 -> 8 [color = 'transparent']
2 -> 3 [label = 'Yes']
2 -> 4 [label = 'No']
4 -> 5
5 -> 6 [label = 'Yes']
5 -> 7 [label = 'No']
6 -> 17
7 -> 17
1 -> 8 [tailport = 'e']
8 -> 9
9 -> 10 [label = 'Yes']
10 -> 11 [label = 'Yes']
10 -> 12 [label = 'No']
11 -> 17
12 -> 17
9 -> 13 [label = 'No']
13 -> 14
14 -> 15 [label = 'Yes']
14 -> 16 [label = 'No']
15 -> 17
16 -> 17

graph [ranksep = 0.15
        rank = sink
        # rankdir = LR
        # splines = ortho
        ]


}
")
# Script for generating frames for a animation on danish population

# convert -delay 10 -loop 0 frame* befolkning.gif

IMAGEFILE = '~/tmp/frame%03d.png'
PLOTTITLE = 'Population, Denmark, %s'
# data1 <- read.csv("befolkningstal1901-1970.csv", head=TRUE, row.names = 1)
# For same reason All lables are prefixed with an X. 
#colnames(data1) = gsub("X","",colnames(data1))

data2 <- read.csv("befolkningstal.csv")

frameI = 1

maxcount =  max(data2, na.rm = TRUE)
originYear = 1970
for(i in 1:ncol(data2)){
	frameName = sprintf(IMAGEFILE, frameI)
	frameI = frameI + 1
	totalPopulation = sum(data2[,i], na.rm = TRUE)
	plotTitle = sprintf("Population, Denmark, %d 
Total Population: %d", originYear + i, totalPopulation)

	png(frameName)
	barplot(data2[,i], main = plotTitle, ylab = "Count", xlab ="Age", ylim=c(0,maxcount),
	 xlim = c(0,100), border = NA, space = 0, names.arg = 1:nrow(data2)-1)
	dev.off()
}

require(dplyr)
require(rvest)
require(gsubfn)

url<-'https://en.wikipedia.org/wiki/2014%E2%80%9315_NBA_season'

#stran <- html_session(url) %>% read_html(encoding = "UTF-8")
#tabela <- stran %>% html_nodes(xpath ="//table[5]") %>% .[[1]] %>% html_table()

podatki<-read.csv("podatki.csv", header=TRUE, sep=",", dec=".", stringsAsFactors = FALSE, na.strings = ".")
podatki$Rk<-NULL
podatki$eFG.<-NULL
a<-c(6:28)
suppressWarnings(podatki[a]<-lapply(podatki[a], as.numeric))
podatki<-podatki[!is.na(podatki$PTS),]
#podatki<-na.omit(podatki)
colnames(podatki)[28]<-"PTS"
podatki<-podatki[order(podatki[,28], decreasing = TRUE),]

link<-'http://www.spotrac.com/widget/sport/nba/current-year/rankings-cap/"'
site<-html_session(link) %>% read_html(encoding = "UTF-8")
salaries<-site %>% html_nodes(xpath ="//table") %>% .[[1]] %>% html_table()
place<-site %>% html_nodes(xpath ="//table") %>% .[[1]] %>% html_table()
place<-place[-1]
salaries<-salaries[-1]
salaries$Pos.<-NULL

celatabela<-inner_join(podatki, salaries, by = "Player")
colnames(celatabela)<-c("Player","Position" ,"Age","Team","Games","Started","Minutes","FG Made", "FG Att","FG %","3Pt Made", "3Pt Att", "3Pt %", "2Pt Made", "2Pt Att", "2Pt %", "FT Made", "FT Att", "FT %", "Off. Reb", "Def. Reb", "Tot. Reb", "Assists", "Steals", "Blocks", "Turnovers", "Fouls", "Points", "Salary")
celatabela$Salary<-as.factor(celatabela$Salary)
celatabela$Salary<-gsub("\\$", "", celatabela$Salary)
celatabela$Salary<-gsub("\\,", "", celatabela$Salary)
celatabela$Salary<-as.numeric(celatabela$Salary)

strelci<-data.frame(Player=celatabela$Player, Points=celatabela$Points)

zlink<-'http://hoopshype.com/2015/02/24/where-are-nba-players-born/'
zstran <- html_session(zlink) %>% read_html(encoding = "UTF-8")
ztabela <- zstran %>% html_nodes(xpath ="//table[2]") %>% .[[1]]  %>% html_table()
ztabela<-na.omit(ztabela)
ztabela<-ztabela[-1,-3]
colnames(ztabela)<-c('City','Players')
ztabela$City<-as.factor(ztabela$City)
ztabela$Players<-as.numeric(ztabela$Players)
ztabela$City<-gsub('[[:digit:]]+', '', ztabela$City)
ztabela$City<-gsub('\\.', '', ztabela$City)
ztabela<-ztabela[-11,]
ztabela1<-ztabela
ztabela$Lat<-c('34.052235', '40.792240', '41.881832', '40.002785', '32.736259', '39.790942', '47.608013', '30.471165', '35.040031', '39.299236', '29.761993', '33.753746', '38.889931', '33.792461', '38.627003')
ztabela$Long<-c('-118.243683', '-73.138260', '-87.623177', '-75.183739', '-96.864586', '-86.147685', '-122.335167', '-91.147385', '-89.981873', '-76.609383', '-95.366302', '-84.386330', '-77.009003', '-118.185005', '-90.199402')
ztabela$STATE_NAME<-c('California', 'New York', 'Illinois', 'Pennsylvania', 'Texas', 'Indiana', 'Washington', 'Louisiana', 'Tennessee', 'Maryland', 'Texas', 'Georgia', 'District of Columbia', 'California', 'Missouri')
ztabela$Lat<-as.numeric(ztabela$Lat)
ztabela$Long<-as.numeric(ztabela$Long)
source("lib/uvozi.zemljevid.r", encoding = "UTF-8")
library(ggplot2)

pretvori.zemljevid <- function(zemljevid) {
  fo <- fortify(zemljevid)
  data <- zemljevid@data
  data$id <- as.character(0:(nrow(data)-1))
  return(inner_join(fo, data, by="id"))
}

zda <- uvozi.zemljevid("http://baza.fmf.uni-lj.si/states_21basic.zip", "states")
ztabela <- preuredi(ztabela, zda, "STATE_NAME")
usa<-pretvori.zemljevid(zda)
usa.cont <- usa %>% filter(! STATE_NAME %in% c("Alaska", "Hawaii"))
map <- ggplot() + geom_polygon(data = usa.cont, color='navajowhite3', aes(x = long, y = lat, group=group),fill="navajowhite")
require(ggrepel)
map1 <- map + geom_point(data = ztabela, color = "green4", aes(x = Long, y = Lat, size = Players)) + geom_text_repel(data = ztabela, color='black', aes(x = Long, y = Lat, label = City), size=5)
map1

ekipe<-read.csv('teams__active.csv')
ekipe$Lg<-NULL
ekipe$To<-NULL
ekipe$Yrs<-NULL
ekipe$W.L.<-NULL
colnames(ekipe)<-c('Team', 'Founded', 'Games', 'Won', 'Lost', 'Playoffs', 'Div. titles', 'Conf. titles', 'Championships')
ekipe1<-ekipe
ekipe<-ekipe[-28,]
ekipe$STATE_NAME<-c('Georgia', 'Massachusetts', 'New York', 'North Carolina', 'Illinois', 'Ohio','Texas','Colorado','Michigan','California','Texas','Indiana','California','California','Tennessee','Florida','Wisconsin','Minnesota','Louisianna','New York','Oklahoma','Florida','Pennsylvania','Arizona','Oregon','California','Texas','Utah','District of Columbia')
ekipe$LAT<-c('33.75375', '42.35843', '40.35000','35.227085', '41.881832','41.505493','32.73626','39.742043','42.331429','	37.801239','29.682720','39.769653','34.052235','34.052235','35.040031',	'25.778135','43.038902','44.986656','29.951065','40.79224','35.481918','28.538336','40.00279','33.453388','45.512794','38.575764','29.424349','40.758701','38.88993')
ekipe$LONG<-c('-84.38633', '-71.05977', '-73.949997', '-80.843124','-87.623177','	-81.681290','-96.86459','	-104.991531','	-83.045753','-122.258301','-95.593239','-86.157143','-118.243683','-118.243683','-89.981873','-80.179100','-87.906471','-93.258133','-90.071533','-73.13826','-97.508469','-81.379234','-75.18374','-112.074623','-122.679565','-121.478851','-98.491142','-111.876183','-77.00900')
ekipe$LAT<-as.numeric(ekipe$LAT)
ekipe$LONG<-as.numeric(ekipe$LONG)
ekipe<-preuredi(ekipe,zda,'STATE_NAME')
map2<-map+geom_point(data=ekipe,color='red',size=2,aes(x=LONG,y=LAT)) + geom_text_repel(data=ekipe,color='black',aes(x=LONG,y=LAT,label=Team),size=5)
map2

datagraf1 <- celatabela[which(celatabela$Points > 1500), ]
qplot(datagraf1$Points,datagraf1$Salary,color=datagraf1$Team,size=(datagraf1$Minutes),xlab = "Points",ylab = "Salary",main = "Points achieved per dollar") + geom_text_repel(aes(label=datagraf1$Player),size=5, color="black")

dataSG <- celatabela[which(celatabela$Position=="SG"), ]
dataSG1 <- dataSG[which(dataSG$Points > mean(dataSG$Points)), ]
qplot(dataSG1$Points,dataSG1$Player,xlab = "Points",ylab = "Player") + geom_vline(xintercept = mean(dataSG1$Points), color="red")

dataC <- celatabela[which(celatabela$Position == "C"), ]
dataC1 <- dataC[which(dataC$Points > mean(dataC$Points)), ]
qplot(dataC1$Points,dataC1$Player,xlab = "Points",ylab = "Player") + geom_vline(xintercept = mean(dataC1$Points), color="red")

dataPG <- celatabela[which(celatabela$Position == "PG"), ]
dataPG1 <- dataPG[which(dataPG$Points > mean(dataPG$Points)), ]
qplot(dataPG1$Points,dataPG1$Player,xlab = "Points",ylab = "Player") + geom_vline(xintercept = mean(dataPG1$Points), color="red")

dataSF <- celatabela[which(celatabela$Position=="SF"), ]
dataSF1 <- dataSF[which(dataSF$Points > mean(dataSF$Points)), ]
qplot(dataSF1$Points,dataSF1$Player,xlab = "Points",ylab = "Player") + geom_vline(xintercept = mean(dataSF1$Points), color="red")

dataPF <- celatabela[which(celatabela$Position=="PF"), ]
dataPF1 <- dataPF[which(dataPF$Points > mean(dataPF$Points)), ]
qplot(dataPF1$Points,dataPF1$Player,xlab = "Points",ylab = "Player") + geom_vline(xintercept = mean(dataPF1$Points), color="red")
# # # setwd('C:/Users/garre/Dropbox/aa projects/DIVA')

# # # backprop
# backpropagate error and update weights
# #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
backprop <- function(out_wts, in_wts, out_activation, current_target, 
                     hid_activation, hid_activation_raw, ins_w_bias, learning_rate){

  # # # calc error on output units
  out_delta <- 2 * (out_activation - current_target)
  
  # # # calc error on hidden units
  hid_delta <- out_delta %*% t(out_wts)
  hid_delta <- hid_delta[,2:ncol(hid_delta)] * sigmoid_grad(hid_activation_raw)
  
  # # # calc weight changes
  out_delta <- learning_rate * (t(hid_activation) %*% out_delta)
  hid_delta <- learning_rate * (t(ins_w_bias) %*% hid_delta)

  # # # adjust wts
  out_wts <- out_wts - out_delta
  in_wts <- in_wts - hid_delta

  return(list(out_wts = out_wts, 
              in_wts  = in_wts))

}

# # # forward_pass
# conduct forward pass
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
forward_pass <- function(in_wts, out_wts, inputs, out_rule) {
  # # # init needed vars
  num_feats <- ncol(out_wts)
  num_cats  <- dim(out_wts)[3]
  num_stims <- nrow(inputs)
  if (is.null(num_stims)) {num_stims <- 1}

  
  # # # add bias to ins
  bias_units <- matrix(rep(1, num_stims), ncol = 1, nrow = num_stims)
  ins_w_bias <- cbind(bias_units,
    matrix(inputs, nrow = num_stims, ncol = num_feats, byrow = TRUE))

  # # # ins to hids propagation
  hid_activation_raw <- ins_w_bias %*% in_wts
  hid_activation <- sigmoid(hid_activation_raw)

  # # # add bias unit to hid activation
  hid_activation <- cbind(bias_units, hid_activation)  

  # # # hids to outs propagation
  out_activation <- array(rep(0, (num_stims * num_feats * num_cats)), 
    dim = c(num_stims, num_feats, num_cats))
  
  # # NEED VECTORIZED HERE
  # # # get output activation
  for (category in 1:num_cats) {
  	out_activation[,,category] <- hid_activation %*% out_wts[,,category]
  }
  
  # # # apply output activatio rule
  if(out_rule == 'sigmoid') {
  	out_activation <- sigmoid(out_activation)
  }

  return(list(out_activation     = out_activation, 
              hid_activation     = hid_activation,
              hid_activation_raw = hid_activation_raw, 
              ins_w_bias         = ins_w_bias))

}

# # # get_wts
# generate net weights
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
get_wts <- function(num_feats, num_hids, num_cats, wts_range, wts_center) {
  # # # set bias
  bias <- 1
  
  # # # generate wts between ins and hids
  in_wts <- 
    (matrix(runif((num_feats + bias) * num_hids), ncol = num_hids) - 0.5) * 2 
  in_wts <- wts_center + (wts_range * in_wts)

  # # # generate wts between hids and outs
  out_wts <- 
    (array(runif((num_hids + bias) * num_feats * num_cats), 
      dim = c((num_hids + bias), num_feats, num_cats)) - 0.5) * 2
  out_wts <- wts_center + (wts_range * out_wts)   
  
  return(list(in_wts  = in_wts, 
              out_wts = out_wts))

}

# # # global_scale
# scale inputs to 0/1
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
global_scale <- function(x) { x / 2 + 0.5 }

# # # trainp_lot
# function to produce line plot of training
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
train_plot <- function(training) {
  # # # get dimensions
  n_cats <- dim(training)[2]
  xrange <- c(1, dim(training)[1])
  yrange <- range(training)

  # # # open plot device
  pdf('training_plot.pdf')

  # # # create frame
  plot(xrange, c(.01, yrange[2]), xlab = 'Block Number', ylab = 'Accuracy')

  # # # aesthetics 
  colors <- rainbow(n_cats)
  line_type <- c(1:n_cats)
  plot_char <- seq(18, 18 + n_cats, 1)

  # # # plot lines
  for (i in 1:n_cats) {
    target_cat <- training[,i]
    lines(seq(1, xrange[2], 1), target_cat, type = 'b', lwd = 1.5, 
      lty = line_type[i], col = colors[i],  pch = plot_char[i])
  }

  # # # title and legend
  title('DIVA Training Accuracy across Blocks')
  legend('bottomright', y = NULL, 1:n_cats, cex = 0.8, col = colors, 
    pch = plot_char, lty = line_type, title = 'SHJ Categories')

  # # # produce plot
  dev.off()
}

# response_rule
# convert output activations to classification
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
response_rule <- function(out_activation, target_activation, beta_val){
  num_feats <- ncol(out_activation)
  num_cats  <- dim(out_activation)[3]
  num_stims <- nrow(target_activation)
  if (is.null(num_stims)) {num_stims <- 1}

  # # # calc error  
  ssqerror <- array(as.vector(
    apply(out_activation, 3, function(x) {x - target_activation})),
      c(num_stims, num_feats, num_cats))
  ssqerror <- ssqerror ^ 2
  ssqerror[ssqerror < 1e-7] <- 1e-7

  # # # generate focus weights
  if(dim(out_activation)[3] > 2 | dim(out_activation)[1] > 1){
    stop('Not coded for >2 channels or batch mode, sorry!')
  } else {
    
    # # # get pairwise differences for feature activation
    # # # this needs to be coded to adjust for n>2 cats
    diversities <- 
      exp(beta_val * diag(as.matrix(dist(out_activation, upper = TRUE))[1:3,4:6]))
    diversities[diversities > 1e+7] <- 1e+7

    # divide diversities by sum of diversities
    fweights = diversities / sum(diversities)

    # # # apply focus weights; then get sum for each category
    ssqerror <- t(apply(ssqerror, 3, function(x) sum(x * fweights))) 
    ssqerror <- 1 / ssqerror
  }

return(list(ps       = (ssqerror / sum(ssqerror)), 
            fweights = fweights, 
            ssqerror = ssqerror))

}

# run_diva
# trains vanilla diva
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
run_diva <- function(model) {
  
  # # # get new seed
  seed <- runif(1) * 100000 * runif(1)
  set.seed(seed)
  
  # # # set mean value of weights
  model$wts_center <- 0 
  # # # convert targets to 0/1
  model$targets <- global_scale(model$inputs) 
  # # # init size parameter variables
  model$num_feats   <- ncol(model$inputs)
  model$num_stims   <- nrow(model$inputs)
  model$num_cats    <- length(unique(model$labels))
  model$num_updates <- model$num_blocks * model$num_stims
  # # # init training accuracy matrix
  training <- 
    matrix(rep(NA, model$num_updates * model$num_inits), 
      nrow = model$num_updates, ncol = model$num_inits)
  
  # # # initialize and run DIVA models
  for (model_num in 1:model$num_inits) {
    
    # # # generate weights
    wts <- get_wts(model$num_feats, model$num_hids, model$num_cats, model$wts_range, model$wts_center)

    # # # generate presentation order
    prez_order <- as.vector(apply(replicate(model$num_blocks, 
      seq(1, model$num_stims)), 2, sample, model$num_stims))

    # # # iterate over each trial in the presentation order 
    for (trial_num in 1:model$num_updates) {
      current_input  <- model$inputs[prez_order[[trial_num]], ]
      current_target <- model$targets[prez_order[[trial_num]], ]
      current_class  <- model$labels[prez_order[[trial_num]]] 

      # # # complete forward pass
      fp <- forward_pass(wts$in_wts, wts$out_wts, current_input, model$out_rule)
    
      # # # calculate classification probability
      response <- response_rule(fp$out_activation, current_target, model$beta_val)

      # # # store classification accuracy
      training[trial_num, model_num] = response$ps[current_class]

      # # # back propagate error to adjust weights
      class_wts <- wts$out_wts[,,current_class]
      class_activation <- fp$out_activation[,,current_class]

      adjusted_wts <- backprop(class_wts, wts$in_wts, class_activation, current_target,  
               fp$hid_activation, fp$hid_activation_raw, fp$ins_w_bias, model$learning_rate)

      wts$out_wts[,,current_class] <- adjusted_wts$out_wts
      wts$in_wts <- adjusted_wts$in_wts
  
    }

  }

training_means <- 
  rowMeans(matrix(rowMeans(training), nrow = model$num_blocks, ncol = model$num_stims, byrow = TRUE))

return(list(training = training_means))

}

# shj_cats
# loads shj category structures
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
shj_cats <- function(type){
  
  if (type == 1) {
    in_patterns <- 
      matrix(c(1,  1,  1,
	             1,  1, -1,
	             1, -1,  1,
  	           1, -1, -1,
	            -1, -1,  1,
	            -1, -1, -1,
	            -1,  1,  1,
	            -1,  1, -1), nrow = 8, ncol = 3, byrow = TRUE)		

  } else if (type == 2){
  	in_patterns <-
  	  matrix(c(1,  1,  1,
  	  	       1,  1, -1,
       	      -1, -1,	 1,
	            -1, -1, -1,
	            -1,	 1,	 1,
	            -1,	 1, -1,
	  	         1, -1,	 1,
		           1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 3){
  	in_patterns <-
  	  matrix(c(1,  1,  1,
  	  	       1,  1, -1,
  	  	       1, -1,  1, 
  	          -1,  1, -1,
  	           1, -1, -1, 
  	          -1,  1,  1, 
  	          -1, -1,  1, 
  	          -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 4){
    in_patterns <-
      matrix(c(1,  1,  1,
               1,  1, -1,
               1, -1,  1,
              -1,  1,  1,
               1, -1, -1,
              -1,  1, -1,
              -1, -1,  1,
              -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 5){
    in_patterns <-
      matrix(c(1,  1,  1,
               1,  1, -1,
               1, -1,  1,
              -1, -1, -1,
               1, -1, -1,
              -1,  1,  1,
              -1,  1, -1,
              -1, -1,  1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 6){
    in_patterns <-
      matrix(c(1,  1,  1,
               1, -1, -1,
              -1,  1, -1,
              -1, -1,  1,
               1,  1, -1,
               1, -1,  1,
              -1,  1,  1,
              -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  }

cat_assignment <- c(1, 1, 1, 1, 2, 2, 2, 2)

return(list(inputs = in_patterns, 
			      labels = cat_assignment))

}

# sigmoid
# returns sigmoid evaluated elementwize in X
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
sigmoid <- function(x) {
  g = 1 / (1 + exp(-x))
  return(g)

}

# sigmoid gradient
# returns the gradient of the sigmoid function evaluated at x
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
sigmoid_grad <- function(x) {
  return(g = ((sigmoid(x)) * (1 - sigmoid(x))))

}# # # setwd('C:/Users/garre/Dropbox/aa projects/DIVA')

# # backprop
# #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
backprop <- function(out_wts, in_wts, out_activation, current_target, 
                     hid_activation, hid_activation_raw, ins_w_bias, learning_rate){

  # # # calc error on output units
  out_delta <- 2 * (out_activation - current_target)
  
  # # # calc error on hidden units
  hid_delta <- out_delta %*% t(out_wts)
  hid_delta <- hid_delta[,2:ncol(hid_delta)] * sigmoid_grad(hid_activation_raw)
  
  # # # calc weight changes
  out_delta <- learning_rate * (t(hid_activation) %*% out_delta)
  hid_delta <- learning_rate * (t(ins_w_bias) %*% hid_delta)

  # # # adjust wts
  out_wts <- out_wts - out_delta
  in_wts <- in_wts - hid_delta

  return(list(out_wts = out_wts, 
              in_wts  = in_wts))

}

# forward_pass
# conduct forward pass
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
forward_pass <- function(in_wts, out_wts, inputs, out_rule) {
  # # # init needed vars
  num_feats <- ncol(out_wts)
  num_cats  <- dim(out_wts)[3]
  num_stims <- nrow(inputs)
  if (is.null(num_stims)) {num_stims <- 1}

  
  # # # add bias to ins
  bias_units <- matrix(rep(1, num_stims), ncol = 1, nrow = num_stims)
  ins_w_bias <- cbind(bias_units,
    matrix(inputs, nrow = num_stims, ncol = num_feats, byrow = TRUE))

  # # # ins to hids propagation
  hid_activation_raw <- ins_w_bias %*% in_wts
  hid_activation <- sigmoid(hid_activation_raw)

  # # # add bias unit to hid activation
  hid_activation <- cbind(bias_units, hid_activation)  

  # # # hids to outs propagation
  out_activation <- array(rep(0, (num_stims * num_feats * num_cats)), 
    dim = c(num_stims, num_feats, num_cats))
  # # NEED VECTORIZED HERE
  for (category in 1:num_cats) {
  	out_activation[,,category] <- hid_activation %*% out_wts[,,category]
  }
  
  # # # apply output activatio rule
  if(out_rule == 'sigmoid') {
  	out_activation <- sigmoid(out_activation)
  }

  return(list(out_activation     = out_activation, 
              hid_activation     = hid_activation,
              hid_activation_raw = hid_activation_raw, 
              ins_w_bias         = ins_w_bias))

}

# get_wts
# generate net weights
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
get_wts <- function(num_feats, num_hids, num_cats, wts_range, wts_center) {
  # # # set bias
  bias <- 1
  
  # # # generate wts between ins and hids
  in_wts <- 
    (matrix(runif((num_feats + bias) * num_hids), ncol = num_hids) - 0.5) * 2 
  in_wts <- wts_center + (wts_range * in_wts)

  # # # generate wts between hids and outs
  out_wts <- 
    (array(runif((num_hids + bias) * num_feats * num_cats), 
      dim = c((num_hids + bias), num_feats, num_cats)) - 0.5) * 2
  out_wts <- wts_center + (wts_range * out_wts)   
  
  return(list(in_wts  = in_wts, 
              out_wts = out_wts))

}

# global_scale
# scale inputs to 0/1
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
global_scale <- function(x) { x / 2 + 0.5 }

#plot training
# function to produce line plot of training
train_plot <- function(training){
  n_cats <- dim(training)[2]
  xrange <- c(1, dim(training)[1])
  yrange <- range(training)

  pdf('training_plot.pdf')

  plot(xrange, c(.01, yrange[2]), xlab = 'Block Number', ylab = 'Accuracy')

  colors <- rainbow(n_cats)
  line_type <- c(1:n_cats)
  plot_char <- seq(18, 18 + n_cats, 1)

  for (i in 1:n_cats) {
    target_cat <- training[,i]
    lines(seq(1, xrange[2], 1), target_cat, type = 'b', lwd = 1.5, 
      lty = line_type[i], col = colors[i],  pch = plot_char[i])
  }

  title('DIVA Training Accuracy across Blocks')

  legend('bottomright', y = NULL, 1:n_cats, cex = 0.8, col = colors, 
    pch = plot_char, lty = line_type, title = 'SHJ Categories')

  dev.off()
}

# response_rule
# convert output activations to classification
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
response_rule <- function(out_activation, target_activation, beta_val){
  num_feats <- ncol(out_activation)
  num_cats  <- dim(out_activation)[3]
  num_stims <- nrow(target_activation)
  if (is.null(num_stims)) {num_stims <- 1}

  # # # calc error  
  ssqerror <- array(as.vector(
    apply(out_activation, 3, function(x) {x - target_activation})),
      c(num_stims, num_feats, num_cats))
  ssqerror <- ssqerror ^ 2
  ssqerror[ssqerror < 1e-7] <- 1e-7

  # # # generate focus weights
  if(dim(out_activation)[3] > 2 | dim(out_activation)[1] > 1){
    stop('Not coded for >2 channels or batch mode, sorry!')
  } else {
    
    # # # get pairwise differences for feature activation
    # # # this needs to be coded to adjust for n>2 cats
    diversities <- 
      exp(beta_val * diag(as.matrix(dist(out_activation, upper = TRUE))[1:3,4:6]))
    diversities[diversities > 1e+7] <- 1e+7

    # divide diversities by sum of diversities
    fweights = diversities / sum(diversities)

    # # # apply focus weights; then get sum for each category
    ssqerror <- t(apply(ssqerror, 3, function(x) sum(x * fweights))) 
    ssqerror <- 1 / ssqerror
  }

return(list(ps       = (ssqerror / sum(ssqerror)), 
            fweights = fweights, 
            ssqerror = ssqerror))

}

# run_diva
# trains vanilla diva
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
run_diva <- function(model) {
  
  # # # get new seed
  seed <- runif(1) * 100000 * runif(1)
  set.seed(seed)
  
  # # # set mean value of weights
  model$wts_center <- 0 
  # # # convert targets to 0/1
  model$targets <- global_scale(model$inputs) 
  # # # init size parameter variables
  model$num_feats   <- ncol(model$inputs)
  model$num_stims   <- nrow(model$inputs)
  model$num_cats    <- length(unique(model$labels))
  model$num_updates <- model$num_blocks * model$num_stims
  # # # init training accuracy matrix
  training <- 
    matrix(rep(NA, model$num_updates * model$num_inits), 
      nrow = model$num_updates, ncol = model$num_inits)
  
  # # # initialize and run DIVA models
  for (model_num in 1:model$num_inits) {
    
    # # # generate weights
    wts <- get_wts(model$num_feats, model$num_hids, model$num_cats, model$wts_range, model$wts_center)

    # # # generate presentation order
    prez_order <- as.vector(apply(replicate(model$num_blocks, 
      seq(1, model$num_stims)), 2, sample, model$num_stims))

    # # # iterate over each trial in the presentation order 
    for (trial_num in 1:model$num_updates) {
      current_input  <- model$inputs[prez_order[[trial_num]], ]
      current_target <- model$targets[prez_order[[trial_num]], ]
      current_class  <- model$labels[prez_order[[trial_num]]] 

      # # # complete forward pass
      fp <- forward_pass(wts$in_wts, wts$out_wts, current_input, model$out_rule)
    
      # # # calculate classification probability
      response <- response_rule(fp$out_activation, current_target, model$beta_val)

      # # # store classification accuracy
      training[trial_num, model_num] = response$ps[current_class]

      # # # back propagate error to adjust weights
      class_wts <- wts$out_wts[,,current_class]
      class_activation <- fp$out_activation[,,current_class]

      adjusted_wts <- backprop(class_wts, wts$in_wts, class_activation, current_target,  
               fp$hid_activation, fp$hid_activation_raw, fp$ins_w_bias, model$learning_rate)

      wts$out_wts[,,current_class] <- adjusted_wts$out_wts
      wts$in_wts <- adjusted_wts$in_wts
  
    }

  }

training_means <- 
  rowMeans(matrix(rowMeans(training), nrow = model$num_blocks, ncol = model$num_stims, byrow = TRUE))

return(list(training = training_means))

}

# shj_cats
# loads shj category structures
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
shj_cats <- function(type){
  
  if (type == 1) {
    in_patterns <- 
      matrix(c(1,  1,  1,
	             1,  1, -1,
	             1, -1,  1,
  	           1, -1, -1,
	            -1, -1,  1,
	            -1, -1, -1,
	            -1,  1,  1,
	            -1,  1, -1), nrow = 8, ncol = 3, byrow = TRUE)		

  } else if (type == 2){
  	in_patterns <-
  	  matrix(c(1,  1,  1,
  	  	       1,  1, -1,
       	      -1, -1,	 1,
	            -1, -1, -1,
	            -1,	 1,	 1,
	            -1,	 1, -1,
	  	         1, -1,	 1,
		           1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 3){
  	in_patterns <-
  	  matrix(c(1,  1,  1,
  	  	       1,  1, -1,
  	  	       1, -1,  1, 
  	          -1,  1, -1,
  	           1, -1, -1, 
  	          -1,  1,  1, 
  	          -1, -1,  1, 
  	          -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 4){
    in_patterns <-
      matrix(c(1,  1,  1,
               1,  1, -1,
               1, -1,  1,
              -1,  1,  1,
               1, -1, -1,
              -1,  1, -1,
              -1, -1,  1,
              -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 5){
    in_patterns <-
      matrix(c(1,  1,  1,
               1,  1, -1,
               1, -1,  1,
              -1, -1, -1,
               1, -1, -1,
              -1,  1,  1,
              -1,  1, -1,
              -1, -1,  1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 6){
    in_patterns <-
      matrix(c(1,  1,  1,
               1, -1, -1,
              -1,  1, -1,
              -1, -1,  1,
               1,  1, -1,
               1, -1,  1,
              -1,  1,  1,
              -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  }

cat_assignment <- c(1, 1, 1, 1, 2, 2, 2, 2)

return(list(inputs = in_patterns, 
			      labels = cat_assignment))

}

# sigmoid
# returns sigmoid evaluated elementwize in X
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
sigmoid <- function(x) {
  g = 1 / (1 + exp(-x))
  return(g)

}

# sigmoid gradient
# returns the gradient of the sigmoid function evaluated at x
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
sigmoid_grad <- function(x) {
  return(g = ((sigmoid(x)) * (1 - sigmoid(x))))

}# Prediction efficiency in two ways, plus identity of taxa for which we obtain a, b, c or d
prediction_accuracy_id <- function(predicted, empirical) {
    # Parameters:
    #   predicted   matrix of predicted interactions
    #   empirical   matrix of empirical interactions

    #   Output      vector of a, b, c, d, and TSS
    #       a       number of links predicted (1) and observed (1)
    #       b       number predicted (1) but not observed (0)
    #       c       number predicted absent (0) but observed (1)
    #       d       number of predicted absent (0) and observed absent (0)
    #       TSS     TSS = (ad-bc)/[(a+c)(b+d)]
    #                   "[...] quantifies the proportion of prediction success relative to false predictions
    #                   and returns values ranging between 1 (perfect predictions) and 1 (inverted forecast)
    #                   (Allouche, Tsoar & Kadmon 2006)." Gravel et al. 2013
    #       ScoreY1 Fraction of 1 correctly predicted a / (a + c)
    #       ScoreY0 Fraction of 0 correctly predicted d / (b + d)
    #       FSS     FSS = ScoreY1 + ScoreY0 / sum(a, b, c, d)^2

    if(identical(colnames(predicted), colnames(empirical)) == FALSE ||
        identical(rownames(predicted), rownames(empirical)) == FALSE ||
        identical(dim(predicted), dim(empirical)) == FALSE) {
            print('matrices need to have same dimensions and row and column names')
            break
    }

    efficiency <- numeric(8)
    aa <- bb <- cc <- dd <-  numeric(2)
    names(efficiency) <- c('a','b','c','d','TSS','ScoreY1','ScoreY0','FSS')

    for(i in 1:ncol(predicted)){
        for(j in 1:nrow(predicted)) {
            if(predicted[i,j] == 1 && empirical[i,j] == 1) {
                efficiency[1] <- efficiency[1] + 1
                aa <- rbind(aa,c(j,i))
            } else if(predicted[i,j] == 1 && empirical[i,j] == 0) {
                efficiency[2] <- efficiency[2] + 1
                bb <- rbind(bb,c(j,i))
            } else if(predicted[i,j] == 0 && empirical[i,j] == 1) {
                efficiency[3] <- efficiency[3] + 1
                cc <- rbind(cc,c(j,i))
            } else if(predicted[i,j] == 0 && empirical[i,j] == 0) {
                efficiency[4] <- efficiency[4] + 1
                dd <- rbind(dd,c(j,i))
            }
        }
    }

    a <- efficiency[1]
    b <- efficiency[2]
    c <- efficiency[3]
    d <- efficiency[4]

    efficiency[5] <- ((a * d) - (b * c)) / ((a + c) * (b + d))  # TSS
    efficiency[6] <- a / (a + c)                                # ScoreY1
    efficiency[7] <- d / (b + d)                                # ScoreY0
    efficiency[8] <- (a + d) / sum(a, b, c, d)    # FSS

    efficiency.id <- vector('list',5)
    efficiency.id[[1]] <- efficiency
    efficiency.id[[2]] <- aa
    efficiency.id[[3]] <- bb
    efficiency.id[[4]] <- cc
    efficiency.id[[5]] <- dd

    return(efficiency.id)
}
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2.8 Example with southern St. Lawrence EwE model for mid-1980s
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "./RawData/South_St_Lawrence_EwE.RData"
#   Script  <- file = "Script/2-8_St_Lawrence_ex.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REFERENCE:
#   Savenkoff, to add
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
library(stringr)
load("./RawData/South_St_Lawrence_EwE.RData")
SSL <- South_St_Lawrence

SSL[[2]][which(SSL[[2]] > 0)] <- 1
rownames(SSL[[2]]) <- colnames(SSL[[2]]) <- SSL[[3]]

sp_SSL <- matrix(ncol = 2, nrow = 29, data = NA, dimnames = list(c(), c('ACCR','SP')))

sp_SSL[,1] <- c('WHA','HAS','HOS','GRS','HSE','SEA','LCO','SCO','LGH','SAP','LAP','FLO','SKA','RED','LDF','SDF','CAP','LPF','PISF','PLSF','SHR','LCRU','ECH','MOL','POL','OBI','LZOO','SZOO','PHY')

sp_SSL[,2] <- c('Balaenoptera physalus - Balaenoptera acutorostrata - Megaptera novaeangliae - Phocoena phocoena - Lagenorhynchus acutus - Lagenorhynchus albirostris',
'Pagophilus groenlandicus',
'Cystophora cristata',
'Halichoerus grypus',
'Phoca vitulina',
'Phalacrocorax carbo - Phalacrocorax auritus - Larus delawarensis - Larus argentatus - Larus marinus - Sterna hirundo - Sterna paradisaea - Cepphus grylle - Oceanodroma leucorhoa - Morus bassanus - Rissa tridactyla - Uria aalge - Alca torda - Fratercula arctica',
'Gadus morhua',
'Gadus morhua',
'Reinhardtius hippoglossoides',
'Hippoglossoides platessoides',
'Hippoglossoides platessoides',
'Limanda ferruginea - Glyptocephalus cynoglossus - Pseudopleuronectes americanus',
'Amblyraja radiata - Malacoraja senta - Leucoraja ocellata',
'Sebastes mentella - Sebastes fasciatus',
'Urophycis tenuis - Melanogrammus aeglefinus - Centroscyllium fabricii - Anarhichas - Cyclopterus lumpus - Lycodes - Macrouridae - Zoarcidae - Lophius americanus - Hippoglossus hippoglossus',
'Myoxocephalus - Tautogolabrus adspersus - Zoarces americanus',
'Mallotus villosus',
'Squalus acanthias - Pollachius virens - Merluccius bilinearis - Cetorhinus maximus',
'Scomber scombrus - Illex illecebrosus',
'Clupea harengus - Scomberesox saurus - Gonatus',
'Argis dentata - Eualus macilentus - Eualus gaimardi - Pandalus montagui',
'Chionoecetes opilio - Hyas',
'Echinarachnius parma - Stronglyocentrotus pallidus - Ophiura robusta',
'Mesodesma deauratum - Cyrtodaria siliqua',
'Parexogone hebes',
'Miscellaneous crustaceans', #to remove OBI
'Euphausiids - chaetognaths', # to remove LZOO
'Oithona similis - Temora longicornis - Pseudocalanus - Calanus finmarchicus',
'Chaetoceros affinis - Chaetoceros - Leptocylindrus minimus - Thalassiiosira nordenskioldii - Thalassiiosira - Fragilariopsis')

# Removing portions of the web for which there is no taxa usable for the analysis, 'OBI' & 'LZOO'
SSL[[2]] <- SSL[[2]][-which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO'), -which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO')]
sp_SSL <- sp_SSL[-which(sp_SSL[,1] == 'OBI' | sp_SSL[,1] == 'LZOO'), ]

S1 <- unique(unlist(str_split(sp_SSL[,2], ' - ')))

load("./RData/Tanimoto_data.RData")
# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
# Format interaction catalogue to fit this table format
    S0 <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
    S0[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
        S0[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
    }


# Have to extract taxonomy for speies that are not found in S0
S1_missing <- which(!S1 %in% S0[,1])

S1_add_S0 <- matrix(ncol = 6, nrow = length(S1_missing), data = "", dimnames = list(c(), c("taxon", "taxonomy", "resource", "non-resource", "consumer", "non-consumer")))

S1_add_S0[, 'taxon'] <- S1[S1_missing]

S1_add_S0[, 'taxonomy'] <- c('Animalia | Chordata | Mammalia | Cetartiodactyla | Delphinidae | Lagenorhynchus | Lagenorhynchus acutus',
'Animalia | Chordata | Mammalia | Carnivora | Phocidae | Halichoerus | Halichoerus grypus',
'Animalia | Chordata | Procellariiformes | Hydrobatidae | Oceanodroma | Oceanodroma leucorhoa',
'Animalia | Chordata | Aves | Pelecaniformes | Sulidae | Morus | Morus bassanus',
'Animalia | Chordata | Aves | Charadriiformes | Alcidae | Alca | Alca torda',
'Animalia | Chordata | Elasmobranchii | Rajiformes | Rajidae | Malacoraja | Malacoraja senta',
'Animalia | Chordata | Elasmobranchii | Squaliformes | Etmopteridae | Centroscyllium | Centroscyllium fabricii',
'Animalia | Arthropoda | Malacostraca | Decapoda | Crangonidae | Argis | Argis dentata',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus macilentus',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus gaimardii',
'Animalia | Echinodermata | Echinoidea | Camarodonta | Strongylocentrotidae | Strongylocentrotus | Strongylocentrotus pallidus',
'Animalia | Mollusca | Bivalvia | Imparidentia | Mesodesmatidae | Mesodesma | Mesodesma deauratum',
'Animalia | Mollusca | Bivalvia | Adapedonta | Hiatellidae | Cyrtodaria | Cyrtodaria siliqua',
'Animalia | Annelida | Polychaeta | Phyllodocida | Syllidae | Parexogone | Parexogone hebes',
'Chromista | Ochrophyta | Bacillariophyceae | Chaetocerotanae | Chaetocerotaceae | Chaetoceros | Chaetoceros affinis',
'Chromista | Ochrophyta | Bacillariophyceae | Leptocylindrales | Leptocylindraceae | Leptocylindrus | Leptocylindrus minimus',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | Thalassiosira nordenskioeldii',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | NA')

 S0 <- rbind(S0, S1_add_S0) #binding missing taxonomies
 rownames(S0) <- S0[, 'taxon']


# #Thinning down catalogue
# S02 <- S0[unique(c(which(S0[, 'resource'] != ""), which(S0[, 'consumer'] != ""))), ]
#
# S1_missing2 <- which(!S1 %in% S02[,1]) #after culling
# S1_missing3 <- S1_missing2[which(!S1_missing2 %in% S1_missing)] #taxo to keep
# S1_add_S0 <- rbind(S1_add_S0, S0[which(S0[, 'taxon'] %in% S1[S1_missing3]), ])
# rownames(S1_add_S0) <- NULL
# S0 <- rbind(S02, S1_add_S0)
# remove(S02,S1_missing3,S1_missing2,S1_missing)

# Predicting interactions
SSL_predict <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.3)

SSL_predict2 <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.2)

SSL_predict_mat <- prediction_matrix(S1 = S1, predictions = SSL_predict)
SSL_predict_mat2 <- prediction_matrix(S1 = S1, predictions = SSL_predict2)
x <- SSL_predict_mat

for(i in 1:nrow(sp_SSL)) {
    Sx <- unique(unlist(str_split(sp_SSL[i,2], ' - ')))
    for(j in 1:length(Sx)){
        for(k in 1:length(S1))
        if(S1[k] %in% Sx == TRUE) {
            colnames(SSL_predict_mat)[k] <- rownames(SSL_predict_mat)[k] <- sp_SSL[i, 2]
            colnames(SSL_predict_mat2)[k] <- rownames(SSL_predict_mat2)[k] <- sp_SSL[i, 2]
        }
    }
}

SSL_predict_mat_combine <- dupl_sp(SSL_predict_mat)
SSL_predict_mat_combine2 <- dupl_sp(SSL_predict_mat2)

SSL_emp <- SSL[[2]]
colnames(SSL_emp) <- rownames(SSL_emp) <- sp_SSL[,2]
SSL_emp <-  dupl_sp(SSL_emp)

accuracy_SSL <- prediction_accuracy_id(predicted = SSL_predict_mat_combine, empirical = SSL_emp)
accuracy_SSL2 <- prediction_accuracy_id(predicted = SSL_predict_mat_combine2, empirical = SSL_emp)
accuracy_SSL
accuracy_SSL2

for(i in 2:nrow(accuracy_SSL[[4]])) {
    print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]))
}

for(i in 2:nrow(accuracy_SSL[[3]])) {
    print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]))
}


SSL_bin_inter <- bin_inter(SSL_predict_mat_combine)
SSL_bin_inter2 <- bin_inter(SSL_predict_mat_combine2)
SSL_emp_bin <- bin_inter(SSL_emp)
SSL_bin_inter <- SSL_bin_inter[which(SSL_bin_inter[, 'FeedInter'] == '1'), ]
SSL_bin_inter2 <- SSL_bin_inter2[which(SSL_bin_inter2[, 'FeedInter'] == '1'), ]
SSL_emp_bin <- SSL_emp_bin[which(SSL_emp_bin[, 'FeedInter'] == '1'), ]

# SSL species with interactions noted in catalogue
x <- which(S0[, 'taxon'] %in% S1)
length(which(S0[x,'resource'] != "" | S0[x,'consumer'] != ""))

id_b <- matrix(nrow = nrow(accuracy_SSL[[4]]), ncol = 2, data = NA, dimnames = list(c(), c('consumer','resource')))
for(i in 2:nrow(accuracy_SSL[[4]])) {
    id_b[i,1] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]
    id_b[i,2] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]]
}



# Load package
library(networkD3)
# Plot
simpleNetwork(as.data.frame(SSL_bin_inter[, c(1,3)]))
simpleNetwork(as.data.frame(SSL_emp_bin[, c(1,3)]))





# remplace , par ' - '
# remplacer les noms de colonnes et lignes
# combiner duplicatas
# rouler fonction du catalogue pour séparer les lignes et colonnes qui ont plusieurs entrées?
# faire l'analyse en séparant toutes les espèces listées, puis comparer l'analyse divisée, compartimenter les résultats (combiner les interactions des espèces qui sont dans un compartiment), et la réseau présenté dans l'article à partir de la matrice de diète.
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2.8 Example with southern St. Lawrence EwE model for mid-1980s
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "./RawData/South_St_Lawrence_EwE.RData"
#   Script  <- file = "Script/2-8_St_Lawrence_ex.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REFERENCE:
#   Savenkoff, to add
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
library(stringr)
load("./RawData/South_St_Lawrence_EwE.RData")
SSL <- South_St_Lawrence

SSL[[2]][which(SSL[[2]] > 0)] <- 1
rownames(SSL[[2]]) <- colnames(SSL[[2]]) <- SSL[[3]]

sp_SSL <- matrix(ncol = 2, nrow = 29, data = NA, dimnames = list(c(), c('ACCR','SP')))

sp_SSL[,1] <- c('WHA','HAS','HOS','GRS','HSE','SEA','LCO','SCO','LGH','SAP','LAP','FLO','SKA','RED','LDF','SDF','CAP','LPF','PISF','PLSF','SHR','LCRU','ECH','MOL','POL','OBI','LZOO','SZOO','PHY')

sp_SSL[,2] <- c('Balaenoptera physalus - Balaenoptera acutorostrata - Megaptera novaeangliae - Phocoena phocoena - Lagenorhynchus acutus - Lagenorhynchus albirostris',
'Pagophilus groenlandicus',
'Cystophora cristata',
'Halichoerus grypus',
'Phoca vitulina',
'Phalacrocorax carbo - Phalacrocorax auritus - Larus delawarensis - Larus argentatus - Larus marinus - Sterna hirundo - Sterna paradisaea - Cepphus grylle - Oceanodroma leucorhoa - Morus bassanus - Rissa tridactyla - Uria aalge - Alca torda - Fratercula arctica',
'Gadus morhua',
'Gadus morhua',
'Reinhardtius hippoglossoides',
'Hippoglossoides platessoides',
'Hippoglossoides platessoides',
'Limanda ferruginea - Glyptocephalus cynoglossus - Pseudopleuronectes americanus',
'Amblyraja radiata - Malacoraja senta - Leucoraja ocellata',
'Sebastes mentella - Sebastes fasciatus',
'Urophycis tenuis - Melanogrammus aeglefinus - Centroscyllium fabricii - Anarhichas - Cyclopterus lumpus - Lycodes - Macrouridae - Zoarcidae - Lophius americanus - Hippoglossus hippoglossus',
'Myoxocephalus - Tautogolabrus adspersus - Zoarces americanus',
'Mallotus villosus',
'Squalus acanthias - Pollachius virens - Merluccius bilinearis - Cetorhinus maximus',
'Scomber scombrus - Illex illecebrosus',
'Clupea harengus - Scomberesox saurus - Gonatus',
'Argis dentata - Eualus macilentus - Eualus gaimardi - Pandalus montagui',
'Chionoecetes opilio - Hyas',
'Echinarachnius parma - Stronglyocentrotus pallidus - Ophiura robusta',
'Mesodesma deauratum - Cyrtodaria siliqua',
'Parexogone hebes',
'Miscellaneous crustaceans', #to remove OBI
'Euphausiids - chaetognaths', # to remove LZOO
'Oithona similis - Temora longicornis - Pseudocalanus - Calanus finmarchicus',
'Chaetoceros affinis - Chaetoceros - Leptocylindrus minimus - Thalassiiosira nordenskioldii - Thalassiiosira - Fragilariopsis')

# Removing portions of the web for which there is no taxa usable for the analysis, 'OBI' & 'LZOO'
SSL[[2]] <- SSL[[2]][-which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO'), -which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO')]
sp_SSL <- sp_SSL[-which(sp_SSL[,1] == 'OBI' | sp_SSL[,1] == 'LZOO'), ]

S1 <- unique(unlist(str_split(sp_SSL[,2], ' - ')))

load("./RData/Tanimoto_data.RData")
# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
# Format interaction catalogue to fit this table format
    S0 <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
    S0[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
        S0[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
    }


# Have to extract taxonomy for speies that are not found in S0
S1_missing <- which(!S1 %in% S0[,1])

S1_add_S0 <- matrix(ncol = 6, nrow = length(S1_missing), data = "", dimnames = list(c(), c("taxon", "taxonomy", "resource", "non-resource", "consumer", "non-consumer")))

S1_add_S0[, 'taxon'] <- S1[S1_missing]

S1_add_S0[, 'taxonomy'] <- c('Animalia | Chordata | Mammalia | Cetartiodactyla | Delphinidae | Lagenorhynchus | Lagenorhynchus acutus',
'Animalia | Chordata | Mammalia | Carnivora | Phocidae | Halichoerus | Halichoerus grypus',
'Animalia | Chordata | Procellariiformes | Hydrobatidae | Oceanodroma | Oceanodroma leucorhoa',
'Animalia | Chordata | Aves | Pelecaniformes | Sulidae | Morus | Morus bassanus',
'Animalia | Chordata | Aves | Charadriiformes | Alcidae | Alca | Alca torda',
'Animalia | Chordata | Elasmobranchii | Rajiformes | Rajidae | Malacoraja | Malacoraja senta',
'Animalia | Chordata | Elasmobranchii | Squaliformes | Etmopteridae | Centroscyllium | Centroscyllium fabricii',
'Animalia | Arthropoda | Malacostraca | Decapoda | Crangonidae | Argis | Argis dentata',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus macilentus',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus gaimardii',
'Animalia | Echinodermata | Echinoidea | Camarodonta | Strongylocentrotidae | Strongylocentrotus | Strongylocentrotus pallidus',
'Animalia | Mollusca | Bivalvia | Imparidentia | Mesodesmatidae | Mesodesma | Mesodesma deauratum',
'Animalia | Mollusca | Bivalvia | Adapedonta | Hiatellidae | Cyrtodaria | Cyrtodaria siliqua',
'Animalia | Annelida | Polychaeta | Phyllodocida | Syllidae | Parexogone | Parexogone hebes',
'Chromista | Ochrophyta | Bacillariophyceae | Chaetocerotanae | Chaetocerotaceae | Chaetoceros | Chaetoceros affinis',
'Chromista | Ochrophyta | Bacillariophyceae | Leptocylindrales | Leptocylindraceae | Leptocylindrus | Leptocylindrus minimus',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | Thalassiosira nordenskioeldii',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | NA')

 S0 <- rbind(S0, S1_add_S0) #binding missing taxonomies
 rownames(S0) <- S0[, 'taxon']


# #Thinning down catalogue
# S02 <- S0[unique(c(which(S0[, 'resource'] != ""), which(S0[, 'consumer'] != ""))), ]
#
# S1_missing2 <- which(!S1 %in% S02[,1]) #after culling
# S1_missing3 <- S1_missing2[which(!S1_missing2 %in% S1_missing)] #taxo to keep
# S1_add_S0 <- rbind(S1_add_S0, S0[which(S0[, 'taxon'] %in% S1[S1_missing3]), ])
# rownames(S1_add_S0) <- NULL
# S0 <- rbind(S02, S1_add_S0)
# remove(S02,S1_missing3,S1_missing2,S1_missing)

# Predicting interactions
SSL_predict <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.3)

SSL_predict2 <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.2)

SSL_predict_mat <- prediction_matrix(S1 = S1, predictions = SSL_predict)
SSL_predict_mat2 <- prediction_matrix(S1 = S1, predictions = SSL_predict2)
x <- SSL_predict_mat

for(i in 1:nrow(sp_SSL)) {
    Sx <- unique(unlist(str_split(sp_SSL[i,2], ' - ')))
    for(j in 1:length(Sx)){
        for(k in 1:length(S1))
        if(S1[k] %in% Sx == TRUE) {
            colnames(SSL_predict_mat)[k] <- rownames(SSL_predict_mat)[k] <- sp_SSL[i, 2]
            colnames(SSL_predict_mat2)[k] <- rownames(SSL_predict_mat2)[k] <- sp_SSL[i, 2]
        }
    }
}

SSL_predict_mat_combine <- dupl_sp(SSL_predict_mat)
SSL_predict_mat_combine2 <- dupl_sp(SSL_predict_mat2)

SSL_emp <- SSL[[2]]
colnames(SSL_emp) <- rownames(SSL_emp) <- sp_SSL[,2]
SSL_emp <-  dupl_sp(SSL_emp)

accuracy_SSL <- prediction_accuracy_id(predicted = SSL_predict_mat_combine, empirical = SSL_emp)
accuracy_SSL2 <- prediction_accuracy_id(predicted = SSL_predict_mat_combine2, empirical = SSL_emp)
accuracy_SSL
accuracy_SSL2

for(i in 2:nrow(accuracy_SSL[[4]])) {
    print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]))
}

for(i in 2:nrow(accuracy_SSL[[3]])) {
    print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]))
}


SSL_bin_inter <- bin_inter(SSL_predict_mat_combine)
SSL_bin_inter2 <- bin_inter(SSL_predict_mat_combine2)
SSL_emp_bin <- bin_inter(SSL_emp)
SSL_bin_inter <- SSL_bin_inter[which(SSL_bin_inter[, 'FeedInter'] == '1'), ]
SSL_bin_inter2 <- SSL_bin_inter2[which(SSL_bin_inter2[, 'FeedInter'] == '1'), ]
SSL_emp_bin <- SSL_emp_bin[which(SSL_emp_bin[, 'FeedInter'] == '1'), ]

# SSL species with interactions noted in catalogue
x <- which(S0[, 'taxon'] %in% S1)
length(which(S0[x,'resource'] != "" | S0[x,'consumer'] != ""))




# Load package
library(networkD3)
# Plot
simpleNetwork(as.data.frame(SSL_bin_inter[, c(1,3)]))
simpleNetwork(as.data.frame(SSL_emp_bin[, c(1,3)]))





# remplace , par ' - '
# remplacer les noms de colonnes et lignes
# combiner duplicatas
# rouler fonction du catalogue pour séparer les lignes et colonnes qui ont plusieurs entrées?
# faire l'analyse en séparant toutes les espèces listées, puis comparer l'analyse divisée, compartimenter les résultats (combiner les interactions des espèces qui sont dans un compartiment), et la réseau présenté dans l'article à partir de la matrice de diète.
###############################################
### COMMONLY USED PACKAGES IN AIM R SCRIPTS ###
###############################################

#### DATA WRANGLING ####
install.packages(
  c(
    "dplyr", ## Notably useful for data frame manipulation with group_by(), summarize(), and mutate() and the piping operator %>%. Do you have a moment to hear the good news of our savior, piping?
    "tidyr", ## Lots of useful things, but specifically gather() and spread() for converting wide data frames into long ones and vice versa
    "stringr", ## All about character strings. Great for str_split() in particular, but the whole str_ family of functions are A+
    "RODBC", ## Allows R to pass SQL queries to Access databases and pull out the results
    "XLSX", ## Read in modern Excel workbooks and spreadsheets
    "broom" ## Get stats objects into tidy data frames. Not as common
  )
)

#### SPATIAL DATA ####
install.packages(
  c(
    "sp", ## Functions for manipulating spatial objects. If you want a Spatial _____ Data Frame, this is part of the deal
    "spsurvey", ## Contains plenty, but the most important to AIM is the GRTS function
    "rgeos", ## Additional spatial object functions
    "rgdal", ## Contains the mission critical readOGR() function that we read shapefiles in with
    "raster" ## Everything you didn't know you needed for dealing with rasters
  )
)

#### DATA VISUALIZATION ####
install.packages(
  c(
    "ggplot2", ## The go-to for figure generation. Most R-using scientists AND Nate Silver use it, so you should too
    "ggthemes", ## Quick themes to painlessly apply to figures from ggplot
    "ggmap", ## Mapping support for ggplot
    "RColorBrewer" ## All about making beautiful color palettes for maps and figures
  )
)

#### MISCELLANEOUS PACKAGES ####
## These are more ala carte. Pick and choose as you need them
install.packages("markdown") ## Generates documents with figures and everything based on your script, which means that if you change the data, the document changes to reflect it. POWERFUL.
install.packages("rJava") ## Chances are really good that this is already installed as a dependency for another package, but just to be safe, here it is
install.packages("devtools") ## For more granular control of the R environment when you need it, which may not be very often at all
install.packages("git2r") ## If you're going to use Git, this is important because it lets you use git from within R. It's a dependency of devtools though, so it may already be installed
install.packages("arcgisbinding") ## Young and finicky, but once you have it all installed (an ordeal) you should be able to read from and write to file geodatabases from R
install.packages("gridExtra") ## Lets you make grid objects that you can place ggplot figures into. May occasionally be preferable to faceting in ggplot, but rarely
install.packages("shiny") ## Required for working with Shiny tools in any form. Can be maddening
install.packages("purrr") ## Really, really useful for writing functions, particularly those that fail gracefully
install.packages("gstat") ## For spatial and spatio-temporal geostatistical modelling and simulation
install.packages("foreach") ## Parallel looping structures. Sarah McCord's thesis work required this
install.packages("snow") ## If you're doing distributed computing across multiple machines, grab this
require(dplyr)
require(rvest)
require(gsubfn)

url<-'https://en.wikipedia.org/wiki/2014%E2%80%9315_NBA_season'

#stran <- html_session(url) %>% read_html(encoding = "UTF-8")
#tabela <- stran %>% html_nodes(xpath ="//table[5]") %>% .[[1]] %>% html_table()

podatki<-read.csv("podatki.csv", header=TRUE, sep=",", dec=".", stringsAsFactors = FALSE, na.strings = ".")
podatki$Rk<-NULL
podatki$eFG.<-NULL
a<-c(6:28)
suppressWarnings(podatki[a]<-lapply(podatki[a], as.numeric))
podatki<-podatki[!is.na(podatki$PTS),]
#podatki<-na.omit(podatki)
colnames(podatki)[28]<-"PTS"
podatki<-podatki[order(podatki[,28], decreasing = TRUE),]

link<-'http://www.spotrac.com/widget/sport/nba/current-year/rankings-cap/"'
site<-html_session(link) %>% read_html(encoding = "UTF-8")
salaries<-site %>% html_nodes(xpath ="//table") %>% .[[1]] %>% html_table()
place<-site %>% html_nodes(xpath ="//table") %>% .[[1]] %>% html_table()
place<-place[-1]
salaries<-salaries[-1]
salaries$Pos.<-NULL

celatabela<-inner_join(podatki, salaries, by = "Player")
colnames(celatabela)<-c("Player","Position" ,"Age","Team","Games","Started","Minutes","FG Made", "FG Att","FG %","3Pt Made", "3Pt Att", "3Pt %", "2Pt Made", "2Pt Att", "2Pt %", "FT Made", "FT Att", "FT %", "Off. Reb", "Def. Reb", "Tot. Reb", "Assists", "Steals", "Blocks", "Turnovers", "Fouls", "Points", "Salary")
celatabela$Salary<-as.factor(celatabela$Salary)
celatabela$Salary<-gsub("\\$", "", celatabela$Salary)
celatabela$Salary<-gsub("\\,", "", celatabela$Salary)
celatabela$Salary<-as.numeric(celatabela$Salary)

strelci<-data.frame(Player=celatabela$Player, Points=celatabela$Points)

zlink<-'http://hoopshype.com/2015/02/24/where-are-nba-players-born/'
zstran <- html_session(zlink) %>% read_html(encoding = "UTF-8")
ztabela <- zstran %>% html_nodes(xpath ="//table[2]") %>% .[[1]]  %>% html_table()
ztabela<-na.omit(ztabela)
ztabela<-ztabela[-1,-3]
colnames(ztabela)<-c('City','Players')
ztabela$City<-as.factor(ztabela$City)
ztabela$Players<-as.numeric(ztabela$Players)
ztabela$City<-gsub('[[:digit:]]+', '', ztabela$City)
ztabela$City<-gsub('\\.', '', ztabela$City)
ztabela<-ztabela[-11,]
ztabela1<-ztabela
ztabela$Lat<-c('34.052235', '40.792240', '41.881832', '40.002785', '32.736259', '39.790942', '47.608013', '30.471165', '35.040031', '39.299236', '29.761993', '33.753746', '38.889931', '33.792461', '38.627003')
ztabela$Long<-c('-118.243683', '-73.138260', '-87.623177', '-75.183739', '-96.864586', '-86.147685', '-122.335167', '-91.147385', '-89.981873', '-76.609383', '-95.366302', '-84.386330', '-77.009003', '-118.185005', '-90.199402')
ztabela$STATE_NAME<-c('California', 'New York', 'Illinois', 'Pennsylvania', 'Texas', 'Indiana', 'Washington', 'Louisiana', 'Tennessee', 'Maryland', 'Texas', 'Georgia', 'District of Columbia', 'California', 'Missouri')
ztabela$Lat<-as.numeric(ztabela$Lat)
ztabela$Long<-as.numeric(ztabela$Long)
source("lib/uvozi.zemljevid.r", encoding = "UTF-8")
library(ggplot2)

pretvori.zemljevid <- function(zemljevid) {
  fo <- fortify(zemljevid)
  data <- zemljevid@data
  data$id <- as.character(0:(nrow(data)-1))
  return(inner_join(fo, data, by="id"))
}

zda <- uvozi.zemljevid("http://baza.fmf.uni-lj.si/states_21basic.zip", "states")
ztabela <- preuredi(ztabela, zda, "STATE_NAME")
usa<-pretvori.zemljevid(zda)
usa.cont <- usa %>% filter(! STATE_NAME %in% c("Alaska", "Hawaii"))
map <- ggplot() + geom_polygon(data = usa.cont, color='navajowhite3', aes(x = long, y = lat, group=group),fill="navajowhite")
require(ggrepel)
map1 <- map + geom_point(data = ztabela, color = "green4", aes(x = Long, y = Lat, size = Players)) + geom_text_repel(data = ztabela, color='black', aes(x = Long, y = Lat, label = City), size=5)
map1

ekipe<-read.csv('teams__active.csv')
ekipe$Lg<-NULL
ekipe$To<-NULL
ekipe$Yrs<-NULL
ekipe$W.L.<-NULL
colnames(ekipe)<-c('Team', 'Founded', 'Games', 'Won', 'Lost', 'Playoffs', 'Div. titles', 'Conf. titles', 'Championships')
ekipe1<-ekipe
ekipe<-ekipe[-28,]
ekipe$STATE_NAME<-c('Georgia', 'Massachusetts', 'New York', 'North Carolina', 'Illinois', 'Ohio','Texas','Colorado','Michigan','California','Texas','Indiana','California','California','Tennessee','Florida','Wisconsin','Minnesota','Louisianna','New York','Oklahoma','Florida','Pennsylvania','Arizona','Oregon','California','Texas','Utah','District of Columbia')
ekipe$LAT<-c('33.75375', '42.35843', '40.35000','35.227085', '41.881832','41.505493','32.73626','39.742043','42.331429','	37.801239','29.682720','39.769653','34.052235','34.052235','35.040031',	'25.778135','43.038902','44.986656','29.951065','40.79224','35.481918','28.538336','40.00279','33.453388','45.512794','38.575764','29.424349','40.758701','38.88993')
ekipe$LONG<-c('-84.38633', '-71.05977', '-73.949997', '-80.843124','-87.623177','	-81.681290','-96.86459','	-104.991531','	-83.045753','-122.258301','-95.593239','-86.157143','-118.243683','-118.243683','-89.981873','-80.179100','-87.906471','-93.258133','-90.071533','-73.13826','-97.508469','-81.379234','-75.18374','-112.074623','-122.679565','-121.478851','-98.491142','-111.876183','-77.00900')
ekipe$LAT<-as.numeric(ekipe$LAT)
ekipe$LONG<-as.numeric(ekipe$LONG)
ekipe<-preuredi(ekipe,zda,'STATE_NAME')
map2<-map+geom_point(data=ekipe,color='red',size=2,aes(x=LONG,y=LAT)) + geom_text_repel(data=ekipe,color='black',aes(x=LONG,y=LAT,label=Team),size=5)
map2

#graf1 <- ggplot(celatabela$Points, celatabela$Salary, main="Število točk glede na plačo", xlab="Točke", ylab="Plača")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2.8 Example with southern St. Lawrence EwE model for mid-1980s
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "./RawData/South_St_Lawrence_EwE.RData"
#   Script  <- file = "Script/2-8_St_Lawrence_ex.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REFERENCE:
#   Savenkoff, to add
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
library(stringr)
load("./RawData/South_St_Lawrence_EwE.RData")
SSL <- South_St_Lawrence

SSL[[2]][which(SSL[[2]] > 0)] <- 1
rownames(SSL[[2]]) <- colnames(SSL[[2]]) <- SSL[[3]]

sp_SSL <- matrix(ncol = 2, nrow = 29, data = NA, dimnames = list(c(), c('ACCR','SP')))

sp_SSL[,1] <- c('WHA','HAS','HOS','GRS','HSE','SEA','LCO','SCO','LGH','SAP','LAP','FLO','SKA','RED','LDF','SDF','CAP','LPF','PISF','PLSF','SHR','LCRU','ECH','MOL','POL','OBI','LZOO','SZOO','PHY')

sp_SSL[,2] <- c('Balaenoptera physalus - Balaenoptera acutorostrata - Megaptera novaeangliae - Phocoena phocoena - Lagenorhynchus acutus - Lagenorhynchus albirostris',
'Pagophilus groenlandicus',
'Cystophora cristata',
'Halichoerus grypus',
'Phoca vitulina',
'Phalacrocorax carbo - Phalacrocorax auritus - Larus delawarensis - Larus argentatus - Larus marinus - Sterna hirundo - Sterna paradisaea - Cepphus grylle - Oceanodroma leucorhoa - Morus bassanus - Rissa tridactyla - Uria aalge - Alca torda - Fratercula arctica',
'Gadus morhua',
'Gadus morhua',
'Reinhardtius hippoglossoides',
'Hippoglossoides platessoides',
'Hippoglossoides platessoides',
'Limanda ferruginea - Glyptocephalus cynoglossus - Pseudopleuronectes americanus',
'Amblyraja radiata - Malacoraja senta - Leucoraja ocellata',
'Sebastes mentella - Sebastes fasciatus',
'Urophycis tenuis - Melanogrammus aeglefinus - Centroscyllium fabricii - Anarhichas - Cyclopterus lumpus - Lycodes - Macrouridae - Zoarcidae - Lophius americanus - Hippoglossus hippoglossus',
'Myoxocephalus - Tautogolabrus adspersus - Zoarces americanus',
'Mallotus villosus',
'Squalus acanthias - Pollachius virens - Merluccius bilinearis - Cetorhinus maximus',
'Scomber scombrus - Illex illecebrosus',
'Clupea harengus - Scomberesox saurus - Gonatus',
'Argis dentata - Eualus macilentus - Eualus gaimardi - Pandalus montagui',
'Chionoecetes opilio - Hyas',
'Echinarachnius parma - Stronglyocentrotus pallidus - Ophiura robusta',
'Mesodesma deauratum - Cyrtodaria siliqua',
'Parexogone hebes',
'Miscellaneous crustaceans', #to remove OBI
'Euphausiids - chaetognaths', # to remove LZOO
'Oithona similis - Temora longicornis - Pseudocalanus - Calanus finmarchicus',
'Chaetoceros affinis - Chaetoceros - Leptocylindrus minimus - Thalassiiosira nordenskioldii - Thalassiiosira - Fragilariopsis')

# Removing portions of the web for which there is no taxa usable for the analysis, 'OBI' & 'LZOO'
SSL[[2]] <- SSL[[2]][-which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO'), -which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO')]
sp_SSL <- sp_SSL[-which(sp_SSL[,1] == 'OBI' | sp_SSL[,1] == 'LZOO'), ]

S1 <- unique(unlist(str_split(sp_SSL[,2], ' - ')))

load("./RData/Tanimoto_data.RData")
# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
# Format interaction catalogue to fit this table format
    S0 <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
    S0[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
        S0[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
    }


# Have to extract taxonomy for speies that are not found in S0
S1_missing <- which(!S1 %in% S0[,1])

S1_add_S0 <- matrix(ncol = 6, nrow = length(S1_missing), data = "", dimnames = list(c(), c("taxon", "taxonomy", "resource", "non-resource", "consumer", "non-consumer")))

S1_add_S0[, 'taxon'] <- S1[S1_missing]

S1_add_S0[, 'taxonomy'] <- c('Animalia | Chordata | Mammalia | Cetartiodactyla | Delphinidae | Lagenorhynchus | Lagenorhynchus acutus',
'Animalia | Chordata | Mammalia | Carnivora | Phocidae | Halichoerus | Halichoerus grypus',
'Animalia | Chordata | Procellariiformes | Hydrobatidae | Oceanodroma | Oceanodroma leucorhoa',
'Animalia | Chordata | Aves | Pelecaniformes | Sulidae | Morus | Morus bassanus',
'Animalia | Chordata | Aves | Charadriiformes | Alcidae | Alca | Alca torda',
'Animalia | Chordata | Elasmobranchii | Rajiformes | Rajidae | Malacoraja | Malacoraja senta',
'Animalia | Chordata | Elasmobranchii | Squaliformes | Etmopteridae | Centroscyllium | Centroscyllium fabricii',
'Animalia | Arthropoda | Malacostraca | Decapoda | Crangonidae | Argis | Argis dentata',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus macilentus',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus gaimardii',
'Animalia | Echinodermata | Echinoidea | Camarodonta | Strongylocentrotidae | Strongylocentrotus | Strongylocentrotus pallidus',
'Animalia | Mollusca | Bivalvia | Imparidentia | Mesodesmatidae | Mesodesma | Mesodesma deauratum',
'Animalia | Mollusca | Bivalvia | Adapedonta | Hiatellidae | Cyrtodaria | Cyrtodaria siliqua',
'Animalia | Annelida | Polychaeta | Phyllodocida | Syllidae | Parexogone | Parexogone hebes',
'Chromista | Ochrophyta | Bacillariophyceae | Chaetocerotanae | Chaetocerotaceae | Chaetoceros | Chaetoceros affinis',
'Chromista | Ochrophyta | Bacillariophyceae | Leptocylindrales | Leptocylindraceae | Leptocylindrus | Leptocylindrus minimus',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | Thalassiosira nordenskioeldii',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | NA')

 S0 <- rbind(S0, S1_add_S0) #binding missing taxonomies
 rownames(S0) <- S0[, 'taxon']


# #Thinning down catalogue
# S02 <- S0[unique(c(which(S0[, 'resource'] != ""), which(S0[, 'consumer'] != ""))), ]
#
# S1_missing2 <- which(!S1 %in% S02[,1]) #after culling
# S1_missing3 <- S1_missing2[which(!S1_missing2 %in% S1_missing)] #taxo to keep
# S1_add_S0 <- rbind(S1_add_S0, S0[which(S0[, 'taxon'] %in% S1[S1_missing3]), ])
# rownames(S1_add_S0) <- NULL
# S0 <- rbind(S02, S1_add_S0)
# remove(S02,S1_missing3,S1_missing2,S1_missing)

# Predicting interactions
SSL_predict <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.3)

SSL_predict2 <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.2)

SSL_predict_mat <- prediction_matrix(S1 = S1, predictions = SSL_predict)
SSL_predict_mat2 <- prediction_matrix(S1 = S1, predictions = SSL_predict2)
x <- SSL_predict_mat

for(i in 1:nrow(sp_SSL)) {
    Sx <- unique(unlist(str_split(sp_SSL[i,2], ' - ')))
    for(j in 1:length(Sx)){
        for(k in 1:length(S1))
        if(S1[k] %in% Sx == TRUE) {
            colnames(SSL_predict_mat)[k] <- rownames(SSL_predict_mat)[k] <- sp_SSL[i, 2]
            colnames(SSL_predict_mat2)[k] <- rownames(SSL_predict_mat2)[k] <- sp_SSL[i, 2]
        }
    }
}

SSL_predict_mat_combine <- dupl_sp(SSL_predict_mat)
SSL_predict_mat_combine2 <- dupl_sp(SSL_predict_mat2)

SSL_emp <- SSL[[2]]
colnames(SSL_emp) <- rownames(SSL_emp) <- sp_SSL[,2]
SSL_emp <-  dupl_sp(SSL_emp)

accuracy_SSL <- prediction_accuracy_id(predicted = SSL_predict_mat_combine, empirical = SSL_emp)
accuracy_SSL2 <- prediction_accuracy_id(predicted = SSL_predict_mat_combine2, empirical = SSL_emp)
accuracy_SSL
accuracy_SSL2

for(i in 2:nrow(accuracy_SSL[[4]])) {
    print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]))
}

for(i in 2:nrow(accuracy_SSL[[3]])) {
    print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]))
}


SSL_bin_inter <- bin_inter(SSL_predict_mat_combine)
SSL_bin_inter2 <- bin_inter(SSL_predict_mat_combine2)
SSL_emp_bin <- bin_inter(SSL_emp)
SSL_bin_inter <- SSL_bin_inter[which(SSL_bin_inter[, 'FeedInter'] == '1'), ]
SSL_bin_inter2 <- SSL_bin_inter2[which(SSL_bin_inter2[, 'FeedInter'] == '1'), ]
SSL_emp_bin <- SSL_emp_bin[which(SSL_emp_bin[, 'FeedInter'] == '1'), ]

# Load package
library(networkD3)
# Plot
simpleNetwork(as.data.frame(SSL_bin_inter[, c(1,3)]))
simpleNetwork(as.data.frame(SSL_emp_bin[, c(1,3)]))





# remplace , par ' - '
# remplacer les noms de colonnes et lignes
# combiner duplicatas
# rouler fonction du catalogue pour séparer les lignes et colonnes qui ont plusieurs entrées?
# faire l'analyse en séparant toutes les espèces listées, puis comparer l'analyse divisée, compartimenter les résultats (combiner les interactions des espèces qui sont dans un compartiment), et la réseau présenté dans l'article à partir de la matrice de diète.
# Run init.r before other scripts
rm(list=ls())
 # for use in R console.
 # set own relevant directory if working in R console, otherwise ignore if in terminal
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "./Script/0-1-Tanimoto_data.r
#           RData <- file = './RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "./Script/0-1-Interactions_sources.r
#           RData <- file = "./RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = './Script/1-Similarity_matrix.r'
#       RData <- file = './RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = './Script/2-1-Tanimoto_analysis.r'
#           RData <- file = './RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = './Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = './RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("./Script/tanimoto.r") # basic tanimoto similarity
source("./Script/tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("./Script/similarity_taxon.r") # similarity matrix for set of taxa
source("./Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("./Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("./Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/consumer_set_of_resource.R")
source("./Script/resource_set_of_consumer.R")
source("./Script/prediction_accuracy.r") #
source("./Script/prediction_accuracy_id.r") #
source("./Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("./Script/serialNext.r") # function to avoid overwriting existing files in temporary analyses folder
source("./Script/eplot.r") # empty plot for figure generation
source("./Script/tanimoto_analysis.r")
source("./Script/catalog_predictions.r") # computing prediction accuracy ~ # taxa in catalog
source("./Script/catalog_predictions_accuracy.r") # accuracy of predictions for accuracy ~ # taxa in catalog
source("./Script/full_algorithm.r") # full algorithm with similarity measurements included
source("./Script/similarity_full_algorithm.r") # similarity measurements for full algorithm
source("./Script/duplicate_row_col.r") # function to combine duplicated row and column names
source("./Script/bin_inter.r") # function to extract binary interaction from diet matrix


# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2.8 Example with southern St. Lawrence EwE model for mid-1980s
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "./RawData/South_St_Lawrence_EwE.RData"
#   Script  <- file = "Script/2-8_St_Lawrence_ex.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REFERENCE:
#   Savenkoff, to add
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
library(stringr)
load("./RawData/South_St_Lawrence_EwE.RData")
SSL <- South_St_Lawrence

SSL[[2]][which(SSL[[2]] > 0)] <- 1
rownames(SSL[[2]]) <- colnames(SSL[[2]]) <- SSL[[3]]

sp_SSL <- matrix(ncol = 2, nrow = 29, data = NA, dimnames = list(c(), c('ACCR','SP')))

sp_SSL[,1] <- c('WHA','HAS','HOS','GRS','HSE','SEA','LCO','SCO','LGH','SAP','LAP','FLO','SKA','RED','LDF','SDF','CAP','LPF','PISF','PLSF','SHR','LCRU','ECH','MOL','POL','OBI','LZOO','SZOO','PHY')

sp_SSL[,2] <- c('Balaenoptera physalus - Balaenoptera acutorostrata - Megaptera novaeangliae - Phocoena phocoena - Lagenorhynchus acutus - Lagenorhynchus albirostris',
'Pagophilus groenlandicus',
'Cystophora cristata',
'Halichoerus grypus',
'Phoca vitulina',
'Phalacrocorax carbo - Phalacrocorax auritus - Larus delawarensis - Larus argentatus - Larus marinus - Sterna hirundo - Sterna paradisaea - Cepphus grylle - Oceanodroma leucorhoa - Morus bassanus - Rissa tridactyla - Uria aalge - Alca torda - Fratercula arctica',
'Gadus morhua',
'Gadus morhua',
'Reinhardtius hippoglossoides',
'Hippoglossoides platessoides',
'Hippoglossoides platessoides',
'Limanda ferruginea - Glyptocephalus cynoglossus - Pseudopleuronectes americanus',
'Amblyraja radiata - Malacoraja senta - Leucoraja ocellata',
'Sebastes mentella - Sebastes fasciatus',
'Urophycis tenuis - Melanogrammus aeglefinus - Centroscyllium fabricii - Anarhichas - Cyclopterus lumpus - Lycodes - Macrouridae - Zoarcidae - Lophius americanus - Hippoglossus hippoglossus',
'Myoxocephalus - Tautogolabrus adspersus - Zoarces americanus',
'Mallotus villosus',
'Squalus acanthias - Pollachius virens - Merluccius bilinearis - Cetorhinus maximus',
'Scomber scombrus - Illex illecebrosus',
'Clupea harengus - Scomberesox saurus - Gonatus',
'Argis dentata - Eualus macilentus - Eualus gaimardi - Pandalus montagui',
'Chionoecetes opilio - Hyas',
'Echinarachnius parma - Stronglyocentrotus pallidus - Ophiura robusta',
'Mesodesma deauratum - Cyrtodaria siliqua',
'Parexogone hebes',
'Miscellaneous crustaceans', #to remove OBI
'Euphausiids - chaetognaths', # to remove LZOO
'Oithona similis - Temora longicornis - Pseudocalanus - Calanus finmarchicus',
'Chaetoceros affinis - Chaetoceros - Leptocylindrus minimus - Thalassiiosira nordenskioldii - Thalassiiosira - Fragilariopsis')

# Removing portions of the web for which there is no taxa usable for the analysis, 'OBI' & 'LZOO'
SSL[[2]] <- SSL[[2]][-which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO'), -which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO')]
sp_SSL <- sp_SSL[-which(sp_SSL[,1] == 'OBI' | sp_SSL[,1] == 'LZOO'), ]

S1 <- unique(unlist(str_split(sp_SSL[,2], ' - ')))

load("./RData/Tanimoto_data.RData")
# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
# Format interaction catalogue to fit this table format
    S0 <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
    S0[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
        S0[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
    }


# Have to extract taxonomy for speies that are not found in S0
S1_missing <- which(!S1 %in% S0[,1])

S1_add_S0 <- matrix(ncol = 6, nrow = length(S1_missing), data = "", dimnames = list(c(), c("taxon", "taxonomy", "resource", "non-resource", "consumer", "non-consumer")))

S1_add_S0[, 'taxon'] <- S1[S1_missing]

S1_add_S0[, 'taxonomy'] <- c('Animalia | Chordata | Mammalia | Cetartiodactyla | Delphinidae | Lagenorhynchus | Lagenorhynchus acutus',
'Animalia | Chordata | Mammalia | Carnivora | Phocidae | Halichoerus | Halichoerus grypus',
'Animalia | Chordata | Procellariiformes | Hydrobatidae | Oceanodroma | Oceanodroma leucorhoa',
'Animalia | Chordata | Aves | Pelecaniformes | Sulidae | Morus | Morus bassanus',
'Animalia | Chordata | Aves | Charadriiformes | Alcidae | Alca | Alca torda',
'Animalia | Chordata | Elasmobranchii | Rajiformes | Rajidae | Malacoraja | Malacoraja senta',
'Animalia | Chordata | Elasmobranchii | Squaliformes | Etmopteridae | Centroscyllium | Centroscyllium fabricii',
'Animalia | Arthropoda | Malacostraca | Decapoda | Crangonidae | Argis | Argis dentata',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus macilentus',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus gaimardii',
'Animalia | Echinodermata | Echinoidea | Camarodonta | Strongylocentrotidae | Strongylocentrotus | Strongylocentrotus pallidus',
'Animalia | Mollusca | Bivalvia | Imparidentia | Mesodesmatidae | Mesodesma | Mesodesma deauratum',
'Animalia | Mollusca | Bivalvia | Adapedonta | Hiatellidae | Cyrtodaria | Cyrtodaria siliqua',
'Animalia | Annelida | Polychaeta | Phyllodocida | Syllidae | Parexogone | Parexogone hebes',
'Chromista | Ochrophyta | Bacillariophyceae | Chaetocerotanae | Chaetocerotaceae | Chaetoceros | Chaetoceros affinis',
'Chromista | Ochrophyta | Bacillariophyceae | Leptocylindrales | Leptocylindraceae | Leptocylindrus | Leptocylindrus minimus',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | Thalassiosira nordenskioeldii',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | NA')

 S0 <- rbind(S0, S1_add_S0) #binding missing taxonomies
 rownames(S0) <- S0[, 'taxon']


# #Thinning down catalogue
# S02 <- S0[unique(c(which(S0[, 'resource'] != ""), which(S0[, 'consumer'] != ""))), ]
#
# S1_missing2 <- which(!S1 %in% S02[,1]) #after culling
# S1_missing3 <- S1_missing2[which(!S1_missing2 %in% S1_missing)] #taxo to keep
# S1_add_S0 <- rbind(S1_add_S0, S0[which(S0[, 'taxon'] %in% S1[S1_missing3]), ])
# rownames(S1_add_S0) <- NULL
# S0 <- rbind(S02, S1_add_S0)
# remove(S02,S1_missing3,S1_missing2,S1_missing)

# Predicting interactions
SSL_predict <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.3)

SSL_predict2 <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.2)

SSL_predict_mat <- prediction_matrix(S1 = S1, predictions = SSL_predict)
SSL_predict_mat2 <- prediction_matrix(S1 = S1, predictions = SSL_predict2)
x <- SSL_predict_mat

for(i in 1:nrow(sp_SSL)) {
    Sx <- unique(unlist(str_split(sp_SSL[i,2], ' - ')))
    for(j in 1:length(Sx)){
        for(k in 1:length(S1))
        if(S1[k] %in% Sx == TRUE) {
            colnames(SSL_predict_mat)[k] <- rownames(SSL_predict_mat)[k] <- sp_SSL[i, 2]
            colnames(SSL_predict_mat2)[k] <- rownames(SSL_predict_mat2)[k] <- sp_SSL[i, 2]
        }
    }
}

SSL_predict_mat_combine <- dupl_sp(SSL_predict_mat)
SSL_predict_mat_combine2 <- dupl_sp(SSL_predict_mat2)

SSL_emp <- SSL[[2]]
colnames(SSL_emp) <- rownames(SSL_emp) <- sp_SSL[,2]
SSL_emp <-  dupl_sp(SSL_emp)

accuracy_SSL <- prediction_accuracy_id(predicted = SSL_predict_mat_combine, empirical = SSL_emp)
accuracy_SSL2 <- prediction_accuracy_id(predicted = SSL_predict_mat_combine2, empirical = SSL_emp)
accuracy_SSL
accuracy_SSL2

for(i in 2:nrow(accuracy_SSL[[4]])) {
    print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]]))
}


SSL_bin_inter <- bin_inter(SSL_predict_mat_combine)
SSL_bin_inter2 <- bin_inter(SSL_predict_mat_combine2)
SSL_emp_bin <- bin_inter(SSL_emp)
SSL_bin_inter <- SSL_bin_inter[which(SSL_bin_inter[, 'FeedInter'] == '1'), ]
SSL_bin_inter2 <- SSL_bin_inter2[which(SSL_bin_inter2[, 'FeedInter'] == '1'), ]
SSL_emp_bin <- SSL_emp_bin[which(SSL_emp_bin[, 'FeedInter'] == '1'), ]

# Load package
library(networkD3)
# Plot
simpleNetwork(as.data.frame(SSL_bin_inter[, c(1,3)]))
simpleNetwork(as.data.frame(SSL_emp_bin[, c(1,3)]))





# remplace , par ' - '
# remplacer les noms de colonnes et lignes
# combiner duplicatas
# rouler fonction du catalogue pour séparer les lignes et colonnes qui ont plusieurs entrées?
# faire l'analyse en séparant toutes les espèces listées, puis comparer l'analyse divisée, compartimenter les résultats (combiner les interactions des espèces qui sont dans un compartiment), et la réseau présenté dans l'article à partir de la matrice de diète.
# Uvozimo knižnjice
source("lib/libraries.r", encoding = "UTF-8")

###########################################CSV#############################################


#tabela po mesecih


stolpci1 <- c("Leto", "Mesec", "Št.sklenitev")
PoMesecih <-read.csv2("podatki/pomesecih.csv", sep = ";", as.is = TRUE, header = FALSE,
                      col.names = stolpci1, skip = 2, nrows = (372-3), fileEncoding = "cp1250")

#zapolnimo prazne prostore z NA in potem nadomestimo z vrednostmi, ki ji pripradajo:

for (i in stolpci1[-3]){
  PoMesecih[i][PoMesecih[i] == " "] <- NA
  PoMesecih[i] <- na.locf(PoMesecih[i], na.rm = FALSE)
}

#izbrišemo vrstice, ki so NA v zadnjem stolpcu:

PoMesecih <- PoMesecih[!is.na(PoMesecih$Št.sklenitev),]


#Spremenim vrstni red mesecev, da bo pravilen
PoMesecih$Mesec <- factor(PoMesecih$Mesec, levels = 
                  c("Januar", "Februar", "Marec", "April", "Maj", "Junij",
                    "Julij", "Avgust", "September", "Oktober", "November", "December"))


#Leto spremenim v številsko spremenljivko
PoMesecih$Leto <- as.numeric(PoMesecih$Leto)




#tabela po regiji

stolpci2 <- c("Spol", "Regija", "Starost", "Leto", "Število")
Po_Regijah_Letih <- read.csv2("podatki/poregijahinletih.csv", sep = ";", as.is = TRUE,
                              header = FALSE, col.names = stolpci2,
                              skip = 3, nrows = (3461-3), fileEncoding = "cp1250")


#Urejanje - NA:

for (i in stolpci2[c(-5)]){
  Po_Regijah_Letih[[i]][Po_Regijah_Letih[i] == " "] <- NA
  Po_Regijah_Letih[[i]] <- na.locf(Po_Regijah_Letih[[i]], na.rm = FALSE)
}


#izbrišemo vrstice, ki so NA v zadnjem stolpcu:

Po_Regijah_Letih <- Po_Regijah_Letih[!is.na(Po_Regijah_Letih$Število),]

Starost <- factor(Po_Regijah_Letih$Starost, levels = 
                  c("Pod 15 let","15-19 let","20-24 let","25-29 let",
                    "30-34 let","35-39 let","40-44 let","45-49 let",
                    "50-54 let","55-59 let","60 ali več let"))
Po_Regijah_Letih$Starost <- Starost

Po_Regijah_Letih$Regija <- as.factor(Po_Regijah_Letih$Regija)


##Uvozim tabelo ločitve:
stolpci3 <- c("Regija", "Leto", "Razveze")
razveze <- read.csv2("podatki/razveze.csv", sep = ";", as.is = TRUE,
                              header = FALSE, col.names = stolpci3,
                              skip = 4, nrows = (244-4), fileEncoding = "cp1250")


#Urejanje - NA:

for (i in stolpci3[c(-3)]){
  razveze[[i]][razveze[i] == " "] <- NA
  razveze[[i]] <- na.locf(razveze[[i]], na.rm = FALSE)
}


#izbrišemo vrstice, ki so NA v zadnjem stolpcu:

razveze <- razveze[!is.na(razveze$Razveze),]

razveze$Leto <- razveze$Leto %>% as.character() %>% as.factor()



###########################################HTML#############################################
link <- "http://www.cdc.gov/nchs/nvss/marriage_divorce_tables.htm" 
stran <- html_session(link) %>% read_html(encoding = "UTF-8") 

tabele <- stran %>% html_nodes(xpath ="//table") 
poroke.USA <- tabele %>% .[[1]] %>% html_table()  
locitve.USA <- tabele %>% .[[2]] %>% html_table()  

#Potrebujem le prve dva stolpca
poroke.USA <- poroke.USA[,c(1,2)]
locitve.USA <- locitve.USA[,c(1,2)]

names(poroke.USA) <- c("Leto", "Poroke")
names(locitve.USA) <- c("Leto", "Ločitve")

#V drugem stolpcu moram izbrisati vejice
poroke.USA$Poroke <- poroke.USA$Poroke %>% gsub("\\,", "", .) %>% as.numeric()
locitve.USA$Ločitve <- locitve.USA$Ločitve %>% gsub("\\,", "", .) %>% as.numeric()

#V prvem stolpcu moram poporaviti letnice, saj so se zraven uvozile še opombe kot številke
poroke.USA$Leto <- poroke.USA$Leto %>% substr(1,4) %>% as.factor()
locitve.USA$Leto <- locitve.USA$Leto %>% substr(1,4) %>% as.factor()




################################GRAFI######################################################

#Prvi graf bo prikazoval število sklenitev glede na mesec ter primerjal leti 1990 in 2014
#Najprej leto spremenimo v FAKTOR, da bomo lahko primerjali leto 1990 in leto 2014

PoMesecih$Leto <- as.factor(PoMesecih$Leto)

GRAF1 <- ggplot(filter(PoMesecih, Leto == 1990 | Leto == 2014), aes(x=Mesec, y=Št.sklenitev, fill=Leto)) + 
  geom_bar(stat = "identity", position = "dodge") + 
  labs(title ="Sklenitve zakonskih zvez po mesecih")+
  theme_minimal()+
  theme(axis.text.x = element_text(angle = 45, vjust = 0.5))


##Drugi graf narišem glede na starost in spet primerjam leto, ponovno spremenim leto v faktor
Po_Regijah_Letih$Leto <- as.factor(Po_Regijah_Letih$Leto)

GRAF2 <- ggplot(data = Po_Regijah_Letih %>% 
                  filter(Leto == "2004" | Leto == "2014") %>%
                  group_by(Starost, Leto) %>%
                  summarise(Število = sum(Število)/2),
                aes(x=Starost, y=Število, color=Leto)) + 
  geom_line(aes(color = Leto, group=Leto))+
  labs(title ="Sklenitve zakonskih zvez po starostnih skupinah")+
  theme_minimal()+
  theme(axis.text.x = element_text(angle = 45, vjust = 0.5))


##Tortni graf glede na leto, da vidim koliko procentov vseh porok je bilo glede na leto
##Izberem 3 leta: 1990, 2000, 2014
GRAF3 <- ggplot(data = PoMesecih %>% filter(Leto == 1990 |Leto == 2000 |Leto == 2014) %>%
                  group_by(Leto) %>% summarise(Št.sklenitev = sum(Št.sklenitev)),
                aes(x="", y=Št.sklenitev, fill=Leto)) + 
  geom_bar(width = 1, stat = "identity") + 
  geom_text(aes(y = Št.sklenitev/3 + 
                  c(0, cumsum(Št.sklenitev)[-length(Št.sklenitev)]), 
                label = percent(Št.sklenitev/sum(Št.sklenitev))), size=5)+
  coord_polar(theta = "y")+
  scale_y_continuous(breaks=NULL)+
  theme_minimal()+
  guides(fill=guide_legend(ncol=2, title=NULL))+
  labs(title ="Število sklenitev glede na leto", x="", y="")

##Četrti graf prikazuje poroko glede na starostno skupino - Ženin/Nevesta

GRAF4 <- ggplot(data = group_by(Po_Regijah_Letih, Starost, Spol)
                %>% summarise(Število = sum(Število)),
                aes(x=Starost, y=Število, color=Spol)) + 
  geom_line(aes(color = Spol, group=Spol))+
  labs(title ="Sklenitve zakonskih zvez po starostnih skupinah glede na spol")+
  theme_minimal()+
  theme(axis.text.x = element_text(angle = 45, vjust = 0.5))




###############################################
### COMMONLY USED PACKAGES IN AIM R SCRIPTS ###
###############################################

#### DATA WRANGLING ####
install.packages(
  c(
    "dplyr", ## Notably useful for data frame manipulation with group_by(), summarize(), and mutate() and the piping operator %>%. Do you have a moment to hear the good news of our savior, piping?
    "tidyr", ## Lots of useful things, but specifically gather() and spread() for converting wide data frames into long ones and vice versa
    "stringr", ## All about character strings. Great for str_split() in particular, but the whole str_ family of functions are A+
    "RODBC", ## Allows R to pass SQL queries to Access databases and pull out the results
    "XLSX", ## Read in modern Excel workbooks and spreadsheets
    "broom" ## Get stats objects into tidy data frames. Not as common
  )
)

#### SPATIAL DATA ####
install.packages(
  c(
    "sp", ## Functions for manipulating spatial objects. If you want a Spatial _____ Data Frame, this is part of the deal
    "spsurvey", ## Contains plenty, but the most important to AIM is the GRTS function
    "rgeos", ## Additional spatial object functions
    "rgdal", ## Contains the mission critical readOGR() function that we read shapefiles in with
    "raster" ## Everything you didn't know you needed for dealing with rasters
  )
)

#### DATA VISUALIZATION ####
install.packages(
  c(
    "ggplot2", ## The go-to for figure generation. Most R-using scientists AND Nate Silver use it, so you should too
    "ggthemes", ## Quick themes to painlessly apply to figures from ggplot
    "ggmap" ## Mapping support for ggplot
  )
)

#### MISCELLANEOUS PACKAGES ####
install.packages("arcgisbinding") ## Young and finicky, but once you have it all installed (an ordeal) you should be able to read from and write to file geodatabases from R
install.packages("gridExtra") ## Lets you make grid objects that you can place ggplot figures into. May occasionally be preferable to faceting in ggplot, but rarely
install.packages("shiny") ## Required for working with Shiny tools in any form. Can be maddening
install.packages("purrr") ## Really, really useful for writing functions, particularly those that fail gracefully# Copyright (C) 2016 Electronic Arts Inc.  All rights reserved.
str(mtcars)

print("Sleeping for 15 seconds")
Sys.sleep(15)


print("Saving RData file")
dir.create("/var/www/html/RServer/reports/mtcars")
save(mtcars, file = "/var/www/html/RServer/reports/mtcars/mtcars.RData")


fit <- lm(mpg~am + wt + hp, data = mtcars) 
summary(fit)


print("Saving Model")
Sys.sleep(10)
save(fit, file = "/var/www/html/RServer/reports/mtcars/Model.RData")
# Copyright (C) 2016 Electronic Arts Inc.  All rights reserved.
warning("This is a warning!")

tryCatch({ 
  stop("This is an error!")
}, error = function(cond) {
  message("Caught the error.")
})   

stop("This is an error!")
print("Reached end of script!")
# Copyright (C) 2016 Electronic Arts Inc.  All rights reserved.
path <- "/var/www/html/RServer/logs"

if (Sys.info()['sysname'] == "Windows") { 
  path <- "C:/wamp/www/RServer/logs"
}

if ("DT" %in% rownames(installed.packages()) == FALSE) {
  install.packages("DT", repos='http://cran.us.r-project.org') 
} 
library(DT)
 
loadTaskData <- function(daysHistory = 60) { 
  events <- data.frame()  
  
  for (file in list.files(path, full.names = TRUE)) { 
    date <- as.Date(strsplit(file, "_", fixed = TRUE)[[1]][2]) 
    daysAgo <- as.numeric(Sys.Date() - date, units = "days")
    
    if (daysAgo <= daysHistory) {  
      res <- readLines(file)
      
      for (line in res) { 
        
        outcome <- NULL
        
        if (length(grep("R Script completed successfully", line)) > 0) {
          outcome <- "Success"
        }

        if (length(grep("R Script failed", line)) > 0 || length(grep("Unable to run R Script", line)) > 0) { 
          outcome <- "Failure"
        }
        
        if (length(grep("R Script was aborted", line)) > 0) { 
          outcome <- "Aborted"
        }
        
        if (!is.null(outcome)) {
        
          # get the task name           
          atts <- strsplit(line, ":", fixed = TRUE)[[1]]
          task <- atts[length(atts)]
          task <- sub("^\\s+|\\s+$", "", task)
          
          # get timestamp 
          atts <- strsplit(line, ": ", fixed = TRUE)[[1]]
          timestamp <- atts[1]
          
          if (grepl("UTC", line)) {
            timestamp <- gsub("UTC ","", timestamp)
            timestamp <- strptime(timestamp, "%a %b %d %H:%M:%S %Y", tz = "UTC") 
          }
          else {
            if (grepl("PDT", line)) {
              timestamp <- gsub("PDT ","", timestamp)
            }else {
              timestamp <- gsub("PST ","", timestamp)
            }
            
            timestamp <- strptime(timestamp, "%a %b %d %H:%M:%S %Y", tz = "PST8PDT") 
          }

          events <- rbind(events, data.frame(TaskName = c(task), CompletionTime = c(as.character(timestamp)), Outcome = c(outcome), timestamp = c(timestamp)))   
        } 
      }
    }
  }  

  # sort by event time 
  if (nrow(events) > 0) {
    events <- events[order(events$timestamp, decreasing = TRUE), ]
  }
  
  events$timestamp <- NULL
  return (events) 
}

# Copyright (C) 2016 Electronic Arts Inc.  All rights reserved.
libraries <- c("rmarkdown", "yaml", "scales")  
for (lib in libraries) {
  if (lib %in% rownames(installed.packages()) == FALSE) {
    install.packages(lib, repos='http://cran.us.r-project.org')  
  } 
} 

require(rmarkdown)      
render("TaskReport.rmd", output_format = "html_document", output_file = "RServerTasks.html")      

if (Sys.info()['sysname'] == "Windows") {  
  file.copy("RServerTasks.html", "C:/wamp/www/RServer/reports/RServer/RServerTasks.html", overwrite = TRUE)     
} else {
  file.copy("RServerTasks.html", "/var/www/html/RServer/reports/RServer/RServerTasks.html", overwrite = TRUE)      
}
# Copyright (C) 2016 Electronic Arts Inc.  All rights reserved.

libraries <- c("rmarkdown", "yaml", "scales")  
for (lib in libraries) {
  if (lib %in% rownames(installed.packages()) == FALSE) {
    install.packages(lib, repos='http://cran.us.r-project.org')  
  } 
} 

  
require(rmarkdown)   
render("ServerReport.Rmd", output_format = "html_document", output_file = "RServerReport.html")      
 
if (Sys.info()['sysname'] == "Windows") { 
  render("ServerReport.Rmd", output_format = "pdf_document", output_file = "RServerReport.pdf")    
  render("ServerReport.Rmd", output_format = "word_document", output_file = "RServerReport.docx")    
  
  file.copy("RServerReport.pdf", "C:/wamp/www/RServer/reports/RServer/RServerReport.pdf", overwrite = TRUE)     
  file.copy("RServerReport.html", "C:/wamp/www/RServer/reports/RServer/RServerReport.html", overwrite = TRUE)       
  file.copy("RServerReport.docx", "C:/wamp/www/RServer/reports/RServer/RServerReport.docx", overwrite = TRUE)     
   
} else {
  file.copy("RServerReport.html", "/var/www/html/RServer/reports/RServer/RServerReport.html", overwrite = TRUE)       
}
# Copyright (C) 2016 Electronic Arts Inc.  All rights reserved.
print("Hello World!")
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        options = NULL,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmOptions R6 object.
#'
#' An interface to SBATCH settings.
SlurmOptions <- R6::R6Class("SlurmOptions",
    public = list(
        options = c(sbatch_opts$nodes(1),
                    sbatch_opts$memory("8g"),
                    sbatch_opts$cpus_per_task(1),
                    sbatch_opts$time("00:30:00")),
        initialize = function(options = c()) {
            for (opt in options) {
                self$options <- sbatch_opts_insert(opt, self$options)
            }
        },
        for_slurm_script = function() {
            comments <- "#!/bin/bash"

            for (opt in self$options) {
                comments <- paste(comments, paste("#SBATCH", opt), sep = "\n")
            }

            return(comments)
        }
    )
)
#' SlurmSettings R6 object.
#'
#' An interface to SBATCH settings.
SlurmSettings <- R6::R6Class("SlurmSettings",
    public = list(
        options = c(sbatch_opts$nodes(1),
                    sbatch_opts$memory("8g"),
                    sbatch_opts$cpus_per_task(1),
                    sbatch_opts$time("00:30:00")),
        initialize = function(options = c()) {
            for (opt in options) {
                self$options <- sbatch_opts_insert(opt, self$options)
            }
        },
        for_command_line = function() {
            line <- ""

            for (opt in self$options) {
                line <- paste(line, opt)
            }

            return(line)
        },
        for_slurm_script = function() {
            comments <- "#!/bin/bash"

            for (opt in self$options) {
                comments <- paste(comments, paste("#SBATCH", opt), sep = "\n")
            }

            return(comments)
        }
    )
)
#' Fit linear models with each column of \code{y}
#' as dependent variables and the fixed and random
#' effects as independent variables.
#' Independent variables lacking variation are omitted.
#' Returns the residual matrix.
adjust.columns <- function(y, fixed.effects=NULL, random.effects=NULL) {
    stopifnot(is.matrix(y))
    stopifnot(is.null(fixed.effects) || (is.matrix(fixed.effects) || is.data.frame(fixed.effects)) && nrow(y) == nrow(fixed.effects))
    stopifnot(is.null(random.effects) || nrow(y) == nrow(random.effects))
    
    remove.invariant.columns <- function(x) {
        if (is.null(x)) return(x)
        is.variable <- apply(x, 2, function(x) length(unique(x))) > 1
        var.idx <- which(is.variable)
        if (length(var.idx) == 0) NULL
        else x[,var.idx,drop=F]
    }

    fixed.effects <- remove.invariant.columns(fixed.effects)
    random.effects <- remove.invariant.columns(random.effects)

    if (is.null(fixed.effects) && is.null(random.effects)) return(y)

    if (is.null(random.effects)) {
        if (is.data.frame(fixed.effects))
            fixed.effects <- do.call(cbind, lapply(fixed.effects, simplify.variable))        
        fit <- lm.fit(x=fixed.effects, y=y)
        return(residuals(fit))
    }
    
    data <- data.frame(random.effects, stringsAsFactors=F)
    formula <- "y ~"
    if (!is.null(fixed.effects)) {
        formula <- paste(formula, paste(colnames(fixed.effects), collapse=" + "), "+")
        data <- data.frame(data, fixed.effects, stringsAsFactors=F)
    }
    formula <- paste(formula, paste("(1 |", colnames(random.effects), ")", collapse=" + "))
    
    ret <- sapply(1:ncol(y), function(i) {
        data$y <- y[,i]
        tryCatch({
            residuals(lme4::lmer(formula, data=data))
            ## chose lme4 because it is faster than nlme
        }, error=function(e) {
            print(e)
            cat("For variable", i, "ignoring random effects.\n")
            tryCatch({
                residuals(lm(y ~ ., data=data))
            }, error=function(e) {
                print(e)
                cat("For variable", i, "setting all values to missing.\n")
                rep(NA, nrow(data))
            })
        })
    })
    dimnames(ret) <- dimnames(y)
    ret
}
#
# Example R code to install packages
# See http://cran.r-project.org/doc/manuals/R-admin.html#Installing-packages for details
#

###########################################################
# Update this line with the R packages to install:

my_packages = c('shiny', 
                'shinyBS', 
                'shinyStore',
                'RCurl', 
                'httr',
                'jsonlite', 
                'rjson',
                'dplyr',
                'tidyr', 
                'lubridate',
                'rhandsontable',
                'sqldf',
                'stringi',
                'digest', 
                'plotly',
                'scales')

###########################################################

install_if_missing = function(p) {
  if (p %in% rownames(installed.packages()) == FALSE) {
    install.packages(p, dependencies = TRUE)
  }
  else {
    cat(paste("Skipping already installed package:", p, "\n"))
  }
}
invisible(sapply(my_packages, install_if_missing))
#!/usr/bin/env RScript
library(parallel)
library(iterators)
library(foreach)
library(doParallel)
library(proto)
library(argparse)

parser <- ArgumentParser()
parser$add_argument('input', help = 'input csv file')
parser$add_argument('gameplayInput', help = 'input gameplay video')
parser$add_argument('output', help = 'output video file')
parser$add_argument('--fps', type = 'integer', default = 3, help = 'frames per second')
parser$add_argument('--dpi', type = 'integer', default = 72, help = 'dpi for generated video frames')
parser$add_argument('--tempdir', help = 'working directory for intermediate files')
parser$add_argument('--graphcolour', default = 'red')
args <- parser$parse_args()

main <- function()
{
	fps <- args$fps
	input <- args$input
	gameplayInput <- args$gameplayInput
	output <- args$output
	dpi <- args$dpi
	frameDir <- if (is.null(args$tempdir)) tempdir() else args$tempdir
	graphColour <- args$graphcolour

	videoAttrs <- system(paste0('ffprobe -v error -show_entries stream=width,height,r_frame_rate ',
		'-of default=noprint_wrappers=1:nokey=1 ', gameplayInput), intern = T)

	videoRes = as.integer(videoAttrs[1:2])
	videoSize = videoRes / dpi
	fpsTokens = as.integer(unlist(strsplit(videoAttrs[3], '/')[1]))
	gameplayFps <- fpsTokens[1] / fpsTokens[2]
	dar <- paste0(videoRes[1], '/', videoRes[2])

	message('Input gameplay runs at ', gameplayFps, ' FPS at ', videoRes[1], 'x', videoRes[2])

	data <- read.csv(input)
	data$offsetSeconds = data$offset / 1000

	duration <- max(data$offsetSeconds)
	frames <- floor(duration * fps)
	cores <- detectCores()
	message('Rendering ', frames, ' frames using ', cores, ' cores')

	cluster <- makeCluster(cores)
	registerDoParallel(cluster)

	foreach(i = 1:frames, .packages = 'ggplot2') %dopar% {
		toRender <- subset(data, offset < i / fps * 1000)
		plot <- ggplot(toRender, aes(x = offsetSeconds, y = value)) +
			geom_line(color = graphColour, size = 2) +
			labs(x = 'Time (s)', y = 'GSR (microsiemens)') +
			ylim(c(floor(min(data$value)), ceiling(max(data$value)))) +
			xlim(c(0, duration)) +
			theme(plot.background = element_rect(fill = 'transparent'),
				panel.background = element_blank())
		ggsave(paste0(frameDir, '/', i, '.png'), plot,
			width = videoSize[1], height = videoSize[2], dpi = dpi, bg = 'transparent')
	}

	stopCluster(cluster)

	fpsRatio <- gameplayFps / fps
	tempVideoPath = paste0(frameDir, '/', 'frames.mov')
	message('Rendering video from frames: ', tempVideoPath)
	system(paste0('ffmpeg -v error -y -r ', gameplayFps, ' -framerate ', fps,
		' -i "', frameDir, '/%d.png" ',
		' -filter:v "setpts=', fpsRatio, '*PTS" -vcodec qtrle ', tempVideoPath))

	message('Merging with gameplay')
	system(paste0('ffmpeg -v error -y -r ', gameplayFps, ' -i "', gameplayInput, '" -i "', tempVideoPath, '" ',
		' -filter_complex "[0:v]format=rgba[a];',
		'[1:v]setdar=', dar, ',format=yuva420p,colorchannelmixer=aa=0.1[b];',
		'[a][b]overlay=shortest=1"',
		' ', output))
}

dummy <- main()# 4. faza: Analiza podatkov

podatki1 <- data.frame(PoMesecih %>% group_by(Leto) 
                       %>% summarise(Sklenitve = sum(Št.sklenitev)))

#apoved
LMZ <- lm(data = podatki1, Sklenitve ~ Leto)
Z <- predict(LMZ, data.frame(Leto = seq(2024, 2044, 10)))
# 3. faza: Izdelava zemljevida

# 3. faza: Izdelava zemljevida

source("lib/uvozi.zemljevid.r", encoding = "UTF-8")
library(ggplot2)
library(dplyr)


# Uvozimo zemljevid.
zemljevid <- uvozi.zemljevid("http://biogeo.ucdavis.edu/data/gadm2.8/shp/SVN_adm_shp.zip",
                             "SVN_adm1", encoding = "UTF-8")


# Preuredimo podatke, da jih bomo lahko izrisali na zemljevid.

pretvori.zemljevid <- function(zemljevid) {
  fo <- fortify(zemljevid)
  data <- zemljevid@data
  data$id <- as.character(0:(nrow(data)-1))
  return(inner_join(fo, data, by="id"))
}


ZEM <- pretvori.zemljevid(zemljevid)

#Naredim zemljevid, ki prikazuje število sklenjenih zakonskih zvez glede na regijo
ZEM_1 <- ggplot() + geom_polygon(data = group_by(Po_Regijah_Letih, Regija) 
                                           %>% summarise(Število = sum(Število)) %>%
                                             right_join(ZEM, by = c("Regija" = "NAME_1")),
                                           aes(x = long, y = lat, group = group, fill = Število),
                                           color = "darkgrey") +
  scale_fill_gradient(low =  "#FF0000", high ="#11FF00")+
  guides(fill = guide_colorbar(title = "Število sklenitev")) +
  ggtitle("Število sklenitev po regijah")
#IMENA REGIJ
ZEM_1 <- ZEM_1 +
  geom_text(data = ZEM %>% group_by(id, NAME_1) %>% summarise(x = mean(long), y = mean(lat)),
            aes(x = x, y = y, label = NAME_1), size = 2.5)
#OZADJE
ZEM_1 <- ZEM_1 +
  labs(x="", y="")+
  scale_y_continuous(breaks=NULL)+
  scale_x_continuous(breaks=NULL)+
  theme_minimal()


library(knitr) 
library(ggplot2) 
require(dplyr) 
library(rvest) 
require(gsubfn) 
library(maptools)
library(sp)
library(digest)
library(MASS)
require(zoo)
library(mgcv)
library(magrittr)
library(httr)
library(scales)

# Uvozimo funkcije za delo z datotekami XML.
source("lib/xml.r", encoding = "UTF-8")

# Uvozimo funkcije za pobiranje in uvoz zemljevida.
source("lib/uvozi.zemljevid.r", encoding = "UTF-8")create_dtm <- function( path ) {

  library(tm)

  a <- Corpus( DirSource( path, encoding = "UTF-8" ) )

  ## bunch of cleanup and transformations
  a <- tm_map(a, removeNumbers )
  a <- tm_map(a, stripWhitespace )
  a <- tm_map(a, removePunctuation )
  a <- tm_map(a, tolower )
  a <- tm_map(a, function(x) iconv(x, to='UTF-8', sub='byte') )
  a <- tm_map(a, removeWords, stopwords("finnish") )

  ## transform back to plaintext documents
  a <- tm_map(a, PlainTextDocument)

  ## compute word frequencies
  dtm <-DocumentTermMatrix(a) ## , control = list( bounds = list( global = c( minDocFreq, maxDocFreq ) ) ) )

  frequency <- col_sums( dtm , na.rm = T )
  frequency <- sort(frequency, decreasing=TRUE)

  upper = floor( length( frequency ) * .005 )
  lower = floor( length( frequency) * .75 )
  upper = frequency[ upper ]
  lower = frequency[ lower ]
  upper = as.integer( upper )
  lower = as.integer( lower ) + 1

  dtm2 = DocumentTermMatrix( a , control = list( bounds = list( global = c( lower, upper ) ) ) )

  ## throw away columns with 0 indicators
  dtm3 <- dtm2[ row_sums( dtm2 ) > 0, ]

  return( dtm3 )

}

create_model <- function( dtm, k ) {

   library(topicmodels)

   burnin = 1000
   iter = 1000
   keep = 50

   model <- LDA( dtm , k = k, method = "Gibbs", control =  list(burnin = burnin, iter = iter, keep = keep) )

   return( model )

}

check_fitness <- function( dtm , k ) {

  library(topicmodels)
  library(Rmpfr)

  burnin = 1000
  iter = 1000
  keep = 50

  model <- create_model( dtm , k )
  ll <- model@logLiks[ -c(1:(burnin/keep)) ]

  precision = 2000L
  llMed <- median( ll )
  ll = as.double( llMed - log( mean( exp( -mpfr(ll , prec = precision) + llMed ) ) ) )

  return( ll )

}


## from http://www.r-bloggers.com/a-link-between-topicmodels-lda-and-ldavis/

visualize_topicmodel <- function(fitted, corpus, doc_term){
    # Required packages
    library(topicmodels)
    library(dplyr)
    library(stringi)
    library(tm)
    library(LDAvis)

    # Find required quantities
    phi <- posterior(fitted)$terms %>% as.matrix
    theta <- posterior(fitted)$topics %>% as.matrix
    vocab <- colnames(phi)
    doc_length <- vector()
    for (i in 1:length(corpus)) {
        temp <- paste(corpus[[i]]$content, collapse = ' ')
        doc_length <- c(doc_length, stri_count(temp, regex = '\\S+'))
    }
    temp_frequency <- inspect(doc_term)
    freq_matrix <- data.frame(ST = colnames(temp_frequency),
                              Freq = colSums(temp_frequency))
    rm(temp_frequency)

    # Convert to json
    json_lda <- LDAvis::createJSON(phi = phi, theta = theta,
                            vocab = vocab,
                            doc.length = doc_length,
                            term.frequency = freq_matrix$Freq)

    return(json_lda)
}
source('topics.r')

df = data.frame( k = integer(), ll =integer() )

for( path in commandArgs(trailingOnly=TRUE) ) {

  for( f in list.files(path) ){
  	load( paste(path, f, sep = '') )
  	k <- model@k
  	ll <- check_fitness_model( model )
  	row = c(k, ll)
  	df[ nrow(df)+1,] <- row
  }

  print("Examinging", path )
  print("Best fit log likelihood", which.max( df$ll ) )
  print("Best fit k", df$k[ which.max( df$ll ) ] )
  print("") ## Empty line

}
#' Class for basic queuing system functions
#'
#' Provides the basic functions needed to communicate between machines
#' This should abstract most functions of rZMQ so the scheduler
#' implementations can rely on the higher level functionality
QSys = R6::R6Class("QSys",
    public = list(
        initialize = function() {
            private$job_num = 1
            private$zmq_context = rzmq::init.context()
        },

        # Submits one job to the queuing system
        #
        # @param memory      The amount of memory (megabytes) to request
        # @param log_worker  Create a log file for each worker
        submit_job = function(memory=NULL, log_worker=FALSE) {
            stop("Derived class needs to overwrite submit_job()")
        },

        # Send the data common to all workers, only serialize once
        send_common_data = function() {
            if (is.null(private$common_data))
                stop("Need to set_common_data() first")

            rzmq::send.socket(socket = private$socket,
                              data = private$common_data,
                              serialize = FALSE,
                              send.more = TRUE)
        },

        # Send iterated data to one worker
        send_job_data = function(...) {
            rzmq::send.socket(socket = private$socket, data = list(...))
        },

        # Read data from the socket
        receive_data = function() {
            rzmq::receive.socket(private$socket)
        },

        # Make sure all resources are closed properly
        cleanup = function() {
        }
    ),

    active = list(
        # We use the listening port as scheduler ID
        id = function() private$port
    ),

    private = list(
        zmq_context = NULL,
        socket = NULL,
        port = NA,
        master = NULL,
        job_num = NULL,
        common_data = NULL,

        set_common_data = function(fun, const, seed) {
            private$common_data = serialize(list(fun=fun, const=const, seed=seed), NULL)
        },

        # Create a socket and listen on a port in range
        #
        # @param fun    The function to be called
        # @param const  Constant arguments to the function call
        # @param seed   Common seed (to be used w/ job ID)
        # @return       Sets "port" and "master" attributes
        listen_socket = function(min_port, max_port=min_port, n_tries=100) {
            if (is.null(private$zmq_context))
                stop("QSys base class not initialized")

            private$socket = rzmq::init.socket(private$zmq_context, "ZMQ_REP")

            on.exit(sink())
            sink('/dev/null')
            for (i in 1:n_tries) {
                exec_socket = sample(min_port:max_port, size=1)
                addr = paste0("tcp://*:", exec_socket)
                port_found = rzmq::bind.socket(private$socket, addr)
                if (port_found)
                    break
            }
            sink()
            on.exit()

            if (!port_found)
                stop("Could not bind to port range (6000,8000) after 100 tries")

            private$port = exec_socket
            private$master = sprintf("tcp://%s:%i", Sys.info()[['nodename']], exec_socket)
        }
    ),

    cloneable = FALSE
)
#' ggplot_builder function
#'
#' This function builds a ggplot2 function to plot data
#' @param d Table of data
#' @param x,y,z Variables for each dimension
#' @param logx,logy Log the variable first. Defaults to F.
#' @param geom Select a ggplot2 geometry (currently point,line,histogram,bar,boxplot,violin)
#' @param facet Facet plot by values in a column
#' @param smooth Add a smooth line to point plots (gam,lm,loess,rlm,glm,auto)
#' @param xlim Range displayed on x-axis
#' @param ylim Range displayed on y-axis
#' @param xrotate Angle to rotate x-axis labels (90=vertical)
#' @param colour A variable to colour by
#' @param fill A variable to fill by
#' @param man_colour Select a solid colour
#' @param man_fill Select a solid fill colour
#' @param bar.position Position of bars in a bar plot (stack,dodge,fill)
#' @param bins Add a stat_bin with this number of bins
#' @param binwidth Size of binwidth in binned plots (histogram)
#' @param outliers Set outliers=F to remove outliers from boxplot
#' @param varwidth Set varwidth=T to plot boxplots with variable width based on dataset size
#' @param gradient Select gradient colour scheme (default,Matlab)
#' @param gradient.steps Set number of shades in gradient
#' @param gradient.range Set range of values covered by gradient
#' @param colourset Select colour scheme (default,Set1,Set2,Set3,Spectral)
#' @param cut_method Select method for binning continuous X axis in boxplots (number,interval,width see cut_interval etc.)
#' @param cut.n Binning number applied to cut_method
#' @param enable.plotly convert to interactive Plotly plot
#' @param theme Set ggplot theme (grey,bw,dark,light,void,linedraw,minimal,classsic)
#' @param factorlim Set maximum levels allowed to use factors for plotting (default=50)
#' @param stat.method Set stat method for barplots (count,identity,summary) (default=bin)
#' @param stat.func Set summary function for stat.method="summary" (default=mean)
#' @param coord_flip Flip the x and y axes (default=F)
#' @param tile_height Set height of tile for geom_tile
#' @param tile_width Set width of tile for geom_tile
#' @param condense Use bigvis package to summarise overlapping points in large datasets
#' @param condense.func Function used to condense (mean,median,sum,count)
#' @param condense.x Size of bin to use on X axis to find overlapping points
#' @param condense.y Size of bin to use on Y axis to find overlapping points
#' @keywords ggplot wrapper builder
#' @export
#' @examples
#' ggplot_builder()


ggplot_builder<-function(d,x,y=NA,geom="point",facet=NA,smooth=NA,smooth.se=T,xlim=NA,ylim=NA,xrotate=0,colour=NA,
                         fill=NA,bar.position="stack",binwidth=0,bins=0,outliers=T,varwidth=F,enable.plotly=F,
                         theme="grey",logx=F,logy=F,man_colour=NA,man_fill=NA,tile_height=NA,tile_width=NA,
                         gradient="default",gradient.steps=10,gradient.range=NA,colourset="default",coord_flip=F,
                         cut_method="number",cut.n=10,factorlim=50,stat.method="count",stat.func="mean",
                         condense=F,condense.func="mean",condense.x=10,condense.y=10){
library(plotly)
library(colorRamps)
library(ggplot2)
library(bigvis)

###Avoid plotting with large factors
for(i in c(facet,colour,fill,x)){
  factor_limit(d,i,factorlim)
}
if(!geom %in% c("histogram","bar") | (geom=="bar" & stat.method!="count")){ ##Check Y variable if applicable
  factor_limit(d,y,factorlim)
}

ml<-matlab.like2(gradient.steps)

###build plot
a<-list()
g<-list()
if(geom=="point"){
  a$x<-x
  a$y<-y
  if(!is.na(colour)){
    a$colour<-colour
  }
  if(!is.na(man_colour)){
    g$colour<-man_colour
  }
  as<-do.call(aes_string,a)
  geo<-do.call(geom_point,g)
}
if(geom=="tile"){
  a$x<-x
  a$y<-y
  if(!is.na(fill)){
    a$fill<-fill
  }
  if(!is.na(man_fill)){
    g$fill<-man_fill
  }
  if(!is.na(tile_width)){
    g$width<-tile_width
  }
  if(!is.na(tile_height)){
    g$height<-tile_height
  }
  as<-do.call(aes_string,a)
  geo<-do.call(geom_tile,g)
  ##BigVis data
  if(condense){
    if(!is.na(fill)){
      tab<-condense(x=bin(d[,x],condense.x),y=bin(d[,y],condense.y),z = d[,fill],summary = condense.func)
    }
    else{
      tab<-condense(x=bin(d[,x],condense.x),y=bin(d[,y],condense.y))
    }
    if(condense.func=="mean"){
      tab<-tab[,-3]
    }
    names(tab)<-c(x,y,fill)
    #if(func=="count" & gradient.log){tab[,paste0(fill,".",tile_bin.func)]<-log(tab[,paste0(fill,".",tile_bin.func)])}
    d<-tab
  }
}
if(geom=="line"){
  a$x<-x
  a$y<-y
  if(!is.na(colour)){
    a$colour<-colour
  }
  if(!is.na(man_colour)){
    g$colour<-man_colour
  }
  as<-do.call(aes_string,a)
  geo<-do.call(geom_line,g)
}
else if(geom=="bar"){
  if(!is.factor(d[,x])){
    stop("bar requires discrete x variable")
  }  
  a$x<-x
  if(stat.method!="count"){
    a$y<-y ##map a y aesthetic if using stat identity or summary
  }
  if(!is.na(fill)){
    a$fill<-fill
  }
  g$position<-bar.position
  if(!is.na(man_fill)){
    g$fill<-man_fill
  }
  if(!is.na(stat.method)){
    g$stat<-stat.method
  }
  if(stat.method=="summary"){
    g$fun.y<-stat.func
  }
  as<-do.call(aes_string,a)
  geo<-do.call(geom_bar,g)
}
else if(geom=="histogram"){
  if(is.factor(d[,x])){
    stop("Histogram requires continuous x variable")
  }
  a$x<-x
  if(!is.na(fill)){
    a$fill<-fill
  }
  if(!is.na(man_fill)){
    g$fill<-man_fill
  }
  if(binwidth>0){
    g$binwidth<-binwidth
  }
  if(bins>0){
    g$bins<-bins
  }
  as<-do.call(aes_string,a)
  geo<-do.call(geom_histogram,g)
}
else if(geom=="boxplot"){
  if(!is.numeric(d[,y])){
    stop("Boxplot requires continuous y variable")
  }
  a$x<-x
  a$y<-y
  if(!is.na(fill)){
    a$fill<-fill
  }
  if(!is.na(man_fill)){
    g$fill<-man_fill
  }
  if(!is.na(colour)){
    a$colour<-colour
  }
  if(!is.na(man_colour)){
    g$colour<-man_colour
  }
  if(is.numeric(d[,x])){
    cut<-switch(cut_method,interval=cut_interval(d[,x],n = cut.n),width=cut_width(d[,x],width=cut.n),number=cut_number(d[,x],n = cut.n))
    a$group<-cut
  }
  if(outliers==F){
    g$outlier.shape<-NA
  }
  if(varwidth==T){
    g$varwidth<-T
  }
  as<-do.call(aes_string,a)
  geo<-do.call(geom_boxplot,g)
}
else if(geom=="violin"){
  if(!is.numeric(d[,y])){
    stop("Violin requires continuous y variable")
  }
  a$x<-x
  a$y<-y
  if(!is.na(fill)){
    a$fill<-fill
  }
  if(!is.na(man_fill)){
    g$fill<-man_fill
  }
  if(!is.na(colour)){
    a$colour<-colour
  }
  if(!is.na(man_colour)){
    g$colour<-man_colour
  }
  if(is.numeric(d[,x])){
    cut<-switch(cut_method,interval=cut_interval(d[,x],n = cut.n),width=cut_width(d[,x],width=cut.n),number=cut_number(d[,x],n = cut.n))
    a$group<-cut
  }
  as<-do.call(aes_string,a)
  geo<-do.call(geom_violin,g)
}
p<-ggplot(d,as)+geo
if(!is.na(facet)){
  if(is.factor(d[,facet])&length(levels(d[,facet]))<=factorlim){
    p<-p+facet_wrap(c(facet))
  }
  else{
    stop(paste("You must facet by a factor variable with <=",factorlim,"levels"))
  }  
}
if(!is.na(smooth) & geom %in% c("point")){
  s<-list()
  if(!is.na(fill)){
    s$fill<-fill
  }
  if(!is.na(colour)){
    s$colour<-colour
  }
  if(smooth.se==F){
    s$se<-F
  }
  statas<-do.call(aes_string,s)
  p<-p+stat_smooth(method=smooth,statas)
}
if(!is.na(xlim) & is.numeric(d[,x])){
  p<-p+xlim(xlim)
}
if(!is.na(ylim)){
  if(!is.null(a$y)){#if y aesthetic exists
    if(is.numeric(d[,y])){ #if y aestheitc is numeric
      p<-p+ylim(ylim)
    }
  }
  else{
    p<-p+ylim(ylim)
  }
}
if(logx & is.numeric(d[,x])){
  p<-p+scale_x_log10()
}
if(logy){
  if(!is.null(a$y)){ #if y aesthetic exists
    if(is.numeric(d[,y])){ #if y aestheitc is numeric
      p<-p+ scale_y_log10()
    }
  }
  else{
    p<-p+ scale_y_log10()
  }
}
p<-switch(theme,grey=p+theme_grey(),dark=p+theme_dark(),light=p+theme_light(),linedraw=p+theme_linedraw(),bw=p+theme_bw(),minimal=p+theme_minimal(),classic=p+theme_classic(),void=p+theme_void(),p+theme_grey())
if(xrotate!=0){
  p<-p+theme(axis.text.x=element_text(angle=xrotate,hjust=1,vjust=0.5))
}

##set colour scales
if(!is.na(colour)){
  if(is.factor(d[,colour])){
    p<-switch(colourset,default=p,Set1=p+scale_colour_brewer(palette="Set1"),
              Set2=p+scale_colour_brewer(palette="Set2"),
              Set3=p+scale_colour_brewer(palette="Set3"),
              Spectral=p+scale_colour_brewer(palette="Spectral"))
  }
  else{
    if(!is.na(gradient.range)){
      p<-switch(gradient,default=p+scale_colour_gradient(limits=gradient.range,oob = scales::squish,space="Lab"),Matlab=p+scale_colour_gradientn(space = "Lab",limits = gradient.range,oob = scales::squish,colours=ml))
    }
    else{
      p<-switch(gradient,default=p,Matlab=p+scale_colour_gradientn(colours=ml))
    }
  }
}
if(!is.na(fill)){
  if(is.factor(d[,fill])){
    p<-switch(colourset,default=p,Set1=p+scale_fill_brewer(palette="Set1"),
              Set2=p+scale_fill_brewer(palette="Set2"),
              Set3=p+scale_fill_brewer(palette="Set3"),
              Spectral=p+scale_fill_brewer(palette="Spectral"))
  }
  else{
    if(!is.na(gradient.range)){
      p<-switch(gradient,default=p+scale_fill_gradient(limits=gradient.range,oob = scales::squish,space="Lab"),Matlab=p+scale_fill_gradientn(space = "Lab",limits = gradient.range,oob = scales::squish,colours=ml))
    }
    else{
      p<-switch(gradient,default=p,Matlab=p+scale_fill_gradientn(colours=ml))
    }  }
}
if(coord_flip){
  p<-p+coord_flip()
}
#p<-p + scale_colour_brewer(palette="Set1") + scale_fill_brewer(palette="Set1")
if(enable.plotly){
  return(ggplotly(p))
}
p
}

#+  scale_fill_brewer(palette="Set1") + scale_colour_brewer(palette="Set1")
#scale_colour_gradientn(colours=rainbow(4))
#matlab_like........

#ggplot_builder(t,"biotype","CpGdensity",geom="",xvert=T,bar.position="stack",
#               theme="dark",bins=20,fill="biotype",logy=F,outliers=F) 


#ggplot(t,aes_string("biotype","length",colour="biotype",fill="OE_direction"))+ geom_boxplot()


#bar.position = stack, dodge or fill


#ggplot_builder(d=t,x="GC",y="length",z="length",logx=F,logy=F,facet="NA",
#               geom="histogram",smooth="NA",xrotate=0,colour="NA",
#               fill=NA,bar.position = "stack",theme = "light",
#               enable.plotly = F,outliers=T,bins = 0,
#               xlim="NA",ylim="NA")
# The functions require rchart-helper.R preloaded

# getQ2TimelapsePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getQ2TimelapsePlot = function(data, names, colors, yLabel, colName="x", verticalLineDate=NULL, timezone="UTC") {
    series <- list()
    dateFactors <- list()
    col <- which(names(data[[1]])==colName)[1]
    for (i in 1:length(data)) {
        dateFactors[[i]] <- as.factor(data[[i]]$date)
        boxplot <- boxplot(data[[i]][, col] ~ dateFactors[[i]],
                          data=data.frame(dateFactors[[i]], data[[i]][, col]), plot=FALSE)
        stats <- setNames(as.data.frame(boxplot$stats), nm=NULL)

        # Timpstamp in miliseconds
        unixTimestamps <-
            1000 * as.numeric(as.POSIXct(sort(unique(data[[i]]$date)),
                                         origin="1970-01-01"))
        statsMedian <- rbind(setNames(unixTimestamps, nm=NULL), stats[3,])
        statsQ2 <- rbind(setNames(unixTimestamps, nm=NULL), stats[c(2, 4),])

        series[[2 * (i - 1) + 1]] <-
            list(name=names[i], data=statsMedian, zIndex=1, color=colors[i],
                 marker=list(fillColor="white", lineWidth=2, lineColor=colors[i]))
        series[[2 * i]] <- list(name="50th quartile", data=statsQ2, zIndex=0,
                 type="arearange", color=colors[i], lineWidth=0, linkedTo=":previous", fillOpacity=0.3)
    }

    chart <- Highcharts$new()
    xAxis <- list(type="datetime")
    if (!is.null(verticalLineDate)){
        date <- as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] <- paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=list(text=yLabel), min=0)
    chart$set(series=series)
    return(chart)
}

# Helper for creating histogram
getBinItemList = function(data, businesses, interval=100) {
    binItemList <- c()
    currentBin <- interval
    maxBin <- max(data$count) + interval
    while (currentBin < maxBin) {
        items <- filter(data, currentBin - interval <= count & count < currentBin)
        binItemList <- c(binItemList,
                        paste("< ", currentBin, "<br>",
                              paste(items$name, collapse="<br>, ")))
        currentBin <- currentBin + interval
    }
    return(binItemList)
}

# getStackedHistogram
# data[[]]$x
getStackedHistogram = function(data,
                               names,
                               xLabel,
                               colName="x",
                               minBin=NULL,
                               maxBin = NULL,
                               interval=100,
                               logScale=FALSE,
                               logBase=exp(1),
                               normalize=FALSE,
                               colors = c("#7cb5ec", "#000000")) {
    series <- list()
    plotLines <- list()
    col <- which(names(data[[1]])==colName)[1]
    actualInterval <- interval
    for (i in 1:length(data)) {
        maxBin <- max(maxBin, max(data[[i]][, col], na.rm=TRUE), na.rm=TRUE)
        minBin <- min(minBin, min(data[[i]][, col], na.rm=TRUE), na.rm=TRUE)
    }
    if (logScale) {
        maxBin <- log(maxBin + 1, base=logBase)
        minBin <- log(minBin + 1, base=logBase)
        actualInterval <- log(interval, base=logBase)
    }

    for (i in 1:length(data)){
        x <- as.vector(as.matrix(data[[i]][, col]))
        if (logScale) {
            x <- log(x + 1, base=logBase)
        }

        plotLines[[i * 2 - 1]] <-
            list(color=colors[i],
                 value=mean(x),
                 width=2,
                 label=list(text="mean", style=list(color=colors[i]), verticalAlign="middle"))
        plotLines[[i * 2]] <-
            list(color=colors[i],
                 value=median(x),
                 dashStyle="dash",
                 width=2,
                 label=list(text="median", style=list(color=colors[i]), verticalAlign="middle"))

        histogram <- hist(x, breaks=seq(minBin, maxBin + actualInterval, actualInterval), plot=FALSE)
        histNames <- getBinItemList(data[[i]], interval=actualInterval)

        nBins <- min(length(histogram$breaks), length(histogram$counts))
        counts <- histogram$counts[1:nBins]
        if (normalize) {
            counts <- 100 * counts / nrow(data[[i]])
        }
        breaks <- c(histogram$breaks[2:nBins], histogram$breaks[nBins] + actualInterval)
        bins <- getValues(
            breaks,
            counts,
            name=histNames)
        series[[i]] <- list(name=names[i], data=bins)
    }
   
    chart <- Highcharts$new()
    chart$chart(type="column")
    chart$plotOptions(
        column="{ grouping: false, pointPadding: 0, borderWidth: 0, groupPadding: 0, shadow: false}")
    chart$xAxis(title=paste("{text: '", xLabel, "'}", sep=""),
                plotLines=plotLines)
    yLabel <- "count"
    if (normalize) {
        yLabel <- "density (%)"
    }
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""))
    chart$set(series=series)
    return(chart)
}

# getTimelapseLinePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getTimelapseLinePlot = function(data, names, yLabel, colName="x", verticalLineDate=NULL, timezone="UTC") {
    series <- list()
    col <- which(names(data[[1]])==colName)[1]
    for (i in 1:length(data)){
        timelapseValues <- getTimelapseValues(
            as.POSIXlt(strptime(as.character(data[[i]]$date), "%Y-%m-%d", tz=timezone)),
            data[[i]][, col])
        series[[i]] <- list(name=names[i], data=timelapseValues)
    }


    chart <- Highcharts$new()
    xAxis <- list(type="datetime")
    if (!is.null(verticalLineDate)){
        date <- as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] <- paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""), gridLineColor="#FFFFFF")
    chart$set(series=series)
    return(chart)
}


# Difference-in-difference plot
# Use with DiffInDiffAggregate function
diffInDiffPlot = function(data,
                     idCol,
                     xCol,
                     idLabelCol=NULL,
                     xLabel="period",
                     yLabel="change",
                     periodNames=NULL,
                     legendStyle=list(align="right", verticalAlign="top", layout="vertical")
                     ) {
    dataChart <- Highcharts$new()
    ids <- unique(data[, idCol])
    numPeriod <- 0
    if (is.null(idLabelCol)) {
        idLabelCol = idCol
    }
    for (i in 1:length(ids)) {
        current <- data[data[, idCol] == ids[i],]
        numPeriod <- nrow(current)
        name <- current[1,][, idLabelCol]
        x <- seq(0, numPeriod - 1, 1)
        y <- current[, xCol]
        z <- current[, xCol]
        
        seriesData <- getValues(x, y, z, name)
        visible <- TRUE
        dataChart$series(name=name,
                         data=seriesData,
                         showInLegend=TRUE,
                         visible=visible)
    }
    if (is.null(periodNames)) {
        periodNames <- paste("period", x)
    }
    dataChart$xAxis(categories=periodNames)
    dataChart$yAxis(title=list(text=yLabel), gridLineColor="#FFFFFF")
    do.call(dataChart$legend, c(legendStyle))
    dataChart$tooltip(pointFormat=getPointFormat(y=yLabel, z=NULL))
    return (dataChart)
}

# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename1 = 'catalog_predictions2'
filename2 = 'catalog_predictions3'


catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions2 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40,60,80),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename1)

catalog_predictions3 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(30,50,70,90),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename2)


# Catalog vs predictions

accuracy <- accuracy0 <- accuracy1 <- accuracy2 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) <- names(accuracy2) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy2[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, empirical.only = TRUE)
accuracy2[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, predict.only = TRUE)
accuracy2[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]], accuracy2[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]], accuracy2[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]], accuracy2[[3]])

percent_remove = c(0,10,20,30,40,50,60,70,80,90,100)
nb_iter = 50
K.values = 8
MW = 1
WT =  c(0.5,1)
minimum_threshold = 0.3

nb.pts <- length(percent_remove)

#Figure version 1
pdf(paste('./Article/','catalog_predictions','.pdf',sep=''),width=6,height=8)
j = 14 #'Score'[y]
        eplot(xmin = -1, xmax = 100 + 1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        col <- c("#FF8822",'#5ED275','#9CCBFF')
        col2 <- c("#FF8822",'#275A31','#0077FF')
        col3 <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.05)
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.05 + 2.5)
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)
            mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            mtext(text = expression(paste("Percent of taxa removed from ", italic(S0), ' (%)')), side = 1, line = 2, at = 50, font = 2, cex = 1)
            mtext(text = seq(0, 100, by = 10), side = 1, line = 0, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            mtext(text = seq(0, 100, by = 10), side = 3, line = -0.5, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            text(x = 5, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col3[1], adj = 0)
            text(x = 5, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col3[2], adj = 0)
            text(x = 5, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col3[3], adj = 0)


        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            points(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it, cex = 0.5, pch = 1, col = col[i])
            points(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it, cex = 0.5, pch = 1, col = col2[i])

            lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it), col = col[i])
            lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it), col = col2[i])

            if(i == 2 || i == 3) {
                text(x = 90, y = 0.9 + it, labels = expression(paste(italic('w'[t]), ' = 0.5')), col = col[i], font = 1, cex = 0.75)
                text(x = 90, y = 0.8 + it, labels = expression(paste(italic('w'[t]), ' = 1')), col = col2[i], font = 1, cex = 0.75)
            }

            it <- it + 1.25
        } #i
dev.off()

#Figure version 2
pdf(paste('./Article/','catalog_predictions2','.pdf',sep=''),width=6,height=8)
j = 14 #'Score'[y]
        eplot(xmin = -1, xmax = 100 + 1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        col <- c("#FF8822",'#5ED275','#9CCBFF')
        col2 <- c("#FF8822",'#275A31','#0077FF')
        col3 <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.05)
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.05 + 2.5)
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)
            mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            mtext(text = expression(paste("Percent of taxa removed from ", italic(S0), ' (%)')), side = 1, line = 2, at = 50, font = 2, cex = 1)
            mtext(text = expression(paste("Percent of ",italic(S1)," taxa in ", italic(S0), ' (%)')), side = 3, line = 1, at = 50, font = 2, cex = 1)
            mtext(text = seq(0, 100, by = 10), side = 1, line = 0, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            mtext(text = seq(100, 0, by = -10), side = 3, line = -0.5, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            text(x = 5, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col3[1], adj = 0)
            text(x = 5, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col3[2], adj = 0)
            text(x = 5, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col3[3], adj = 0)


        it <- 0
        for(i in 1:length(accuracy)) {
            if(i == 2 || i == 3) {
                accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'pc_rm']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
                # hack: we draw arrows but with very special "arrowheads" for error bars

                arrows(seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][,1] - accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 2]+it, seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 1] + accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
                points(x = seq(0,100,by=10), y = accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])

                arrows(seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][,1] - accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 2]+it, seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 1] + accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 2]+it, length=0.025, angle=90, code=3, col = col2[i])
                points(x = seq(0,100,by=10), y = accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 1]+it, cex = 0.75, pch = 22, col = col2[i])

                lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it), col = col[i])
                lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it), col = col2[i])

                text(x = 90, y = 0.9 + it, labels = expression(paste(italic('w'[t]), ' = 0.5')), col = col[i], font = 1, cex = 0.75)
                text(x = 90, y = 0.8 + it, labels = expression(paste(italic('w'[t]), ' = 1')), col = col2[i], font = 1, cex = 0.75)
                } else {
                    accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'pc_rm']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                    accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
                    # hack: we draw arrows but with very special "arrowheads" for error bars

                    arrows(seq(0,100,by=10), accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2]+it, seq(0,100,by=10), accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2]+it, length=0.025, angle=90, code=3, col = col3[i])
                    points(x = seq(0,100,by=10), y = accuracy_mean[, 2][, 1]+it, cex = 0.75, pch = 22, col = col3[i])

                    lines(lowess(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it), col = col3[i])
                }

            it <- it + 1.25
        } #i
dev.off()
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename <- 'multiple_parameters2'


multiple_parameters2 <- tanimoto_analysis(filename = filename,
                                            min.tx = 45,
                                            K.values = c(2,4,6,8),
                                            MW = 1,
                                            WT = c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1),
                                            blind = FALSE,
                                            minimum_threshold = 0.3)

WT = c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
K.values = c(2,4,6,8)
MW = 1

# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = multiple_parameters2, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = multiple_parameters2, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = multiple_parameters2)

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = nb.pts, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(multiple_parameters2[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(WT) * length(K.values)) + 0.5, labels = FALSE, las = 1, pos = -0.02) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, nb.pts, by = length(K.values)) + 0.5, labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)

            abline(v = seq(length(K.values)+0.5,(nb.pts-length(K.values))+0.5,by = length(K.values)), col = "grey", lty = 2)
            # abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
            abline(h = c(1.125,2.375), col = "black", lty = 2)


            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,nb.pts), accuracy_mean[, 3][,1] - accuracy_mean[, 3][, 2]+it, seq(1,nb.pts), accuracy_mean[, 3][, 1] + accuracy_mean[, 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,nb.pts), y = accuracy_mean[, 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()


#Figure2
pdf(paste('./Article/',filename,'.pdf',sep=''),width=6,height=8)
# Plots
par(mfrow=c(3,1), mar=c(4,4,4,4))
# layout(matrix(c(1,2,3), 3, 1, byrow = TRUE), heights = c(4,4,4))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in c(10,11,9)) {
    j = 9
        eplot(xmin = -1, xmax = nb.pts+1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(multiple_parameters2[[1]][[1]][[1]])
        col <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(K.values)), labels = FALSE, las = 1, pos = -0.2) #wt
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
            axis(side = 3, at = seq(0, nb.pts, by = 1), labels = FALSE, las = 1, pos = 1.2 + 2.5) #K.values
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))

            abline(v = seq(length(K.values),(nb.pts-length(K.values)),by = length(K.values)), col = "grey", lty = 2)
            # abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
            abline(h = c(1.125,2.375), col = "black", lty = 2)

            if(j == 9) {
                mtext(text = 'TSS', side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            } else if(j == 10) {
                mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            } else if(j == 11) {
                mtext(text = expression('Score'[-y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            }

            mtext(text = "K values", side = 3, line = 2, at = nb.pts/2, font = 1.5, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2.5, at = nb.pts/2, font = 1.5, cex = 1)
            mtext(text = rep(K.values, times = length(WT)), side = 3, line = 1, at = seq(0.5, nb.pts-0.5, by = 1), font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 1, line = 1.5, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,nb.pts)-0.5, accuracy_mean[, 3][,1] - accuracy_mean[, 3][, 2]+it, seq(1,nb.pts)-0.5, accuracy_mean[, 3][, 1] + accuracy_mean[, 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,nb.pts)-0.5, y = accuracy_mean[, 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])
            it <- it + 1.25
        } #i
} #j

dev.off()


# ----- Force brute, pas le temps de gérer le problème de loop
#Figure2
cairo_pdf(paste('./Article/',filename,'.pdf',sep=''),width=6,height=8)
# Plots
par(mfrow=c(3,1), mar=c(4,4,4,4))
# layout(matrix(c(1,2,3), 3, 1, byrow = TRUE), heights = c(4,4,4))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph 1
    j = 10
        eplot(xmin = -1, xmax = nb.pts+1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(multiple_parameters2[[1]][[1]][[1]])
        col <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(K.values)), labels = FALSE, las = 1, pos = -0.2) #wt
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
            axis(side = 3, at = seq(0, nb.pts, by = 1), labels = FALSE, las = 1, pos = 1.2 + 2.5) #K.values
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))

            abline(v = seq(length(K.values),(nb.pts-length(K.values)),by = length(K.values)), col = "grey", lty = 2)
            # abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
            abline(h = c(1.125,2.375), col = "black", lty = 2)

            if(j == 9) {
                mtext(text = 'TSS', side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            } else if(j == 10) {
                mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            } else if(j == 11) {
                mtext(text = expression('Score'[-y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            }

            mtext(text = "K values", side = 3, line = 2, at = nb.pts/2, font = 1.5, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2.5, at = nb.pts/2, font = 1.5, cex = 1)
            mtext(text = rep(K.values, times = length(WT)), side = 3, line = 1, at = seq(0.5, nb.pts-0.5, by = 1), font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 1, line = 1.5, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,nb.pts)-0.5, accuracy_mean[, 3][,1] - accuracy_mean[, 3][, 2]+it, seq(1,nb.pts)-0.5, accuracy_mean[, 3][, 1] + accuracy_mean[, 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,nb.pts)-0.5, y = accuracy_mean[, 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])
            it <- it + 1.25
        } #i

        # Graph 2
            j = 11
                eplot(xmin = -1, xmax = nb.pts+1, ymax = 3.6)
                par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
                foodwebs <- names(multiple_parameters2[[1]][[1]][[1]])
                col <- c("#FF8822","#449955","#2288FF")

                # Axes
                    axis(side = 1, at = seq(0, nb.pts, by = length(K.values)), labels = FALSE, las = 1, pos = -0.2) #wt
                    axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
                    axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
                    axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
                    axis(side = 3, at = seq(0, nb.pts, by = 1), labels = FALSE, las = 1, pos = 1.2 + 2.5) #K.values
                    axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))
                    axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))
                    axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))

                    abline(v = seq(length(K.values),(nb.pts-length(K.values)),by = length(K.values)), col = "grey", lty = 2)
                    # abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
                    abline(h = c(1.125,2.375), col = "black", lty = 2)

                    if(j == 9) {
                        mtext(text = 'TSS', side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
                    } else if(j == 10) {
                        mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
                    } else if(j == 11) {
                        mtext(text = expression('Score'[-y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
                    }

                    mtext(text = "K values", side = 3, line = 2, at = nb.pts/2, font = 1.5, cex = 1)
                    mtext(text = "Similarity weight", side = 1, line = 2.5, at = nb.pts/2, font = 1.5, cex = 1)
                    mtext(text = rep(K.values, times = length(WT)), side = 3, line = 1, at = seq(0.5, nb.pts-0.5, by = 1), font = 1, cex = 0.75)
                    mtext(text = rep(WT, times = length(WT)), side = 1, line = 1.5, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
                    text(x = 1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
                    text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
                    text(x = 1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

                it <- 0
                for(i in 1:length(accuracy)) {
                    accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                    accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
                    # hack: we draw arrows but with very special "arrowheads" for error bars
                    arrows(seq(1,nb.pts)-0.5, accuracy_mean[, 3][,1] - accuracy_mean[, 3][, 2]+it, seq(1,nb.pts)-0.5, accuracy_mean[, 3][, 1] + accuracy_mean[, 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
                    points(x = seq(1,nb.pts)-0.5, y = accuracy_mean[, 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])
                    it <- it + 1.25
                } #i

                # Graph 3
                    j = 9
                        eplot(xmin = -1, xmax = nb.pts+1, ymax = 3.6)
                        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
                        foodwebs <- names(multiple_parameters2[[1]][[1]][[1]])
                        col <- c("#FF8822","#449955","#2288FF")

                        # Axes
                            axis(side = 1, at = seq(0, nb.pts, by = length(K.values)), labels = FALSE, las = 1, pos = -0.2) #wt
                            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
                            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
                            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
                            axis(side = 3, at = seq(0, nb.pts, by = 1), labels = FALSE, las = 1, pos = 1.2 + 2.5) #K.values
                            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))
                            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))
                            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))

                            abline(v = seq(length(K.values),(nb.pts-length(K.values)),by = length(K.values)), col = "grey", lty = 2)
                            # abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
                            abline(h = c(1.125,2.375), col = "black", lty = 2)

                            if(j == 9) {
                                mtext(text = 'TSS', side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
                            } else if(j == 10) {
                                mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
                            } else if(j == 11) {
                                mtext(text = expression('Score'[-y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
                            }

                            mtext(text = "K values", side = 3, line = 2, at = nb.pts/2, font = 1.5, cex = 1)
                            mtext(text = "Similarity weight", side = 1, line = 2.5, at = nb.pts/2, font = 1.5, cex = 1)
                            mtext(text = rep(K.values, times = length(WT)), side = 3, line = 1, at = seq(0.5, nb.pts-0.5, by = 1), font = 1, cex = 0.75)
                            mtext(text = rep(WT, times = length(WT)), side = 1, line = 1.5, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
                            text(x = 1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
                            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
                            text(x = 1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

                        it <- 0
                        for(i in 1:length(accuracy)) {
                            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                            accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
                            # hack: we draw arrows but with very special "arrowheads" for error bars
                            arrows(seq(1,nb.pts)-0.5, accuracy_mean[, 3][,1] - accuracy_mean[, 3][, 2]+it, seq(1,nb.pts)-0.5, accuracy_mean[, 3][, 1] + accuracy_mean[, 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
                            points(x = seq(1,nb.pts)-0.5, y = accuracy_mean[, 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])
                            it <- it + 1.25
                        } #i


dev.off()
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename1 = 'catalog_predictions2'
filename2 = 'catalog_predictions3'


catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions2 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40,60,80),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename1)

catalog_predictions3 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(30,50,70,90),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename2)


# Catalog vs predictions

accuracy <- accuracy0 <- accuracy1 <- accuracy2 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) <- names(accuracy2) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy2[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, empirical.only = TRUE)
accuracy2[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, predict.only = TRUE)
accuracy2[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]], accuracy2[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]], accuracy2[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]], accuracy2[[3]])

percent_remove = c(0,10,20,30,40,50,60,70,80,90,100)
nb_iter = 50
K.values = 8
MW = 1
WT =  c(0.5,1)
minimum_threshold = 0.3

nb.pts <- length(percent_remove)

#Figure version 1
pdf(paste('./Article/','catalog_predictions','.pdf',sep=''),width=6,height=8)
j = 14 #'Score'[y]
        eplot(xmin = -1, xmax = 100 + 1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        col <- c("#FF8822",'#5ED275','#9CCBFF')
        col2 <- c("#FF8822",'#275A31','#0077FF')
        col3 <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.05)
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.05 + 2.5)
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)
            mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            mtext(text = expression(paste("Percent of taxa removed from ", italic(S0), ' (%)')), side = 1, line = 2, at = 50, font = 2, cex = 1)
            mtext(text = seq(0, 100, by = 10), side = 1, line = 0, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            mtext(text = seq(0, 100, by = 10), side = 3, line = -0.5, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            text(x = 5, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col3[1], adj = 0)
            text(x = 5, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col3[2], adj = 0)
            text(x = 5, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col3[3], adj = 0)


        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            points(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it, cex = 0.5, pch = 1, col = col[i])
            points(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it, cex = 0.5, pch = 1, col = col2[i])

            lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it), col = col[i])
            lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it), col = col2[i])

            if(i == 2 || i == 3) {
                text(x = 90, y = 0.9 + it, labels = expression(paste(italic('w'[t]), ' = 0.5')), col = col[i], font = 1, cex = 0.75)
                text(x = 90, y = 0.8 + it, labels = expression(paste(italic('w'[t]), ' = 1')), col = col2[i], font = 1, cex = 0.75)
            }

            it <- it + 1.25
        } #i
dev.off()

#Figure version 2
pdf(paste('./Article/','catalog_predictions2','.pdf',sep=''),width=6,height=8)
j = 14 #'Score'[y]
        eplot(xmin = -1, xmax = 100 + 1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        col <- c("#FF8822",'#5ED275','#9CCBFF')
        col2 <- c("#FF8822",'#275A31','#0077FF')
        col3 <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.05)
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.05 + 2.5)
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)
            mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            mtext(text = expression(paste("Percent of taxa removed from ", italic(S0), ' (%)')), side = 1, line = 2, at = 50, font = 2, cex = 1)
            mtext(text = seq(0, 100, by = 10), side = 1, line = 0, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            mtext(text = seq(0, 100, by = 10), side = 3, line = -0.5, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            text(x = 5, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col3[1], adj = 0)
            text(x = 5, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col3[2], adj = 0)
            text(x = 5, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col3[3], adj = 0)


        it <- 0
        for(i in 1:length(accuracy)) {
            if(i == 2 || i == 3) {
                accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'pc_rm']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
                # hack: we draw arrows but with very special "arrowheads" for error bars

                arrows(seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][,1] - accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 2]+it, seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 1] + accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
                points(x = seq(0,100,by=10), y = accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])

                arrows(seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][,1] - accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 2]+it, seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 1] + accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 2]+it, length=0.025, angle=90, code=3, col = col2[i])
                points(x = seq(0,100,by=10), y = accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 1]+it, cex = 0.75, pch = 22, col = col2[i])

                lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it), col = col[i])
                lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it), col = col2[i])

                text(x = 90, y = 0.9 + it, labels = expression(paste(italic('w'[t]), ' = 0.5')), col = col[i], font = 1, cex = 0.75)
                text(x = 90, y = 0.8 + it, labels = expression(paste(italic('w'[t]), ' = 1')), col = col2[i], font = 1, cex = 0.75)
                } else {
                    accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'pc_rm']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                    accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
                    # hack: we draw arrows but with very special "arrowheads" for error bars

                    arrows(seq(0,100,by=10), accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2]+it, seq(0,100,by=10), accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2]+it, length=0.025, angle=90, code=3, col = col3[i])
                    points(x = seq(0,100,by=10), y = accuracy_mean[, 2][, 1]+it, cex = 0.75, pch = 22, col = col3[i])

                    lines(lowess(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it), col = col3[i])
                }

            it <- it + 1.25
        } #i
dev.off()
#' Class for basic queuing system functions
#'
#' Provides the basic functions needed to communicate between machines
#' This should abstract most functions of rZMQ so the scheduler
#' implementations can rely on the higher level functionality
QSys = R6::R6Class("QSys",
    public = list(
        initialize = function() {
            private$job_num = 1
            private$zmq_context = rzmq::init.context()
        },

        # Submits one job to the queuing system
        #
        # @param memory      The amount of memory (megabytes) to request
        # @param log_worker  Create a log file for each worker
        submit_job = function(...) {
            stop("Derived class needs to overwrite submit_job()")
        },

        # Send the data common to all workers, only serialize once
        send_common_data = function() {
            if (is.null(private$common_data))
                stop("Need to set_common_data() first")

            rzmq::send.socket(socket = private$socket,
                              data = private$common_data,
                              serialize = FALSE,
                              send.more = TRUE)
        },

        # Send iterated data to one worker
        send_job_data = function(...) {
            rzmq::send.socket(socket = private$socket, data = list(...))
        },

        # Read data from the socket
        receive_data = function() {
            rzmq::receive.socket(private$socket)
        },

        # Make sure all resources are closed properly
        cleanup = function() {
        }
    ),

    private = list(
        job_num = NULL,
        zmq_context = NULL,
        socket = NULL,
        port = NULL,
        master = NULL,

        set_common_data = function(fun, const, seed) {
            private$common_data = serialize(list(fun=fun, const=const, seed=seed), NULL)
        },

        # Create a socket and listen on a port in range
        #
        # @param fun    The function to be called
        # @param const  Constant arguments to the function call
        # @param seed   Common seed (to be used w/ job ID)
        # @return       Sets "port" and "master" attributes
        listen_socket = function(min_port, max_port=min_port, n_tries=100) {
            private$socket = rzmq::init.socket(private$zmq_context, "ZMQ_REP")

            on.exit(sink())
            sink('/dev/null')
            for (i in 1:n_tries) {
                exec_socket = sample(min_port:max_port, size=1)
                addr = paste0("tcp://*:", exec_socket)
                port_found = rzmq::bind.socket(private$socket, addr)
                if (port_found)
                    break
            }
            sink()
            on.exit()

            if (!port_found)
                stop("Could not bind to port range (6000,8000) after 100 tries")

            private$port = exec_socket
            private$master = sprintf("tcp://%s:%i", Sys.info()[['nodename']], exec_socket)
        }
    ),

    cloneable = FALSE
)
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename <- 'multiple_parameters2'


multiple_parameters2 <- tanimoto_analysis(filename = filename,
                                            min.tx = 45,
                                            K.values = c(2,4,6,8),
                                            MW = 1,
                                            WT = c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1),
                                            blind = FALSE,
                                            minimum_threshold = 0.3)

WT = c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
K.values = c(2,4,6,8)
MW = 1

# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = multiple_parameters2, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = multiple_parameters2, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = multiple_parameters2)

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = nb.pts, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(multiple_parameters2[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(WT) * length(K.values)) + 0.5, labels = FALSE, las = 1, pos = -0.02) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, nb.pts, by = length(K.values)) + 0.5, labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)

            abline(v = seq(length(K.values)+0.5,(nb.pts-length(K.values))+0.5,by = length(K.values)), col = "grey", lty = 2)
            # abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
            abline(h = c(1.125,2.375), col = "black", lty = 2)


            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,nb.pts), accuracy_mean[, 3][,1] - accuracy_mean[, 3][, 2]+it, seq(1,nb.pts), accuracy_mean[, 3][, 1] + accuracy_mean[, 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,nb.pts), y = accuracy_mean[, 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()


#Figure2
pdf(paste('./Article/',filename,'.pdf',sep=''),width=6,height=8)
# Plots
par(mfrow=c(3,1), mar=c(4,4,4,4))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in c(10,11,9)) {
        eplot(xmin = -1, xmax = nb.pts+1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(multiple_parameters2[[1]][[1]][[1]])
        col <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(K.values)), labels = FALSE, las = 1, pos = -0.2) #wt
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
            axis(side = 3, at = seq(0, nb.pts, by = 1), labels = FALSE, las = 1, pos = 1.2 + 2.5) #K.values
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))

            abline(v = seq(length(K.values),(nb.pts-length(K.values)),by = length(K.values)), col = "grey", lty = 2)
            # abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
            abline(h = c(1.125,2.375), col = "black", lty = 2)

            if(j == 9) {
                mtext(text = 'TSS', side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            } else if(j == 10) {
                mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            } else if(j == 11) {
                mtext(text = expression('Score'[-y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            }

            mtext(text = "K values", side = 3, line = 2, at = nb.pts/2, font = 1.5, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2.5, at = nb.pts/2, font = 1.5, cex = 1)
            mtext(text = rep(K.values, times = length(WT)), side = 3, line = 1, at = seq(0.5, nb.pts-0.5, by = 1), font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 1, line = 1.5, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,nb.pts)-0.5, accuracy_mean[, 3][,1] - accuracy_mean[, 3][, 2]+it, seq(1,nb.pts)-0.5, accuracy_mean[, 3][, 1] + accuracy_mean[, 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,nb.pts)-0.5, y = accuracy_mean[, 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
library("ggplot2")
library("reshape2")
setwd("~/dev/BitFunnel/src/Scripts")

# png(filename="wat.png",width=800,height=600)
png(filename="talk.png",width=1600,height=1200)
# df <- read.csv(header=FALSE, file="wat.csv")
df <- read.csv(header=FALSE, file="talk.csv")
## df <- read.csv(file="wat.csv")
## munged <- melt(df)
## ggplot(munged, aes(x=variable, y=value)) + geom_point()

# plot single
# ggplot(data=df, aes(x=factor(V1), y=V2)) + geom_bar(stat="identity") + labs(x = "Number of cache misses", y = "count")

# plot uniform 20 vs. buggy distribution
# ggplot(data=df, aes(x=factor(V1), y=V2)) + geom_bar(stat="identity") + facet_wrap(~ V3, ncol=1) + labs(x = "Number of cache misses", y = "count")

# plot for talk
ggplot(data=df, aes(x=factor(V1), y=V2)) + geom_bar(stat="identity") + labs(x = "Memory accesses", y = "Percent") +
  theme_bw() +
  theme(axis.text = element_text(size=40),
        axis.title = element_text(size=40))

dev.off()
catalog_predictions <- function(min.tx = 45, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, percent_remove = 0, nb_iter = 1, comm_id = FALSE, community) {

    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        if(comm_id == FALSE) {
            to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        } else { # comm_id = TRUE
            to.delete <- which(!Cm %in% community)
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        }

    # Setting up lists to store the results
    # weights
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        #Minimum weight
        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

        #Number of iterations
        iter <- vector('list', nb_iter)
            for(i in 1:nb_iter) {
                iter[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- iter
        names(Tanimoto_analysis) <- seq(1,nb_iter)
        remove(iter)


        # Percent remove in communities
        pc_rm <- vector('list', length(percent_remove))
            for(i in 1:length(percent_remove)) {
                pc_rm[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- pc_rm
        names(Tanimoto_analysis) <- percent_remove
        remove(pc_rm)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(percent_remove) * nb_iter * length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(p in 1:length(percent_remove)){
        percent_rm <- percent_remove[p]
        for(o in 1:nb_iter){
            for(n in 1:length(MW)) {
                mw <- MW[n]
                for(m in 1:length(K.values)) {

                    # Tanimoto analysis with different weights for different communities
                        # Parameters:
                            Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                            Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                            # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                        #   wt  Weight of traits in similarity measurement
                        #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                        #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                        # Output:
                        #   A vector of sets of resources for each taxon
                        for(i in 1:length(WT)){ #1st loop for all types of wt values
                            wt <- WT[i]
                            for(j in 1:length(Cm)) { #2nd loop for all C[i]
                                S1 <- communities[[j]]
                                S0 <- S0_catalog

                                if(similarity == 'both') { # For similarity matrices already evaluated
                                    similarity.consumer <- similarity.consumers[[i]]
                                    similarity.resource <- similarity.resources[[i]]
                                } else if(similarity == 'consumer') {
                                    similarity.consumer <- similarity.consumers[[i]]
                                } else if (similarity == 'resource') {
                                    similarity.resource <- similarity.resources[[i]]
                                }

                                # setting up the iterative process to evaluate the accuracy ~ # taxa in catalog
                                # removing a certain percentage of the # of species for which there are interactions as consumers described in the original food web.

                                # inter_Cm <- unique(subset(interactions_sources[, 'consumer'], interactions_sources[, 'source'] == Cm[j] & interactions_sources[, 'inter'] == "1")) # Species for which there are interactions as consumer in Cm[j]

                                interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3] # interaction catalog without interactions coming from Cm[j]

                                # inter_Cm2 <- unique(interactions[which(interactions[, 'consumer'] %in% inter_Cm), 'consumer']) # consumers in Cm[j] for which information is still available in catalog after deletion of Cm[j] from catalog

                                #Removing a percentage of consumers described in catalog
                                    # sample_iter <- sample(x = inter_Cm2, size = round((percent_rm / 100) * length(inter_Cm2)), replace = FALSE)
                                    sample_iter <- sample(x = S1, size = round((percent_rm / 100) * length(S1)), replace = FALSE) # To use if removing a percent of all taxa in original web

                                    if(length(sample_iter) == 0) {
                                        S1_no_mod <- seq(1,length(S1))
                                    } else {
                                        for(k in 1:length(sample_iter)) {
                                          S0[sample_iter[k], 'resource'] <- ""
                                          S0[sample_iter[k], 'non-resource'] <- ""
                                          S0[sample_iter[k], 'consumer'] <- ""
                                          S0[sample_iter[k], 'non-consumer'] <- ""
                                        }
                                        S1_no_mod <- which(!S1 %in% sample_iter)
                                    }

                                # 2. Preexisting information kept to inform algorithm
                                    if(length(S1_no_mod) == 0) {
                                        NULL
                                    } else {
                                    # Only modifying those that are loosing data from the catalogue, less time
                                        to.change <- numeric()
                                        for(k in 1:length(S1_no_mod)) {
                                            to.change <- c(to.change, which(interactions[, 'consumer'] == S1[S1_no_mod[k]]), which(interactions[, 'resource'] == S1[S1_no_mod[k]]))
                                        }
                                        to.change <- unique(to.change)

                                    # Modifying sets of resources and non-resources for taxa in S1_no_mod
                                        interactions <- interactions[to.change, ]
                                        rownames(interactions) <- seq(1,nrow(interactions))
                                        resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                                  resource = interactions[, 'resource'],
                                                                                  inter_type = interactions[, 'inter'])

                                        consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                                resource = interactions[, 'resource'],
                                                                                inter_type = interactions[, 'inter'])


                                    # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                        for(k in 1:nrow(resource_set)) {
                                          S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                          S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                        }
                                        for(k in 1:nrow(consumer_set)) {
                                          S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                          S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                        }
                                    remove(interactions, resource_set, to.change)
                                    }#if

                                # Recalculate similarity
                                    similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.consumer,
                                                                                        taxa = 'consumer')

                                    similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.resource,
                                                                                        taxa = 'resource')

                                # Predicting interactions
                                    Tanimoto_analysis[[p]][[o]][[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                            Kr = Kr,
                                                                                            S0 = S0,
                                                                                            S1 = S1,
                                                                                            MW = mw,
                                                                                            similarity.consumer = similarity.consumer,
                                                                                            similarity.resource = similarity.resource,
                                                                                            minimum_threshold = minimum_threshold)

                                save(x = Tanimoto_analysis, file = file.to.save)
                                remove(S0, S1, similarity.consumer, similarity.resource)
                                iteration <- iteration + 1
                                setTxtProgressBar(pb, iteration)
                            }#2nd loop for all C[i]

                            save(x = Tanimoto_analysis, file = file.to.save)
                            remove(wt)

                        }#1st loop for all types of wt values
                }#m
            }#n
        }#o
    }#p
    #Saving number of species in original web vs catalog once web removed
    # percent_original <- length(inter_Cm2) / length(inter_Cm)
    # x <- c(percent_original, length(inter_Cm), length(inter_Cm2))
    # file.to.save2 <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis_pc_tx.RData")
    # save(x = x, file = file.to.save2)

    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
marginOfError =
function(prob,  # sample probability (or response rate)
         n,  # sample size
         N=NULL,
         conf.level=0.95  # Confidence interval
         ) {
    z <- qnorm(p=1.0 - (1.0 - conf.level) * 0.5)
    B <- prob * (1 - prob)
    moe <- z * sqrt(B / n)

    if (!is.null(N)) {
        # tmp <- z ^ 2 * (prob * (1 - prob)) / moe^2
        # n <- tmp / (1 + tmp / N)
        # n + n/N * tmp <- tmp
        # n <- tmp * (1 - n/N)
        fpcf <- sqrt((N - n) / (N - 1))
        moe <-  moe * fpcf
    }
    return(moe)
}

sampleSize =
function(prob,
         moe,  # Margin of error
         N=NULL,  # Population size
         conf.level=0.95
         ) {
    z <- qnorm(p=1.0 - (1.0 - conf.level) * 0.5)
    B <- prob * (1 - prob)
    n <- z ^ 2 * B / moe^2
    if (!is.null(N)) {
        n <- n * N / (n + N - 1)
    }
    return(n)
}


binom.test =
function() {
    prob <- 0.15
    moe <- 0.025
    N <- 1000
    n <- sampleSize(prob=prob, moe=moe, N=N)
    message(n)
    message("Expected margin of error: ", moe)
    moe <- marginOfError(prob=prob, n=n, N=N)
    message(moe)
}
REBOL [
    System: "REBOL [R3] Language Interpreter and Run-time Environment"
    Title: "Make Reb-Lib related files"
    Rights: {
        Copyright 2012 REBOL Technologies
        REBOL is a trademark of REBOL Technologies
    }
    License: {
        Licensed under the Apache License, Version 2.0
        See: http://www.apache.org/licenses/LICENSE-2.0
    }
    Author: "Carl Sassenrath"
    Needs: 2.100.100
]

do %common.r

print "--- Make Reb-Lib Headers ---"

verbose: true

lib-ver: 2

preface: "RL_"

src-dir: %../core/
reb-lib: src-dir/a-lib.c
ext-lib: src-dir/f-extension.c

args: parse-args system/options/args
output-dir: to file! any [args/OUTDIR %../]
output-dir: fix-win32-path output-dir
out-dir: output-dir/include
mkdir/deep out-dir

reb-ext-lib:  out-dir/reb-lib.h   ; for Host usage
reb-ext-defs: out-dir/reb-lib-lib.h  ; for REBOL usage

ver: load %../boot/version.r

do %common.r
do %common-parsers.r

do %form-header.r

;-----------------------------------------------------------------------------
;-----------------------------------------------------------------------------

proto-count: 0

xlib-buffer: make string! 20000
rlib-buffer: make string! 1000
mlib-buffer: make string! 1000
dlib-buffer: make string! 1000
comments-buffer: make string! 1000
xsum-buffer: make string! 1000

emit:  func [d] [append repend xlib-buffer d newline]
emit-rlib: func [d] [append repend rlib-buffer d newline]
emit-dlib: func [d] [append repend dlib-buffer d newline]
emit-comment: func [d] [append repend comments-buffer d newline]
emit-mlib: proc [d /nol] [
    repend mlib-buffer d
    if not nol [append mlib-buffer newline]
]

count: func [s c /local n] [
    if find ["()" "(void)"] s [return "()"]
    out: copy "(a"
    n: 1
    while [s: find/tail s c][
        repend out [#"," #"a" + n]
        n: n + 1
    ]
    append out ")"
]

in-sub: func [text pattern /local position] [
    all [
        position: find text pattern ":"
        insert position "^/:"
        position: find next position newline
        remove position
        insert position " - "
    ]
]

gen-doc: func [name proto text] [
    replace/all text "**" "  "
    replace/all text "/*" "  "
    replace/all text "*/" "  "
    trim text
    append text newline

    insert find text "Arguments:" "^/:"
    bb: beg: find/tail text "Arguments:"
    insert any [find bb "notes:" tail bb] newline
    while [
        all [
            beg: find beg " - "
            positive? offset-of beg any [find beg "notes:" tail beg]
        ]
    ][
        insert beg </tt>
        insert find/tail/reverse beg newline {<br><tt class=word>}
        beg: find/tail beg " - "
    ]

    beg: insert bb { - } ;<div style="white-space: pre;">}
    remove find beg newline
    remove/part find beg "<br>" 4 ; extra <br>

    remove find text "^/Returns:"
    in-sub text "Returns:"
    in-sub text "Notes:"

    insert text reduce [
        ":Function: - " <tt class=word> proto </tt>
        "^/^/:Summary: - "
    ]
    emit-comment ["===" name newline newline text]
]

pads: func [start col] [
    str: copy ""
    col: col - offset-of start tail start
    head insert/dup str #" " col
]

emit-proto: proc [
    proto
] [

    if all [
        proto
        trim proto
        pos.id: find proto preface
        find proto #"("
    ] [
        emit ["RL_API " proto ";"] ;    // " the-file]
        append xsum-buffer proto
        fn.declarations: copy/part proto pos.id
        pos.lparen: find pos.id #"("
        fn.name: copy/part pos.id pos.lparen
        fn.name.upper: uppercase copy fn.name
        fn.name.lower: lowercase copy find/tail fn.name preface

        emit-dlib [tab fn.name ","]

        emit-rlib [tab fn.declarations "(*" fn.name.lower ")" pos.lparen ";"]

        args: count pos.lparen #","
        mlib.tail: tail mlib-buffer
        emit-mlib/nol ["#define " fn.name.upper args]
        emit-mlib [pads mlib.tail 35 " RL->" fn.name.lower args]

        comment-text: proto-parser/notes
        encode-lines comment-text {**} { }

        emit-mlib ["/*^/**^-" proto "^/**^/" comment-text "*/" newline]

        gen-doc fn.name proto comment-text

        proto-count: proto-count + 1
    ]
]

process: func [file] [
    if verbose [probe [file]]
    data: read the-file: file
    data: to-string data

    proto-parser/proto-prefix: "RL_API "
    proto-parser/emit-proto: :emit-proto
    proto-parser/process data
]

write-if: proc [file data] [
    if data != attempt [to string! read file][
        print ["UPDATE:" file]
        write file data
    ]
]

;-----------------------------------------------------------------------------

emit-rlib {
typedef struct rebol_ext_api ^{}

emit-comment [{Host/Extension API

=r3

=*Updated for A} ver/3 { on } now/date {

=*Describes the functions of reb-lib, the REBOL API (both the DLL and extension library.)

=!This document is auto-generated and changes should not be made within this wiki.

=note WARNING: PRELIMINARY Documentation

=*This API is under development and subject to change. Various functions may be moved, removed, renamed, enhanced, etc.

Also note: the formatting of this document will be enhanced in future revisions.

=/note

==Concept

The REBOL API provides common API functions needed by the Host-Kit and also by
REBOL extension modules. This interface is commonly referred to as "reb-lib".

There are two methods of linking to this code:

*Direct calls as you would use functions within any DLL.

*Indirect calls through a set of macros (that use a structure pointer to the library.)

==Functions
}]

;-----------------------------------------------------------------------------

process reb-lib
process ext-lib

;-----------------------------------------------------------------------------

emit-rlib "} RL_LIB;"

out: to-string reduce [
form-header/gen "REBOL Host and Extension API" %reb-lib.r %make-reb-lib.r
{
// These constants are created by the release system and can be used to check
// for compatiblity with the reb-lib DLL (using RL_Version.)
#define RL_VER } ver/1 {
#define RL_REV } ver/2 {
#define RL_UPD } ver/3 {


// Function entry points for reb-lib (used for MACROS below):}
rlib-buffer
{
// Extension entry point functions:
#ifdef TO_WINDOWS
    #define RXIEXT __declspec(dllexport)
#else
    #define RXIEXT extern
#endif

#ifdef __cplusplus
extern "C" ^{
#endif

RXIEXT const char *RX_Init(int opts, RL_LIB *lib);
RXIEXT int RX_Quit(int opts);
RXIEXT int RX_Call(int cmd, RXIFRM *frm, void *data);

// The macros below will require this base pointer:
extern RL_LIB *RL;  // is passed to the RX_Init() function

// Macros to access reb-lib functions (from non-linked extensions):

}
mlib-buffer
{

#define RL_MAKE_BINARY(s) RL_MAKE_STRING(s, FALSE)

#ifndef REB_EXT // not extension lib, use direct calls to r3lib

}
xlib-buffer
{
#endif // REB_EXT

#ifdef __cplusplus
^}
#endif

}
]

write-if reb-ext-lib out

;-----------------------------------------------------------------------------

out: to-string reduce [
form-header/gen "REBOL Host/Extension API" %reb-lib-lib.r %make-reb-lib.r
{RL_LIB Ext_Lib = ^{
}
dlib-buffer
{^};
}
]

write-if reb-ext-defs out

write-if output-dir/reb-lib-doc.txt comments-buffer

;ask "Done"
print "   "
REBOL [
    System: "Ren/C Core Extraction of the Rebol System"
    Title: "Common Routines for Tools"
    Rights: {
        Rebol is Copyright 1997-2015 REBOL Technologies
        REBOL is a trademark of REBOL Technologies

        Ren/C is Copyright 2015 MetaEducation
    }
    License: {
        Licensed under the Apache License, Version 2.0
        See: http://www.apache.org/licenses/LICENSE-2.0
    }
    Author: "@HostileFork"
    Version: 2.100.0
    Needs: 2.100.100
    Purpose: {
        These are some common routines used by the utilities
        that build the system, which are found in %src/tools/
    }
]

;-- !!! BACKWARDS COMPATIBILITY: this does detection on things that have
;-- changed, in order to adapt the environment so that the build scripts
;-- can still work in older as well as newer Rebols.  Thus the detection
;-- has to be a bit "dynamic"

do %r2r3-future.r


spaced-tab: rejoin [space space space space]


to-c-name: function [
    {Take a Rebol value and transliterate it as a (likely) valid C identifier.}

    value
        {Any Rebol value (will be FORM'd before processing)}
    /scope
        {See scope rules: http://stackoverflow.com/questions/228783/}
    word [word!]
        {Either 'global or 'local (defaults global)}
][
    c-chars: charset [
        #"a" - #"z"
        #"A" - #"Z"
        #"0" - #"9"
        #"_"
    ]

    string: form value

    string: switch/default attempt [to-word string] [
        ; Take care of special cases of singular symbols

        ; Used specifically by t-routine.c to make SYM_ELLIPSIS
        ... [copy "ellipsis"]

        ; Used to make SYM_HYPHEN which is needed by `charset [#"A" - #"Z"]`
        - [copy "hyphen"]

        ; Used by u-dialect apparently
        * [copy "asterisk"]

        ; None of these are used at present, but included in case
        . [copy "period"]
        ? [copy "question"]
        ! [copy "exclamation"]
        + [copy "plus"]
        ~ [copy "tilde"]
        | [copy "bar"]
    ][
        ; If these symbols occur composite in a longer word, they use a
        ; shorthand; e.g. `true?` => `true_q`

        for-each [reb c] [
            -   "_"
            *   "_p"    ; !!! because it symbolizes a (p)ointer in C??
            .   "_"     ; !!! same as hyphen?
            ?   "_q"
            !   "_x"    ; e(x)clamation
            +   "_a"    ; (a)ddition
            ~   "_t"
            |   "_b"

        ][
            replace/all string (form reb) c
        ]

        string
    ]

    if empty? string [
        fail [
            "empty identifier produced by to-c-name for"
            (mold value) "of type" (mold type-of value)
        ]
    ]

    comment [
        ; Don't worry about leading digits at the moment, because currently
        ; the code will do a to-c-name transformation and then often prepend
        ; something to it.

        if find charset [#"0" - #"9"] string/1 [
            fail ["identifier" string "starts with digit in to-c-name"]
        ]
    ]

    for-each char string [
        if char = space [
            ; !!! The way the callers seem to currently be written is to
            ; sometimes throw "foo = 2" kinds of strings and expect them to
            ; be converted to a "C string".  Only check the part up to the
            ; first space for legitimacy then.  :-/
            break
        ]

        unless find c-chars char [
            fail ["Non-alphanumeric or hyphen in" string "in to-c-name"]
        ]
    ]

    unless scope [word: 'global] ; default to assuming global need

    ; Easiest rule is just "never start a global identifier with underscore",
    ; but we check the C rules.  Since currently this routine is sometimes
    ; called to produce a partial name, it may not be a problem if that part
    ; starts with an underscore if something legal will be prepended.  But
    ; there are no instances of that need so better to plant awareness.

    catch [case/all [
        string/1 != "_" [throw string]

        word = 'global [
            fail [
                "global identifiers in C starting with underscore"
                "are reserved for standard library usage"
            ]
        ]

        word = 'local [
            unless find charset [#"A" - #"Z"] value/2 [
                throw string
            ]
            fail [
                "local identifiers in C starting with underscore and then"
                "a capital letter are reserved for standard library usage"
            ]
        ]

        'default [fail "scope word must be 'global or 'local"]
    ]]

    string
]


; http://stackoverflow.com/questions/11488616/
binary-to-c: func [
    {Converts a binary to a string of C source that represents an initializer
    for a character array.  To be "strict" C standard compatible, we do not
    use a string literal due to length limits (509 characters in C89, and
    4095 characters in C99).  Instead we produce an array formatted as
    '{0xYY, ...}' with 8 bytes per line}

    data [binary!]
    ; !!! Add variable name to produce entire 'const char *name = {...};' ?
     /local out str comma-count
] [
    out: make string! 6 * (length data)
    while [not tail? data] [
        append out spaced-tab

        ;-- grab hexes in groups of 8 bytes
        hexed: enbase/base (copy/part data 8) 16
        data: skip data 8
        for-each [digit1 digit2] hexed [
            append out rejoin [{0x} digit1 digit2 {,} space]
        ]

        take/last out ;-- drop the last space
        if tail? data [
            take/last out ;-- lose that last comma
        ]
        append out newline ;-- newline after each group, and at end
    ]

    ;-- Sanity check (should be one more byte in source than commas out)
    parse out [(comma-count: 0) some [thru "," (++ comma-count)] to end]
    assert [(comma-count + 1) = (length head data)]

    out
]

;
; Rebol needs to bootstrap using old versions prior to having definitionally
; scoped returns implemented.  Hence don't assume passing a body with
; RETURN in it will return from the *caller*.  It will just wind up returning
; from *this loop wrapper* (in older Rebols) when the call is finished!
;
for-each-record-NO-RETURN: proc [
    {Iterate a table with a header by creating an object for each row}

    'record [word!]
        {Word to set each time to the row made into an object}
    table [block!]
        {Table of values with header block as first element}
    body [block!]
        {Block to evaluate each time}
    /local headings result spec
] [
    unless block? first table [
        fail {Table of records does not start with a header block}
    ]
    headings: map-each word first table [
        unless word? word [
            fail [{Heading} word {is not a word}]
        ]
        to-set-word word
    ]

    table: next table

    ; Note: this code must run in R3-Alpha, so can't just use `result:`
    ; like in Ren-C (which will unset the variable if VOID? argument)
    ;
    set/opt (quote result:) while [not empty? table] [
        if (length headings) > (length table) [
            fail {Element count isn't even multiple of header count}
        ]

        spec: collect [
            for-each column-name headings [
                keep column-name
                keep compose/only [quote (table/1)]
                table: next table
            ]
        ]

        set record has spec

        do body
    ]

    :result
]

find-record-unique: func [
    {Get a record in a table as an object, error if duplicate, blank if absent}
    ;; return: [object! blank!]
    table [block!] {Table of values with header block as first element}
    key [word!] {Object key to search for a match on}
    value {Value that the looked up key must be uniquely equal to}
    /local rec result
] [
    unless find first table key [
        fail [key {not found in table headers:} (first table)]
    ]

    result: _
    for-each-record-NO-RETURN rec table [
        unless value = select rec key [continue]

        if result [
            fail [{More than one table record matches} key {=} value]
        ]

        result: rec

        ; RETURN won't work.  We could break, but walk whole table to verify
        ; that it is well-formed.  (Here, correctness is more important.)
    ]
    result
]

parse-args: func [
	args ;args in form of "NAME=VALUE"
	/local a name value ret
][
	ret: make block! 4
	args: any [args copy []]
	unless block? args [args: split args [some " "]]
	foreach a args [
		if to logic! idx: find a #"=" [
			name: to word! copy/part a (index-of idx) - 1
			value: copy next idx
			append ret reduce [name value]
		]
	]
	ret
]

fix-win32-path: func [
	path [file!]
	/local letter colon
][
    if 3 != fourth system/version [return path] ;non-windows system

    drive: first path
    colon: second path

    if all [
    	any [
	    all [#"A" <= drive #"Z" >= drive] 
	    all [#"a" <= drive #"z" >= drive] 
	]
	#":" = colon
    ][
    	insert path #"/"
	remove skip path 2 ;remove ":"
    ]

    path
]
library(plyr)
library(ggplot2)

setwd("Desktop/Hannuus_lines_repeat_analysis")

lines <- read.table("all_lines_family_stats_6-30.tsv",header=T,sep="\t",comment.char="")
lines.filtered <- lines[lines$GenomeFrac >= 0.01,]

ggplot(lines.filtered, aes(x=reorder(Identifier, GenomeFrac), y=GenomeFrac)) + geom_bar(aes(fill=Family, order=desc(Family)), stat="identity") + theme_bw() + theme(axis.text.x = element_text(angle=90, hjust=1, color="black"), axis.text.y = element_text(color="black"), axis.title.x = element_blank(), axis.text.y = element_blank())
alllines.noha <- alllines[!alllines$Line == "HA",]
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename1 = 'catalog_predictions2'
filename2 = 'catalog_predictions3'


catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions2 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40,60,80),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename1)

catalog_predictions3 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(30,50,70,90),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename2)


# Catalog vs predictions

accuracy <- accuracy0 <- accuracy1 <- accuracy2 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) <- names(accuracy2) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy2[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, empirical.only = TRUE)
accuracy2[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, predict.only = TRUE)
accuracy2[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]], accuracy2[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]], accuracy2[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]], accuracy2[[3]])

percent_remove = c(0,10,20,30,40,50,60,70,80,90,100)
nb_iter = 100
K.values = 8
MW = 1
WT =  0.5
minimum_threshold = 0.3

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

# Graph
for(j in 13:16) {
        eplot(xmin = -0.09, xmax = 100, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.1) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            # mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            # mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 0.1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 0.1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 0.1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            points(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it, cex = 0.5, pch = 1, col = col[i])
            lines(lowess(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it))
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
catalog_predictions <- function(min.tx = 45, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, percent_remove = 0, nb_iter = 1, comm_id = FALSE, community) {

    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        if(comm_id == FALSE) {
            to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        } else { # comm_id = TRUE
            to.delete <- which(!Cm %in% community)
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        }

    # Setting up lists to store the results
    # weights
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        #Minimum weight
        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

        #Number of iterations
        iter <- vector('list', nb_iter)
            for(i in 1:nb_iter) {
                iter[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- iter
        names(Tanimoto_analysis) <- seq(1,nb_iter)
        remove(iter)


        # Percent remove in communities
        pc_rm <- vector('list', length(percent_remove))
            for(i in 1:length(percent_remove)) {
                pc_rm[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- pc_rm
        names(Tanimoto_analysis) <- percent_remove
        remove(pc_rm)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(percent_remove) * nb_iter * length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(p in 1:length(percent_remove)){
        percent_rm <- percent_remove[p]
        for(o in 1:nb_iter){
            for(n in 1:length(MW)) {
                mw <- MW[n]
                for(m in 1:length(K.values)) {

                    # Tanimoto analysis with different weights for different communities
                        # Parameters:
                            Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                            Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                            # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                        #   wt  Weight of traits in similarity measurement
                        #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                        #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                        # Output:
                        #   A vector of sets of resources for each taxon
                        for(i in 1:length(WT)){ #1st loop for all types of wt values
                            wt <- WT[i]
                            for(j in 1:length(Cm)) { #2nd loop for all C[i]
                                S1 <- communities[[j]]
                                S0 <- S0_catalog

                                if(similarity == 'both') { # For similarity matrices already evaluated
                                    similarity.consumer <- similarity.consumers[[i]]
                                    similarity.resource <- similarity.resources[[i]]
                                } else if(similarity == 'consumer') {
                                    similarity.consumer <- similarity.consumers[[i]]
                                } else if (similarity == 'resource') {
                                    similarity.resource <- similarity.resources[[i]]
                                }

                                # setting up the iterative process to evaluate the accuracy ~ # taxa in catalog
                                # removing a certain percentage of the # of species for which there are interactions as consumers described in the original food web.

                                # inter_Cm <- unique(subset(interactions_sources[, 'consumer'], interactions_sources[, 'source'] == Cm[j] & interactions_sources[, 'inter'] == "1")) # Species for which there are interactions as consumer in Cm[j]

                                interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3] # interaction catalog without interactions coming from Cm[j]

                                # inter_Cm2 <- unique(interactions[which(interactions[, 'consumer'] %in% inter_Cm), 'consumer']) # consumers in Cm[j] for which information is still available in catalog after deletion of Cm[j] from catalog

                                #Removing a percentage of consumers described in catalog
                                    # sample_iter <- sample(x = inter_Cm2, size = round((percent_rm / 100) * length(inter_Cm2)), replace = FALSE)
                                    sample_iter <- sample(x = S1, size = round((percent_rm / 100) * length(S1)), replace = FALSE) # To use if removing a percent of all taxa in original web

                                    if(length(sample_iter) == 0) {
                                        S1_no_mod <- S1
                                    } else {
                                        for(k in 1:length(sample_iter)) {
                                          S0[sample_iter[k], 'resource'] <- ""
                                          S0[sample_iter[k], 'non-resource'] <- ""
                                          S0[sample_iter[k], 'consumer'] <- ""
                                          S0[sample_iter[k], 'non-consumer'] <- ""
                                        }
                                        S1_no_mod <- which(!S1 %in% sample_iter)
                                    }

                                # 2. Preexisting information kept to inform algorithm
                                    if(length(S1_no_mod) == 0) {
                                        NULL
                                    } else {
                                    # Only modifying those that are loosing data from the catalogue, less time
                                        to.change <- numeric()
                                        for(k in 1:length(S1_no_mod)) {
                                            to.change <- c(to.change, which(interactions[, 'consumer'] == S1_no_mod[k]), which(interactions[, 'resource'] == S1_no_mod[k]))
                                        }
                                        to.change <- unique(to.change)

                                    # Modifying sets of resources and non-resources for taxa in S1_no_mod
                                        interactions <- interactions[to.change, ]
                                        rownames(interactions) <- seq(1,nrow(interactions))
                                        resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                                  resource = interactions[, 'resource'],
                                                                                  inter_type = interactions[, 'inter'])

                                        consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                                resource = interactions[, 'resource'],
                                                                                inter_type = interactions[, 'inter'])


                                    # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                        for(k in 1:nrow(resource_set)) {
                                          S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                          S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                        }
                                        for(k in 1:nrow(consumer_set)) {
                                          S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                          S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                        }
                                    remove(interactions, resource_set, to.change)
                                    }#if

                                # Recalculate similarity
                                    similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.consumer,
                                                                                        taxa = 'consumer')

                                    similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.resource,
                                                                                        taxa = 'resource')

                                # Predicting interactions
                                    Tanimoto_analysis[[p]][[o]][[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                            Kr = Kr,
                                                                                            S0 = S0,
                                                                                            S1 = S1,
                                                                                            MW = mw,
                                                                                            similarity.consumer = similarity.consumer,
                                                                                            similarity.resource = similarity.resource,
                                                                                            minimum_threshold = minimum_threshold)

                                save(x = Tanimoto_analysis, file = file.to.save)
                                remove(S0, S1, similarity.consumer, similarity.resource)
                                iteration <- iteration + 1
                                setTxtProgressBar(pb, iteration)
                            }#2nd loop for all C[i]

                            save(x = Tanimoto_analysis, file = file.to.save)
                            remove(wt)

                        }#1st loop for all types of wt values
                }#m
            }#n
        }#o
    }#p
    #Saving number of species in original web vs catalog once web removed
    # percent_original <- length(inter_Cm2) / length(inter_Cm)
    # x <- c(percent_original, length(inter_Cm), length(inter_Cm2))
    # file.to.save2 <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis_pc_tx.RData")
    # save(x = x, file = file.to.save2)

    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
# 2. FAZA
source("lib/libraries.r", encoding = "UTF-8")


naslov1 = "http://www.multpl.com/us-gdp-inflation-adjusted/table"
gdp <- readHTMLTable(naslov1, which=1, encoding = "UTF-8", stringsAsFactors = FALSE)
gdp[[1]] <- strapplyc(gdp[[1]], "([0-9]+)$") %>% as.numeric()
gdp[[2]] <- strapplyc(gdp[[2]], "^([0-9.]+)") %>% as.numeric()
colnames(gdp) <- c("Leto", "BDP (v trilijonih $)")
gdp <- gdp %>% filter(Leto <= 2015 & Leto >= 1950)
gdp <- gdp %>% arrange(Leto)



naslov2 = "http://www.multpl.com/us-real-gdp-per-capita/table/by-year"
gdppc <- readHTMLTable(naslov2, which=1, encoding = "UTF-8", stringsAsFactors = FALSE)
gdppc[[1]] <- strapplyc(gdppc[[1]], "([0-9]+)$") %>% as.numeric()
gdppc[[2]] <- gsub(",", "", gdppc[[2]]) %>% as.numeric()
colnames(gdppc) <- c("Letnica", "BDPp.c. (v $)")
gdppc <- gdppc %>% filter(Letnica <= 2015 & Letnica >= 1950)
gdppc <- gdppc %>% arrange(Letnica)


naslov3 = "http://www.multpl.com/us-real-gdp-growth-rate/table/by-year"
gr <- readHTMLTable(naslov3, which=1, encoding = "UTF-8", stringsAsFactors = FALSE)
gr[[1]] <- strapplyc(gr[[1]], "([0-9]+)$") %>% as.numeric()
gr[[2]] <- strapplyc(gr[[2]], "^([-, 0-9.]+)") %>% as.numeric()
colnames(gr) <- c("Letnica", "Stopnja rasti")
gr <- gr %>% filter(Letnica <= 2015 & Letnica >=1950)
gr <- gr %>% arrange(Letnica)


naslov4 = "http://www.usinflationcalculator.com/inflation/consumer-price-index-and-annual-percent-changes-from-1913-to-2008/"
cpi <- htmlTreeParse(naslov4, encoding = "UTF-8", useInternal = TRUE)
cpi <- readHTMLTable(naslov4,which=1, stringsAsFactors = FALSE)
cpi <- cpi[-c(1,2), c(1, 14)]
cpi <- apply(cpi, 2, . %>% strapplyc("([0-9.]+)") %>% as.numeric(.)) %>% data.frame()
colnames(cpi) <- c("Letnica", "Indeks cen")
cpi <- cpi %>% filter(Letnica <= 2015 & Letnica >= 1950)
cpi <- cpi %>% arrange(Letnica)


naslov5 = "http://www.usinflationcalculator.com/inflation/historical-inflation-rates/"
usinf <- readHTMLTable(naslov5, which=1, encoding = "UTF-8", stringsAsFactors = FALSE)
usinf <- usinf[-c(1), c(1, 14)]
usinf[[1]] <- strapplyc(usinf[[1]], "([0-9]+)$") %>% as.numeric()
usinf[[2]] <- strapplyc(usinf[[2]], "^([-, 0-9.]+)") %>% as.numeric()
colnames(usinf) <- c("Letnica", "Stopnja inflacije (v %)")
usinf <- usinf %>% filter(Letnica <= 2015 & Letnica >= 1950)
usinf <- usinf %>% arrange(Letnica)


naslov6 = "http://www.multpl.com/unemployment/table"
unemp <- readHTMLTable(naslov6, which=1, encoding = "UTF-8", stringsAsFactors = FALSE)
unemp[[1]] <- strapplyc(unemp[[1]], "([0-9]+)$") %>% as.numeric()
unemp[[2]] <- strapplyc(unemp[[2]], "^([0-9.]+)") %>% as.numeric()
colnames(unemp) <- c("Letnica", "Stopnja brezposlenosti (v %)")
unemp <- unemp %>% filter(Letnica <= 2015 & Letnica >= 1950)
unemp <- unemp %>% arrange(Letnica)


skupna.tabela <- cbind(gdp, gdppc, gr, cpi, usinf, unemp)
skupna.tabela <- skupna.tabela[names(skupna.tabela) != "Letnica"]

skupna.tabela2 <- skupna.tabela %>% arrange(-Leto)

naslov7 <- "http://www.usgovernmentspending.com/gdp_by_state" 
stran <- html_session(naslov7) %>% read_html(encoding = "UTF-8") 
GSP_tabele <- stran %>% html_nodes(xpath ="//table") 
GSP <- GSP_tabele %>% .[[7]] %>% html_table(fill = TRUE) 
GSP <- GSP[c(-1,-46,-54),c(2,5)] 
names(GSP) <- c("Država", "GSP (v milijon $)") 
GSP[2] <- apply(GSP[2], 2, .%>% gsub("\\$", "", .) %>% gsub("\\,", "", .)) %>% as.numeric()
GSP3 <- GSP %>% arrange (`GSP (v milijon $)`)



### GRAFI
graf1 <- ggplot(data = gdp, aes(x=Leto, y=`BDP (v trilijonih $)`), height=5, width=5)+
                            geom_line(size=1, color='red')+ggtitle("BDP")
graf2 <- ggplot(data = gdppc, aes(x=Letnica, y=`BDPp.c. (v $)`))+geom_line(size=1, color='darkgreen')+
                            ggtitle("BDP per capita skozi leta")
graf3 <- ggplot(data = gr, aes(x=Letnica, y=`Stopnja rasti`))+geom_line(size=1, color='blue')+
                            ggtitle("Stopnja rasti skozi leta (v%)")
graf4 <- ggplot(data = cpi, aes(x=Letnica, y=`Indeks cen`))+geom_line(size=1, color='orange')+
                            ggtitle("Spreminjanje indeksa cen")
graf5 <- ggplot(data = usinf, aes(x=Letnica, y=`Stopnja inflacije (v %)`))+geom_line(size=1, color='purple')+
                            ggtitle("Stopnja inflacije v ZDA (v %)")
graf6 <- ggplot(data = unemp, aes(x=Letnica, y=`Stopnja brezposlenosti (v %)`))+geom_line(size=1, color='black')+
                            ggtitle("Brezposelnost skozi leta (v %)")



# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename1 = 'catalog_predictions2'
filename2 = 'catalog_predictions3'


catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions2 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40,60,80),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename1)

catalog_predictions3 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(30,50,70,90),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename2)


# Catalog vs predictions

accuracy <- accuracy0 <- accuracy1 <- accuracy2 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) <- names(accuracy2) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy2[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, empirical.only = TRUE)
accuracy2[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, predict.only = TRUE)
accuracy2[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]], accuracy2[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]], accuracy2[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]], accuracy2[[3]])

percent_remove = c(0,10,20,40,60,80,100)
nb_iter = 100
K.values = 8
MW = 1
WT =  0.5
minimum_threshold = 0.3

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

# Graph
for(j in 13:16) {
        eplot(xmin = -0.09, xmax = 100, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.1) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            # mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            # mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 0.1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 0.1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 0.1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            points(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it, cex = 0.5, pch = 1, col = col[i])
            lines(lowess(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it))
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
catalog_predictions <- function(min.tx = 45, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, percent_remove = 0, nb_iter = 1, comm_id = FALSE, community) {

    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        if(comm_id == FALSE) {
            to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        } else { # comm_id = TRUE
            to.delete <- which(!Cm %in% community)
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        }

    # Setting up lists to store the results
    # weights
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        #Minimum weight
        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

        #Number of iterations
        iter <- vector('list', nb_iter)
            for(i in 1:nb_iter) {
                iter[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- iter
        names(Tanimoto_analysis) <- seq(1,nb_iter)
        remove(iter)


        # Percent remove in communities
        pc_rm <- vector('list', length(percent_remove))
            for(i in 1:length(percent_remove)) {
                pc_rm[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- pc_rm
        names(Tanimoto_analysis) <- percent_remove
        remove(pc_rm)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(percent_remove) * nb_iter * length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(p in 1:length(percent_remove)){
        percent_rm <- percent_remove[p]
        for(o in 1:nb_iter){
            for(n in 1:length(MW)) {
                mw <- MW[n]
                for(m in 1:length(K.values)) {

                    # Tanimoto analysis with different weights for different communities
                        # Parameters:
                            Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                            Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                            # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                        #   wt  Weight of traits in similarity measurement
                        #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                        #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                        # Output:
                        #   A vector of sets of resources for each taxon
                        for(i in 1:length(WT)){ #1st loop for all types of wt values
                            wt <- WT[i]
                            for(j in 1:length(Cm)) { #2nd loop for all C[i]
                                S1 <- communities[[j]]
                                S0 <- S0_catalog

                                if(similarity == 'both') { # For similarity matrices already evaluated
                                    similarity.consumer <- similarity.consumers[[i]]
                                    similarity.resource <- similarity.resources[[i]]
                                } else if(similarity == 'consumer') {
                                    similarity.consumer <- similarity.consumers[[i]]
                                } else if (similarity == 'resource') {
                                    similarity.resource <- similarity.resources[[i]]
                                }

                                # setting up the iterative process to evaluate the accuracy ~ # taxa in catalog
                                # removing a certain percentage of the # of species for which there are interactions as consumers described in the original food web.

                                # inter_Cm <- unique(subset(interactions_sources[, 'consumer'], interactions_sources[, 'source'] == Cm[j] & interactions_sources[, 'inter'] == "1")) # Species for which there are interactions as consumer in Cm[j]

                                interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3] # interaction catalog without interactions coming from Cm[j]

                                # inter_Cm2 <- unique(interactions[which(interactions[, 'consumer'] %in% inter_Cm), 'consumer']) # consumers in Cm[j] for which information is still available in catalog after deletion of Cm[j] from catalog

                                #Removing a percentage of consumers described in catalog
                                    # sample_iter <- sample(x = inter_Cm2, size = round((percent_rm / 100) * length(inter_Cm2)), replace = FALSE)
                                    sample_iter <- sample(x = S1, size = round((percent_rm / 100) * length(S1)), replace = FALSE) # To use if removing a percent of all taxa in original web

                                    for(k in 1:length(sample_iter)) {
                                      S0[sample_iter[k], 'resource'] <- ""
                                      S0[sample_iter[k], 'non-resource'] <- ""
                                      S0[sample_iter[k], 'consumer'] <- ""
                                      S0[sample_iter[k], 'non-consumer'] <- ""
                                    }

                                    S1_no_mod <- which(!S1 %in% sample_iter)

                                # 2. Preexisting information kept to inform algorithm
                                    if(length(S1_no_mod) == 0) {
                                        NULL
                                    } else {

                                    # Only modifying those that are loosing data from the catalogue, less time
                                        to.change <- numeric()
                                        for(k in 1:length(S1_no_mod)) {
                                            to.change <- c(to.change, which(interactions[, 'consumer'] == S1[S1_no_mod[k]]), which(interactions[, 'resource'] == S1[S1_no_mod[k]]))
                                        }
                                        to.change <- unique(to.change)

                                    # Modifying sets of resources and non-resources for taxa in S1_no_mod
                                        interactions <- interactions[to.change, ]
                                        rownames(interactions) <- seq(1,nrow(interactions))
                                        resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                                  resource = interactions[, 'resource'],
                                                                                  inter_type = interactions[, 'inter'])

                                        consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                                resource = interactions[, 'resource'],
                                                                                inter_type = interactions[, 'inter'])


                                    # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                        for(k in 1:nrow(resource_set)) {
                                          S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                          S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                        }
                                        for(k in 1:nrow(consumer_set)) {
                                          S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                          S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                        }
                                    remove(interactions, resource_set, to.change)
                                    }#if

                                # Recalculate similarity
                                    similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.consumer,
                                                                                        taxa = 'consumer')

                                    similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.resource,
                                                                                        taxa = 'resource')

                                # Predicting interactions
                                    Tanimoto_analysis[[p]][[o]][[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                            Kr = Kr,
                                                                                            S0 = S0,
                                                                                            S1 = S1,
                                                                                            MW = mw,
                                                                                            similarity.consumer = similarity.consumer,
                                                                                            similarity.resource = similarity.resource,
                                                                                            minimum_threshold = minimum_threshold)

                                save(x = Tanimoto_analysis, file = file.to.save)
                                remove(S0, S1, similarity.consumer, similarity.resource)
                                iteration <- iteration + 1
                                setTxtProgressBar(pb, iteration)
                            }#2nd loop for all C[i]

                            save(x = Tanimoto_analysis, file = file.to.save)
                            remove(wt)

                        }#1st loop for all types of wt values
                }#m
            }#n
        }#o
    }#p
    #Saving number of species in original web vs catalog once web removed
    # percent_original <- length(inter_Cm2) / length(inter_Cm)
    # x <- c(percent_original, length(inter_Cm), length(inter_Cm2))
    # file.to.save2 <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis_pc_tx.RData")
    # save(x = x, file = file.to.save2)

    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container_dir, settings) {
            private$settings <- settings

            private$cat_main_file_magic(container_dir)
            private$write_slurm_script(container_dir)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir) {
            main_file <- ".default_stain_main.R"
            file <- paste0(dir, "/.stain/sources/", main_file)
            sourcing <- paste("sapply(list.files('./.stain/sources', full.names = TRUE)[!(list.files('./.stain/sources')) %in%",
                              paste0("'", main_file, "'"), "], source)")
            loading <- paste("sapply(list.files('./.stain/objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./.stain $PFSDIR
cd $PFSDIR

mkdir .data
mv ./.stain/data/* ./.data

module load hpc-ods
module load pandoc

R CMD BATCH ./.stain/sources/.default_stain_main.R

rm -rf ./.data ./.stain

cp -r * $SLURM_SUBMIT_DIR/output"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, "submit.slurm", sep = "/"))
        }
    )
)
library(shiny)
library(shinydashboard)

shinyUI(dashboardPage(
  title="Quest",
  skin="yellow",
  dashboardHeader(title = "Quest", titleWidth = 220),
  dashboardSidebar(width=220,
      sidebarMenu(
        #sidebarSearchForm(textId = "searchText", buttonId = "searchButton",label = "Search..."),
        menuItem("Files",tabName="files",icon=shiny::icon("upload")),
        menuItem("Data Table",tabName="data",icon=shiny::icon("database")),
        menuItem("1D plots",tabName="1d",icon=shiny::icon("line-chart")),
        menuItem("2D plots",tabName="2d",icon=shiny::icon("line-chart")),
        menuItem("ggplot wrapper",tabName="gg",icon=shiny::icon("line-chart")),
        menuItem("Binned plots",tabName="bin",icon=shiny::icon("line-chart")),
        menuItem("3D tile plots",tabName="3d",icon=shiny::icon("line-chart")),
        menuItem("Heatmaps",tabName="heatmap",icon=shiny::icon("th")),
        menuItem("Settings",tabName="settings",icon=shiny::icon("cogs")),
        menuItem("Help",tabName="help",icon=shiny::icon("question")),
        checkboxInput("auto","Auto-plot",value = T),
        checkboxInput("freeze","Freeze inputs",value = F),
        checkboxInput("execute","Apply R code",value = F),
        actionButton("close","Close Quest",icon = shiny::icon("close"),style="color: #fff; background-color: #337ab7; border-color: #2e6da4")
      )
  ),
  dashboardBody(
   tags$head(
    tags$link(rel = "stylesheet", type = "text/css", href = "custom.css")
   ),
   tabItems(
     tabItem(tabName="files",
               fluidRow(
                 box(
                   title="Load from your computer",width = 12,status="primary",solidHeader=TRUE,
                   #htmlOutput("fileUI"),
                   selectInput("inputType","Input file location:",choices=c("Upload","Server","Environment")),
                   conditionalPanel(
                     condition = "input.inputType == 'Upload'",
                     fileInput("file", "Input File",multiple = FALSE) ##May add upload file option)
                   ),
                   conditionalPanel(
                     condition = "input.inputType == 'Server'",
                     textInput("dir","Select file directory:",value=getwd()),
                     checkboxInput("recursive", "Search directory recursively", FALSE),
                     textInput("pattern","Search pattern","",placeholder="*.tab"),
                     actionButton("list_dir","List",icon = shiny::icon("folder-open")),
                     uiOutput("inFiles")
                   ),
                   conditionalPanel(
                     condition = "input.inputType == 'Environment'",
                     uiOutput("inObjects")
                   ),
                   #checkboxInput("show", "Show columns", FALSE),
                   #checkboxInput('show_all', 'All/None', TRUE),
                   #conditionalPanel(
                   #condition = "input.show == true",
                    #uiOutput("show_cols")
                   #),
                   checkboxInput("header", "File has column headers", TRUE)
                 ),
                 box(
                   title="Download table",width = 12,status="primary",solidHeader=TRUE,
                   uiOutput("downloadFiles")
                 )
             )
     ),
     tabItem(tabName="data",
             fluidRow(
               box(
                 title = "Data Table", width = 12, status = "primary",solidHeader=TRUE,
                 div(style = 'overflow-x: scroll', dataTableOutput('table'))
               )
             )
     ),
     tabItem(tabName="1d",
             fluidRow(
               box(
                 title="1D plots",width = 8,status="primary",solidHeader=TRUE,
                 plotOutput("plot")
               ),
               box(
                 title="Controls",width = 4,collapsible = T,status="success",solidHeader=TRUE,
                 wellPanel(p(strong("Data")), 
                           uiOutput("plot_cols")
                 ),
                 wellPanel(p(strong("Controls")),
                           selectInput("type","Plot Type:",choices=c("boxplot","histogram")),
                           conditionalPanel(condition="input.type=='boxplot'",
                                            textInput("bversus","Add filters to plot against a rival",value="")
                           ),
                           conditionalPanel(condition="input.type=='histogram'",
                                            checkboxInput("hlogx","Log X-axis",value = F),
                                            numericInput("breaks","Breaks",0),
                                            helpText("Uses default if set to 0")
                           )          
                 )
               )
             )
     ),
     tabItem(tabName="2d",
             fluidRow(
               box(
                   title="2D plots",width = 8,status="primary",solidHeader=TRUE,
                   plotOutput("dplot")
               ),
               box(
                 title="Controls",width = 4,collapsible = T,status="success",solidHeader=TRUE,
                 wellPanel(p(strong("Data")), 
                           uiOutput("dplot_cols")
                 ),
                 wellPanel(p(strong("Controls")),
                           selectInput("dtype","Plot type",choices=c("scatter","smoothScatter")),
                           checkboxInput("logx","Log X-axis",value = F),
                           checkboxInput("logy","Log Y-axis",value = F),
                           textInput("hilite","Highlight subset",value="")
                 )
               )
             )
     ),
     tabItem(tabName="gg",
             fluidRow(
               box(
                 title="gg plot",width = 8,status="primary",solidHeader=TRUE,
                 conditionalPanel(condition="input.gg_plotly==false",
                  plotOutput("ggplot")
                 ),
                 conditionalPanel(condition = "input.gg_plotly==true",
                  plotlyOutput("ggplotly")
                 )
               ),
               tabBox(
                 width = 4,
                 tabPanel("Inputs",uiOutput("ggplot_cols")),
                 tabPanel("Colours",uiOutput("ggplot_colours")),
                 tabPanel("Layout",uiOutput("ggplot_plot")),
                 tabPanel("Controls",uiOutput("ggplot_controls"))
               )
             )
     ),
     tabItem(tabName="bin",
             fluidRow(
               box(
                 title="Binned plot",width = 8,status="primary",solidHeader=TRUE,
                 plotOutput("bplot")
               ),
               box(
                 title="Controls",width = 4,status="success",solidHeader=TRUE,
                 div(style = 'overflow-y: scroll', 
                 wellPanel(p(strong("Data")), 
                           uiOutput("bin_cols")
                 ),
                 wellPanel(p(strong("Controls")),style = 'overflow-y: scroll; max-height: 400px',
                           numericInput("bw","Bin size",200,min=1),
                           numericInput("bs","Step size",40,min=1),
                           numericInput("bys","Rescale y-axis ",1,min=1),
                           selectInput("bf","Operation",choices=c("mean","median","boxes","sum","max","min")),
                           selectInput("bscale","Scale",choices=c("linear","log","bins")), 
                           selectInput("bleg","Legend Position",choices=c("topleft","topright","bottomleft","bottomright")),
                           textInput("bmin","Minimum y-axis value","default"),
                           textInput("bmax","Maximum y-axis value","default"),
                           numericInput("bystep","Y axis step size",0,min=0),
                           textInput("bylab","Y axis label",""),
                           textInput("bfeature","Name of features","data points")
                 )
                 )
                 )
             )
     ),
     tabItem(tabName="3d",
             fluidRow(
               box(
                   title="3D tile plot",width = 8,status="primary",solidHeader=TRUE,
                   plotOutput("tplot")
               ),
               box(
                 title="Data",width = 4,status="success",solidHeader=TRUE,
                 wellPanel(p(strong("Data")),style = 'overflow-y: scroll; max-height: 300px',
                  uiOutput("t_cols")
                 )
               )
             ),
             fluidRow(
               box(
                 title="Controls",width = 12,status="success",solidHeader=TRUE,
                 wellPanel(p(strong("Controls")),style = 'overflow-y: scroll; max-height: 400px',
                           numericInput("bins","Bins",1,min=1,max=1000),
                           selectInput("tsummary","Operation",choices=c("mean","median","sum","count")),                                   
                           checkboxInput("tzman","Manually alter colour scale",F),
                           conditionalPanel("input.tzman == true",
                             numericInput("tzmin","Minimum colour scale",0),
                             numericInput("tzmax","Maximum colour scale",0)
                           ),
                           checkboxInput("txman","Manually alter X scale",F),
                           conditionalPanel("input.txman == true",
                             numericInput("txmin","Minimum x-axis value",0),
                             numericInput("txmax","Maximum x-axis value",0)
                           ),
                           checkboxInput("tyman","Manually alter Y scale",F),
                           conditionalPanel("input.tyman == true",                                                    
                            numericInput("tymin","Minimum y-axis value",0),
                            numericInput("tymax","Maximum y-axis value",0)
                           )
                 )
               )
             )
     ),
     tabItem(tabName="heatmap",
             fluidRow(
               box(
                 title="Heatmaps",width = 8,status="primary",solidHeader=TRUE,
                 d3heatmapOutput("hmap")
               ),
               box(
                 title="Data",width = 4,status="success",solidHeader=TRUE,
                 uiOutput("h_cols")
               )
             ),
             fluidRow(
               box(
                 title="Controls",width = 12,status="success",solidHeader=TRUE,
                 numericInput("hnrow","Row limit",100,min=1,max=2000),
                 numericInput("hkrow","Number of K-means clusters",5,min=1,max=10)
               )
             )
     ),
     tabItem(tabName="settings",
             fluidRow(
               box(
                   title="Settings",width = 12,status="primary",solidHeader=TRUE,
                   numericInput("factorlim","Limit on factor levels to process in plots",50)
               )
             )
     ),
     tabItem(tabName="help",
             fluidRow(
               box(
                 title="Help",width = 12,status="primary",solidHeader=TRUE,
                 includeMarkdown("README.md")
               )
             )
     )
   ), 
   fluidRow(
     box(
       title="R Code",width = 12,status="danger",collapsible=TRUE,collapsed = TRUE,solidHeader=TRUE,
       HTML('<textarea id="add" rows="6" cols="150"></textarea>'),
       helpText("See help tab for examples")
     )
   )
  )
)
)#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        settings = NULL,
        initialize = function(dir = ".", options = c()) {
            self$settings <- SlurmSettings$new(option)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
                script <- SlurmBashScript$new(dir, self$settings)
            }
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        settings = NULL,
        initialize = function(dir = ".", settings = c()) {
            self$settings <- SlurmSettings$new(settings)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
                script <- SlurmBashScript$new(dir, self$settings)
            }
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#SNOPSIS
#calculates genomic estimated breeding values (GEBVs) using rrBLUP,
#GBLUP method

#AUTHOR
# Isaak Y Tecle (iyt2@cornell.edu)

options(echo = FALSE)

library(rrBLUP)
library(plyr)
library(stringr)
library(lme4)
library(randomForest)
library(data.table)
#library(genetics)

allArgs <- commandArgs()

inputFiles  <- scan(grep("input_files", allArgs, ignore.case = TRUE, perl = TRUE, value = TRUE),
                   what = "character")

outputFiles <- scan(grep("output_files", allArgs, ignore.case = TRUE,perl = TRUE, value = TRUE),
                    what = "character")

traitsFile <- grep("traits", inputFiles, ignore.case = TRUE, value = TRUE)
traitFile  <- grep("trait_info", inputFiles, ignore.case = TRUE, value = TRUE)
traitInfo  <- scan(traitFile, what = "character",)
traitInfo  <- strsplit(traitInfo, "\t");
traitId    <- traitInfo[[1]]
trait      <- traitInfo[[2]]

datasetInfoFile <- grep("dataset_info", inputFiles, ignore.case = TRUE, value = TRUE)
datasetInfo     <- c()

if (length(datasetInfoFile) != 0 ) { 
    datasetInfo <- scan(datasetInfoFile, what = "character")    
    datasetInfo <- paste(datasetInfo, collapse = " ")   
  } else {   
    datasetInfo <- c('single population')  
  }

validationTrait <- paste("validation", trait, sep = "_")
validationFile  <- grep(validationTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(validationFile)) {
  stop("Validation output file is missing.")
}

kinshipTrait <- paste("kinship", trait, sep = "_")
blupFile     <- grep(kinshipTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(blupFile)) {
  stop("GEBVs file is missing.")
}
markerTrait <- paste("marker", trait, sep = "_")
markerFile  <- grep(markerTrait, outputFiles, ignore.case = TRUE, value = TRUE)

traitPhenoFile <- paste("phenotype_trait", trait, sep = "_")
traitPhenoFile <- grep(traitPhenoFile, outputFiles,ignore.case = TRUE, value = TRUE)

varianceComponentsFile <- grep("variance_components", outputFiles, ignore.case = TRUE, value = TRUE)

formattedPhenoFile <- grep("formatted_phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE)

formattedPhenoData <- c()
phenoData          <- c()

genoFile <- grep("genotype_data", inputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(genoFile)) {
  stop("genotype data file is missing.")
}

if (file.info(genoFile)$size == 0) {
  stop("genotype data file is empty.")
}

genoData <- fread(genoFile, na.strings = c("NA", " ", "--", "-"),  header = TRUE)

if (length(formattedPhenoFile) != 0 && file.info(formattedPhenoFile)$size != 0) {
  formattedPhenoData <- as.data.frame(fread(formattedPhenoFile,
                                            na.strings = c("NA", " ", "--", "-", ".")
                                            ))
      
  row.names(formattedPhenoData) <- formattedPhenoData[, 1]
  formattedPhenoData[, 1]       <- NULL    
} else {
  phenoFile <- grep("\\/phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE, perl = TRUE)

  if (is.null(phenoFile)) {
    stop("phenotype data file is missing.")
  }

  if (file.info(phenoFile)$size == 0) {
    stop("phenotype data file is empty.")
  }
  
  phenoData <- fread(phenoFile, na.strings = c("NA", " ", "--", "-", "."), header = TRUE) 
}

phenoData  <- as.data.frame(phenoData)
phenoTrait <- c()

if (datasetInfo == 'combined populations') {
  
   if (!is.null(formattedPhenoData)) {
      phenoTrait <- subset(formattedPhenoData, select = trait)
      phenoTrait <- na.omit(phenoTrait)
   
    } else {
      dropColumns <- grep(trait, names(phenoData), ignore.case = TRUE, value = TRUE)
      phenoTrait  <- phenoData[, !(names(phenoData) %in% dropColumns)]
   
      phenoTrait            <- as.data.frame(phenoTrait)
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1]       <- NULL
      colnames(phenoTrait)  <- trait
    }
   
} else {

  if (!is.null(formattedPhenoData)) {
    phenoTrait <- subset(formattedPhenoData, select = trait)
    phenoTrait <- na.omit(phenoTrait)
   
  } else {
    dropColumns <- c("uniquename", "stock_name")
    phenoData   <- phenoData[, !(names(phenoData) %in% dropColumns)]
    
    phenoTrait <- subset(phenoData, select = c("object_name", "object_id", "design", "block", "replicate", trait))
   
    experimentalDesign <- phenoTrait[2, 'design']
  
    if (class(phenoTrait[, trait]) != 'numeric') {
      phenoTrait[, trait] <- as.numeric(as.character(phenoTrait[, trait]))
    }
      
    if (is.na(experimentalDesign) == TRUE) {experimentalDesign <- c('No Design')}
    
    if ((experimentalDesign == 'Augmented' || experimentalDesign == 'RCBD')  &&  unique(phenoTrait$block) > 1) {

      message("GS experimental design: ", experimentalDesign)

      augData <- subset(phenoTrait, select = c("object_name", "object_id",  "block",  trait))

      colnames(augData)[1] <- "genotypes"
      colnames(augData)[4] <- "trait"

      model <- try(lmer(trait ~ 0 + genotypes + (1|block),
                        augData,
                        na.action = na.omit))

      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
        
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))  
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
      }
            
    } else if (experimentalDesign == 'Alpha') {
   
      message("Experimental desgin: ", experimentalDesign)
      
      alphaData <- subset(phenoData,
                            select = c("object_name", "object_id","block", "replicate", trait)
                            )
      
      colnames(alphaData)[1] <- "genotypes"
      colnames(alphaData)[5] <- "trait"
         
      model <- try(lmer(trait ~ 0 + genotypes + (1|replicate/block),
                        alphaData,
                        na.action = na.omit))
        
      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
      
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))     
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
        
      }
      
    } else {

      phenoTrait <- subset(phenoData,
                           select = c("object_name", "object_id",  trait))
       
      if (sum(is.na(phenoTrait)) > 0) {
        message("No. of pheno missing values: ", sum(is.na(phenoTrait)))      
        phenoTrait <- na.omit(phenoTrait)
      }

        #calculate mean of reps/plots of the same accession and
        #create new df with the accession means    
     
      phenoTrait   <- phenoTrait[order(row.names(phenoTrait)), ]
      phenoTrait   <- data.frame(phenoTrait)
      message('phenotyped lines before averaging: ', length(row.names(phenoTrait)))
   
      phenoTrait<-ddply(phenoTrait, "object_name", colwise(mean))
      message('phenotyped lines after averaging: ', length(row.names(phenoTrait)))
        
      phenoTrait <- subset(phenoTrait, select = c("object_name", trait))
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1] <- NULL
       
        #format all-traits population phenotype dataset
        ## formattedPhenoData <- phenoData
        ## dropColumns <- c("object_id", "stock_id", "design", "block", "replicate" )

        ## formattedPhenoData <- formattedPhenoData[, !(names(formattedPhenoData) %in% dropColumns)]
        ## formattedPhenoData <- ddply(formattedPhenoData,
        ##                             "object_name",
        ##                             colwise(mean)
        ##                             )

        ## row.names(formattedPhenoData) <- formattedPhenoData[, 1]
        ## formattedPhenoData[, 1] <- NULL

        ## formattedPhenoData <- round(formattedPhenoData,
        ##                             digits=3
        ##                             )     
    }
  }
}



#remove markers with > 60% missing marker data
message('no of markers before filtering out: ', ncol(genoData))
genoData[, which(colSums(is.na(genoData)) >= nrow(genoData) * 0.6) := NULL]
message('no of markers after filtering out 60% missing: ', ncol(genoData))

#remove indls with > 80% missing marker data
genoData[, noMissing := apply(.SD, 1, function(x) sum(is.na(x)))]
genoData <- genoData[noMissing <= ncol(genoData) * 0.8]
genoData[, noMissing := NULL]
message('no of indls after filtering out ones with 80% missing: ', nrow(genoData))

### MAF calculation ###
calculateMAF <- function(x) {
  mafThreshold <- c(0.05)
 
  a0 <-  length(x[x==0])
  a1 <-  length(x[x==1])
  a2 <-  length(x[x==2])
  aT <- a0 + a1 + a2

  message('a0: ', a0, ' a1: ', a1, ' a2:', a2, ' aT: ', aT)
  p   <- ((2*a0)+a1)/(2*aT)
  q   <- 1- p
  maf <- min(p, q)
  
  return (maf)

}

#remove monomorphic markers
#genoData[, which(apply(.SD, 2,  function(x) length(unique(x)) == 1 )) ]

#remove markers with MAF < 5%
genoData[, which(apply(genoData, 2,  calculateMAF) < 0.05) := NULL ]
message('marker no after MAF cleaning ', ncol(genoData))

genoData           <- as.data.frame(genoData)
rownames(genoData) <- genoData[, 1]
genoData[, 1]      <- NULL

predictionTempFile <- grep("prediction_population", inputFiles, ignore.case = TRUE, value = TRUE)
predictionFile     <- c()

message('prediction temp genotype file: ', predictionTempFile)

if (length(predictionTempFile) !=0 ) {
  predictionFile <- scan(predictionTempFile, what = "character")
}

message('prediction genotype file: ', predictionFile)

predictionPopGEBVsFile <- grep("prediction_pop_gebvs", outputFiles, ignore.case = TRUE, value = TRUE)
message("prediction gebv file: ",  predictionPopGEBVsFile)

predictionData <- c()

if (length(predictionFile) !=0 ) {

  predictionData <- fread(predictionFile, na.strings = c("NA", " ", "--", "-"),)
  message('selection population: no of markers before filtering out: ', ncol(genoData))
  predictionData[, which(colSums(is.na(predictionData)) >= nrow(predictionData) * 0.6) := NULL]

  #remove indls with > 80% missing marker data
  predictionData[, noMissing := apply(.SD, 1, function(x) sum(is.na(x)))]
  predictionData <- predictionData[noMissing <= ncol(predictionData) * 0.8]
  predictionData[, noMissing := NULL]
  
  predictionData[, which(apply(predictionData, 2,  calculateMAF) < 0.05) := NULL ]
  message('selection pop marker no after MAF cleaning ', ncol(preditionData))
  predictionData           <- as.data.frame(predictionData)
  rownames(predictionData) <- predictionData[, 1]
  predictionData[, 1]      <- NULL
 
}

#impute genotype values for obs with missing values,
#based on mean of neighbouring 10 (arbitrary) obs
genoDataMissing <- c()

if (sum(is.na(genoData)) > 0) {
  genoDataMissing<- c('yes')

  message("sum of geno missing values, ", sum(is.na(genoData)) )  
  genoData <- na.roughfix(genoData)
  genoData <- data.matrix(genoData)
}

genoData <- genoData[order(row.names(genoData)), ]

#create phenotype and genotype datasets with
#common stocks only
message('phenotyped lines: ', length(row.names(phenoTrait)))
message('genotyped lines: ', length(row.names(genoData)))

#extract observation lines with both
#phenotype and genotype data only.
commonObs <- intersect(row.names(phenoTrait), row.names(genoData))
commonObs <- data.frame(commonObs)
rownames(commonObs)<-commonObs[, 1]

message('lines with both genotype and phenotype data: ', length(row.names(commonObs)))

#include in the genotype dataset only observation lines
#with phenotype data
message("genotype lines before filtering for phenotyped only: ", length(row.names(genoData)))        
genoDataFiltered <- genoData[(rownames(genoData) %in% rownames(commonObs)), ]
message("genotype lines after filtering for phenotyped only: ", length(row.names(genoDataFiltered)))

#drop observation lines without genotype data
message("phenotype lines before filtering for genotyped only: ", length(row.names(phenoTrait)))        
phenoTrait <- merge(data.frame(phenoTrait), commonObs, by=0, all=FALSE)
rownames(phenoTrait) <- phenoTrait[, 1]
phenoTrait <- subset(phenoTrait, select=trait)

message("phenotype lines after filtering for genotyped only: ", length(row.names(phenoTrait)))
#a set of only observation lines with genotype data

traitPhenoData   <- data.frame(round(phenoTrait, digits = 2))           
phenoTrait       <- data.matrix(phenoTrait)
genoDataFiltered <- data.matrix(genoDataFiltered)

#impute missing data in prediction data
predictionDataMissing <- c()
if (length(predictionData) != 0) {
  #purge markers unique to both populations
  commonMarkers    <- intersect(names(data.frame(genoDataFiltered)), names(predictionData))
  predictionData   <- subset(predictionData, select = commonMarkers)
  genoDataFiltered <- subset(genoDataFiltered, select= commonMarkers)
  
 # predictionData <- data.matrix(predictionData)
 
  if (sum(is.na(predictionData)) > 0) {
    predictionDataMissing <- c('yes')
    message("sum of geno missing values, ", sum(is.na(predictionData)) )  
    predictionData <- data.matrix(na.roughfix(predictionData))
    
  }
}

relationshipMatrixFile <- grep("relationship_matrix", outputFiles, ignore.case = TRUE, value = TRUE)

message("relationship matrix file: ", relationshipMatrixFile)

relationshipMatrix <- c()
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size > 0 ) {
    relationshipDf <- as.data.frame(fread(relationshipMatrixFile))

    rownames(relationshipDf) <- relationshipDf[, 1]
    relationshipDf[, 1]      <- NULL
    relationshipMatrix       <- data.matrix(relationshipDf)
  }
}


#change genotype coding to [-1, 0, 1], to use the A.mat ) if  [0, 1, 2]
genoTrCode <- grep("2", genoDataFiltered[1, ], value = TRUE)
if(length(genoTrCode) != 0) {
  genoDataFiltered <- genoDataFiltered - 1
}

if (length(predictionData) != 0 ) {
  genoSlCode <- grep("2", predictionData[1, ], value = TRUE)
  if (length(genoSlCode) != 0 ) {
    predictionData <- predictionData - 1
  }
}

ordered.markerEffects <- c()
if ( length(predictionData) == 0 ) {
  markerEffects <- mixed.solve(y = phenoTrait,
                               Z = genoDataFiltered
                               )

  ordered.markerEffects <- data.matrix(markerEffects$u)
  ordered.markerEffects <- data.matrix(ordered.markerEffects [order (-ordered.markerEffects[, 1]), ])
  ordered.markerEffects <- round(ordered.markerEffects, digits=5)

  colnames(ordered.markerEffects) <- c("Marker Effects")

}

#additive relationship model
#calculate the inner products for
#genotypes (realized relationship matrix)
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size == 0) {
    relationshipMatrix <- tcrossprod(data.matrix(genoData))
  }
}
relationshipMatrixFiltered <- relationshipMatrix[(rownames(relationshipMatrix) %in% rownames(commonObs)),]
relationshipMatrixFiltered <- relationshipMatrixFiltered[, (colnames(relationshipMatrixFiltered) %in% rownames(commonObs))]

#construct an identity matrix for genotypes
identityMatrix <- diag(nrow(phenoTrait))

relationshipMatrixFiltered <- data.matrix(relationshipMatrixFiltered)

iGEBV  <- mixed.solve(y = phenoTrait, Z = identityMatrix, K = relationshipMatrixFiltered) 
iGEBVu <- iGEBV$u

heritability  <- c()

if ( is.null(predictionFile) == TRUE ) {
  additiveEffects <- data.frame(iGEBVu)
 
  pN <- nrow(phenoTrait)
  aN <- nrow(additiveEffects)

  if (pN <= 1 || pN != aN) {
    stop("phenoTrait and additiveEffects have different lengths: ",
         pN, " and ", aN, ".")
  }
      
  if (TRUE %in% is.na(phenoTrait) || TRUE %in% is.na(additiveEffects)) {
    stop(" Arguments phenoTrait and additiveEffects have missing values.")
  }
  
  phenoVariance <- var(phenoTrait)
  gebvVariance  <- var(additiveEffects)
  heritability  <- round((gebvVariance / phenoVariance), digits = 2)
      
  cat("\n", file = varianceComponentsFile,  append = FALSE)
  cat('Error variance', iGEBV$Ve, file = varianceComponentsFile, sep = "\t", append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Additive genetic variance',  iGEBV$Vu, file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Phenotype mean', iGEBV$beta,file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Heritability (h)', heritability, file = varianceComponentsFile, sep = '\t', append = TRUE)
}

iGEBV         <- data.matrix(iGEBVu)
ordered.iGEBV <- as.data.frame(iGEBV[order(-iGEBV[, 1]), ])
ordered.iGEBV <- round(ordered.iGEBV, digits = 3)

combinedGebvsFile <- grep('selected_traits_gebv', outputFiles, ignore.case = TRUE,value = TRUE)

allGebvs<-c()
if (length(combinedGebvsFile) != 0) {
    fileSize <- file.info(combinedGebvsFile)$size
    if (fileSize != 0 ) {
        combinedGebvs <- as.data.frame(fread(combinedGebvsFile))

        rownames(combinedGebvs) <- combinedGebvs[,1]
        combinedGebvs[,1]       <- NULL

        colnames(ordered.iGEBV) <- c(trait)
      
        traitGEBV <- as.data.frame(ordered.iGEBV)
        allGebvs <- merge(combinedGebvs, traitGEBV,
                          by = 0,
                          all = TRUE                     
                          )

        rownames(allGebvs) <- allGebvs[,1]
        allGebvs[,1] <- NULL
     }
  }

colnames(ordered.iGEBV) <- c(trait)
                  
#cross-validation
validationAll <- c()

if(is.null(predictionFile)) {
  genoNum <- nrow(phenoTrait)
if(genoNum < 20 ) {
  warning(genoNum, " is too small number of genotypes.")
}
  
reps <- round_any(genoNum, 10, f = ceiling) %/% 10

genotypeGroups <-c()

if (genoNum %% 10 == 0) {
    genotypeGroups <- rep(1:10, reps)
  } else {
    genotypeGroups <- rep(1:10, reps) [- (genoNum %% 10) ]
  }

set.seed(4567)                                   
genotypeGroups <- genotypeGroups[ order (runif(genoNum)) ]

for (i in 1:10) {
  tr <- paste("trPop", i, sep = ".")
  sl <- paste("slPop", i, sep = ".")
 
  trG <- which(genotypeGroups != i)
  slG <- which(genotypeGroups == i)
  
  assign(tr, trG)
  assign(sl, slG)

  kblup <- paste("rKblup", i, sep = ".")
  
  result <- kinship.BLUP(y = phenoTrait[trG, ],
                         G.train = genoDataFiltered[trG, ],
                         G.pred = genoDataFiltered[slG, ],                      
                         mixed.method = "REML",
                         K.method = "RR",
                         )
 
  assign(kblup, result)

#calculate cross-validation accuracy  
  valCorData <- merge(phenoTrait[slG, ], result$g.pred, by=0, all=FALSE)
  rownames(valCorData) <- valCorData[, 1]
  valCorData[, 1]      <- NULL
 
  accuracy <- try(cor(valCorData))
  validation <- paste("validation", i, sep = ".")

  cvTest <- paste("Validation test", i, sep = " ")

  if ( class(accuracy) != "try-error")
    {
      accuracy <- round(accuracy[1,2], digits = 3)
      accuracy <- data.matrix(accuracy)
    
      colnames(accuracy) <- c("correlation")
      rownames(accuracy) <- cvTest

      assign(validation, accuracy)
      
      if (!is.na(accuracy[1,1])) {
        validationAll <- rbind(validationAll, accuracy)
      }    
    }
}

validationAll <- data.matrix(validationAll[order(-validationAll[, 1]), ])
     
if (!is.null(validationAll)) {
    validationMean <- data.matrix(round(colMeans(validationAll), digits = 2))
   
    rownames(validationMean) <- c("Average")
     
    validationAll <- rbind(validationAll, validationMean)
    colnames(validationAll) <- c("Correlation")
  }
}

predictionPopResult <- c()
predictionPopGEBVs  <- c()

if (length(predictionData) != 0) {
    message("running prediction for selection candidates...marker data", ncol(predictionData), " vs. ", ncol(genoDataFiltered))

    predictionPopResult <- kinship.BLUP(y = phenoTrait,
                                        G.train = genoDataFiltered,
                                        G.pred = predictionData,
                                        mixed.method = "REML",
                                        K.method = "RR"
                                        )
 message("running prediction for selection candidates...DONE!!")

    predictionPopGEBVs <- round(data.matrix(predictionPopResult$g.pred), digits = 3)
    predictionPopGEBVs <- data.matrix(predictionPopGEBVs[order(-predictionPopGEBVs[, 1]), ])
   
    colnames(predictionPopGEBVs) <- c(trait)
  
}

if (!is.null(predictionPopGEBVs) & length(predictionPopGEBVsFile) != 0)  {
    write.table(predictionPopGEBVs,
                file = predictionPopGEBVsFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if(!is.null(validationAll)) {
    write.table(validationAll,
                file = validationFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.markerEffects)) {
    write.table(ordered.markerEffects,
                file = markerFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.iGEBV)) {
    write.table(ordered.iGEBV,
                file = blupFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (length(combinedGebvsFile) != 0 ) {
    if(file.info(combinedGebvsFile)$size == 0) {
        write.table(ordered.iGEBV,
                    file = combinedGebvsFile,
                    sep = "\t",
                    col.names = NA,
                    quote = FALSE,
                    )
      } else {
      write.table(allGebvs,
                  file = combinedGebvsFile,
                  sep = "\t",
                  quote = FALSE,
                  col.names = NA,
                  )
    }
}

if (!is.null(traitPhenoData) & length(traitPhenoFile) != 0) {
    write.table(traitPhenoData,
                file = traitPhenoFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                )
}



## if (!is.null(genoDataMissing)) {
##   write.table(genoData,
##               file = genoFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##             )

## }

## if (!is.null(predictionDataMissing)) {
##   write.table(predictionData,
##               file = predictionFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##               )
## }


if (file.info(relationshipMatrixFile)$size == 0) {
  write.table(relationshipMatrix,
              file = relationshipMatrixFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}


if (file.info(formattedPhenoFile)$size == 0 && !is.null(formattedPhenoData) ) {
  write.table(formattedPhenoData,
              file = formattedPhenoFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}

message("Done.")

q(save = "no", runLast = FALSE)

source('utils.r')

# # # Initialize model parameters
model <- list(num_blocks    = 20,
			  num_inits     = 5,
			  wts_range     = 1,
			  num_hids      = 3,
			  learning_rate = 0.15,
			  beta_val      = 5,
			  out_rule      = 'sigmoid') # linear / tan not implemented

training = matrix(rep(0, model$num_blocks * 6), ncol = 6)
for (shj in 1:6) { 
  
  # # # get shj stimuli
  cases <- shj_cats(shj)
  model$inputs <- cases$inputs
  model$labels <- cases$labels

  # # # train model
  result <- run_diva(model)

# # # add result to training matrix
training[,shj] <- result$training

}

# display results
print(training)
train_plot(training)
save.image(paste0('diva_run.rdata'))

# warnings()


two_way_tanimoto_predict <- function(Kc, Kr, S0, S1, MW, similarity.consumer, similarity.resource, minimum_threshold) {
    # Two-way Tanimoto Algorithm
    # ===========================

    # Parameters:
    #   Kc  Integer, how many neighbors to select for consumers
    #   Kr  Integer, how many neighbors to select for resources
    #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
    #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name
    #   MW  Mimimum weight to accept a candidate as a prey
    #

    # // TODO: I think MW should be a function of Kc & Kr and perhaps of the number of candidate resources. For example, a similar consumer could have multiple prey, which would artificially inflate the weight added to each prey in the candidate list. For exemple, Atlantic cod has over 600 prey species listed in the interaction catalogue... Hence, the longer the candidate list, the more likely a very small similarity will be turned into a predicted interaction
    # // REVIEW: Multiply similar.consumer[similarity] * similar.resource[similarity]? It's a similarity of a similarity in a sense...

    # // TODO: Different similarity measurement for resources and consumers

    # // REVIEW: Remove cannibalism from empirical data, or allow for it, or add parameter that allows or prevents cannibalism in the predictions. There are lots of predicted cannibalism interations in the catalogue and empirical webs. Accuracy would increase if it was allowed.


    # Output
    #   A vector of sets (the preys for each species)

    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # List of things to adjust - make it
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    # Process steps:
      # A prior process to this is to get the similarity matrix between all combinations of catalogue taxa and species in S1
      # For each species in S1:
      # 1. Identify resources already known in interaction catalogue (S0) for S1 species
        # 1.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
        # 1.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

      # 2. Identify Kc similar consumers to S1 in S0
        # 2.1 Extract set of candidate resources from each similar consumer, if any
        # 2.2 If candidate resource is in S1, add it to candidate list with weight 1
        # 2.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

      # 3. Make predictions:
        # 3.1 Remove taxa with weight < to minimum weight (MW) from prediction list
        # 3.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed


    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # !!! étendre predator et non predator pour resource... il faudrait aussi calculer la similarité des proies sur la base de leurs prédateurs partagés !!!
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    predictions <- matrix(nrow = length(S1), ncol = 3, data = "", dimnames = list(c(S1), c('consumer','resource_empirical','resource_predictions'))) # empty object for resource predictions
    predictions[, 'consumer'] <- S1

    # pb <- txtProgressBar(min = 0,max = length(S1), style = 3)
    for(i in 1:length(S1)) { # loop through each taxon in S1
        candidates <- matrix(nrow = 0, ncol = 2, dimnames = list(c(), c('resource', 'weight')), data = NA) # empty matrix for resource candidate list for S1[i], with taxon name and weight
        resources.S1 <- unlist(strsplit(S0[S1[i], 'resource'], " \\|\\ ")) # resources of S1[i]

        # Add resources that are already listed as resources for S1[i] in predictions[, 'resource_empirical'] or
        # Find similar resources to resources for S1[i] in S1
        if(length(resources.S1) > 0) {
            empirical <- character()
            for(j in 1:length(resources.S1)) { #loop through empirical resources for S1
                if(resources.S1[j] %in% S1) {
                    empirical <- c(empirical, resources.S1[j]) # observed resource found in S1 are automatically added to the column resource_empirical
                } else { # selecting Kr most similar resources in S1
                    # Let's assume for this part that we are not compiling a different similarity measure for predators and preys.
                    similar.resource <- matrix(nrow = length(S1)-1, ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources
                    similar.resource[, 'resource'] <- names(sort(similarity.resource[S1[-which(S1 == S1[i])], resources.S1[j]], decreasing = TRUE))
                    similar.resource[, 'similarity'] <- sort(similarity.resource[S1[-which(S1 == S1[i])], resources.S1[j]], decreasing = TRUE)

                    # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
                    if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {
                        same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])
                        similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]
                        similar.resource <- similar.resource[1:Kr, ]
                    } else {
                        similar.resource <- similar.resource[1:Kr, ]
                    }# if for random draw

                    for(l in 1:Kr) { # extracting resource candidates
                        if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break
                            break
                        } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                            NULL
                            # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed
                        } else if(similar.resource[l, 'similarity'] < minimum_threshold) {
                            NULL
                        } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add resource' with wt to its weight
                          candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])
                        } else {
                              candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it resource' with wt to its weight
                        }#if3
                    }#l
                }#if
            }#j
            predictions[S1[i], 'resource_empirical'] <- paste(empirical, collapse = ' | ')
        }#if1

        # Identify similar consumers to S1[i]
        similar.consumer <- matrix(nrow = nrow(similarity.consumer)-1, ncol = 2, dimnames = list(c(), c('consumer','similarity')), data = NA) # emporting K nearest neighbors for consumers
        similar.consumer[, 'consumer'] <- names(sort(similarity.consumer[-which(colnames(similarity.consumer) == S1[i]), S1[i]], decreasing = TRUE))
        similar.consumer[, 'similarity'] <- sort(similarity.consumer[-which(colnames(similarity.consumer) == S1[i]), S1[i]], decreasing = TRUE)

        # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
        if(similar.consumer[Kc+1, 'similarity'] == similar.consumer[Kc, 'similarity']) {
            same.similarity <- which(similar.consumer[, 'similarity'] == similar.consumer[Kc, 'similarity'])
            similar.consumer[same.similarity, ] <- similar.consumer[sample(same.similarity), ]
            similar.consumer <- similar.consumer[1:Kc, ]
        } else {
            similar.consumer <- similar.consumer[1:Kc, ]
        }# if for random draw


        # Est-ce que la valeur de similarité a de l'importance pour l'attribution des proies?
        # If yes, we could add an argument call wt_predator.
          # if(wt_predator == FALSE) {
          #   resources <- unique of all prey species of all similar predators
          # } else {}

        for(j in 1:Kc) { #loop through consumers

            if(all.equal(similar.consumer[, 'similarity'], rep('0',Kc)) == TRUE) { # if similarities all == 0, break
                break
            } else if(similar.consumer[j, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                NULL
            } else {

                # It's possible that consumers in the list have high taxonomic similarity, but no recorded resource
                candidate.resource <- unlist(strsplit(S0[similar.consumer[j, 'consumer'], 'resource'], " \\|\\ ")) # list of resources for consumer j
                # candidate.resource <- candidate.resource[(candidate.resource %in% resources.S1) == FALSE] # substracting candidate resources that are already listed as resources for S1[i] and hence considered in the preceding code segment

                for(k in 1:length(candidate.resource)) { # loop through resources of consumer j
                    if(length(candidate.resource) == 0) { # if candidate resource list is empty, break
                        break
                    } else if(candidate.resource[1] == "") { # if candidate list is an empty vector "", break
                        break
                    } else if(candidate.resource[k] == S1[i]) {
                    #   #// FIXME: if candidate resource is taxon for which predictions are being made, break (unless we want to allow CANIBALISM). Add argument for cannibalism allowed or not
                         NULL
                    } else if((candidate.resource[k] %in% S1) == TRUE) {
                        if((candidate.resource[k] %in% candidates[, 'resource']) == TRUE) {# if candidate is already in candidate list, add 1 to its weight
                            candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight']) + 1
                        } else {
                            candidates <- rbind(candidates, c(candidate.resource[k], 1)) # if candidate is not in the list, add it with 1 to its weight
                        }#if2

                    } else {
                        # Let's assume for this part that we are not compiling a different similarity measure for predators and preys.
                        similar.resource <- matrix(nrow = length(S1)-1, ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources
                        similar.resource[, 'resource'] <- names(sort(similarity.resource[S1[-which(S1 == S1[i])], candidate.resource[k]], decreasing = TRUE))
                        similar.resource[, 'similarity'] <- sort(similarity.resource[S1[-which(S1 == S1[i])], candidate.resource[k]], decreasing = TRUE)

                        # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
                        if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {
                            same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])
                            similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]
                            similar.resource <- similar.resource[1:Kr, ]
                        } else {
                            similar.resource <- similar.resource[1:Kr, ]
                        }# if for random draw

                        for(l in 1:Kr) { # extracting resource candidates
                            if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break
                                break
                            } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                                NULL
                                # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed
                            } else if(similar.resource[l, 'similarity'] < minimum_threshold) {
                                NULL
                            } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add 1 to its weight
                              candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])
                            } else {
                                  candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it with its weight = similarity
                            }#if3
                        }#l
                    } #if1
                }#k
            }#if
        }#j

        candidates <- candidates[which(candidates[, 'weight'] >= MW), ] # remove candidates with a weight below MW
        if(is.matrix(candidates) == TRUE) { #if it's a vector, there's only one predicted resource, no need to order
            candidates[order(candidates[, 'weight']), ] # sorts candidates according to their weight
            predictions[S1[i], 'resource_predictions'] <- paste(candidates[, 'resource'], collapse = ' | ')
        } else {
          predictions[S1[i], 'resource_predictions'] <- paste(candidates['resource'], collapse = ' | ')
        }#if
    # setTxtProgressBar(pb, i)
    }#i
    # close(pb)
    return(predictions)
}#two_way_tanimoto_predict function
#' Find unassigned global variables.
#'
#' This funciton sources files and loads objects into an environment
#' and then runs \code{codetools::findGlobals} on the environment.
#'
#' NOTE: Globals are determined for the \code{main()} function only!
#'
#' @param source_files R files containing globals to exclude such as
#' function declarations.
#'
#' @param object_files Rdata files that contain globals to exclude.
#'
#' @return A list of globals without assignments.
find_globals = function(source_files, object_files = c()) {
    e <- new.env()

    for (file in source_files) {
        testthat::source_file(file, e)
    }

    for (object_file in object_files) {
        load(object_file, envir = e)
    }

    globals <- list()

    tryCatch({
        globals <- codetools::findGlobals(e$main)
    }, error = function(e) {
        warning("No main() function was found. Globals cannot be set until a main function is found.")
        return(globals)
    })

    # Filter known `findGlobals` errors
    known_errors <- c("{", "}", "::")
    globals <- globals[!(globals %in% known_errors)]

    # Filter all functions in loaded packages
    for (package in (.packages())) {
        package <- paste0("package:", package)
        exports <- names(as.list(as.environment(package)))
        globals <- globals[!(globals %in% exports)]
    }

    # Filter functions and variables in source files
    globals <- globals[!(globals %in% names(as.list(e)))]

    nglobals <- length(globals)

    if (nglobals > 0) {
        if (nglobals == 1) {
            vars <- "var"
            t_vars <- "this var"
        } else {
            vars <- "vars"
            t_vars <- "these vars"
        }

        cat(paste("Found", nglobals, vars, "to specify:"))
        for (global in globals) {
            cat(paste("\n    -", global))
        }

        cat(paste("\n\nSet", t_vars, "in the `globals` property of your `Stain` instance."))
    }

    # Set the values of all gobals to NA
    global_list <- list()

    for (global in globals) {
        global_list[[global]] <- NA
    }

    return(global_list)
}
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container_dir, settings) {
            private$settings <- settings

            private$cat_main_file_magic(container_dir)
            private$write_slurm_script(container_dir)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir) {
            main_file <- ".default_stain_main.R"
            file <- paste0(dir, "/.stain/sources/", main_file)
            sourcing <- paste("sapply(list.files('./.stain/sources', full.names = TRUE)[!(list.files('./.stain/sources')) %in%",
                              paste0("'", main_file, "'"), "], source)")
            loading <- paste("sapply(list.files('./.stain/objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./.stain $PFSDIR
cd $PFSDIR

mkdir .data
mv ./.stain/data/* ./.data

module load hpc-ods
module load pandoc

R CMD BATCH ./.stain/sources/.default_stain_main.R

cp -r * $SLURM_SUBMIT_DIR/output"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, "submit.slurm", sep = "/"))
        }
    )
)
# # # setwd('C:/Users/garre/Dropbox/aa projects/DIVA')

# # backprop
# #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
backprop <- function(out_wts, in_wts, out_activation, current_target, 
                     hid_activation, hid_activation_raw, ins_w_bias, learning_rate){

  # # # calc error on output units
  out_delta <- 2 * (out_activation - current_target)
  
  # # # calc error on hidden units
  hid_delta <- out_delta %*% t(out_wts)
  hid_delta <- hid_delta[,2:ncol(hid_delta)] * sigmoid_grad(hid_activation_raw)
  
  # # # calc weight changes
  out_delta <- learning_rate * (t(hid_activation) %*% out_delta)
  hid_delta <- learning_rate * (t(ins_w_bias) %*% hid_delta)

  # # # adjust wts
  out_wts <- out_wts - out_delta
  in_wts <- in_wts - hid_delta

  return(list(out_wts = out_wts, 
              in_wts  = in_wts))

}

# forward_pass
# conduct forward pass
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
forward_pass <- function(in_wts, out_wts, inputs, out_rule) {
  # # # init needed vars
  num_feats <- ncol(out_wts)
  num_cats  <- dim(out_wts)[3]
  num_stims <- nrow(inputs)
  if (is.null(num_stims)) {num_stims <- 1}

  
  # # # add bias to ins
  bias_units <- matrix(rep(1, num_stims), ncol = 1, nrow = num_stims)
  ins_w_bias <- cbind(bias_units,
    matrix(inputs, nrow = num_stims, ncol = num_feats, byrow = TRUE))

  # # # ins to hids propagation
  hid_activation_raw <- ins_w_bias %*% in_wts
  hid_activation <- sigmoid(hid_activation_raw)

  # # # add bias unit to hid activation
  hid_activation <- cbind(bias_units, hid_activation)  

  # # # hids to outs propagation
  out_activation <- array(rep(0, (num_stims * num_feats * num_cats)), 
    dim = c(num_stims, num_feats, num_cats))
  # # NEED VECTORIZED HERE
  for (category in 1:num_cats) {
  	out_activation[,,category] <- hid_activation %*% out_wts[,,category]
  }
  
  # # # apply output activatio rule
  if(out_rule == 'sigmoid') {
  	out_activation <- sigmoid(out_activation)
  }

  return(list(out_activation     = out_activation, 
              hid_activation     = hid_activation,
              hid_activation_raw = hid_activation_raw, 
              ins_w_bias         = ins_w_bias))

}

# get_wts
# generate net weights
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
get_wts <- function(num_feats, num_hids, num_cats, wts_range, wts_center) {
  # # # set bias
  bias <- 1
  
  # # # generate wts between ins and hids
  in_wts <- 
    (matrix(runif((num_feats + bias) * num_hids), ncol = num_hids) - 0.5) * 2 
  in_wts <- wts_center + (wts_range * in_wts)

  # # # generate wts between hids and outs
  out_wts <- 
    (array(runif((num_hids + bias) * num_feats * num_cats), 
      dim = c((num_hids + bias), num_feats, num_cats)) - 0.5) * 2
  out_wts <- wts_center + (wts_range * out_wts)   
  
  return(list(in_wts  = in_wts, 
              out_wts = out_wts))

}

# global_scale
# scale inputs to 0/1
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
global_scale <- function(x) { x / 2 + 0.5 }

# response_rule
# convert output activations to classification
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
response_rule <- function(out_activation, target_activation, beta_val){
  num_feats <- ncol(out_activation)
  num_cats  <- dim(out_activation)[3]
  num_stims <- nrow(target_activation)
  if (is.null(num_stims)) {num_stims <- 1}

  # # # calc error  
  ssqerror <- array(as.vector(
    apply(out_activation, 3, function(x) {x - target_activation})),
      c(num_stims, num_feats, num_cats))
  ssqerror <- ssqerror ^ 2
  ssqerror[ssqerror < 1e-7] <- 1e-7
  
  # # # generate focus weights
  if(dim(out_activation)[3] > 2 | dim(out_activation)[1] > 1){
    stop('Not coded for >2 channels or batch mode, sorry!')
  } else {
    
    # # # candidate for errors:
    diversities <- 
      exp(beta_val * abs(matrix(dist(out_activation))[num_feats:((num_feats*2)-1)]))  
    diversities[diversities > 1e+7] <- 1e+7

    # divide diversities by sum of diversities
    fweights = diversities / sum(diversities)

    # # # apply focus weights; then get sum for each category
    ssqerror <- t(apply(ssqerror, 3, function(x) sum(x * fweights))) 
    ssqerror <- 1 / ssqerror
  }

return(list(ps       = (ssqerror / sum(ssqerror)), 
            fweights = fweights, 
            ssqerror = ssqerror))

}

# run_diva
# trains vanilla diva
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
run_diva <- function(model) {
  # # # extract model vars
  attach(model)
  # # # get new seed
  seed <- runif(1) * 100000 * runif(1)
  set.seed(seed)
  # # # set mean value of weights
  wts_center <- 0 
  # # # convert targets to 0/1
  targets <- global_scale(model$inputs) 
  
  # # # init size parameter variables
  num_feats   <- ncol(inputs)
  num_stims   <- nrow(inputs)
  num_cats    <- length(unique(labels))
  num_updates <- num_blocks * num_stims
  
  # # # init training accuracy matrix
  training <- 
    matrix(rep(NA, num_updates * num_inits), nrow = num_updates, ncol = num_inits)
  
  # # # initialize and run DIVA models
  for (model_num in 1:num_inits) {
  	
    # # # generate weights
  	wts_list <- get_wts(num_feats, num_hids, num_cats, wts_range, wts_center)
    attach(wts_list)

    # # # generate presentation order
  	prez_order <- as.vector(apply(replicate(num_blocks, seq(1, num_stims)), 
  	  2, sample, num_stims))

    # # # iterate over each trial in the presentation order 
    for (trial_num in 1:num_updates) {
      current_input  <- inputs[prez_order[[trial_num]], ]
      current_target <- targets[prez_order[[trial_num]], ]
      current_class  <- labels[prez_order[[trial_num]]] 

      # # # complete forward pass
      fp_result <- forward_pass(in_wts, out_wts, current_input, out_rule)
      attach(fp_result)

      # # # calculate classification probability
      rr_result <- response_rule(out_activation, current_target, beta_val)
      attach(rr_result)

      # # # store classification accuracy
      training[trial_num, model_num] = ps[current_class]

      # # # back propagate error to adjust weights
      class_wts <- out_wts[,,current_class]
      class_activation <- out_activation[,,current_class]

      adjusted_wts <- backprop(class_wts, in_wts, class_activation, current_target,  
               hid_activation, hid_activation_raw, ins_w_bias, learning_rate)

      out_wts[,,current_class] <- adjusted_wts$out_wts
      in_wts <- adjusted_wts$in_wts

      detach(fp_result)
      detach(rr_result)

    }
    
    detach(wts_list)
  
  }

print(rowMeans(matrix(rowMeans(training), nrow = num_blocks, ncol = num_stims, byrow = TRUE)))
detach(model)
#return(list(training = training))
}

# shj_cats
# loads shj category structures
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
shj_cats <- function(type){
  
  if (type == 1) {
    in_patterns <- 
      matrix(c(1,  1,  1,
	             1,  1, -1,
	             1, -1,  1,
  	           1, -1, -1,
	            -1, -1,  1,
	            -1, -1, -1,
	            -1,  1,  1,
	            -1,  1, -1), nrow = 8, ncol = 3, byrow = TRUE)		

  } else if (type == 2){
  	in_patterns <-
  	  matrix(c(1,  1,  1,
  	  	       1,  1, -1,
       	      -1, -1,	 1,
	            -1, -1, -1,
	            -1,	 1,	 1,
	            -1,	 1, -1,
	  	         1, -1,	 1,
		           1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 3){
  	in_patterns <-
  	  matrix(c(1,  1,  1,
  	  	       1,  1, -1,
  	  	       1, -1,  1, 
  	          -1,  1, -1,
  	           1, -1, -1, 
  	          -1,  1,  1, 
  	          -1, -1,  1, 
  	          -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 4){
    in_patterns <-
      matrix(c(1,  1,  1,
               1,  1, -1,
               1, -1,  1,
              -1,  1,  1,
               1, -1, -1,
              -1,  1, -1,
              -1, -1,  1,
              -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 5){
    in_patterns <-
      matrix(c(1,  1,  1,
               1,  1, -1,
               1, -1,  1,
              -1, -1, -1,
               1, -1, -1,
              -1,  1,  1,
              -1,  1, -1,
              -1, -1,  1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 6){
    in_patterns <-
      matrix(c(1,  1,  1,
               1, -1, -1,
              -1,  1, -1,
              -1, -1,  1,
               1,  1, -1,
               1, -1,  1,
              -1,  1,  1,
              -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  }

cat_assignment <- c(1, 1, 1, 1, 2, 2, 2, 2)

return(list(inputs = in_patterns, 
			      labels = cat_assignment))

}

# sigmoid
# returns sigmoid evaluated elementwize in X
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
sigmoid <- function(x) {
  g = 1 / (1 + exp(-x))
  return(g)

}

# sigmoid gradient
# returns the gradient of the sigmoid function evaluated at x
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
sigmoid_grad <- function(x) {
  return(g = ((sigmoid(x)) * (1 - sigmoid(x))))

}# 4. faza: Analiza podatkov

#Iščemo, kdo je bil najbolj uspešen v klubu
normaliziran <- scale(as.matrix(IGRALCI[c(3:4, 8)]))
matrikarazdalj<-dist(normaliziran)
razdelitev<- hclust(matrikarazdalj, method = "complete")
plot(razdelitev, hang=-1, cex=0.6, main = "USPEŠNOST")
rect.hclust(razdelitev,k=4,border="red")
#Iz tabele vidimo, da so gralci, ki so se najbolj izkazali Dennis Wise,
#George Mills, Dick Spence in Frank Lampard

p <- cutree(razdelitev, k=4)
barve=c("red", "green", "blue","yellow")
table(p)
barve



pairs(normaliziran, col = barve[p])

IGRALCI[p %in% c(1),]

razdelitev1 <- hclust(matrikarazdalj, method = "single")
plot(razdelitev1, hang=-1, cex=0.6, main = "USPEŠNOST 1")
rect.hclust(razdelitev1,k=4,border="red")

#Iščemo najboljšo sezono po uspešnosti
#Normaliziramo število zmag, danih golov in doseženih točk
normaliziran2 <- scale(as.matrix(ZGODOVINA[c(2,5,7)]))
matrikarazdalj2<-dist(normaliziran2)
razdelitev2<- hclust(matrikarazdalj2, method = "complete")
plot(razdelitev2, hang=-1, cex=0.6, main = "USPEŠNOST2")
rect.hclust(razdelitev2,k=4,border="red")
#Vidimo, da so bili najbolj uspešni v letih 1983, 1988 in 2009, ko so tudi osvojili prvo mesto
p2 <- cutree(razdelitev2, k=4)
barve2=c("red", "green", "blue","yellow")
table(p2)
barve2
pairs(normaliziran2, col = barve[p2])# Container for plot parameters
PlotParams <- function(args) {
  this <- list(
    depth = ('-d' %in% args),
    orphaned = ('-or' %in% args),
    inverted = ('-v' %in% args),
    samestrand = ('-ss' %in% args),
    secondary = ('-se' %in% args),
    supplementary = ('-su' %in% args),
    hardclipped = ('-hc' %in% args),
    ins = ('-i' %in% args),
    refgene = ('-r' %in% args),
    svMAF = ('-af' %in% args),
    legend = ('-l' %in% args)
  )
  class(this) <- append(class(this), "PlotParams")
  return (this)
}

# Container for data for a given sample
Sample <- function(folder, sample, label = FALSE) {
  depths <- read.delim(paste0(folder, sample, '/depths.tsv'), header = TRUE,  sep = '\t')
  bin_size <- depths$bin[2] -  depths$bin[1]
  num_bins <- nrow(depths)
  xlims <- c(depths$bin[1], (depths$bin[nrow(depths)] + bin_size))
  #read in SV calls for this sample
  svs <- read.delim(paste0(folder, sample, '/svs.tsv'), header = TRUE, sep = '\t')
  #convert to list, separating calls from different vcfs
  svs <- split.data.frame(svs, svs$vcf)
  svTracks <- lapply(svs, function(x) get_tracks(x$start, x$end))
  #read in foward and reverse inserts
  fwd_ins <- read.table(paste0(folder, sample, '/fwd_ins.tsv'), fill=TRUE, sep="\t", stringsAsFactors = FALSE, header = FALSE)
  rvs_ins <- read.delim(paste0(folder, sample, '/rvs_ins.tsv'), fill=TRUE, sep="\t", stringsAsFactors = FALSE, header = FALSE)
  #convert inserts from strings to numerics
  fwd_ins <- cbind(fwd_ins[,1], lapply(fwd_ins[,2], function(x) as.numeric(unlist(strsplit(x, ',')))))
  rvs_ins <- cbind(rvs_ins[,1], lapply(rvs_ins[,2], function(x) as.numeric(unlist(strsplit(x, ',')))))
  #read aln_stats
  aln_stats <- read.delim(paste0(folder, sample, '/aln_stats.tsv'), header = TRUE,  sep = '\t')
  aln_stats_bin_size <- aln_stats$bin[2] - aln_stats$bin[1]
  split <- FALSE
  for (i in 3:nrow(aln_stats)){
    if (aln_stats_bin_size != aln_stats$bin[i] - aln_stats$bin[i-1]){
      split = i
    }
  }
  ins_ylim <- max(max(unlist(sapply(fwd_ins, function(x)  estimate_upper_bound(x)))),  max(unlist(sapply(rvs_ins, function(x) estimate_upper_bound(x)))))
  
  this <- list(
    Name = sample,
    Depths = depths,
    Bin_size = bin_size,
    Num_bins = num_bins,
    Xlims = xlims,
    SVs = svs,
    SVtracks = svTracks,
    Fwd_ins = fwd_ins,
    Rvs_ins = rvs_ins,
    Aln_stats = aln_stats,
    Split = split,
    Ins_ylim = ins_ylim
  )
  class(this) <- append(class(this), "Sample")
  return(this)
}
#container for annotations
Annotations <- function(folder) {
  #check if refgenes file exists, if so read
  genes_file <- paste0(folder, 'refgene.tsv')
  if (file.exists(genes_file)) {
    genes <- read.delim(genes_file, header = TRUE, sep = '\t')
  } else {
    genes = NULL
  }
  #check if SV_AF file exists, if so read
  SV_AF_file = paste0(folder, 'SV_AF.tsv')
  if (file.exists(SV_AF_file)) {
    SV_AF <- read.delim(SV_AF_file, header = TRUE, sep = '\t')
    SV_AF <- split.data.frame(SV_AF, SV_AF$vcf)
    AF_tracks <-
      lapply(SV_AF, function(x)
        get_tracks(x$start, x$end))
  } else {
    SV_AF = NULL
    AF_tracks = NULL
  }
  
  this <- list(
    Genes = genes,
    SV_AF = SV_AF,
    AF_tracks = AF_tracks
  )
  class(this) <- append(class(this), "Annotations")
  return(this)
}

# add a border around a given plot area
add_border <- function(xlims, ylims, lwd = 0.5) {
  rect(xlims[1], ylims[1], xlims[2], ylims[2], lwd = lwd)
}

# horizontal line separator between samples
separator <- function() {
  empty_plot(c(0, 1))
  par(xpd = NA)
  abline(h = 0.5, lwd = 4, col = 'gray25')
  par(xpd = FALSE)
}

# create an empty plot
empty_plot <- function(xlim,ylim = c(0, 1),type = 'n',bty = 'n', xaxt = 'n', yaxt = 'n', ylab = '', xlab = '') {
    plot(1, type = type, ylim = ylim, xlim = xlim, bty = bty, xaxt = xaxt, yaxt = yaxt, ylab = ylab, xlab = xlab)
}

# add axis to a plot
add_position_axis <- function(xlims, side) {
  units <- get_units(xlims[2] - xlims[1])
  empty_plot(xlims / units$val)
  mtext( paste0('Position (', units$sym, ')'), side = side, line = -1, cex = 0.85
  )
  axis(side = side, line = -3)
}

# plot read depth and mapping quality
plot_depth <- function(depth, xlims) {
  par(las = 1)
  bin_size = depth$bin[2] - depth$bin[1]
  ylims = c(0, 1.2 * max(depth$total - depth$mapQ0 - depth$mapQltT, na.rm = TRUE))
  empty_plot(xlims, ylim = ylims)
  title(ylab = 'Depth\n(reads/ bp)', line=2)
  add_border(xlims, ylims)
  # add depth$total depth
  rect(depth$bin, c(0), (depth$bin + bin_size), depth$total, col = '#74C476')
  # add depth$mapQ0 to depth
  rect(depth$bin, depth$total, (depth$bin + bin_size), (depth$total - depth$mapQ0), col = 'white')
  # add depth$mapQltT to depth
  rect(depth$bin, (depth$total - depth$mapQ0), (depth$bin + bin_size), depth$total - (depth$mapQ0 + depth$mapQltT), col = 'khaki1')
  axis(2, tick = TRUE, labels = TRUE, line = -1)
}

# add the legend
add_legend <- function() {
  # create a plot with room for four legends: depth, inserts, mapping stats, svtype/freq
  empty_plot(c(0, 4), ylim = c(0, 1))
  add_border(c(0, 1), c(0, 1))
  add_border(c(1, 2), c(0, 1))
  add_border(c(2, 3), c(0, 1))
  add_border(c(3, 4), c(0, 1))
  par(font = 2)
  text(c(0.5, 1.5, 2.5, 3.5), 1,  pos = 1, labels = c("Read MapQ", "Inferred Insert Size", "Mapping Stats", "SV Allele Frequency"))
  par(font = 1)
  # constants
  bottom = 0.20
  top = bottom + 0.20
  # depth legend
  rect(c((1 / 6 - 0.1), (3 / 6 - 0.1), (5 / 6 - 0.1)), bottom, c((1 / 6 + 0.1), (3 / 6 + 0.1), (5 / 6 + 0.1)), top,  col = c('seagreen3', 'darkolivegreen1', 'gray95'))
  text( c((1 / 6), (3 / 6), (5 / 6)), c(top + 0.1), pos = 3, labels = c(">= 30", "< 30", "= 0") )
  
  # inferred insert size legend
  
  text(1.5, top + 0.25, labels = c("Proportion in position x\nwith mapping distance y"))
  rect(1.15 + 0.7 / 10 * (0:9), bottom, 1.15 + 0.7 / 10 * (1:10), top, col=insert_size_pallete(10)[(1:10)])
  text(c(1.18, 1.82), bottom - 0.08, as.character(c(0, 1)))
  
  # Mapping stats legend 
  text(2.5, top + 0.1, pos = 3, labels = c("proportion of reads in position x"))
  rect(2.15 + 0.7 / 10 * (0:9), bottom, 2.15 + 0.7 / 10 * (1:10), top, col=aln_stats_pallete(10)[(1:10)])
  text(c(2.18, 2.82), bottom - 0.08, as.character(c(0, 1)))
  
  # SV AF legend
  sv_types <- c("DEL", "DUP", "CNV", "INV")
  height = 0.13
  top = bottom + 0.15 * length(sv_types)
  par(family='mono', font = 2)
  for (i in 1:length(sv_types)){
    rect(3.20 + 0.7 / 10 * (0:9), bottom + (i-1) * height, 3.20 + 0.7 / 10 * (1:10), bottom + (i) * height, col=sapply(1:10, function(x) get_sv_col(sv_types[i], x/10)))
    text(3.20, bottom + (i-0.5) * height, sv_types[i], pos=2)
  }
  par(family='sans', font = 1)
  text(c(3.23, 3.87), bottom - 0.08, as.character(c(0, 1)))
}

aln_stats_pallete <- function(n){
  return(colorRampPalette(c("gray95", "#FDAE6B", "#FD8D3C", "#F16913", "#D94801", "#A63603", "#7F2704"))(n))
}
# plot alignment stats
plot_aln_stats <- function(total, numerator, label, split, spacer=2) {
    if (split) {end = length(total)+4*spacer} else { end = length(total)}
    empty_plot(c(0, end))
    par(las = 1)
    mtext(label, side = 2, line = -1,  cex = 0.75)
    #brewer YlGnBu pallete
    if (split){
      rect(spacer:(spacer+split-2), c(0), (spacer+1):(spacer+split-1), c(1), col=aln_stats_pallete(20)[(19 * numerator[1:(split-1)] / total[1:(split-1)]) + 1], border =NA)
      add_border(c(spacer, spacer+split-1), c(0, 1))
      rect((3*spacer+split-1):(3*spacer+length(total)-1), c(0), (3*spacer+split):(3*spacer+length(total)), c(1), col=aln_stats_pallete(20)[(19 * numerator[split:length(total)] / total[split:length(total)]) + 1], border =NA)
      add_border(c(3*spacer+split-1, 3*spacer+length(total)), c(0, 1))
    } else {
      rect(0:(end-1), c(0), 1:end, c(1), col=aln_stats_pallete(20)[(19 * numerator[1:end] / total[1:end]) + 1], border =NA)
      add_border(c(0, end), c(0, 1))
    }
}

# returns a list of the form (val=, sym=)
get_units <- function(num_bp) {
  if (num_bp < 1000) {
    return(list(val = 1, sym = 'bp'))
  } else if (num_bp < 1000000) {
    return(list(val = 1000, sym = 'kbp'))
  } else if (num_bp < 1000000000) {
    return(list(val = 1000000, sym = 'Mbp'))
  } else {
    return(list(val = 1000000000, sym = 'Gbp'))
  }
}

# return the lowest insert size in the highest top 15%
# simple heuristic for avoiding outliers (assumes outliers are less than 15% abundant, and true inserts are at least 15% abundant)
estimate_upper_bound <- function(ins) {
  return(1.1 * sort(ins)[floor(length(ins) * 0.85)])
}

insert_size_pallete <- function(n){
  return(colorRampPalette(c("gray95", "#C6DBEF", "#9ECAE1", "#6BAED6", "#4292C6", "#2171B5", "#08519C", "#08306B"))(n))
}

# plots the inserts in specifiend interval
plot_binned_inserts <- function(binned_inserts, num_y_bins, split, spacer=2){
  if (split) {end = nrow(binned_inserts) + 4*spacer} else {end = nrow(binned_inserts)}
  empty_plot(c(0,end), ylab = '' ,ylim = c(0, num_y_bins + 1))
  if (split){
    for (i in 1:(num_y_bins + 1)) {
      rect(spacer:(spacer+split-2), i - 1, (spacer+1):(spacer+split-1), i, col=insert_size_pallete(25)[24 * binned_inserts[1:(split-1), i] + 1],  border = NA)
      rect((3*spacer+split-1):(3*spacer+nrow(binned_inserts)-1), i - 1, (3*spacer+split):(3*spacer+nrow(binned_inserts)), i, col=insert_size_pallete(25)[24 * binned_inserts[(split:nrow(binned_inserts)), i] + 1],  border = NA)
      add_border(c(spacer, spacer+split-1), c(0, num_y_bins))
      add_border(c(spacer, spacer+split-1), c(num_y_bins, num_y_bins + 1))
      add_border(c(3*spacer+split-1, 3*spacer+nrow(binned_inserts)), c(0, num_y_bins))
      add_border(c(3*spacer+split-1, 3*spacer+nrow(binned_inserts)), c(num_y_bins, num_y_bins + 1))
    }
  } else {
    for (i in 1:(num_y_bins + 1)) {
      rect((1:nrow(binned_inserts))-1, i - 1, (1:nrow(binned_inserts)), i, col=insert_size_pallete(25)[24 * binned_inserts[(1:nrow(binned_inserts)), i] + 1],  border = NA)
      add_border(c(0, end), c(0, num_y_bins))
      add_border(c(0, end), c(num_y_bins, num_y_bins + 1))
    }
  }
}

plot_insert_sizes <- function(fwd_ins, rvs_ins, ylim, split, num_y_bins = 10) {
  # divide into 10 bins spaced equally between 0 and ylim
  ybin_size <- ylim / num_y_bins
  # create an extra bin to store anythin larger than ylim
  fwd_bins <- matrix(nrow = nrow(fwd_ins), ncol = (num_y_bins + 1))
  rvs_bins <- matrix(nrow = nrow(rvs_ins), ncol = (num_y_bins + 1))
  # get counts for each bin
  for (i in 1:num_y_bins) {
    fwd_bins[, i] = sapply(fwd_ins[,2], function(x) sum((((i - 1) * ybin_size)  <= x) & (x < ((i) * ybin_size))))
    rvs_bins[, i] = sapply(rvs_ins[,2], function(x) sum((((i - 1) * ybin_size)  <= x) & (x < ((i) * ybin_size))))
  }
  fwd_bins[, (num_y_bins + 1)] = sapply(fwd_ins[,2], function(x) sum(ylim <= x))
  rvs_bins[, (num_y_bins + 1)] = sapply(rvs_ins[,2], function(x) sum(ylim <= x))
  
  # convert to proportions
  fwd_bins = fwd_bins / rowSums(fwd_bins)
  # fwd_bins[is.nan(fwd_bins)] <- 0
  rvs_bins = rvs_bins / rowSums(rvs_bins)
  # rvs_bins[is.nan(rvs_bins)] <- 0
  
  # organise sensible units for ticks on plot
  units <- get_units(ylim / 2)
  ylim <- ylim / units$val
  mid <- round(ylim / 2)
  interval <- round(mid * 2 / 3)
  ticks_at <- c((mid - interval), mid, (mid + interval))

  # plot binned foward inserts
  par(las = 1)
  plot_binned_inserts(fwd_bins, num_y_bins, split)
  axis(2, at = 10 * ticks_at / ylim,  labels = as.character(ticks_at),  line = -1)
  title(ylab=paste0('forward\ninsert\nlength (', units$sym, ')'), line=2)
  par(xpd = NA)
  text(0, num_y_bins + 0.5, labels =">", cex = 0.85, pos = 2)
  
  # plot binned reverse inserts
  plot_binned_inserts(rvs_bins, num_y_bins, split)
  axis( 2, at = 10 * ticks_at / ylim,  labels = as.character(ticks_at), line = -1)
  title(ylab=paste0('reverse\ninsert\nlength (', units$sym, ')'), line=2)
  text(0, num_y_bins + 0.5, labels =">", cex = 0.85, pos = 2)
  par(xpd = FALSE)
}

plot_svs <- function(svs, xlims, tracks, AF=TRUE) {
  empty_plot(xlims)
  add_border(xlims,c(0,1))
  mtext(svs$vcf, side = 2, line = -1, cex = 0.8)
  if (is.null(svs)) {
    text(0.5 * (xlims[1] + xlims[2]), 0.5, labels = "None")
  }
  # get mapping of svs to tracks to ensure no overlap
  scale = 1 / max(tracks)
  par(las = 1)
  par(font = 2)
  for (i in 1:nrow(svs)) {
    # create a rectange covering each sv call
    start <- max(xlims[1], svs$start[i])
    end <- min(xlims[2], svs$end[i])
    x_prop <- (end - start) / (xlims[2] - xlims[1])
    bottom <- ((tracks[i] - 1) * scale)
    top <- ((tracks[i]) * scale)
    spacer = 0.1*(top-bottom)
    # label the sv, if it is of sufficient length to not overlap bounds
    if (!AF){
      rect(start, bottom + spacer, end, top - spacer, col=get_sv_col(svs$svtype[i], 0.8*(0.5*grepl('1', svs$gt[i]) + 0.5*grepl('1/1', svs$gt[i]))), border=get_sv_col(svs$svtype[i], 1), lwd=2)
      if (x_prop > 1/5){
        text(  0.5 * (max(xlims[1], svs$start[i]) + min(xlims[2], svs$end[i])), ((tracks[i] - 0.5) * scale), labels = paste(svs$svtype[i], ':', svs$gt[i], ':', as.character(svs$end[i] - svs$start[i]), 'bp' ))
      } else {
        text(  0.5 * (max(xlims[1], svs$start[i]) + min(xlims[2], svs$end[i])), ((tracks[i] - 0.5) * scale), labels = svs$gt[i])
      }
    } else {
      rect(start, bottom + spacer, end, top - spacer, col=get_sv_col(svs$svtype[i], as.numeric(svs$MAF[i])), border=get_sv_col(svs$svtype[i], 1), lwd=2)
      if (x_prop > 1/5){
        len <- svs$end[i] - svs$start[i]
        units = get_units(len)
        text(0.5 * (start + end), 0.5 * (top + bottom), labels = paste0(svs$svtype[i], ' : AF = ', as.character(round(as.numeric(svs$MAF[i]), digits = 3)), ' : ',as.character(round(len/units$val, digits=2)), " ", units$sym))
      } else if (x_prop > 1/10){
        text(0.5 * (start + end), 0.5 * (top + bottom), labels = paste0('AF = ', as.character(round(as.numeric(svs$MAF[i]), digits = 3))))
      }
    }
  }
  par(font = 1)
}

gt_to_intensity <- function(gt){
  if (grepl("0/1", gt)){
    return(0.3)
  } else if (grepl("0/1", gt)){
    return(1)
  } else {
    return(0)
  }
}
# return a colour for a given SV type
# intensity is a value between 0 and 1, if intensity is zero white is alwaya returned
get_sv_col <- function(type, intensity) {
  if ((is.na(intensity)) | (is.nan(intensity))){
    return('white')
  } else if (intensity == 0){
    return('white')
  } else if ((grepl('DEL', type))) {
      return(colorRampPalette(c("#FFF5F0", "#FEE0D2", "#FCBBA1", "#FC9272", "#FB6A4A", "#EF3B2C", "#CB181D", "#A50F15"))(100)[20 + floor(80 * intensity)])
  } else if ((grepl('DUP', type))) {
      return(colorRampPalette(c("#F7FBFF", "#DEEBF7", "#C6DBEF", "#9ECAE1", "#6BAED6", "#4292C6", "#2171B5", "#08519C"))(100)[20 + floor(80 * intensity)])
  } else if ((grepl('INV', type))) {
      return(colorRampPalette(c("#F7FCF5", "#E5F5E0", "#C7E9C0", "#A1D99B", "#74C476", "#41AB5D", "#238B45", "#006D2C"))(100)[20 + floor(80 * intensity)])
  } else if ((grepl('CNV', type))) {
    return(colorRampPalette(c("#FCFBFD", "#EFEDF5", "#DADAEB", "#BCBDDC", "#9E9AC8", "#807DBA", "#6A51A3", "#54278F"))(100)[20 + floor(80 * intensity)])
  } else {
    return(colorRampPalette(c("#FFFFFF", "#F0F0F0", "#D9D9D9", "#BDBDBD", "#969696", "#737373", "#525252", "#252525"))(100)[20 + floor(80 * intensity)])
  }
}

# plot specified tracks for a given sample
plot_sample <- function(sample, plot_params, ins_ylim) {
  #plot sample title
  empty_plot(sample$Xlims)
  par(font = 2)
  text(sample$Xlims[1], 0.5, paste("Sample:", sample$Name), cex = 1, pos = 4)
  par(font = 1)
  #plot sample SVs
  par(las=1)
  for (i in 1:length(sample$SVs)) {
    plot_svs(sample$SVs[[i]], sample$Xlims, sample$SVtracks[[i]], AF=FALSE)
  }
  # plot sample depth
  if (plot_params$depth) { plot_depth(sample$Depths, sample$Xlims)}
  # plot zoom details
  if (sample$Split){
    add_zoom_detail(sample$Xlims, sample$Aln_stats$bin[1], sample$Aln_stats$bin[sample$Split-1], sample$Aln_stats$bin[sample$Split], sample$Aln_stats$bin[length(sample$Aln_stats$bin)], length(sample$Aln_stats$bin))
  }
  # plot sample insert sizes
  if (plot_params$ins) {
    plot_insert_sizes(sample$Fwd_ins, sample$Rvs_ins, ins_ylim, sample$Split)
  }
  # plot remaining tracks
  if (plot_params$hardclipped) {
    plot_aln_stats( sample$Aln_stats$reads, sample$Aln_stats$hardclipped, 'hardclipped', sample$Split)
  }
  if (plot_params$secondary) {
    plot_aln_stats( sample$Aln_stats$reads, sample$Aln_stats$secondary, 'secondary', sample$Split)
  }
  if (plot_params$supplementary) {
    plot_aln_stats( sample$Aln_stats$reads, sample$Aln_stats$supplementary, 'supplementary', sample$Split)
  }
  if (plot_params$orphaned) {
    plot_aln_stats( sample$Aln_stats$reads, sample$Aln_stats$orphaned, 'orphaned', sample$Split)
  }
  if (plot_params$inverted) {
    plot_aln_stats( sample$Aln_stats$reads, sample$Aln_stats$inverted, 'inverted', sample$Split)
  }
  if (plot_params$samestrand) {
    plot_aln_stats( sample$Aln_stats$reads, sample$Aln_stats$samestrand, 'samestrand', sample$Split)
  }
  # plot zoom details
  if (sample$Split){
    add_zoom_detail(sample$Xlims, sample$Aln_stats$bin[1], sample$Aln_stats$bin[sample$Split-1], sample$Aln_stats$bin[sample$Split], sample$Aln_stats$bin[length(sample$Aln_stats$bin)], length(sample$Aln_stats$bin), axes=TRUE)
  }
  # add separator
  separator()
}

plot_details <- function(bin_size, num_bins) {
  mtext( paste("Bin size: ", as.character(bin_size), "    Num bins: ", as.character(num_bins), "    Date: ", as.character(Sys.Date()) ), side = 1, line = 0, adj = 0, cex = 0.65 )
}
# graphical representation of linear transformation between depth plot and zoomed in inserts size and aln stats plots
add_zoom_detail <- function(xlims, start_1, end_1, start_2, end_2, num_bins, col='black', spacer=2, axes = FALSE){
  range = xlims[2] - xlims[1]
  zoom_start_1 = xlims[1] + (spacer/(num_bins+4*spacer))*range
  zoom_end_1 = xlims[1] + ((spacer + 0.5*num_bins)/(num_bins+4*spacer))*range
  zoom_start_2 = xlims[1] + ((3*spacer+0.5*num_bins)/(num_bins+4*spacer))*range
  zoom_end_2 = xlims[1] + ((3*spacer+num_bins)/(num_bins+4*spacer))*range
  empty_plot(xlims)
  if (axes){
    # add axes for the zoomed regions
    units <- get_units(end_1-start_1)
    at = (zoom_start_1 + (zoom_end_1-zoom_start_1)*c((1/6),(1/2),(5/6)))
    labels = ((start_1 + (end_1-start_1)*c((1/6),(1/2),(5/6)))/units$val)
    axis(side=1, at=at, labels=paste(as.character(round(labels, digits=1)), units$sym), line=-2)
    at = (zoom_start_2 + (zoom_end_2-zoom_start_2)*c((1/6),(1/2),(5/6)))
    labels = ((start_2 + (end_2-start_2)*c((1/6),(1/2),(5/6)))/units$val)
    axis(side=1, at=at, labels=paste(as.character(round(labels, digits=1)), units$sym),line=-2)
  } else {
    # show the level of zoom
    segments(c(start_1, end_1, start_2, end_2), c(0.7), c(start_1, end_1, start_2, end_2), c(2), col=col, lwd=2)
    segments(c(start_1, end_1, start_2, end_2), c(0.7), c(zoom_start_1, zoom_end_1, zoom_start_2, zoom_end_2), c(0.3), col=col, lwd=2)
    segments(c(zoom_start_1, zoom_end_1, zoom_start_2, zoom_end_2), c(0.3), c(zoom_start_1, zoom_end_1, zoom_start_2, zoom_end_2), c(-1), col=col, lwd=2)
  }
}

#returns an assignment to tracks for a set of regions such that there are no overlaps
get_tracks <- function(starts, ends) {
  # assume that starts and ends are of same length
  # assume also that they are sorted by lowest start first
  tracks <- vector("integer", length = length(starts))
  tracks[1] = 1
  if (length(starts) >= 2) {
    for (i in 2:length(starts)) {
      for (j in 1:i) {
        overlap = FALSE
        if (j %in% tracks) {
          check = which(tracks %in% j)
          for (k in 1:length(check)) {
            if (starts[i] <= ends[check[k]]) {
              overlap = TRUE
              break
            }
          }
        }
        if (!overlap) {
          tracks[i] = j
          break
        }
      }
    }
  }
  return(tracks)
}

plot_refgenes <- function(refgenes, xlims) {
  empty_plot(xlims)
  plot_range <- xlims[2] - xlims[1]
  # if no refgene annotation in region don't plot it
  if (is.null(refgenes)) {
    text(0.5 * (xlims[1] + xlims[2]), 0.5, labels = "None")
  } else {
    # ensure no genes are plotted overlapping by assigning those that do overlap to separate tracks in a greedy fashion
    # since refgenes should already be sorted by start position this is fairly straightforward
    tracks <- 1:nrow(refgenes)
    scale = 1/max(tracks)
    for (i in 1:(nrow(refgenes))) {
      # plot thin rectangle for whole length of transcript
      plot_start = max(xlims[1], refgenes$txStart[i])
      plot_end = min(xlims[2], refgenes$txEnd[i])
      plot_len = plot_end - plot_start + 1
      total_len = refgenes$txEnd[i] - refgenes$txStart[i] + 1
      fwd = ("+" == as.character(refgenes$strand[i]))
      if (fwd) {dir = '->'} else {dir = '<-'}
      segments(xlims[1], (tracks[i]- 0.5) * scale, xlims[2], (tracks[i]- 0.5) * scale, col='gray50')
      rect(plot_start, ((tracks[i] - 0.8) * scale), plot_end, ((tracks[i]-0.2) * scale), col = '#74C476', border='gray50')
      units <- get_units(plot_len)
      par(font=2)
      #l abel the gene
      par(xpd=NA)
      text(xlims[1], ((tracks[i]- 0.5) * scale), labels=paste(refgenes$name2[i], dir), pos=2)
      text(xlims[2], ((tracks[i]- 0.5) * scale), labels=paste(as.character(round(100*plot_len/total_len, digits=0)), '%'), pos=4)
      par(xpd=FALSE)
      # get the exon starts and ends
      starts = as.numeric(strsplit(as.character(refgenes$exonStarts[i]), ',')[[1]])
      ends = as.numeric(strsplit(as.character(refgenes$exonEnds[i]), ',')[[1]])
      fwd = ("+" == as.character(refgenes$strand[i]))
      min_exon_label_dist = 0.02 * (xlims[2] - xlims[1])
      last_exon_labelled = NA
      # plot exons
      for (j in 1:length(starts)) {
        # check if exon is within plot limits
        if ((ends[j] < xlims[1]) | (starts[j] > xlims[2])) { next }
        rect(max(xlims[1], starts[j]), ((tracks[i] - 0.925) * scale),  min(xlims[2], ends[j]), ((tracks[i] - 0.075) * scale), col = '#6BAED6', border='gray50')
      }
      for (j in 1:length(starts)) {
        if ((ends[j] < xlims[1]) | (starts[j] > xlims[2])) { next }
        if (fwd) {num = j} else {num = length(starts) - j + 1}
        label_pos = 0.5 * (max(xlims[1], starts[j]) + min(xlims[2], ends[j]))
        # ensure enought distance between exon labels and gene name label before annotating
        if (is.na(last_exon_labelled) | (label_pos - last_exon_labelled) > min_exon_label_dist){
          text(0.5 * (max(xlims[1], starts[j]) + min(xlims[2], ends[j])), ((tracks[i]-0.5) * scale), labels = as.character(num))
          last_exon_labelled = label_pos
        }
      }
    }
    par(font=1)
    }
  }

get_plot_layout <- function(plot_params, annotations, num_samples, vcfs_per_sample, split, max=200) {
    # note: order of plots to be as implied here
    # top x-axis
    heights <- c(3)
    # title
    heights <- c(heights,1)
    # separator
    heights <- c(heights, 1)
    for (i in 1:num_samples){
      # sample title
      heights <- c(heights, 1.5)
      # add in vcf plots
      for (j in 1:length(vcfs_per_sample[[i]])){
        heights <- c(heights, 1.5*vcfs_per_sample[[i]][j])
      }
      # depth
      if (plot_params$depth) { heights <- c(heights, 7) }
      # breakpoint zoom illustration
      if (split){ heights <- c(heights, 2) }
      # add tracks according to plot params
      if (plot_params$ins) { heights <- c(heights, 4, 4)  }
      if (plot_params$hardclipped) {  heights <- c(heights, 1) }
      if (plot_params$secondary) { heights <- c(heights, 1) }
      if (plot_params$supplementary) { heights <- c(heights, 1) }
      if (plot_params$orphaned) { heights <- c(heights, 1) }
      if (plot_params$inverted) { heights <- c(heights, 1) }
      if (plot_params$samestrand) { heights <- c(heights, 1) }
      # breakpoint zoom axes
      if (split){ heights <- c(heights, 2) }
      # separator
      heights <- c(heights, 1)
    }
    # add in heights for SV_AF tracks
    if (plot_params$svMAF) {
      for (i in 1:length(annotations$SV_AF)) {
        heights <- c(heights, 1.5*max(annotations$AF_tracks[[i]]))
      }
    }
    # add in heights for refGene annotation tracks
    if (plot_params$refgene) {
      if (!is.null(annotations$Genes)) {
        heights <- c(heights, 1*nrow(annotations$Genes))
      } else {
        heights <- c(heights, 1)
      }
    }
    # add in bottom x-axis
    heights <- c(heights, 3)
    # add room for legend
    if (plot_params$legend) {
      heights <- c(heights, 6)
    }
    return(heights)
}

# main method
visualise <- function(folder, sample_names, args, outfile, title='') {
  num_samples <- length(sample_names)
  samples <-  lapply(sample_names, function(x) Sample(folder, x))
  vcfs_per_sample <- lapply(samples, function(x) sapply(x$SVtracks, function(y) max(y)))
  xlims <- samples[[1]]$Xlims
  Ins_ylim <- max(sapply(samples, function(x) x$Ins_ylim))
  annotations <- Annotations(folder)
  plot_params <- PlotParams(args)
  heights <- get_plot_layout(plot_params, annotations, num_samples, vcfs_per_sample, samples[[1]]$Split)
  pdf(outfile, title='SVPV Graphics Output', width = 8, height = 0.15* sum(heights), bg = 'white')
  # initialise first layout
  layout(matrix(1:length(heights), length(heights), 1, byrow = TRUE), heights=heights)
  par(mar = c(0.1, 6, 0.1, 2), oma = c(1, 0.1, 0.1, 0.1))
  # plot top x-axis
  add_position_axis(xlims, 3)
  # plot title
  empty_plot(c(0,1))
  par(font = 2)
  text(0.5, 0.5, title, cex = 1.25)
  par(font = 1)
  separator()
  # plot samples
  for (i in 1:num_samples) {
    plot_sample(samples[[i]], plot_params, Ins_ylim)
  }
  # add in heights for SVMAF tracks
  if (plot_params$svMAF) {
    for (i in 1:length(annotations$SV_AF)) {
      plot_svs(annotations$SV_AF[[i]], xlims, annotations$AF_tracks[[i]])
    }
  }
  # add in heights for refGene annotation tracks
  if (plot_params$refgene) {  plot_refgenes(annotations$Genes, xlims) }
  # plot bottom x-axis
  add_position_axis(xlims, 1)
  # add legend
  if (plot_params$legend) { add_legend() }
  # add details
  plot_details(samples[[1]]$Bin_size, samples[[1]]$Num_bins)
  graphics.off()
}
# read command-line arguments
args <- commandArgs(trailingOnly = TRUE)
sample_names <- strsplit(as.character(args[1]), ',')[[1]]
folder <- args[2]
outfile <- args[3]
title <- args[4]
visualise(folder, sample_names, args[5:length(args)], outfile, title)
tanimoto <- function(resource_x, resource_y) {
  # The Tanimoto similarity computes the sum of shared elements in vectors resource_x and resource_y and divides this by the length of the longest vector
  # If either length of resource_x or resource_y == 0, similarity == 0
  # The order of vectors consumer_x or consumer_y has no importance, as long as elements in vectors are unique

  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  # The same funcion is apparently used for trait similarity, including phylogeny
  # !!! There are NAs in the taxonomy that need to be taken into account, which is not the case at the moment !!!
  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    if(length(resource_x) == 0 || length(resource_y) == 0) {
        return(0.0)
    } else if(resource_x == "" || resource_y == "") {
        return(0.0)
    } else {
        inter <- length(resource_y[match(resource_x, resource_y, nomatch = 0)])
        return(inter / ((length(resource_x) + length(resource_y)) - inter))
    }#if
}#end tanimoto function
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        settings = NULL,
        initialize = function(dir = ".", settings = SlurmSettings$new()) {
            self$settings <- settings

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
                script <- SlurmBashScript$new(dir, self$settings)
            }
        },
        save_objects = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
tanimoto <- function(resource_x, resource_y) {
  # The Tanimoto similarity computes the sum of shared elements in vectors resource_x and resource_y and divides this by the length of the longest vector
  # If either length of resource_x or resource_y == 0, similarity == 0
  # The order of vectors consumer_x or consumer_y has no importance, as long as elements in vectors are unique

  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  # The same funcion is apparently used for trait similarity, including phylogeny
  # !!! There are NAs in the taxonomy that need to be taken into account, which is not the case at the moment !!!
  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    if(length(resource_x) == 0 || length(resource_y) == 0) {
        return(0.0)
    } else if(resource_x == "" || resource_y == "") {
        return(0.0)
    } else {
        inter <- sum(resource_x %in% resource_y)
        return(inter / ((length(resource_x) + length(resource_y)) - inter))
    }#if
}#end tanimoto function
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        settings = NULL,
        initialize = function(dir = ".", settings = SlurmSettings$new()) {
            self$settings <- settings

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
                script <- SlurmBashScript$new(dir, self$settings)
            }
        },
        save_objects = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container_dir, settings) {
            private$settings <- settings

            private$cat_main_file_magic(container_dir)
            private$write_slurm_script(container_dir)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir) {
            main_file <- ".default_stain_main.R"
            file <- paste0(dir, "/.stain/sources/", main_file)
            sourcing <- paste("sapply(list.files('./.stain/sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", main_file, "'"), "], source)")
            loading <- paste("sapply(list.files('./.stain/objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./.stain $PFSDIR
cd $PFSDIR

mkdir .data
mv ./.stain/data/* ./.data

module load hpc-ods
module load pandoc

R CMD BATCH ./.stain/sources/.default_stain_main.R

cp -r * $SLURM_SUBMIT_DIR/output"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, "submit.slurm", sep = "/"))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        settings = NULL,
        initialize = function(dir = ".", settings = SlurmSettings$new()) {
            self$settings <- settings

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }

            script <- SlurmBashScript$new(container$dir, self$settings)
        },
        save_objects = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        settings = NULL,
        initialize = function(dir = ".", settings = SlurmSettings$new()) {
            self$settings <- settings

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }

            script <- SlurmBashScript$new(container$dir, self$settings)
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container_dir, settings) {
            private$settings <- settings

            private$cat_main_file_magic(container_dir)
            private$write_slurm_script(container_dir)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir) {
            main_file <- ".default_stain_main.R"
            file <- paste(dir, ".stain/sources", main_file, sep = "/")
            sourcing <- paste("sapply(list.files('./.stain/sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", main_file, "'"), "], source)")
            loading <- paste("sapply(list.files('./.stain/objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./.stain $PFSDIR
cd $PFSDIR

mkdir .data
mv ./.stain/data/* ./.data

module load hpc-ods
module load pandoc

R CMD BATCH ./.stain/sources/.default_stain_main.R

cp -r * $SLURM_SUBMIT_DIR/output"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, "submit.slurm", sep = "/"))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && name %in% names(globals)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, settings) {
            private$settings <- settings

            main_file <- paste0("cp_of_", main_file)

            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir, main_file) {
            main_file <- paste0(".default_stain_main.R")
            file <- paste(dir, ".stain/sources", main_file, sep = "/")
            sourcing <- paste("sapply(list.files('./.stain/sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", main_file, "'"), "], source)")
            loading <- paste("sapply(list.files('./.stain/objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./.stain $PFSDIR
cd $PFSDIR

mkdir .data
mv ./.stain/data/* ./.data

module load hpc-ods
module load pandoc

R CMD BATCH ./.stain/sources/.default_stain_main.R

cp -r * $SLURM_SUBMIT_DIR/output"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, "submit.slurm", sep = "/"))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, settings) {
            private$settings <- settings

            main_file <- paste0("cp_of_", main_file)

            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir, main_file) {
            main_file <- paste0(".default_stain_main.R")
            file <- paste(dir, ".stain/sources", main_file, sep = "/")
            sourcing <- paste("sapply(list.files('./.stain/sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", main_file, "'"), "], source)")
            loading <- paste("sapply(list.files('./.stain/objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./.stain $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

R CMD BATCH ./.stain/sources/.default_stain_main.R

cp -r * $SLURM_SUBMIT_DIR/output"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, "submit.slurm", sep = "/"))
        }
    )
)
library(ggplot2)
df <- read.csv('sueldos.sysarmy.csv')

rename <- function(df, old, wants) {
  names(df)[names(df)==old] <- wants
  return(df)
}

tukey <- function(data) {
  iqr <- IQR(data$Income)
  firstQ <- quantile(data$Income)[2]
  thirdQ <- quantile(data$Income)[4]
  low <- firstQ - (iqr * 1.5)
  high <- thirdQ + (iqr * 1.5)
  data <- subset(data, Income < high)
  data <- subset(data, Income > low)
  return(data)
}

cleanup <- function(data, handleOutliers) {
  # clean gender.
  data$Gender = ifelse(data$Soy == "Hombre", "M", "F")
  data$Gender = as.factor(data$Gender)

  # rename columns.
  data <- rename(data, "Tengo", "Age")
  data <- rename(data, "Argentina", "Region")
  data <- rename(data, "A..os.de.experiencia", "YearsExperience")
  data <- rename(data, "A..os.en.el.puesto.actual", "YearsCurrentJob")
  data <- rename(data, "Trabajo.de", "JobDescription")
  data <- rename(data, "Tipo.de.contrato", "JobType")
  data <- rename(data, "Qu...tan.conforme.est..s.con.tu.sueldo.", "Happiness")
  data <- rename(data, "Cambiaste.de.empresa.en.los...ltimos.6.meses.", "SwitchedJobsLast6Months")

  # fix region names.
  levels(data$Region)[levels(data$Region) == "Entre R\303\255os"] <- "Entre Rios"
  levels(data$Region)[levels(data$Region) == "Ciudad Aut\303\263noma de Buenos Aires"] <- "CABA"
  levels(data$Region)[levels(data$Region) == "C\303\263rdoba"] <- "Cordoba"
  levels(data$Region)[levels(data$Region) == "Neuqu\303\251n"] <- "Neuquen"
  levels(data$Region)[levels(data$Region) == "R\303\255o Negro"] <- "Rio Negro"
  levels(data$Region)[levels(data$Region) == "Tucum\303\241n"] <- "Tucuman"
  levels(data$Region)[levels(data$Region) == "Provincia de Buenos Aires"] <- "GBA"
  
  # fix age.
  levels(data$Age)[levels(data$Age) == "Menos de 18 a\303\261os"] <- "18-"

  # fix salary.
  data <- rename(data, "Salario.mensual..en.tu.moneda.local.", "Income")
  data$Income <- ifelse(data$Bruto.o.neto. == "Bruto", data$Income, data$Income/0.70)
  data$Bruto.o.neto. = NULL
  
  # fix job switch.
  data$SwitchedJobsLast6Months = ifelse(data$SwitchedJobsLast6Months == "No", 0, 1)

  # remove ficticious data.
  data <- subset(data, Income < 200000)
  data <- subset(data, Income > 1000)
  
  # handle outliers.
  data <- handleOutliers(data)
  
  keep <- c("Age", "Region", "YearsExperience", "YearsCurrentJob", "JobDescription",
            "JobType", "Happiness", "Income", "Gender", "SwitchedJobsLast6Months")
  return(data[keep])
}

all.salaries.hist <- function(df) {
  plot <- ggplot(df, aes(x=Income), ylab="") + 
    geom_histogram(binwidth = 1000, fill="#3399FF", alpha=0.9)
  return(plot)
}

all.salaries.hist.median <- function(df) {
  plot <- all.salaries.hist(df) + 
    geom_vline(aes(xintercept = mean(Income)), linetype="longdash", color="red")
  return(plot)
}

all.salaries.gender <- function(df) {
  plot <- ggplot(df, aes(x=Income, fill=Gender), ylab="") + 
    geom_histogram(binwidth = 1000, alpha=0.9)
  return(plot)
}

color.outliers <- function(df) {
  iqr <- IQR(df$Income)
  firstQ <- quantile(df$Income)[2]
  thirdQ <- quantile(df$Income)[4]
  low <- firstQ - (iqr * 1.5)
  high <- thirdQ + (iqr * 1.5)
  df$OutlierTag = "Middle"
  df$OutlierTag[df$Income <= low] = "LowOutliers"
  df$OutlierTag[df$Income >= high] = "HighOutliers"
  plot <- ggplot(df, aes(x=Income, fill=OutlierTag)) +
      geom_histogram(binwidth = 1000) +
      geom_vline(aes(xintercept = high), linetype="longdash", color="red")
  return(plot)
}

# red #D57668
# green #67ACB3

clean <- cleanup(df, handleOutliers = identity)
write.csv(clean, 'clean.csv', row.names=FALSE)

default.plot <- color.outliers
default.plot(clean)
#' Find unassigned global variables.
#'
#' This funciton sources files and loads objects into an environment
#' and then runs \code{codetools::findGlobals} on the environment.
#'
#' NOTE: Globals are determined for the \code{main()} function only!
#'
#' @param source_files R files containing globals to exclude such as
#' function declarations.
#'
#' @param object_files Rdata files that contain globals to exclude.
#'
#' @return A list of globals without assignments.
find_globals = function(source_files, object_files = c()) {
    e <- new.env()

    for (file in source_files) {
        testthat::source_file(file, e)
    }

    for (object_file in object_files) {
        load(object_file, envir = e)
    }

    globals <- list()

    tryCatch({
        globals <- codetools::findGlobals(e$main)
    }, error = function(e) {
        warning("No main() function was found. Globals cannot be set until a main function is found.")
        return(globals)
    })

    # Filter known `findGlobals` errors
    known_errors <- c("{", "}", "::")
    globals <- globals[!(globals %in% known_errors)]

    # Filter all functions in loaded packages
    for (package in (.packages())) {
        package <- paste0("package:", package)
        exports <- names(as.list(as.environment(package)))
        globals <- globals[!(globals %in% exports)]
    }

    # Filter functions and variables in source files
    globals <- globals[!(globals %in% names(as.list(e)))]

    nglobals <- length(globals)

    if (nglobals > 0) {
        if (nglobals == 1) {
            vars <- "var"
            t_vars <- "this var"
        } else {
            vars <- "vars"
            t_vars <- "these vars"
        }

        cat(paste("Found", nglobals, vars, "to specify:"))
        for (global in globals) {
            cat(paste("\n    -", global))
        }

        cat(paste("\n\nSet", t_vars, "in the `params` property of your `SlurmJob` instance."))
    }

    # Set the values of all gobals to NA
    global_list <- list()

    for (global in globals) {
        global_list[[global]] <- NA
    }

    return(global_list)
}
#' SlurmJob R6 object.
#'
#' A wrapper around SlurmContainer objects.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        data_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".",
                              source_files = list(),
                              settings = SlurmSettings$new()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                globals <- find_globals(c(main_file, source_files))
                self$params <- globals
                private$globals <- globals
                private$settings <- settings
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function(allow_creation_without_data_files = FALSE) {

            if (!allow_creation_without_data_files && length(self$data_files) == 0) {
                stop("Attempting to create slurm job without `data_files`. Pass TRUE to `create` to override.")
            }

            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                container$add_sources(c(self$source_files, self$main_file))
                container$add_data(self$data_files)
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })

            script <- SlurmBashScript$new(container, self$main_file, private$settings)
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        settings = NA
    )
)


#' Submit one or more slurm jobs.
#'
#' This function will submit your slurm job given the path
#' to a slurm container.
#'
#' @param jobs The \code{job_<alphanumeric>/} directories for
#' the slurm container. May also
#'
#' @export
submit_jobs <- function(jobs) {
    wd <- getwd()

    for (dir in jobs) {
        tryCatch({
            setwd(dir)
            system("sh submit.sh")
        }, error = function(e) {
            setwd(wd)
            stop(e)
        })

    }

    setwd(wd)
}


#' Find unassigned global variables.
#'
#' This funciton sources files and loads objects into an environment
#' and then runs \code{codetools::findGlobals} on the environment.
#'
#' NOTE: Globals are determined for the \code{main()} function only!
#'
#' @param source_files R files containing globals to exclude such as
#' function declarations.
#'
#' @param object_files Rdata files that contain globals to exclude.
#'
#' @return A list of globals without assignments.
find_globals = function(source_files, object_files = c()) {
    e <- new.env()

    for (file in source_files) {
        testthat::source_file(file, e)
    }

    for (object_file in object_files) {
        load(object_file, envir = e)
    }

    globals <- list()

    tryCatch({
        globals <- codetools::findGlobals(e$main)
    }, error = function(e) {
        return(globals)
    })

    # Filter known `findGlobals` errors
    known_errors <- c("{", "}", "::")
    globals <- globals[!(globals %in% known_errors)]

    # Filter all functions in loaded packages
    for (package in (.packages())) {
        package <- paste0("package:", package)
        exports <- names(as.list(as.environment(package)))
        globals <- globals[!(globals %in% exports)]
    }

    # Filter functions and variables in source files
    globals <- globals[!(globals %in% names(as.list(e)))]

    nglobals <- length(globals)

    if (nglobals > 0) {
        if (nglobals == 1) {
            vars <- "var"
            t_vars <- "this var"
        } else {
            vars <- "vars"
            t_vars <- "these vars"
        }

        cat(paste("Found", nglobals, vars, "to specify:"))
        for (global in globals) {
            cat(paste("\n    -", global))
        }

        cat(paste("\n\nSet", t_vars, "in the `params` property of your `SlurmJob` instance."))
    }

    # Set the values of all gobals to NA
    global_list <- list()

    for (global in globals) {
        global_list[[global]] <- NA
    }

    return(global_list)
}
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }

            self$dir <- dir
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && name %in% names(globals)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            self$dir <- dir

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            if (!dir.exists(stain_dir)) {
                return()
            }

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain) {
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, dir, recursive = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && name %in% names(globals)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            self$dir <- dir

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            if (!dir.exists(stain_dir)) {
                return()
            }

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain) {
                private$load_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, dir, recursive = TRUE)
            }
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        load_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && name %in% names(globals)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            self$dir <- dir

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            if (!dir.exists(stain_dir)) {
                return()
            }

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain) {
                private$load_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, dir, recursive = TRUE)
            }
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        load_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e)) {
                    globals[[name]] <- e[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            self$dir <- dir

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            if (!dir.exists(stain_dir)) {
                return()
            }

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain) {
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, dir, recursive = TRUE)
            }
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e)) {
                    globals[[name]] <- e[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' Find unassigned global variables.
#'
#' This funciton sources files and loads objects into an environment
#' and then runs \code{codetools::findGlobals} on the environment.
#'
#' NOTE: Globals are determined for the \code{main()} function only!
#'
#' @param source_files R files containing globals to exclude such as
#' function declarations.
#'
#' @param object_files Rdata files that contain globals to exclude.
#'
#' @return A list of globals without assignments.
find_globals = function(source_files, object_files = c()) {
    e <- new.env()

    for (file in source_files) {
        testthat::source_file(file, e)
    }

    for (object_file in object_files) {
        load(object_file, envir = e)
    }

    globals <- codetools::findGlobals(e$main)

    # Filter known `findGlobals` errors
    known_errors <- c("{", "}", "::")
    globals <- globals[!(globals %in% known_errors)]

    # Filter all functions in loaded packages
    for (package in (.packages())) {
        package <- paste0("package:", package)
        exports <- names(as.list(as.environment(package)))
        globals <- globals[!(globals %in% exports)]
    }

    # Filter functions and variables in source files
    globals <- globals[!(globals %in% names(as.list(e)))]

    nglobals <- length(globals)

    if (nglobals > 0) {
        if (nglobals == 1) {
            vars <- "var"
            t_vars <- "this var"
        } else {
            vars <- "vars"
            t_vars <- "these vars"
        }

        cat(paste("Found", nglobals, vars, "to specify:"))
        for (global in globals) {
            cat(paste("\n    -", global))
        }

        cat(paste("\n\nSet", t_vars, "in the `params` property of your `SlurmJob` instance."))
    }

    # Set the values of all gobals to NA
    global_list <- list()

    for (global in globals) {
        global_list[[global]] <- NA
    }

    return(global_list)
}
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            self$dir <- dir

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            if (!dir.exists(stain_dir)) {
                return()
            }

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (!is_stain) {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, dir, recursive = TRUE)
            }
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            self$dir <- dir

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            if (!dir.exists(stain_dir)) {
                return()
            }

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (!is_stain) {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_object = function(name) {
            private$remove_file(paste0(name, ".RData"), "objects")
        },
        add_source = function(file) {
            private$add_file(file, "sources")
        },
        remove_source = function(basename) {
            private$remove_file(file, "sources")
        },
        add_data = function(file) {
            private$add_file(file, "data")
        },
        remove_data = function(basename) {
            private$remove_file(file, "data")
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")
            file.copy(file, dir, recursive = TRUE)
        },
        remove_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
            file.remove(file)
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            self$dir <- dir

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            if (!dir.exists(stain_dir)) {
                return()
            }

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (!is_stain) {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_object = function(name) {
            private$remove_file(paste0(name, ".RData"), "objects")
        },
        add_source = function(file) {
            private$add_file(file, "sources")
        },
        remove_source = function(basename) {
            private$remove_file(file, "sources")
        },
        add_data = function(file) {
            private$add_file(file, "data")
        },
        remove_data = function(basename) {
            private$remove_file(file, "data")
        }
    ),
    private = list(
        add_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")
            file.copy(file, dir, recursive = TRUE)
        },
        remove_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
            file.remove(file)
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            sub_dirs <- c("data", "sources", "objects")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(paste0(dir, ".stain")), basename))
            if (!is_stain) {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }

            self$dir <- dir
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_object = function(name) {
            private$remove_file(paste0(name, ".RData"), "objects")
        },
        add_source = function(file) {
            private$add_file(file, "sources")
        },
        remove_source = function(basename) {
            private$remove_file(file, "sources")
        },
        add_data = function(file) {
            private$add_file(file, "data")
        },
        remove_data = function(basename) {
            private$remove_file(file, "data")
        }
    ),
    private = list(
        add_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")
            file.copy(file, dir, recursive = TRUE)
        },
        remove_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
            file.remove(file)
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            sub_dirs <- c("/data", "/sources", "/objects")

            is_stain <- Reduce("&", sub_dirs %in% list.dirs(dir))
            if (!is_stain) {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste0(dir, "/.stain", sub_dir), recursive = TRUE,
                               showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }

            self$dir <- dir
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_object = function(name) {
            private$remove_file(paste0(name, ".RData"), "objects")
        },
        add_source = function(file) {
            private$add_file(file, "sources")
        },
        remove_source = function(basename) {
            private$remove_file(file, "sources")
        },
        add_data = function(file) {
            private$add_file(file, "data")
        },
        remove_data = function(basename) {
            private$remove_file(file, "data")
        }
    ),
    private = list(
        add_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")
            file.copy(file, dir, recursive = TRUE)
        },
        remove_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
            file.remove(file)
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            sub_dirs <- c("/data", "/sources", "/objects")

            is_stain <- Reduce("&", sub_dirs %in% list.dirs(dir))
            if (!is_stain) {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste0(dir, "/.stain", sub_dir), recursive = TRUE,
                               showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }

            self$dir <- dir
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        add_source = function(file) {
            if (file.exists(file)) {
                source_dir <- paste0(self$dir, "/.stain/sources")
                destination <- paste0(source_dir, paste0("/cp_of_", basename(file)))
                system(paste("cp -r", file, destination))
            } else {
                stop("Source file does not exist.")
            }
        },
        add_data = function(file) {
            if (file.exists(file)) {
                data_dir <- paste0(self$dir, "/.stain/data")
                destination <- paste0(data, paste0("/cp_of_", basename(file)))
                system(paste("cp -r", file, destination))
            } else {
                stop("Source file does not exist.")
            }
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            sub_dirs <- c("/input", "/output", "/sources", "/.objects")

            is_stain <- Reduce("&", sub_dirs %in% list.dirs(dir))
            if (!is_stain) {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste0(dir, sub_dir), recursive = TRUE,
                               showWarnings = FALSE)
                }
            }

            self$dir <- dir
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        add_source = function(file) {
            if (file.exists(file)) {
                source_dir <- paste0(self$dir, "/sources")
                destination <- paste0(source_dir, paste0("/cp_of_", basename(file)))
                system(paste("cp -r", file, destination))
            } else {
                stop("Source file does not exist.")
            }
        },
        add_input = function(file) {
            if (file.exists(file)) {
                input_dir <- paste0(self$dir, "/input")
                destination <- paste0(input_dir, paste0("/cp_of_", basename(file)))
                system(paste("cp -r", file, destination))
            } else {
                stop("Source file does not exist.")
            }
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
REBOL [
	System: "REBOL [R3] Language Interpreter and Run-time Environment"
	Title: "Make the R3 Core Makefile"
	Rights: {
		Copyright 2012 REBOL Technologies
		REBOL is a trademark of REBOL Technologies
	}
	License: {
		Licensed under the Apache License, Version 2.0
		See: http://www.apache.org/licenses/LICENSE-2.0
	}
	Author: "Carl Sassenrath"
	Purpose: {
		Build a new makefile for a given platform.
	}
	Note: [
		"This runs relative to ../tools directory."
		"Make OS-specific changes to the systems.r file."
	]
]

path-host:   %../os/
path-make:   %../../make/
path-incl:   %../../src/include/

;******************************************************************************

; (Warning: format is a bit sensitive to extra spacing. E.g. see macro+ func)

makefile-head:

{# REBOL Makefile -- Generated by make-make.r (!!! EDITS WILL BE LOST !!!)
# This automatically produced file was created !date

# This makefile is intentionally kept simple to make builds possible on
# a wide range of target platforms.  While this generated file has several
# capabilities, it is not tracked by version control.  So to kick off the
# process you need to use the tracked bootstrap makefile:
#
#	make -f makefile.boot
#
# See the comments in %makefile.boot for more information on the workings of
# %make-make.r and what the version numbers mean.  This generated file is a
# superset of the functionality in %makefile.boot, however.  So you can
# retarget simply by typing:
#
#    make make OS_ID=0.4.3
#
# To cross-compile using a different toolchain and include files:
#
#    $TOOLS - should point to bin where gcc is found
#    $INCL  - should point to the dir for includes
#
# Example make:
#
#    make TOOLS=~/amiga/amiga/bin/ppc-amigaos- INCL=/SDK/newlib/include
#
# !!! Efforts to be able to have Rebol build itself in absence of a make
# tool are being considered.  Please come chime in on chat if you are
# interested in that and other projects, or need support while building:
#
#	http://rebolsource.net/go/chat-faq
#

# For the build toolchain:
CC=	$(TOOLS)gcc
NM=	$(TOOLS)nm
STRIP=	$(TOOLS)strip

# CP allows different copy progs:
CP=
# LS allows different ls progs:
LS=
# UP - some systems do not use ../
UP=
# CD - some systems do not use ./
CD=
# Special tools:
T= $(UP)/src/tools
# Paths used by make:
S= ../src
R= $S/core

INCL ?= .
I= -I$(INCL) -I$S/include/ -I$S/codecs/

TO_OS_BASE?=
TO_OS_NAME?=
OS_ID?=
BIN_SUFFIX=
RAPI_FLAGS=
HOST_FLAGS=	-DREB_EXE
RLIB_FLAGS=

# Flags for core and for host:
RFLAGS= -c -D$(TO_OS_BASE) -D$(TO_OS_NAME) -DREB_API  $(RAPI_FLAGS) $I
HFLAGS= -c -D$(TO_OS_BASE) -D$(TO_OS_NAME) -DREB_CORE $(HOST_FLAGS) $I
CLIB=

# REBOL is needed to build various include files:
REBOL_TOOL= r3-make$(BIN_SUFFIX)
REBOL= $(CD)$(REBOL_TOOL) -qs

# For running tests, ship, build, etc.
R3_TARGET= r3$(BIN_SUFFIX)
R3= $(CD)$(R3_TARGET) -qs

### Build targets:
top:
	$(MAKE) $(R3_TARGET)

update:
	-cd $(UP)/; cvs -q update src

# Uses "phony target" %make that should never be the name of a file in
# this directory, hence, it will always regenerate if the make target
# is requested.  Note: Cannot call it %makefile without winding up
# running make-make.r four extra times:
#
#     http://stackoverflow.com/questions/31490689/
#
# Consider being able to continue to type `make make` instead of having
# to re-run the line including `makefile.boot` to be a special
# undocumented feature, as people are used to it...but it might go away
# someday.  Maybe.

make: $(REBOL_TOOL)
	$(REBOL) $T/make-make.r $(OS_ID)

clean:
	@-rm -rf $(R3_TARGET) libr3.so objs/

all:
	$(MAKE) clean
	$(MAKE) prep
	$(MAKE) $(R3_TARGET)
	$(MAKE) lib
	$(MAKE) host$(BIN_SUFFIX)

prep: $(REBOL_TOOL)
	$(REBOL) $T/make-natives.r
	$(REBOL) $T/make-headers.r
	$(REBOL) $T/make-boot.r $(OS_ID)
	$(REBOL) $T/make-host-init.r
	$(REBOL) $T/make-os-ext.r
	$(REBOL) $T/core-ext.r
	$(REBOL) $T/make-host-ext.r
	$(REBOL) $T/make-reb-lib.r

zlib:
	$(REBOL) $T/make-zlib.r	

### Provide more info if make fails due to no local Rebol build tool:
tmps: $S/include/tmp-bootdefs.h

$S/include/tmp-bootdefs.h: $(REBOL_TOOL)
	$(MAKE) prep

$(REBOL_TOOL):
	$(MAKE) -f makefile.boot $(REBOL_TOOL)

### Post build actions
purge:
	-rm libr3.*
	-rm host$(BIN_SUFFIX)
	$(MAKE) lib
	$(MAKE) host$(BIN_SUFFIX)

test:
	$(CP) $(R3_TARGET) $(UP)/src/tests/
	$(R3) $S/tests/test.r

install:
	sudo cp $(R3_TARGET) /usr/local/bin

ship:
	$(R3) $S/tools/upload.r

build:	libr3.so
	$(R3) $S/tools/make-build.r

cln:
	rm libr3.* r3.o

check:
	$(STRIP) -s -o r3.s $(R3_TARGET)
	$(STRIP) -x -o r3.x $(R3_TARGET)
	$(STRIP) -X -o r3.X $(R3_TARGET)
	$(LS) r3*

}

;******************************************************************************

makefile-link: {
# Directly linked r3 executable:
$(R3_TARGET): tmps objs $(OBJS) $(HOST)
	$(CC) -o $(R3_TARGET) $(OBJS) $(HOST) $(CLIB)
	$(STRIP) $(R3_TARGET)
	-$(NM) -a $(R3_TARGET)
	$(LS) $(R3_TARGET)

objs:
	mkdir -p objs
}

makefile-so: {
lib:	libr3.so

# PUBLIC: Shared library:
# NOTE: Did not use "-Wl,-soname,libr3.so" because won't find .so in local dir.
libr3.so:	$(OBJS)
	$(CC) -o libr3.so -shared $(OBJS) $(CLIB)
	$(STRIP) libr3.so
	-$(NM) -D libr3.so
	-$(NM) -a libr3.so | grep "Do_"
	$(LS) libr3.so

# PUBLIC: Host using the shared lib:
host$(BIN_SUFFIX):	$(HOST)
	$(CC) -o host$(BIN_SUFFIX) $(HOST) libr3.so $(CLIB)
	$(STRIP) host$(BIN_SUFFIX)
	$(LS) host$(BIN_SUFFIX)
	echo "export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH"
}

makefile-dyn: {
lib:	libr3.dylib

# Private static library (to be used below for OSX):
libr3.dylib:	$(OBJS)
	ld -r -o r3.o $(OBJS)
	$(CC) -dynamiclib -o libr3.dylib r3.o $(CLIB)
	$(STRIP) -x libr3.dylib
	-$(NM) -D libr3.dylib
	-$(NM) -a libr3.dylib | grep "Do_"
	$(LS) libr3.dylib

# PUBLIC: Host using the shared lib:
host$(BIN_SUFFIX):	$(HOST)
	$(CC) -o host$(BIN_SUFFIX) $(HOST) libr3.dylib $(CLIB)
	$(STRIP) host$(BIN_SUFFIX)
	$(LS) host$(BIN_SUFFIX)
	echo "export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH"
}

not-used: {
# PUBLIC: Static library (to distrirbute) -- does not work!
libr3.lib:	r3.o
	ld -static -r -o libr3.lib r3.o
	$(STRIP) libr3.lib
	-$(NM) -a libr3.lib | grep "Do_"
	$(LS) libr3.lib
}

;******************************************************************************
;** Options and Config
;******************************************************************************

do %common.r
do %systems.r

file-base: has load %file-base.r
config: config-system/guess system/options/args

print ["Option set for building:" config/id config/os-name]

; Words are cleaner-looking in the table, and hyphens look better (and are
; easier to type).  But we need a string, and one that C can accept and not
; think you're doing subtraction.  Transform it (e.g. osx-64 => "TO_OSX_X64")
to-base-def: rejoin [{TO_} uppercase to-string config/os-base]
to-name-def: rejoin [
	{TO_} replace/all (uppercase to-string config/os-name) {-} {_}
]

; Make plat id string:
plat-id: form config/id/2
if tail? next plat-id [insert plat-id #"0"]
append plat-id config/id/3

; Collect OS-specific host files:
unless (
    os-specific-objs: select file-base to word! rejoin ["os-" config/os-base]
) [
	fail [
		"make-make.r requires os-specific obj list in file-base.r"
        "blank was provided for" rejoin ["os-" config/os-base]
	]
]

; The + sign is used to tell the make-os-ext.r script to scan a host kit file
; for headers (the way make-headers.r does).  But we don't care about that
; here in make-make.r... so remove any + signs we find before processing.

remove-each item file-base/os [item = '+]
remove-each item os-specific-objs [item = '+]

outdir: path-make
make-dir outdir
make-dir outdir/objs

nl2: "^/^/"
output: make string! 10000

;******************************************************************************
;** Functions
;******************************************************************************

flag?: func ['word] [not blank? find config/build-flags word]

macro+: func [
	"Appends value to end of macro= line"
	'name
	value
	/local n a
][
	n: rejoin [newline name]
	value: form value
	unless parse makefile-head [
		any [
			thru n opt [
				any space ["=" | "?="] to newline
				insert #" " insert value to end
			]
		]
	][
		print ajoin ["Cannot find " name "= definition"]
	]
	true ;; for ren-c compatibility: func must return value
]

macro++: func ['name obj [object!] /local out] [
	out: make string! 10
	for-each n words-of obj [
		all [
			obj/:n
			flag? (n)
			repend out [space obj/:n]
		]
	]
	macro+ (name) out
]

emit: func [d] [repend output d]

pad: func [str] [head insert/dup copy "" " " 16 - length str]

to-obj: func [
	"Create .o object filename (with no dir path)."
	file
][
	;?? file

	; Use of split path to remove directory had been commented out, but
	; was re-added to incorporate the paths on codecs in a stop-gap measure
	; to use make-make.r with Atronix repo

	file: (comment [to-file file] second split-path to-file file)
	head change back tail file "o"
]

emit-obj-files: func [
	"Output a line-wrapped list of object files."
	files [block!]
	/local cnt
][
	cnt: 1
	for-each file files [
		file: to-obj file
		emit [%objs/ file " "]
		if (cnt // 4) = 0 [emit "\^/^-"]
		cnt: cnt + 1
	]
	if tab = last output [clear skip tail output -3]
	emit nl2
]

emit-file-deps: func [
	"Emit compiler and file dependency lines."
	files
	;flags
	/dir path  ; from path
	/local obj
][
	for-each src files [
		obj: to-obj src
		src: rejoin pick [["$R/" src]["$S/" path src]] not dir
		emit [
			%objs/ obj ":" pad obj src
			newline tab
			"$(CC) "
			src " "
			;flags " "
			pick ["$(RFLAGS)" "$(HFLAGS)"] not dir
			" -o " %objs/ obj ; " " src
			nl2
		]
	]
]

;******************************************************************************
;** Build
;******************************************************************************

replace makefile-head "!date" now

macro+ TO_OS_BASE to-base-def
macro+ TO_OS_NAME to-name-def

macro+ OS_ID config/id
macro+ LS pick ["dir" "ls -l"] flag? DIR
macro+ CP pick [copy cp] flag? COP
unless flag? -SP [ ; Use standard paths:
	macro+ UP ".."
	macro+ CD "./"
]
if flag? EXE [macro+ BIN_SUFFIX %.exe]
macro++ CLIB linker-flags
macro++ RAPI_FLAGS compiler-flags
macro++ HOST_FLAGS construct compiler-flags [PIC: NCM: _]
macro+  HOST_FLAGS compiler-flags/f64 ; default for all

if flag? +SC [remove find os-specific-objs 'host-readline.c]

emit makefile-head
emit ["OBJS =" tab]
emit-obj-files file-base/core
emit ["HOST =" tab]
emit-obj-files append copy file-base/os os-specific-objs
emit makefile-link
emit get pick [makefile-dyn makefile-so] config/id/2 = 2
emit {
### File build targets:
b-boot.c: $(SRC)/boot/boot.r
	$(REBOL) -sqw $(SRC)/tools/make-boot.r
}
emit newline

emit-file-deps file-base/core

emit-file-deps/dir file-base/os %os/
emit-file-deps/dir os-specific-objs %os/

;print copy/part output 300 halt
print ["Created:" outdir/makefile]
write outdir/makefile output
tanimoto_analysis <- function(min.tx, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, blind = FALSE) {
    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon
                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog

                        if(similarity == 'both') { # For similarity matrices already evaluated
                            similarity.consumer <- similarity.consumers[[i]]
                            similarity.resource <- similarity.resources[[i]]
                        } else if(similarity == 'consumer') {
                            similarity.consumer <- similarity.consumers[[i]]
                        } else if (similarity == 'resource') {
                            similarity.resource <- similarity.resources[[i]]
                        }

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                              S0[S1[k], 'consumer'] <- ""
                              S0[S1[k], 'non-consumer'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                                consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                        resource = interactions[, 'resource'],
                                                                        inter_type = interactions[, 'inter'])


                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                }
                                for(k in 1:nrow(consumer_set)) {
                                  S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                  S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.consumer,
                                                                                taxa = 'consumer')

                            similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.resource,
                                                                                taxa = 'resource')

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.consumer = similarity.consumer,
                                                                                    similarity.resource = similarity.resource,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.consumer, similarity.resource)
                        iteration <- iteration + 1
                        setTxtProgressBar(pb, iteration)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values

        }#m
    }#n
    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
catalog_predictions <- function(min.tx = 45, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, percent_remove = 0, nb_iter = 1, comm_id = FALSE, community) {

    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        if(comm_id == FALSE) {
            to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        } else { # comm_id = TRUE
            to.delete <- which(!Cm %in% community)
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        }

    # Setting up lists to store the results
    # weights
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        #Minimum weight
        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

        #Number of iterations
        iter <- vector('list', nb_iter)
            for(i in 1:nb_iter) {
                iter[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- iter
        names(Tanimoto_analysis) <- seq(1,nb_iter)
        remove(iter)


        # Percent remove in communities
        pc_rm <- vector('list', length(percent_remove))
            for(i in 1:length(percent_remove)) {
                pc_rm[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- pc_rm
        names(Tanimoto_analysis) <- percent_remove
        remove(pc_rm)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(percent_remove) * nb_iter * length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(p in 1:length(percent_remove)){
        percent_rm <- percent_remove[p]
        for(o in 1:nb_iter){
            for(n in 1:length(MW)) {
                mw <- MW[n]
                for(m in 1:length(K.values)) {

                    # Tanimoto analysis with different weights for different communities
                        # Parameters:
                            Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                            Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                            # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                        #   wt  Weight of traits in similarity measurement
                        #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                        #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                        # Output:
                        #   A vector of sets of resources for each taxon
                        for(i in 1:length(WT)){ #1st loop for all types of wt values
                            wt <- WT[i]
                            for(j in 1:length(Cm)) { #2nd loop for all C[i]
                                S1 <- communities[[j]]
                                S0 <- S0_catalog

                                if(similarity == 'both') { # For similarity matrices already evaluated
                                    similarity.consumer <- similarity.consumers[[i]]
                                    similarity.resource <- similarity.resources[[i]]
                                } else if(similarity == 'consumer') {
                                    similarity.consumer <- similarity.consumers[[i]]
                                } else if (similarity == 'resource') {
                                    similarity.resource <- similarity.resources[[i]]
                                }

                                # setting up the iterative process to evaluate the accuracy ~ # taxa in catalog
                                # removing a certain percentage of the # of species for which there are interactions as consumers described in the original food web.

                                inter_Cm <- unique(subset(interactions_sources[, 'consumer'], interactions_sources[, 'source'] == Cm[j] & interactions_sources[, 'inter'] == "1")) # Species for which there are interactions as consumer in Cm[j]

                                interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3] # interaction catalog without interactions coming from Cm[j]

                                inter_Cm2 <- unique(interactions[which(interactions[, 'consumer'] %in% inter_Cm), 'consumer']) # consumers in Cm[j] for which information is still available in catalog after deletion of Cm[j] from catalog

                                #Removing a percentage of consumers described in catalog
                                    sample_iter <- sample(x = inter_Cm2, size = round((percent_rm / 100) * length(inter_Cm2)), replace = FALSE)
                                    # sample_iter <- sample(x = seq(1,length(S1)), size = round((percent_rm / 100) * length(S1)), replace = FALSE) # To use if removing a percent of all taxa in original web
                                    # for(k in sample_iter) {
                                    #   S0[S1[k], 'resource'] <- ""
                                    #   S0[S1[k], 'non-resource'] <- ""
                                    #   S0[S1[k], 'consumer'] <- ""
                                    #   S0[S1[k], 'non-consumer'] <- ""
                                    # }

                                    for(k in length(sample_iter)) {
                                      S0[sample_iter[k], 'resource'] <- ""
                                      S0[sample_iter[k], 'non-resource'] <- ""
                                      S0[sample_iter[k], 'consumer'] <- ""
                                      S0[sample_iter[k], 'non-consumer'] <- ""
                                    }

                                    S1_no_mod <- which(!S1 %in% sample_iter)

                                # 2. Preexisting information kept to inform algorithm
                                    # if(length(S1_no_mod) == length(S1)) {
                                        # NULL
                                    # } else {

                                    # Only modifying those that are loosing data from the catalogue, less time
                                        to.change <- numeric()
                                        for(k in 1:length(S1_no_mod)) {
                                            to.change <- c(to.change, which(interactions[, 'consumer'] == S1[S1_no_mod[k]]), which(interactions[, 'resource'] == S1[S1_no_mod[k]]))
                                        }
                                        to.change <- unique(to.change)

                                    # Modifying sets of resources and non-resources for taxa in S1_no_mod
                                        interactions <- interactions[to.change, ]
                                        rownames(interactions) <- seq(1,nrow(interactions))
                                        resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                                  resource = interactions[, 'resource'],
                                                                                  inter_type = interactions[, 'inter'])

                                        consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                                resource = interactions[, 'resource'],
                                                                                inter_type = interactions[, 'inter'])


                                    # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                        for(k in 1:nrow(resource_set)) {
                                          S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                          S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                        }
                                        for(k in 1:nrow(consumer_set)) {
                                          S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                          S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                        }
                                    remove(interactions, resource_set, to.change)
                                    # }#if

                                # Recalculate similarity
                                    similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.consumer,
                                                                                        taxa = 'consumer')

                                    similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.resource,
                                                                                        taxa = 'resource')

                                # Predicting interactions
                                    Tanimoto_analysis[[p]][[o]][[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                            Kr = Kr,
                                                                                            S0 = S0,
                                                                                            S1 = S1,
                                                                                            MW = mw,
                                                                                            similarity.consumer = similarity.consumer,
                                                                                            similarity.resource = similarity.resource,
                                                                                            minimum_threshold = minimum_threshold)

                                save(x = Tanimoto_analysis, file = file.to.save)
                                remove(S0, S1, similarity.consumer, similarity.resource)
                                iteration <- iteration + 1
                                setTxtProgressBar(pb, iteration)
                            }#2nd loop for all C[i]

                            save(x = Tanimoto_analysis, file = file.to.save)
                            remove(wt)

                        }#1st loop for all types of wt values
                }#m
            }#n
        }#o
    }#p
    #Saving number of species in original web vs catalog once web removed
    percent_original <- length(inter_Cm2) / length(inter_Cm)
    x <- c(percent_original, length(inter_Cm), length(inter_Cm2))
    file.to.save2 <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis_pc_tx.RData")
    save(x = x, file = file.to.save2)

    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename = 'catalog_predictions2'

catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions2 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40,60,80),
                                            nb_iter = 100,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = filename)

catalog_predictions3 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(30,50,70,90),
                                            nb_iter = 100,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = filename)


# Catalog vs predictions

accuracy <- accuracy0 <- accuracy1 <- accuracy2 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) <- names(accuracy2) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy2[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, empirical.only = TRUE)
accuracy2[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, predict.only = TRUE)
accuracy2[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]], accuracy2[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]], accuracy2[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]], accuracy2[[3]])

percent_remove = c(0,10,20,40,60,80,100)
nb_iter = 100
K.values = 8
MW = 1
WT =  0.5
minimum_threshold = 0.3

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

# Graph
for(j in 13:16) {
        eplot(xmin = -0.09, xmax = 100, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.1) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            # mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            # mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 0.1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 0.1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 0.1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            points(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it, cex = 0.5, pch = 1, col = col[i])
            lines(lowess(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it))
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
tanimoto <- function(resource_x, resource_y) {
  # The Tanimoto similarity computes the sum of shared elements in vectors resource_x and resource_y and divides this by the length of the longest vector
  # If either length of resource_x or resource_y == 0, similarity == 0
  # The order of vectors consumer_x or consumer_y has no importance, as long as elements in vectors are unique

  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  # The same funcion is apparently used for trait similarity, including phylogeny
  # !!! There are NAs in the taxonomy that need to be taken into account, which is not the case at the moment !!!
  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    if(length(resource_x) == 0 || length(resource_y) == 0) {
        return(0.0)
    } else if(resource_x == "" || resource_y == "") {
        return(0.0)
    } else {
        return(sum(resource_x %in% resource_y) / length(unique(c(resource_x, resource_y))))
    }#if
}#end tanimoto function
# The functions require rchart-helper.R preloaded

# getQ2TimelapsePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getQ2TimelapsePlot = function(data, names, colors, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    dateFactors = list()
    for (i in 1:length(data)) {
        dateFactors[[i]] = as.factor(data[[i]]$date)
        boxplot = boxplot(data[[i]]$x ~ dateFactors[[i]],
                          data=data.frame(dateFactors[[i]], data[[i]]$x), plot=FALSE)
        stats = setNames(as.data.frame(boxplot$stats), nm=NULL)

        # Timpstamp in miliseconds
        unixTimestamps =
            1000 * as.numeric(as.POSIXct(sort(unique(data[[i]]$date)),
                                         origin="1970-01-01"))
        statsMedian = rbind(setNames(unixTimestamps, nm=NULL), stats[3,])
        statsQ2 = rbind(setNames(unixTimestamps, nm=NULL), stats[c(2, 4),])

        series[[2 * (i - 1) + 1]] =
            list(name=names[i], data=statsMedian, zIndex=1, color=colors[i],
                 marker=list(fillColor="white", lineWidth=2, lineColor=colors[i]))
        series[[2 * i]] = list(name="50th quartile", data=statsQ2, zIndex=0,
                 type="arearange", color=colors[i], lineWidth=0, linkedTo=":previous", fillOpacity=0.3)
    }

    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=list(text=yLabel), min=0)
    chart$set(series=series)
    return(chart)
}

# Helper for creating histogram
getBinItemList = function(data, businesses, interval=100) {
    binItemList = c()
    currentBin = interval
    maxBin = max(data$count) + interval
    while (currentBin < maxBin) {
        items = filter(data, currentBin - interval <= count & count < currentBin)
        binItemList = c(binItemList,
                        paste("< ", currentBin, "<br>",
                              paste(items$name, collapse="<br>, ")))
        currentBin = currentBin + interval
    }
    return(binItemList)
}

# getStackedHistogram
# data[[]]$x
getStackedHistogram = function(data,
                               names,
                               xLabel,
                               minBin=NULL,
                               maxBin = NULL,
                               interval=100,
                               logScale=FALSE,
                               logBase=exp(1),
                               normalize=FALSE,
                               colors = c("#7cb5ec", "#000000")) {
    series = list()
    plotLines = list()

    actualInterval = interval
    for (i in 1:length(data)) {
        maxBin = max(maxBin, max(data[[i]]$x, na.rm=TRUE), na.rm=TRUE)
        minBin = min(minBin, min(data[[i]]$x, na.rm=TRUE), na.rm=TRUE)
    }
    if (logScale) {
        maxBin = log(maxBin + 1, base=logBase)
        minBin = log(minBin + 1, base=logBase)
        actualInterval = log(interval, base=logBase)
    }

    for (i in 1:length(data)){
        x = data[[i]]$x
        if (logScale) {
            x = log(x + 1, base=logBase)
        }

        plotLines[[i * 2 - 1]] =
            list(color=colors[i],
                 value=mean(x),
                 width=2,
                 label=list(text="mean", style=list(color=colors[i]), verticalAlign="middle"))
        plotLines[[i * 2]] =
            list(color=colors[i],
                 value=median(x),
                 dashStyle="dash",
                 width=2,
                 label=list(text="median", style=list(color=colors[i]), verticalAlign="middle"))

        histogram = hist(x, breaks=seq(minBin, maxBin + actualInterval, actualInterval), plot=FALSE)
        histNames = getBinItemList(data[[i]], interval=actualInterval)

        nBins = min(length(histogram$breaks), length(histogram$counts))
        counts = histogram$counts[1:nBins]
        if (normalize) {
            counts = 100 * counts / nrow(data[[i]])
        }
        breaks = c(histogram$breaks[2:nBins], histogram$breaks[nBins] + actualInterval)
        bins = getValues(
            breaks,
            counts,
            name=histNames)
        series[[i]] = list(name=names[i], data=bins)
    }
   
    chart <- Highcharts$new()
    chart$chart(type="column")
    chart$plotOptions(
        column="{ grouping: false, pointPadding: 0, borderWidth: 0, groupPadding: 0, shadow: false}")
    chart$xAxis(title=paste("{text: '", xLabel, "'}", sep=""),
                plotLines=plotLines)
    yLabel = "count"
    if (normalize) {
        yLabel = "density (%)"
    }
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""))
    chart$set(series=series)
    return(chart)
}

# getTimelapseLinePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getTimelapseLinePlot = function(data, names, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    for (i in 1:length(data)){
        timelapseValues = getTimelapseValues(
            as.POSIXlt(strptime(as.character(data[[i]]$date), "%Y-%m-%d", tz=timezone)),
            data[[i]]$x)
        series[[i]] = list(name=names[i], data=timelapseValues)
    }


    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""), gridLineColor="#FFFFFF")
    chart$set(series=series)
    return(chart)
}


# Difference-in-difference plot
# Use with DiffInDiffAggregate function
diffInDiffPlot <- function(data,
                     idCol,
                     xCol,
                     yLabel="change",
                     periodNames=NULL
                     ) {
    dataChart <- Highcharts$new()
    ids = unique(data[, idCol])
    numPeriod = 0
    for (i in 1:length(ids)) {
        current = data[data[, idCol] == ids[i],]
        numPeriod = nrow(current)
        name = current[1,]$name
        x = seq(0, numPeriod - 1, 1)
        y = current[, xCol]
        z = current[, xCol]
        
        seriesData = getValues(x, y, z, name)
        visible = TRUE
        dataChart$series(name=name,
                         data=seriesData,
                         showInLegend=TRUE,
                         visible=visible)
    }
    if (is.null(periodNames)) {
        periodNames = paste("period", x)
    }
    dataChart$xAxis(categories=periodNames)
    dataChart$yAxis(title=list(text=yLabel), gridLineColor="#FFFFFF")
    dataChart$legend(align="right", verticalAlign="top", layout="vertical")
    dataChart$tooltip(pointFormat=getPointFormat(y=yLabel, z=xCol))
    return (dataChart)
}


library(stringr)
library(reshape2)
library(ggplot2)


filenames_all <- list.files(path = "datasets/AllAttributes/",pattern = ".csv",full.names = TRUE)
ldf <- lapply(filenames_all, read.csv, skip=0, header=TRUE, sep=";",blank.lines.skip = TRUE,strip.white = TRUE, colClasses = rep("character",7))
for(i in seq(from=1,to=length(filenames_all),by = 1)){
  ldf[[i]]$Dataset <- sapply(str_split(filenames_all, '/'), '[', 4)[i]
  ldf[[i]]$Attributes <- "All"
}


filenames_sel <- list.files(path = "datasets/ReliefFAttributeEval-FS//",pattern = ".csv",full.names = TRUE)
ldf_s <- lapply(filenames_sel, read.csv, skip=0, header=TRUE, sep=";",blank.lines.skip = TRUE,strip.white = TRUE, colClasses = rep("character",7))
for(i in seq(from=1,to=length(filenames_sel),by = 1)){
  ldf_s[[i]]$Dataset <- sapply(str_split(filenames_sel, '/'), '[', 5)[i]
  ldf_s[[i]]$Attributes <- "ReliefFAttributeEval-FS"
}

filenames_som <- list.files(path = "datasets/SOM-FS//",pattern = ".csv",full.names = TRUE)
ldf_som <- lapply(filenames_som, read.csv, skip=0, header=TRUE, sep=";",blank.lines.skip = TRUE,strip.white = TRUE, colClasses = rep("character",7))
for(i in seq(from=1,to=length(filenames_som),by = 1)){
  ldf_som[[i]]$Dataset <- sapply(str_split(filenames_som, '/'), '[', 5)[i]
  ldf_som[[i]]$Attributes <- "SOM-FS"
}


filenames_cfs <- list.files(path = "datasets/CfsSubsetEval-FS//",pattern = ".csv",full.names = TRUE)
ldf_cfs <- lapply(filenames_cfs, read.csv, skip=0, header=TRUE, sep=";",blank.lines.skip = TRUE,strip.white = TRUE, colClasses = rep("character",7))
for(i in seq(from=1,to=length(filenames_cfs),by = 1)){
  ldf_cfs[[i]]$Dataset <- sapply(str_split(filenames_cfs, '/'), '[', 5)[i]
  ldf_cfs[[i]]$Attributes <- "CfsSubsetEval-FS"
}

m_all <- do.call(rbind,ldf)
m_sel <- do.call(rbind,ldf_s)
m_som <- do.call(rbind,ldf_som)
m_cfs <- do.call(rbind,ldf_cfs)

m <- rbind(m_all,m_sel)
m <- rbind(m,m_som)
m <- rbind(m,m_cfs)

rm(m_all,m_sel,m_som,m_cfs,ldf,ldf_s,ldf_som,ldf_cfs,filenames_sel,filenames_all,filenames_som,filenames_cfs,i)

datos <- melt(data = m,id.vars = c("Method","Dataset","Attributes"),measure.vars = c("R.","MAE","RMSE","RAE","RRSE","TIME"),)

datos$Dataset <- str_replace(datos$Dataset,".csv","")

datos$error <- as.numeric(sapply(str_split(datos$value, '_'), '[', 2))
datos$value <- as.numeric(sapply(str_split(datos$value, '_'), '[', 1))

datos$variable <- as.character(datos$variable)
datos[datos$variable=="R.","variable"] <- "R^2"
dataset = unique(datos$Dataset)

#ggplot(data = subset(datos,Dataset==dataset[1]), aes(x=Attributes,y=value,color=Attributes,shape=Attributes)) + geom_point(stat="identity",size=3) + 
#  facet_grid(variable ~ Method,scales = "free_y",labeller = as_labeller(expression()) + 
#  scale_color_grey(start=0.0,end=0.2) + labs(title=dataset[1],x="",y="") + 
#  geom_errorbar(aes(ymin=value-error,ymax=value+error), width=0.2,size=0.25) + theme_bw()  + theme(legend.position="bottom", axis.title.x=element_blank(),
#                                                                                                   axis.text.x=element_blank(),
#                                                                                                   axis.ticks.x=element_blank())


#ggplot(data = subset(datos,Dataset==dataset[1]), aes(x=Attributes,y=value,fill=Attributes,shape=Attributes)) + geom_bar(stat="identity") + 
#  facet_grid(variable ~ Method,scales = "free_y",) + 
#  scale_fill_grey(start=0.2,end=0.6) + labs(title=dataset[1],x="",y="") + 
#  geom_errorbar(aes(ymin=value-error,ymax=value+error), width=0.5,size=0.5) + theme_bw()  + theme(legend.position="bottom", axis.title.x=element_blank(),
#                                                                                                   axis.text.x=element_blank(),
#                                                                                                   axis.ticks.x=element_blank())

# Publisher > Method > Metric > Attribute Selection

dataset = unique(datos$Dataset)

for(i in dataset){
  print(ggplot(data = subset(datos,Dataset==i), aes(x=Attributes,y=value,fill=Attributes,shape=Attributes)) + geom_point(size=2) + geom_bar(stat="identity") + 
    facet_grid(variable ~ Method,scales = "free_y") + 
    scale_fill_grey(start=0.2,end=0.6) + labs(title=i,x="",y="") + 
    geom_errorbar(aes(ymin=value-error,ymax=value+error), width=0.5,size=0.5) + theme_bw()  + theme(legend.position="bottom", axis.title.x=element_blank(),
                                                                                                    axis.text.x=element_blank(),
                                                                                             axis.ticks.x=element_blank()))
  ggsave(file=paste0("../imgs/datasets_",i,".png"),scale=1.2)
  
}

# Attribute Selection > Publisher > Method > Metric

att = unique(datos$Attributes)

#for(i in dataset){
  for(j in att){
  
print(ggplot(data = subset(datos,Attributes==j & Dataset==i), aes(x=Method,y=value,color=Attributes,shape=Attributes)) + 
        geom_point(stat="identity",size=2)  +geom_bar(stat="identity") + 
  facet_grid(variable ~ Dataset,scales = "free_y") + 
  scale_color_grey(start=0.0,end=0.2) + labs(title="",x="",y="") + 
  geom_errorbar(aes(ymin=value-error,ymax=value+error), width=0.2,size=0.25) + theme_bw()  + theme(legend.position="none"))

  ggsave(file=paste0("../imgs/attribute_",j,".png"),scale=1.2)

  }

var = unique(datos$variable)

for(i in var){
  
  ggplot(data = subset(datos,variable==i), aes(x=Method,y=value)) + geom_point(stat="identity",size=3) +
    geom_bar(stat="identity",size=3) + 
    facet_grid(Dataset ~ Attributes,scales = "free_y") + 
    scale_fill_grey(start=0.2,end=0.8) + labs(title=i,x="Method",y="Seconds") + 
    geom_errorbar(aes(ymin=value-error,ymax=value+error), width=0.2,size=0.25) + theme_bw()  + theme(legend.position="bottom")
  
  
  ggsave(file=paste0("../imgs/metric_",i,".png"),scale=1.2)
}




#}

# 
# p2 <- ggplot(data = subset(datos,Attributes==att[2]), aes(x=Method,y=value,color=Attributes,shape=Attributes)) + geom_point(stat="identity",size=2) + 
#   facet_grid(variable ~ Dataset,scales = "free_y") + 
#   scale_color_grey(start=0.0,end=0.2) + labs(title=att[2],x="",y="") + 
#   geom_errorbar(aes(ymin=value-error,ymax=value+error), width=0.2,size=0.25) + theme_bw()  + theme(legend.position="none")
# 
# multiplot(p1,p2,cols=1)
# 
# #Time dataset, selection, method
# 
# 
# ggplot(data = subset(datos,variable=="TIME"), aes(x=Method,y=value)) + geom_point(stat="identity",size=3) +
#   geom_bar(stat="identity",size=3) + 
#   facet_grid(Dataset ~ Attributes,scales = "free_y") + 
#   scale_fill_grey(start=0.2,end=0.8) + labs(title="TIME",x="Method",y="Seconds") + 
#   geom_errorbar(aes(ymin=value-error,ymax=value+error), width=0.2,size=0.25) + theme_bw()  + theme(legend.position="bottom")
#   
# 
# ggplot(data = subset(datos,variable=="MAE"), aes(x=Method,y=value)) + geom_bar(stat="identity",size=3) + 
#   facet_grid(Dataset ~ Attributes,scales = "free_y") + 
#   scale_fill_grey(start=0.2,end=0.8) + labs(title="MAE",x="Method",y="Units") + 
#   geom_errorbar(aes(ymin=value-error,ymax=value+error), width=0.2,size=0.25) + theme_bw()  + theme(legend.position="bottom")
# 
# 
# 
# 
# 
# 
# 
# 
# 
# 
# 
# 
# 
# 
# 
# 
# 
# ggplot(data = datos, aes(x=variable,y=value)) + geom_point() + facet_grid(Attributes ~ Dataset)
# 
# ggplot(data = subset(datos,variable=="R2"), aes(x=Attributes,y=value,fill=Attributes)) + geom_bar(stat="identity",position="dodge") + facet_grid(variable ~ Dataset)
# 
# ggplot(data = subset(datos), aes(x=Attributes,y=value,fill=Attributes)) + geom_bar(stat="identity",position="dodge") + 
#   facet_grid(variable ~ Dataset,scales = "free_y") + theme(legend.position="bottom") + scale_fill_brewer(type="qual",palette = "Set1")
# 
# 
# dataset = unique(datos$Dataset)
# 
# ggplot(data = subset(datos,Dataset==dataset[1]), aes(x=Attributes,y=value,fill=Attributes)) + geom_bar(stat="identity",position="dodge") + 
#   facet_grid(variable ~ Method,scales = "free_y") + theme(legend.position="bottom", axis.title.x=element_blank(),
#                                                           axis.text.x=element_blank(),
#                                                           axis.ticks.x=element_blank()) + 
#   scale_fill_grey(start=0.2,end=0.8) + labs(title=dataset[1],x="",y="")
# 
# 
# 
# ggplot(data = subset(datos,Dataset==dataset[1]), aes(x=Attributes,y=value,fill=Attributes)) + geom_point(stat="identity",position="dodge") + 
#   facet_grid(variable ~ Method,scales = "free_y") + theme(legend.position="bottom", axis.title.x=element_blank(),
#                                                           axis.text.x=element_blank(),
#                                                           axis.ticks.x=element_blank()) + 
#   scale_fill_grey(start=0.2,end=0.8) + labs(title=dataset[1],x="",y="")
# 
# 
# 
#coverage/inst/shiny/coverage1/ui.r
#andy south 12/5/16

library(shiny)


shinyUI(fluidPage(

  #can add CSS controls in here
  #http://shiny.rstudio.com/articles/css.html
  #http://www.w3schools.com/css/css_rwd_mediaqueries.asp
  tags$head(
    tags$style(HTML("

                    .col-sm-2 {padding: 80px 0px; /*border: 1px solid green;*/}

                    /* For mobile phones: */
                    /* note here I'm not following mobile first design ! */
                    @media only screen and (max-width: 768px) {


                        [class*='col-'] {
                        padding: 5px;
                        border: 1px;
                        position: relative;
                        min-height: 1px;
                        }

                        .container {
                        margin-right: 0;
                        margin-left: 0;
                        float: left;
                        }
                        .col-sm-2 {width: 50%; float: left; height: 150px;}
                        .col-sm-3 {width: 25%; float: left;}
                        .col-sm-8 {width: 100%; float: left; height: 350px;} ! padding: 5px;} !to make more space for plots
                        ! so on pc the where the css doesn't kick in the 12 columns fit in one row (8+2+2)
                        ! on the phone the width8 col takes up 100%, and the width2 columns take up 50% of the next row
                        }


                    "))
    ),

  title = "coverage of vector control interventions",

  h5("Vector control demonstrator prototype. Gerry Killeen & Andy South."),
  h5("Vectors feed indoors and outdoors, on humans and cattle. Interventions target a subset of these behaviours."),
  h5("Change inputs below to see implications."),

  fluidRow(
    column(8, plotOutput('plot_feed')),
    # column(2, h5("Vector feeding"), plotOutput('plot_pie_feed') ),
    # column(2, h5("Human exposure"), plotOutput('plot_pie_expose') )
    column(2, plotOutput('plot_pie_feed') ),
    column(2, plotOutput('plot_pie_expose') )

    # column(2, HTML("<div style='height: 150px;'>"), plotOutput('plot_pie_feed'), HTML("</div>")),
    # column(2, HTML("<div style='height: 150px;'>"), plotOutput('plot_pie_expose'), HTML("</div>"))

  ), #end fluid row


  #hr(),

  fluidRow(
    column(3,
           #h4("Vector feeding"),
           sliderInput("feed_man", "vectors feeding on man", 0.7, min = 0, max = 1, step = 0.1, ticks=FALSE)
           #numericInput("feed_cow", "cattle", 0.3, min = 0, max = 1, step = 0.1),
           #sliderInput("feed_in","indoor", 0.6, min = 0, max = 1, step = 0.1)
           #numericInput("feed_out","outdoor", 0.4, min = 0, max = 1, step = 0.1)
    ),
    column(3,
           sliderInput("feed_in","vectors feeding indoors", 0.6, min = 0, max = 1, step = 0.1, ticks=FALSE)
    ),
    column(3, offset = 0,
           #h4("Intervention"),
           radioButtons("intervention","intervention",choices=c("bed nets","vet insecticide"))
           #sliderInput("target_coverage", "coverage", 0.7, min = 0, max = 1, step = 0.1)
    ),
    column(3, offset = 0,
           sliderInput("target_coverage", "intervention coverage", 0, min = 0, max = 1, step = 0.1, ticks=FALSE)
    )
           # h4("Intervention target"),
           # numericInput("target_man", "human", 0.7, min = 0, max = 1, step = 0.1),
           # numericInput("target_cow", "cattle", 0.3, min = 0, max = 1, step = 0.1),
           # numericInput("target_in","indoor", 0.6, min = 0, max = 1, step = 0.1),
           # numericInput("target_out","outdoor", 0.4, min = 0, max = 1, step = 0.1)


  ) #end fluid row

))
#coverage/inst/shiny/coverage1/server.r
#andy south 12/5/16

#https://andysouth.shinyapps.io/coverage1/

library(shiny)
#library(devtools)
#install_github('AndySouth/coverage')
library(coverage)
library(png)

shinyServer(function(input, output, session) {


  ################################
  output$plot_feed <- renderPlot({

    #add dependency on the button
    #if ( input$aButtonRun > 0 )
    #{
      #isolate reactivity of other objects
    #  isolate({

        plot_feeding( man = input$feed_man,
                      cow = 1-input$feed_man,
                      indoor = input$feed_in,
                      outdoor = 1-input$feed_in,
                      intervention = input$intervention,
                      coverage = input$target_coverage )


      #}) #end isolate
    #} #end if ( input$aButtonRun > 0 )
  })


  ####################################
  output$plot_pie_feed <- renderPlot(width = 150, height = 150,{
  #output$plot_pie_feed <- renderPlot({

    plot_pie_feeding( man = input$feed_man,
                  cow = 1-input$feed_man,
                  indoor = input$feed_in,
                  outdoor = 1-input$feed_in,
                  intervention = input$intervention,
                  coverage = input$target_coverage )
  })


  ####################################
  output$plot_pie_expose <- renderPlot(width = 150, height = 150,{
  #output$plot_pie_expose <- renderPlot({


    plot_pie_exposure(man = input$feed_man,
                      cow = 1-input$feed_man,
                      indoor = input$feed_in,
                      outdoor = 1-input$feed_in,
                      intervention = input$intervention,
                      coverage = input$target_coverage )
  })


  #to update values based on changes in others

  #stop feed_man going below feed_indoors
  #not needed now that human feed is a proportion of indoors
  #observe({ if ( input$feed_man < input$feed_in ) updateSliderInput(session, "feed_man", value = input$feed_in ) })

  #stop feedindoors going above feed_man
  # observe({ updateNumericInput(session, "feed_man", value = 1-input$feed_cow) })
  # observe({ updateNumericInput(session, "feed_cow", value = 1-input$feed_man) })
  # observe({ updateNumericInput(session, "feed_in", value = 1-input$feed_out) })
  # observe({ updateNumericInput(session, "feed_out", value = 1-input$feed_in) })


})
                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

# not used

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

# not used. and slow

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    list1 <- df1$id
    list2 <- df2$id
    for (j in 1:length(list2)) {
        id <- list2[j]
        list[id] <- NA
        i <- match(id, list1)
        if (!is.na(i)) {
            list[id] <- j - i
        }
    }
    return (list)
}

# slow. not used

getperiodmapold <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
#        list12 <- stocklistperiod[period, 2][[1]]
#        for (i in 1:max) {
#            print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
#        }
        for (i in 1:max) {
            id <- list11$id[i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
                if (is.null(rise)) {
                    rise <- 0
                }
            }
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), rise, list11$id[[i]]))
        }
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
                                        #    list12 <- stocklistperiod[period, 2][[1]]
                                        #
                                        #    len <- nrow(list12)
                                        #    len <- len + 1

                                        #    for (i in 1:max) {
                                        #        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
                                        #    }

                                        #    len <- nrow(list11)
                                        #    len <- len + 1

        len <- nrow(list11)
        len <- len + 1
        for (i in 1:max) {
            id <- list11$id[len - i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
                if (is.null(rise)) {
                    rise <- 0
                }
            }
            
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), rise, list11$id[[len - i]]))
        }
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, mynames, topbottom, periodtext, maindate, olddate, days) {
    dev.new()
    colours <- rainbow(topbottom)
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE, col = colours[i], pch = i)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o", lty = i, col = colours[i], pch = i)
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(mynames[1]))
        legend(1, g_range[2], mynames, cex=0.8, lty=1:6, pch=1:25, col=colours) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (type == pricetype) {
        return (df$price)
    }
    if (type == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    normalize <- 0
    if (length(ids) > 1) {
        if (periodtext == "price") {
            normalize <- 1
        }
        if (periodtext == "index") {
            normalize <- 1
        }
    }
    
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, pricetype)
        perioddata[["text"]] <- pairs
        perioddatamap[["price"]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, indextype)
        perioddata[["text"]] <- pairs
        perioddatamap[["index"]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    dayset <- list()
    ls <- list()
    mynames <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        if (normalize == 1) {
                            str("minmax")
                            str(l)
                            mymin <- abs(min(l))
                            mymax <- abs(max(l))
                            if (mymin > mymax) {
                                mymax <- mymin
                            }
                            for (j in 1:length(l)) {
                                l[j] <- l[j] * 100 / mymax;
                            }
                            str(l)
                        }
                        
                        dayset <- append(dayset, bigretl[[2]])
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        mynames[c] <- df$name
                    }
                }
            }
        }
    }
    daynames <- names(dayset)
    olddate <- min(daynames)
    newdate <- max(daynames)
    displaychart(ls, mynames, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

#coverage/inst/shiny/coverage1/server.r
#andy south 12/5/16

#https://andysouth.shinyapps.io/coverage1/

library(shiny)
#library(devtools)
#install_github('AndySouth/coverage')
library(coverage)
library(png)

shinyServer(function(input, output, session) {


  ################################
  output$plot_feed <- renderPlot({

    #add dependency on the button
    #if ( input$aButtonRun > 0 )
    #{
      #isolate reactivity of other objects
    #  isolate({

        plot_feeding( man = input$feed_man,
                      cow = 1-input$feed_man,
                      indoor = input$feed_in,
                      outdoor = 1-input$feed_in,
                      intervention = input$intervention,
                      coverage = input$target_coverage )


      #}) #end isolate
    #} #end if ( input$aButtonRun > 0 )
  })


  ####################################
  #output$plot_pie_feed <- renderPlot(width = 150, height = 150,{
  output$plot_pie_feed <- renderPlot({

    plot_pie_feeding( man = input$feed_man,
                  cow = 1-input$feed_man,
                  indoor = input$feed_in,
                  outdoor = 1-input$feed_in,
                  intervention = input$intervention,
                  coverage = input$target_coverage )
  })


  ####################################
  output$plot_pie_expose <- renderPlot({


    plot_pie_exposure(man = input$feed_man,
                      cow = 1-input$feed_man,
                      indoor = input$feed_in,
                      outdoor = 1-input$feed_in,
                      intervention = input$intervention,
                      coverage = input$target_coverage )
  })


  #to update values based on changes in others

  #stop feed_man going below feed_indoors
  #not needed now that human feed is a proportion of indoors
  #observe({ if ( input$feed_man < input$feed_in ) updateSliderInput(session, "feed_man", value = input$feed_in ) })

  #stop feedindoors going above feed_man
  # observe({ updateNumericInput(session, "feed_man", value = 1-input$feed_cow) })
  # observe({ updateNumericInput(session, "feed_cow", value = 1-input$feed_man) })
  # observe({ updateNumericInput(session, "feed_in", value = 1-input$feed_out) })
  # observe({ updateNumericInput(session, "feed_out", value = 1-input$feed_in) })


})
generateBagIt {
# -----------------------------------------------------
# generateBagIt for HydroShare
# adapted by Hong Yi on May 2015 to fit HydroShare use case 
# from rulegenerateBagIt.r originally developed by Terrell 
# Russell on August 2010
# -----------------------------------------------------
#
#  University of North Carolina at Chapel Hill
#  - Requires iRODS 2.4.1
#  - Conforms to BagIt Spec v0.96
#
# -----------------------------------------------------
#
### - use the input BAGITDATA directory to generate bagit 
###   files in place without creating new bagit root directory
### - writes bagit.txt to BAGITDATA/bagit.txt
### - generates payload manifest file of BAGITDATA/data
### - writes payload manifest to BAGITDATA/manifest-sha256.txt
### - writes tagmanifest file to BAGITDATA/tagmanifest-sha256.txt
### - writes to rodsLog
#
# -----------------------------------------------------

  ### - writes bagit.txt to NEWBAGITROOT/bagit.txt
  writeLine("stdout", "BagIt-Version: 0.96");
  writeLine("stdout", "Tag-File-Character-Encoding: UTF-8");
  msiDataObjCreate("*BAGITDATA" ++ "/bagit.txt", "destRescName=" ++ "*DESTRESC" ++ "++++forceFlag=", *FD);
  msiDataObjWrite(*FD, "stdout", *WLEN);
  msiDataObjClose(*FD, *Status);
  msiFreeBuffer("stdout");

  ### - generates payload manifest file of BAGITDATA/data
  msiStrlen(*BAGITDATA, *ROOTLENGTH);
  *OFFSET = int(*ROOTLENGTH) + 1;
  *NEWBAGITDATA = "*BAGITDATA" ++ "/data";
  *ContInxOld = 1;
  *Condition = "COLL_NAME like '*NEWBAGITDATA%%'";
  msiMakeGenQuery("DATA_ID, DATA_NAME, COLL_NAME", *Condition, *GenQInp);
  msiExecGenQuery(*GenQInp, *GenQOut);
  msiGetContInxFromGenQueryOut(*GenQOut, *ContInxNew);
  while(*ContInxOld > 0) {
    foreach(*GenQOut) {
      msiGetValByKey(*GenQOut, "DATA_NAME", *Object);
      msiGetValByKey(*GenQOut, "COLL_NAME", *Coll);
      *FULLPATH = "*Coll" ++ "/" ++ "*Object";
      msiDataObjChksum(*FULLPATH, "forceChksum=", *CHKSUM);
      msiSubstr(*FULLPATH,str(*OFFSET), "null", *RELATIVEPATH);
      writeString("stdout", *CHKSUM);
      writeLine("stdout", "    *RELATIVEPATH")
    }
    *ContInxOld = *ContInxNew;
    if(*ContInxOld > 0) {
      msiGetMoreRows(*GenQInp, *GenQOut, *ContInxNew);
    }
  }

  ### - writes payload manifest to BAGITDATA/manifest-sha256.txt
  msiDataObjCreate("*BAGITDATA" ++ "/manifest-sha256.txt", "destRescName=" ++ "*DESTRESC" ++ "++++forceFlag=", *FD);
  msiDataObjWrite(*FD, "stdout", *WLEN);
  msiDataObjClose(*FD, *Status);
  msiFreeBuffer("stdout");

  ### - writes tagmanifest file to BAGITDATA/tagmanifest-sha256.txt
  msiDataObjChksum("*BAGITDATA" ++ "/bagit.txt", "forceChksum", *CHKSUM);
  writeString("stdout", *CHKSUM);
  writeLine("stdout", "    bagit.txt")
  msiDataObjChksum("*BAGITDATA" ++ "/manifest-sha256.txt", "forceChksum", *CHKSUM);
  writeString("stdout", *CHKSUM);
  writeLine("stdout", "    manifest-sha256.txt");
  msiDataObjCreate("*BAGITDATA" ++ "/tagmanifest-sha256.txt", "destRescName=" ++ "*DESTRESC" ++ "++++forceFlag=", *FD);
  msiDataObjWrite(*FD, "stdout", *WLEN);
  msiDataObjClose(*FD, *Status);
  msiFreeBuffer("stdout");

  ### - writes to rodsLog
  msiWriteRodsLog("BagIt bag files created in place: *BAGITDATA <- *BAGITDATA", *Status);
}
INPUT *BAGITDATA="/dummy/dummy/dummy", *DESTRESC="dummy"
OUTPUT ruleExecOut
# 2. faza: Uvoz podatkov


# Funkcija, ki uvozi podatke iz datoteke druzine.csv
#uvozi.druzine <- function() {
 # return(read.table("podatki/druzine.csv", sep = ";", as.is = TRUE,
  #                  row.names = 1,
   #                 col.names = c("obcina", "en", "dva", "tri", "stiri"),
    #                fileEncoding = "Windows-1250"))
#}

# Zapišimo podatke v razpredelnico druzine.
#druzine <- uvozi.druzine()

#obcine <- uvozi.obcine()

# Če bi imeli več funkcij za uvoz in nekaterih npr. še ne bi
# potrebovali v 3. fazi, bi bilo smiselno funkcije dati v svojo
# datoteko, tukaj pa bi klicali tiste, ki jih potrebujemo v
# 2. fazi. Seveda bi morali ustrezno datoteko uvoziti v prihodnjih
# fazah.

# Funkcija, ki uvozi podatke iz datoteke druzine.csv

#Podatki za Slovenijo

         tabela_vozači_SLO<-read.csv2("podatki/vozaci.csv", skip=1,na.strings = "-", stringsAsFactors = FALSE,
                                  fileEncoding = "UTF-8", col.names = c("Vrsta prevoza","Leto", "Število potnikov"))
  
         tabela_registracije_SLO<-read.csv2("podatki/registracije.csv",na.strings = "-",stringsAsFactors = FALSE,
                                  fileEncoding = "Windows-1250",col.names = c("Leto","2004", "2005","2006","2007","2008","2009","2010","2011","2012","2013","2014"))
         names(tabela_registracije_SLO)<-gsub("X","",names(tabela_registracije_SLO))
         tabela_registracije_SLO<-melt(tabela_registracije_SLO, na.rm=FALSE,"Leto")
         names(tabela_registracije_SLO)<-c("","Leto","Stevilo")
         
         
         tabela_indeks_cen_mot_voz_SLO<-read.csv2("podatki/indeks_cen_mot_voz_SLO.csv",skip=1,na.strings="-",stringsAsFactors = FALSE,
                                  fileEncoding = "Windows-1250",col.names = c("","Leto","Tekoči mesec na isti mesec prejšnjega leta"))
         names(tabela_indeks_cen_mot_voz_SLO)<-gsub("X","",names(tabela_indeks_cen_mot_voz_SLO))
         
         tabela_prometne_nesrece_SLO<-tabela_prometne_nesrece_SLO<-read.csv2("podatki/prometne_nesrece_SLO.csv",na.strings="-",stringsAsFactors = FALSE,
                                  fileEncoding = "Windows-1250",col.names =c("Leto","2004", "2005","2006","2007","2008","2009","2010","2011","2012","2013","2014"))
         names(tabela_prometne_nesrece_SLO)<-gsub("X","",names(tabela_prometne_nesrece_SLO))
         tabela_prometne_nesrece_SLO<-melt(tabela_prometne_nesrece_SLO, na.rm=FALSE,"Leto")
         names(tabela_prometne_nesrece_SLO)<-c("","Leto","Kolicina")
         
         
        
         tabela_dolzina_cest_SLO<-read.csv2("podatki/dolzina_cest_SLO.csv",na.strings="-",stringsAsFactors = FALSE,fileEncoding = "Windows-1250")
         
         
         tabela_Cestni_javni_linijski_prevoz_medkrajevni_in_mednarodni_SLO<-read.csv2("podatki/Cestni_javni_linijski_prevoz_medkrajevni_in_mednarodni.csv",
                                                                                  na.strings="-",stringsAsFactors = FALSE, fileEncoding = "Windows-1250",
                                                                                  col.names=c("Leto","Potniki v 1000","Potniški kilometri v mio"))
         
         tabela_prve_reg_vrsta_vozila_SLO_vsa<-read.csv2("podatki/prve_reg_vrsta_vozila_SLO.csv",na.strings="-",stringsAsFactors = FALSE,
                                                     fileEncoding = "Windows-1250")
         names(tabela_prve_reg_vrsta_vozila_SLO_vsa)<-gsub("X","", names(tabela_prve_reg_vrsta_vozila_SLO_vsa))
         
         tabela_vozila_na_gorivo_SLO<-read.csv2("podatki/vozila_na_gorivo.csv",na.strings="",stringsAsFactors = FALSE,
                                            fileEncoding = "Windows-1250",col.names = c("Tip_vozila","Gorivo","Dan","2004", "2005","2006","2007","2008","2009","2010","2011","2012","2013"))
         names(tabela_vozila_na_gorivo_SLO)<-gsub("X","",names(tabela_vozila_na_gorivo_SLO))
         tabela_vozila_na_gorivo_SLO<-melt(tabela_vozila_na_gorivo_SLO, na.rm=FALSE,c("Tip_vozila","Gorivo","Dan"))
         names(tabela_vozila_na_gorivo_SLO)<-c("Tip vozila","Gorivo","Dan","Leto","Kolicina")
         
         
         
         tabela_starost_vozil_SLO<-read.csv2("podatki/starost_vozil_SLO.csv",na.strings="",stringsAsFactors = FALSE,
                                             fileEncoding = "windows-1250",col.names = c("Tip_vozila","Starost","2004", "2005","2006","2007","2008","2009","2010","2011","2012","2013","2014"))
         names(tabela_starost_vozil_SLO)<-gsub("X","",names(tabela_starost_vozil_SLO))
         tabela_starost_vozil_SLO<-melt(tabela_starost_vozil_SLO, na.rm=FALSE,c("Tip_vozila","Starost"))
         names(tabela_starost_vozil_SLO)<-c("Tip_vozila","Starost","Leto","Kolicina")
         
#Podatki za Eu
         
         tabela_EU_vozaci<-read.csv2("podatki/EU_vozaci.csv",na.strings=":",stringsAsFactors = FALSE, 
                                     fileEncoding = "windows-1250")
         names(tabela_EU_vozaci)<-gsub("X","",names(tabela_EU_vozaci))
         tabela_EU_vozaci<-melt(tabela_EU_vozaci, na.rm=FALSE,"GEO.TIME")
         names(tabela_EU_vozaci)<-c("Drzava","Leto","Stevilo vozacev")
         tabela_EU_vozaci<-tabela_EU_vozaci[ !tabela_EU_vozaci$Drzava %in% c(""),]
         tabela_EU_vozaci$`Stevilo vozacev` <- tabela_EU_vozaci$`Stevilo vozacev` %>% {gsub("\\.", "", .)} %>% {gsub(",", ".", .)} %>% as.numeric()
         tabela_EU_vozaci$`Stevilo vozacev` <- gsub("\\.", "", tabela_EU_vozaci$`Stevilo vozacev`) %>% as.numeric()
         tabela_EU_vozaci$Drzava[grep("Germany",tabela_EU_vozaci$Drzava)] <- "Germany"
         tabela_EU_vozaci$Drzava[grep("Former Yugoslav",tabela_EU_vozaci$Drzava)] <- "Macedonia, FYR"
         
         
         
         
         tabela_EU_registracije_ostalo<-read.csv2("podatki/EU_registracije_ostalo.csv",na.strings=":",stringsAsFactors = FALSE, 
                                                      fileEncoding = "windows-1250")
         names(tabela_EU_registracije_ostalo)<-gsub("X","",names(tabela_EU_registracije_ostalo))
         tabela_EU_registracije_ostalo<-melt(tabela_EU_registracije_ostalo, na.rm=FALSE,"GEO.TIME")
         names(tabela_EU_registracije_ostalo)<-c("Drzava","Leto","Registracije ostalih vozil")
        
         
         tabela_EU_prevozeni_km<-read.csv2("podatki/EU_prevozeni_km.csv",na.strings=":",stringsAsFactors = FALSE, 
                                                  fileEncoding = "windows-1250")
         names(tabela_EU_prevozeni_km)<-gsub("X","",names(tabela_EU_prevozeni_km))
         tabela_EU_prevozeni_km<-melt(tabela_EU_prevozeni_km, na.rm=FALSE,"GEO.TIME")
         names(tabela_EU_prevozeni_km)<-c("Drzava","Leto","Prevozeni km")
         
         
         

         
           
         tabela_EU_stevilo_umrlih_prometne_nesrece<-read.csv2("podatki/EU_stevilo_umrlih_prometne_nesrece.csv",na.strings=":",stringsAsFactors = FALSE, 
                                                              fileEncoding = "windows-1250")
         names(tabela_EU_stevilo_umrlih_prometne_nesrece)<-gsub("X","",names(tabela_EU_stevilo_umrlih_prometne_nesrece))
         tabela_EU_stevilo_umrlih_prometne_nesrece<-melt(tabela_EU_stevilo_umrlih_prometne_nesrece, na.rm=FALSE,"geo.time")
         names(tabela_EU_stevilo_umrlih_prometne_nesrece)<-c("Drzava","Leto","Stevilo_umrlih")
         tabela_EU_stevilo_umrlih_prometne_nesrece<-tabela_EU_stevilo_umrlih_prometne_nesrece[ !tabela_EU_stevilo_umrlih_prometne_nesrece$Drzava %in% c(""),]
         rownames(tabela_EU_stevilo_umrlih_prometne_nesrece)<-c(1:480)
         tabela_EU_stevilo_umrlih_prometne_nesrece<-tabela_EU_stevilo_umrlih_prometne_nesrece[-c(1:162),]
         tabela_EU_stevilo_umrlih_prometne_nesrece<-tabela_EU_stevilo_umrlih_prometne_nesrece[!tabela_EU_stevilo_umrlih_prometne_nesrece$Drzava %in% c("EU (28 countries)","EU (27 countries)"),]
         tabela_EU_stevilo_umrlih_prometne_nesrece$Drzava[grep("Germany",tabela_EU_stevilo_umrlih_prometne_nesrece$Drzava)] <- "Germany"
        
         
         tabela_EU_registracije_avtomobili<-read.csv2("podatki/EU_registracije.csv",na.strings=":",stringsAsFactors = FALSE, 
                                                      fileEncoding = "windows-1250")
         names(tabela_EU_registracije_avtomobili)<-gsub("X","",names(tabela_EU_registracije_avtomobili))
         tabela_EU_registracije_avtomobili<-melt(tabela_EU_registracije_avtomobili, na.rm=FALSE,"GEO.TIME")
         names(tabela_EU_registracije_avtomobili)<-c("Drzava","Leto","Stevilo_registracij")
         tabela_EU_registracije_avtomobili$`Stevilo_registracij` <- gsub("\\.", "", tabela_EU_registracije_avtomobili$`Stevilo_registracij`) %>% as.numeric()
         tabela_EU_registracije_avtomobili$Drzava[grep("Germany",tabela_EU_registracije_avtomobili$Drzava)] <- "Germany"
         tabela_EU_registracije_avtomobili$Drzava[grep("Former Yugoslav",tabela_EU_registracije_avtomobili$Drzava)] <- "Macedonia, FYR"
         tabela_zemljevid<-tabela_EU_registracije_avtomobili
         tabela_EU_registracije_avtomobili$vozaci<-tabela_EU_vozaci$`Stevilo vozacev`
         tabela_EU_registracije_avtomobili$nesrece<-tabela_EU_stevilo_umrlih_prometne_nesrece$`Stevilo_umrlih`
         
         
         
         
         Leto<-tabela_Cestni_javni_linijski_prevoz_medkrajevni_in_mednarodni_SLO$Leto
         Število.v.tisočih<-tabela_Cestni_javni_linijski_prevoz_medkrajevni_in_mednarodni_SLO$Potniki.v.1000
         
         Vozaci<-ggplot(tabela_Cestni_javni_linijski_prevoz_medkrajevni_in_mednarodni_SLO)+
           aes(x=Leto,y=Število.v.tisočih)+
           geom_line(colour="red")+
           ggtitle("Vozači v javnem linijskem prevozu(medkrajevni in mednarodni) ")+
           theme(plot.title = element_text(lineheight=.8, face="bold"))
         

         
         
         
         
         
 #html

         
         url<-'http://left-lane.com/european-car-sales-data/audi/'
         
         stran <- html_session(url) %>% read_html(encoding = "Windows-1250")
         Audi_prodaja<- stran %>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Audi_prodaja<-Audi_prodaja[-1,]
         names(Audi_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Audi_prodaja$Mesec <- factor(Audi_prodaja$Mesec, levels =Audi_prodaja$Mesec,
                                       Audi_prodaja$Mesec, ordered = TRUE)
         Audi_prodaja[-1] <- apply(Audi_prodaja[-1], 2, as.numeric)
         Audi_prodaja$Povprečno <- apply(Audi_prodaja[-1], 1, mean, na.rm = TRUE)
         Audi_prodaja$Povprečno<-round(Audi_prodaja$Povprečno,3)
         Audi_prodaja$Proizvajalec <- "Audi"

         
         url2<-'http://left-lane.com/european-car-sales-data/bmw/'
         stran2<-html_session(url2) %>% read_html(encoding = "Windows-1250")
         
         Bmw_prodaja<-stran2%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         names(Bmw_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Bmw_prodaja<-Bmw_prodaja[-1,]
         Bmw_prodaja$Mesec <- factor(Bmw_prodaja$Mesec, levels =
                                        Bmw_prodaja$Mesec, ordered = TRUE)
         Bmw_prodaja[-1] <- apply(Bmw_prodaja[-1], 2, as.numeric)
         Bmw_prodaja$Povprečno <- apply(Bmw_prodaja[-1], 1, mean, na.rm = TRUE)
         Bmw_prodaja$Povprečno<-round(Bmw_prodaja$Povprečno,3)
         Bmw_prodaja$Proizvajalec <- "Bmw"
         
         url3<-'http://left-lane.com/european-car-sales-data/citroen/'
         stran3<-html_session(url3) %>% read_html(encoding = "Windows-1250")
         Citroen_prodaja<-stran3%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Citroen_prodaja<-Citroen_prodaja[-1,]
         names(Citroen_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Citroen_prodaja$Povprečno<-round((as.numeric(Citroen_prodaja$`2012`)+as.numeric(Citroen_prodaja$`2013`)+as.numeric(Citroen_prodaja$`2014`)+as.numeric(Citroen_prodaja$`2015`))/4,3)
         Citroen_prodaja$Mesec <- factor(Citroen_prodaja$Mesec, levels =
                                       Citroen_prodaja$Mesec, ordered = TRUE)
         Citroen_prodaja[-1] <- apply(Citroen_prodaja[-1], 2, as.numeric)
         Citroen_prodaja$Povprečno <- apply(Citroen_prodaja[-1], 1, mean, na.rm = TRUE)
         Citroen_prodaja$Povprečno<-round(Citroen_prodaja$Povprečno,3)
         Citroen_prodaja$Proizvajalec <- "Citroen"
         
         url4<-'http://left-lane.com/european-car-sales-data/ford/'
         stran4<-html_session(url4) %>% read_html(encoding = "Windows-1250")
         Ford_prodaja<-stran4%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Ford_prodaja<-Ford_prodaja[-1,]
         names(Ford_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Ford_prodaja$Povprečno<-round((as.numeric(Ford_prodaja$`2012`)+as.numeric(Ford_prodaja$`2013`)+as.numeric(Ford_prodaja$`2014`)+as.numeric(Ford_prodaja$`2015`))/4,3)
         Ford_prodaja$Mesec <- factor(Ford_prodaja$Mesec, levels =
                                       Ford_prodaja$Mesec, ordered = TRUE)
         Ford_prodaja[-1] <- apply(Ford_prodaja[-1], 2, as.numeric)
         Ford_prodaja$Povprečno <- apply(Ford_prodaja[-1], 1, mean, na.rm = TRUE)
         Ford_prodaja$Povprečno<-round(Ford_prodaja$Povprečno,3)
         Ford_prodaja$Proizvajalec <- "Ford"
         
         url5<-'http://left-lane.com/european-car-sales-data/fiat/'
         stran5<-html_session(url5) %>% read_html(encoding = "Windows-1250")
         Fiat_prodaja<-stran5%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Fiat_prodaja<-Fiat_prodaja[-1,]
         names(Fiat_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Fiat_prodaja$Povprečno<-round((as.numeric(Fiat_prodaja$`2012`)+as.numeric(Fiat_prodaja$`2013`)+as.numeric(Fiat_prodaja$`2014`)+as.numeric(Fiat_prodaja$`2015`))/4,3)
         Fiat_prodaja$Mesec <- factor(Fiat_prodaja$Mesec, levels =
                                       Fiat_prodaja$Mesec, ordered = TRUE)
         Fiat_prodaja[-1] <- apply(Fiat_prodaja[-1], 2, as.numeric)
         Fiat_prodaja$Povprečno <- apply(Fiat_prodaja[-1], 1, mean, na.rm = TRUE)
         Fiat_prodaja$Povprečno<-round(Fiat_prodaja$Povprečno,3)
         Fiat_prodaja$Proizvajalec <- "Fiat"
         
         url6<-'http://left-lane.com/european-car-sales-data/mazda/'
         stran6<-html_session(url6) %>% read_html(encoding = "Windows-1250")
         Mazda_prodaja<-stran6%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Mazda_prodaja<-Mazda_prodaja[-1,]
         names(Mazda_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Mazda_prodaja$Povprečno<-round((as.numeric(Mazda_prodaja$`2012`)+as.numeric(Mazda_prodaja$`2013`)+as.numeric(Mazda_prodaja$`2014`)+as.numeric(Mazda_prodaja$`2015`))/4,3)
         Mazda_prodaja$Mesec <- factor(Mazda_prodaja$Mesec, levels =
                                       Mazda_prodaja$Mesec, ordered = TRUE)
         Mazda_prodaja[-1] <- apply(Mazda_prodaja[-1], 2, as.numeric)
         Mazda_prodaja$Povprečno <- apply(Mazda_prodaja[-1], 1, mean, na.rm = TRUE)
         Mazda_prodaja$Povprečno<-round(Mazda_prodaja$Povprečno,3)
         Mazda_prodaja$Proizvajalec <- "Mazda"
         
         url7<-'http://left-lane.com/european-car-sales-data/peugeot/'
         stran7<-html_session(url7) %>% read_html(encoding = "Windows-1250")
         Peugeot_prodaja<-stran7%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Peugeot_prodaja<-Peugeot_prodaja[-1,]
         names(Peugeot_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Peugeot_prodaja$Povprečno<-round((as.numeric(Peugeot_prodaja$`2012`)+as.numeric(Peugeot_prodaja$`2013`)+as.numeric(Peugeot_prodaja$`2014`)+as.numeric(Peugeot_prodaja$`2015`))/4,3)
         Peugeot_prodaja$Mesec <- factor(Peugeot_prodaja$Mesec, levels =
                                       Peugeot_prodaja$Mesec, ordered = TRUE)
         Peugeot_prodaja[-1] <- apply(Peugeot_prodaja[-1], 2, as.numeric)
         Peugeot_prodaja$Povprečno <- apply(Peugeot_prodaja[-1], 1, mean, na.rm = TRUE)
         Peugeot_prodaja$Povprečno<-round(Peugeot_prodaja$Povprečno,3)
         Peugeot_prodaja$Proizvajalec <- "Peugeot"
         
         url8<-'http://left-lane.com/european-car-sales-data/renault/'
         stran8<-html_session(url8) %>% read_html(encoding = "Windows-1250")
         Renault_prodaja<-stran8%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Renault_prodaja<-Renault_prodaja[-1,]
         names(Renault_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Renault_prodaja$Povprečno<-round((as.numeric(Renault_prodaja$`2012`)+as.numeric(Renault_prodaja$`2013`)+as.numeric(Renault_prodaja$`2014`)+as.numeric(Renault_prodaja$`2015`))/4,3)
         Renault_prodaja$Mesec <- factor(Renault_prodaja$Mesec, levels =
                                       Renault_prodaja$Mesec, ordered = TRUE)
         Renault_prodaja[-1] <- apply(Renault_prodaja[-1], 2, as.numeric)
         Renault_prodaja$Povprečno <- apply(Renault_prodaja[-1], 1, mean, na.rm = TRUE)
         Renault_prodaja$Povprečno<-round(Renault_prodaja$Povprečno,3)
         Renault_prodaja$Proizvajalec <- "Renault"
         
         url9<-'http://left-lane.com/european-car-sales-data/opel-vauxhall/'
         stran9<-html_session(url9) %>% read_html(encoding = "Windows-1250")
         Opel_prodaja<-stran9%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Opel_prodaja<-Opel_prodaja[-1,]
         names(Opel_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Opel_prodaja$Povprečno<-round((as.numeric(Opel_prodaja$`2012`)+as.numeric(Opel_prodaja$`2013`)+as.numeric(Opel_prodaja$`2014`)+as.numeric(Opel_prodaja$`2015`))/4,3)
         Opel_prodaja$Mesec <- factor(Opel_prodaja$Mesec, levels =
                                       Opel_prodaja$Mesec, ordered = TRUE)
         Opel_prodaja[-1] <- apply(Opel_prodaja[-1], 2, as.numeric)
         Opel_prodaja$Povprečno <- apply(Opel_prodaja[-1], 1, mean, na.rm = TRUE)
         Opel_prodaja$Povprečno<-round(Opel_prodaja$Povprečno,3)
         Opel_prodaja$Proizvajalec <- "Opel"
         

         graf_Mazda<-ggplot(Mazda_prodaja, aes(x=Mesec, y=Povprečno, group=1)) + geom_line(colour="red")+
                               ggtitle("Povprečna prodaja avtomobilov\nznamke Mazda(2012-2015) v tisočih po mesecih")+
                               theme(plot.title = element_text(lineheight=.8, face="bold"),axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) 
  
         
         graf_Ford<-ggplot(Ford_prodaja, aes(x=Mesec, y=Povprečno, group=1)) + geom_line(colour="blue")+
                               ggtitle("Povprečna prodaja avtomobilov\nznamke Ford(2012-2015) v tisočih po mesecih")+
                               theme(plot.title = element_text(lineheight=.8, face="bold"),axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
        
         Prodaja <- rbind(Audi_prodaja, Bmw_prodaja,Citroen_prodaja,Ford_prodaja,Fiat_prodaja,Mazda_prodaja,Peugeot_prodaja,Renault_prodaja,Opel_prodaja) 
         skupni_graf<-ggplot(Prodaja, aes(x=Mesec, y=Povprečno, group=Proizvajalec, color =
                               Proizvajalec)) + geom_line() +
                               ggtitle("Povprečna prodaja avtomobilov po\nznamkah(2012-2015) v Europi po mesecih v tisočih")+
                               theme(plot.title = element_text(lineheight=.8, face="bold"),axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
         
         Prodaja<-melt(Prodaja, na.rm=FALSE , "Mesec")
         names(Prodaja)<-c("Mesec","Leto", "Stevilo_prodanih_avtomobilov")
         
         
      #' @export
CalcAlleleDiffs <- function(f){
  infoTable <- as.matrix(read.csv(f, header=TRUE))
  BEG1 <- as.numeric(infoTable[1,2])
  END1 <- as.numeric(infoTable[2,2])
  str1 <- toString(infoTable[4,2])
  
  for(j in BEG1:END1){
    filePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4.txt"), collapse = "")	
    if (file.exists(filePath) == TRUE){
    outFilePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4_diffs.txt"), collapse = "")	
    outTable <- matrix(nrow = 1, ncol = 8)	
    k <-scan(filePath, sep = ">", what = "complex")	
    for(i in seq(2,length(k),12)){
      textMat <- matrix(nrow = 6, ncol = 8)
      allele <- strsplit(k[i],".", fixed = TRUE)
      locus <- strsplit(allele[[1]][1],"L")[[1]][2]
      copy <- allele[[1]][2]
      alleleNumber <- allele[[1]][3]
      a1 <- k[i+1]
      a2 <- k[i+4]
      a3 <- k[i+7]
      a4 <- k[i+10]
      textMat[,c(1,4)] <- locus
      textMat[,c(2,5)] <- copy
      textMat[,3] <- c(1,1,1,2,2,3)
      textMat[,6] <- c(2,3,4,3,4,4)
      textMat[,7] <- c(adist(a1,a2),adist(a1,a3), adist(a1,a4), adist(a2,a3), adist(a2,a4), adist(a3,a4))
      textMat[,8] <- nchar(a1)
      outTable <- rbind(outTable,textMat)
    }
    outTable <- outTable[2:length(outTable[,1]),]
    write.table(outTable,file = outFilePath, quote = FALSE, sep = "\t", row.names = FALSE, col.names = FALSE)
    print(j)
    
    }
    else {
     print(paste(c("I",j," FILE NOT FOUND"), collapse = ""), quote = FALSE)
    }
    
  }
  assign("infoTable",infoTable,globalenv())
}
#' @export
CalcAlleleDiffs <- function(f){
  infoTable <- as.matrix(read.csv(f, header=TRUE))
  BEG1 <- as.numeric(infoTable[1,2])
  END1 <- as.numeric(infoTable[2,2])
  str1 <- toString(infoTable[4,2])
  
  for(j in BEG1:END1){
    filePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4.txt"), collapse = "")	
    if (file.exists(filePath) == TRUE){
    print("frig")
    outFilePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4_diffs.txt"), collapse = "")	
    outTable <- matrix(nrow = 1, ncol = 8)	
    k <-scan(filePath, sep = ">", what = "complex")	
    for(i in seq(2,length(k),12)){
      textMat <- matrix(nrow = 6, ncol = 8)
      allele <- strsplit(k[i],".", fixed = TRUE)
      locus <- strsplit(allele[[1]][1],"L")[[1]][2]
      copy <- allele[[1]][2]
      alleleNumber <- allele[[1]][3]
      a1 <- k[i+1]
      a2 <- k[i+4]
      a3 <- k[i+7]
      a4 <- k[i+10]
      textMat[,c(1,4)] <- locus
      textMat[,c(2,5)] <- copy
      textMat[,3] <- c(1,1,1,2,2,3)
      textMat[,6] <- c(2,3,4,3,4,4)
      textMat[,7] <- c(adist(a1,a2),adist(a1,a3), adist(a1,a4), adist(a2,a3), adist(a2,a4), adist(a3,a4))
      textMat[,8] <- nchar(a1)
      outTable <- rbind(outTable,textMat)
    }
    outTable <- outTable[2:length(outTable[,1]),]
    write.table(outTable,file = outFilePath, quote = FALSE, sep = "\t", row.names = FALSE, col.names = FALSE)
    print(j)
    
    }
    else {
     print(paste(c("I",j," FILE NOT FOUND"), collapse = ""), quote = FALSE)
    }
    
  }
  assign("infoTable",infoTable,globalenv())
}
#' @export
CalcAlleleDiffs <- function(f){
  infoTable <- as.matrix(read.csv(f, header=TRUE))
  BEG1 <- as.numeric(infoTable[1,2])
  END1 <- as.numeric(infoTable[2,2])
  str1 <- toString(infoTable[4,2])
  
  for(j in BEG1:END1){
    filePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4.txt"), collapse = "")	
    if (file.exists(filePath) == TRUE){
    outFilePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4_diffs.txt"), collapse = "")	
    outTable <- matrix(nrow = 1, ncol = 8)	
    k <-scan(filePath, sep = ">", what = "complex")	
    for(i in seq(2,length(k),12)){
      textMat <- matrix(nrow = 6, ncol = 8)
      allele <- strsplit(k[i],".", fixed = TRUE)
      locus <- strsplit(allele[[1]][1],"L")[[1]][2]
      copy <- allele[[1]][2]
      alleleNumber <- allele[[1]][3]
      a1 <- k[i+1]
      a2 <- k[i+4]
      a3 <- k[i+7]
      a4 <- k[i+10]
      textMat[,c(1,4)] <- locus
      textMat[,c(2,5)] <- copy
      textMat[,3] <- c(1,1,1,2,2,3)
      textMat[,6] <- c(2,3,4,3,4,4)
      textMat[,7] <- c(adist(a1,a2),adist(a1,a3), adist(a1,a4), adist(a2,a3), adist(a2,a4), adist(a3,a4))
      textMat[,8] <- nchar(a1)
      outTable <- rbind(outTable,textMat)
    }
    outTable <- outTable[2:length(outTable[,1]),]
    write.table(outTable,file = outFilePath, quote = FALSE, sep = "\t", row.names = FALSE, col.names = FALSE)
    print(j)
    
    }
    else {
     print(paste(c("I",j," FILE NOT FOUND"), collapse = ""), quote = FALSE)
    }
    
  }
  assign("infoTable",infoTable,globalenv())
}
#' @export
CalcAlleleDiffs <- function(f){
  infoTable <- as.matrix(read.csv(f, header=TRUE))
  BEG1 <- as.numeric(infoTable[1,2])
  END1 <- as.numeric(infoTable[2,2])
  str1 <- toString(infoTable[4,2])
  
  for(j in BEG1:END1){
    if (file.exists(filePath) == TRUE){
    
    filePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4.txt"), collapse = "")	
    outFilePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4_diffs.txt"), collapse = "")	
    outTable <- matrix(nrow = 1, ncol = 8)	
    k <-scan(filePath, sep = ">", what = "complex")	
    for(i in seq(2,length(k),12)){
      textMat <- matrix(nrow = 6, ncol = 8)
      allele <- strsplit(k[i],".", fixed = TRUE)
      locus <- strsplit(allele[[1]][1],"L")[[1]][2]
      copy <- allele[[1]][2]
      alleleNumber <- allele[[1]][3]
      a1 <- k[i+1]
      a2 <- k[i+4]
      a3 <- k[i+7]
      a4 <- k[i+10]
      textMat[,c(1,4)] <- locus
      textMat[,c(2,5)] <- copy
      textMat[,3] <- c(1,1,1,2,2,3)
      textMat[,6] <- c(2,3,4,3,4,4)
      textMat[,7] <- c(adist(a1,a2),adist(a1,a3), adist(a1,a4), adist(a2,a3), adist(a2,a4), adist(a3,a4))
      textMat[,8] <- nchar(a1)
      outTable <- rbind(outTable,textMat)
    }
    outTable <- outTable[2:length(outTable[,1]),]
    write.table(outTable,file = outFilePath, quote = FALSE, sep = "\t", row.names = FALSE, col.names = FALSE)
    print(j)
    
    }
    else {
     print(paste(c("I",j," FILE NOT FOUND"), collapse = ""), quote = FALSE)
    }
    
  }
  assign("infoTable",infoTable,globalenv())
}
#!/usr/bin/env RScript
library(parallel)
library(iterators)
library(foreach)
library(doParallel)
library(proto)
library(argparse)

parser <- ArgumentParser()
parser$add_argument('input', help = 'input csv file')
parser$add_argument('gameplayInput', help = 'input gameplay video')
parser$add_argument('output', help = 'output video file')
parser$add_argument('--fps', type = 'integer', default = 3, help = 'frames per second')
parser$add_argument('--dpi', type = 'integer', default = 72, help = 'dpi for generated video frames')
parser$add_argument('--tempdir', help = 'working directory for intermediate files')
parser$add_argument('--graphcolour', default = 'red')
args <- parser$parse_args()

main <- function()
{
	fps <- args$fps
	input <- args$input
	gameplayInput <- args$gameplayInput
	output <- args$output
	dpi <- args$dpi
	frameDir <- if (is.null(args$tempdir)) tempdir() else args$tempdir
	graphColour <- args$graphcolour

	videoAttrs <- system(paste0('ffprobe -v error -show_entries stream=width,height,r_frame_rate ',
		'-of default=noprint_wrappers=1:nokey=1 ', gameplayInput), intern = T)

	videoRes = as.integer(videoAttrs[1:2])
	videoSize = videoRes / dpi
	fpsTokens = as.integer(unlist(strsplit(videoAttrs[3], '/')[1]))
	gameplayFps <- fpsTokens[1] / fpsTokens[2]
	dar <- paste0(videoRes[1], '/', videoRes[2])

	message('Input gameplay runs at ', gameplayFps, ' FPS at ', videoRes[1], 'x', videoRes[2])

	data <- read.csv(input)
	data$offsetSeconds = data$offset / 1000

	duration <- max(data$offsetSeconds)
	frames <- floor(duration * fps)
	cores <- detectCores()
	message('Rendering ', frames, ' frames using ', cores, ' cores')

	cluster <- makeCluster(cores)
	registerDoParallel(cluster)

	foreach(i = 1:frames, .packages = 'ggplot2') %dopar% {
		toRender <- subset(data, offset < i / fps * 1000)
		plot <- ggplot(toRender, aes(x = offsetSeconds, y = value)) +
			geom_line(color = graphColour, size = 2) +
			labs(x = 'Time (s)', y = 'GSR (microsiemens)') +
			ylim(c(0, ceiling(max(data$value)))) +
			xlim(c(0, duration)) +
			theme(plot.background = element_rect(fill = 'transparent'),
				panel.background = element_blank())
		ggsave(paste0(frameDir, '/', i, '.png'), plot,
			width = videoSize[1], height = videoSize[2], dpi = dpi, bg = 'transparent')
	}

	stopCluster(cluster)

	fpsRatio <- gameplayFps / fps
	tempVideoPath = paste0(frameDir, '/', 'frames.mov')
	message('Rendering video from frames: ', tempVideoPath)
	system(paste0('ffmpeg -v error -y -r ', gameplayFps, ' -framerate ', fps,
		' -i "', frameDir, '/%d.png" ',
		' -filter:v "setpts=', fpsRatio, '*PTS" -vcodec qtrle ', tempVideoPath))

	message('Merging with gameplay')
	system(paste0('ffmpeg -v error -y -r ', gameplayFps, ' -i "', gameplayInput, '" -i "', tempVideoPath, '" ',
		' -filter_complex "[0:v]format=rgba[a];',
		'[1:v]setdar=', dar, ',format=yuva420p,colorchannelmixer=aa=0.1[b];',
		'[a][b]overlay=shortest=1"',
		' ', output))
}

dummy <- main()#!/usr/bin/env RScript
library(parallel)
library(iterators)
library(foreach)
library(doParallel)
library(proto)
library(argparse)

parser <- ArgumentParser()
parser$add_argument('input', help = 'input csv file')
parser$add_argument('gameplayInput', help = 'input gameplay video')
parser$add_argument('output', help = 'output video file')
parser$add_argument('--fps', type = 'integer', default = 3, help = 'frames per second')
parser$add_argument('--dpi', type = 'integer', default = 72, help = 'dpi for generated video frames')
parser$add_argument('--tempdir', help = 'working directory for intermediate files')
args <- parser$parse_args()

main <- function()
{
	fps <- args$fps
	input <- args$input
	gameplayInput <- args$gameplayInput
	output <- args$output
	dpi <- args$dpi
	frameDir <- if (is.null(args$tempdir)) tempdir() else args$tempdir

	videoAttrs <- system(paste0('ffprobe -v 1 -show_entries stream=width,height,r_frame_rate ',
		'-of default=noprint_wrappers=1:nokey=1 ', gameplayInput), intern = T)

	videoRes = as.integer(videoAttrs[1:2])
	videoSize = videoRes / dpi
	fpsTokens = as.integer(unlist(strsplit(videoAttrs[3], '/')[1]))
	gameplayFps <- fpsTokens[1] / fpsTokens[2]
	dar <- paste0(videoRes[1], '/', videoRes[2])

	message('Input gameplay runs at ', gameplayFps, ' FPS at ', videoRes[1], 'x', videoRes[2])

	data <- read.csv(input)
	data$offsetSeconds = data$offset / 1000

	duration <- max(data$offsetSeconds)
	frames <- floor(duration * fps)
	cores <- detectCores()
	message('Rendering ', frames, ' frames using ', cores, ' cores')

	cluster <- makeCluster(cores)
	registerDoParallel(cluster)

	foreach(i = 1:frames, .packages = 'ggplot2') %dopar% {
		toRender <- subset(data, offset < i / fps * 1000)
		plot <- ggplot(toRender, aes(x = offsetSeconds, y = value)) +
			geom_line() +
			labs(x = 'Time (s)', y = 'GSR (microsiemens)') +
			ylim(c(0, ceiling(max(data$value)))) +
			xlim(c(0, duration))
		ggsave(paste0(frameDir, '/', i, '.jpg'), plot,
			width = videoSize[1], height = videoSize[2], dpi = dpi)
	}

	stopCluster(cluster)

	fpsRatio <- gameplayFps / fps 
	tempVideoPath = paste0(frameDir, '/', 'frames.mp4')
	message('Rendering video from frames: ', tempVideoPath)
	system(paste0('ffmpeg -v 1 -y -r ', gameplayFps, ' -framerate ', fps,
		' -i "', frameDir, '/%d.jpg" ', ' -filter:v "setpts=', fpsRatio, '*PTS" ', tempVideoPath))

	message('Merging with gameplay')
	system(paste0('ffmpeg -v 1 -y -r ', gameplayFps, ' -i "', gameplayInput, '" -i "', tempVideoPath, '" ',
		' -filter_complex "[1:0]format=rgba[a];',
		'[0:0]setdar=', dar, ',format=yuva420p,colorchannelmixer=aa=0.8[b];',
		'[a][b]overlay=shortest=1"',
		' ', output))
}

dummy <- main()#!/usr/bin/env RScript
library(parallel)
library(iterators)
library(foreach)
library(doParallel)
library(proto)
library(argparse)

parser <- ArgumentParser()
parser$add_argument('input', help = 'input csv file')
parser$add_argument('gameplayInput', help = 'input gameplay video')
parser$add_argument('output', help = 'output video file')
parser$add_argument('--fps', type = 'integer', default = 3, help = 'frames per second')
parser$add_argument('--dpi', type = 'integer', default = 72, help = 'dpi for generated video frames')
parser$add_argument('--tempdir', default = tempdir(), help = 'working directory for intermediate files')
args <- parser$parse_args()

main <- function()
{
	fps <- args$fps
	input <- args$input
	gameplayInput <- args$gameplayInput
	output <- args$output
	dpi <- args$dpi
	frameDir <- args$tempdir

	videoAttrs <- system(paste0('ffprobe -v 1 -show_entries stream=width,height,r_frame_rate ',
		'-of default=noprint_wrappers=1:nokey=1 ', gameplayInput), intern = T)

	videoRes = as.integer(videoAttrs[1:2])
	videoSize = videoRes / dpi
	fpsTokens = as.integer(unlist(strsplit(videoAttrs[3], '/')[1]))
	gameplayFps <- fpsTokens[1] / fpsTokens[2]
	dar <- paste0(videoRes[1], '/', videoRes[2])

	message('Input gameplay runs at ', gameplayFps, ' FPS at ', videoRes[1], 'x', videoRes[2])

	data <- read.csv(input)
	data$offsetSeconds = data$offset / 1000

	duration <- max(data$offsetSeconds)
	frames <- floor(duration * fps)
	cores <- detectCores()
	message('Rendering ', frames, ' frames using ', cores, ' cores')

	cluster <- makeCluster(cores)
	registerDoParallel(cluster)

	foreach(i = 1:frames, .packages = 'ggplot2') %dopar% {
		toRender <- subset(data, offset < i / fps * 1000)
		plot <- ggplot(toRender, aes(x = offsetSeconds, y = value)) +
			geom_line() +
			labs(x = 'Time (s)', y = 'GSR (microsiemens)') +
			ylim(c(0, ceiling(max(data$value)))) +
			xlim(c(0, duration))
		ggsave(paste0(frameDir, '/', i, '.jpg'), plot,
			width = videoSize[1], height = videoSize[2], dpi = dpi)
	}

	stopCluster(cluster)

	fpsRatio <- gameplayFps / fps 
	tempVideoPath = paste0(frameDir, '/', 'frames.mp4')
	message('Rendering video from frames: ', tempVideoPath)
	system(paste0('ffmpeg -v 1 -y -r ', gameplayFps, ' -framerate ', fps,
		' -i "', frameDir, '/%d.jpg" ', ' -filter:v "setpts=', fpsRatio, '*PTS" ', tempVideoPath))

	message('Merging with gameplay')
	system(paste0('ffmpeg -v 1 -y -r ', gameplayFps, ' -i "', gameplayInput, '" -i "', tempVideoPath, '" ',
		' -filter_complex "[1:0]format=rgba[a];',
		'[0:0]setdar=', dar, ',format=yuva420p,colorchannelmixer=aa=0.8[b];',
		'[a][b]overlay=shortest=1"',
		' ', output))
}

dummy <- main()#!/usr/bin/env RScript
library(ggplot2)
library(proto)
library(argparse)

parser <- ArgumentParser()
parser$add_argument('input', help = 'input csv file')
parser$add_argument('output', help = 'output image file')
args <- parser$parse_args()

main <- function()
{
	data <- read.csv(args$input)
	plot <- ggplot(data, aes(x = offset / 1000, y = value)) +
		geom_line() +
		labs(x = 'Time (s)', y = 'GSR (microsiemens)') +
		ylim(c(0, ceiling(max(data$value))))

	ggsave(args$output, plot)
}

dummy <- main()#!/usr/bin/env RScript
library(parallel)
library(iterators)
library(foreach)
library(doParallel)
library(proto)
library(argparse)

parser <- ArgumentParser()
parser$add_argument('input', help = 'input csv file')
parser$add_argument('output', help = 'output video file')
parser$add_argument('--fps', type = 'integer', default = 3, help = 'frames per second')
args <- parser$parse_args()

main <- function()
{
	fps <- args$fps
	input <- args$input
	output <- args$output

	data <- read.csv(input)
	data$offsetSeconds = data$offset / 1000

	duration <- max(data$offsetSeconds)
	frames <- floor(duration * fps)
	cores <- detectCores()
	message('Rendering ', frames, ' frames using ', cores, ' cores')

	cluster <- makeCluster(cores)
	registerDoParallel(cluster)

	frameDir <- tempdir()
	foreach(i = 1:frames, .packages = 'ggplot2') %dopar% {
		toRender <- subset(data, offset < i / fps * 1000)
		plot <- ggplot(toRender, aes(x = offsetSeconds, y = value)) +
			geom_line() +
			labs(x = 'Time (s)', y = 'GSR (microsiemens)') +
			ylim(c(0, ceiling(max(data$value)))) +
			xlim(c(0, duration))
		ggsave(paste0(frameDir, '/', i, '.jpg'), plot)
	}

	stopCluster(cluster)

	message('Rendering video from frames: ', output)
	system(paste0('ffmpeg -v 1 -y -r ', fps, ' -i "', frameDir, '/%d.jpg" ', output))
}

dummy <- main()##
## Run this demo with
## mpirun -np 32 Rscript -e 'dir <- "your-airline-data-directory"; demo("matrix", package="pbdIO", echo=FALSE)'
##

## TODO Unfinished example code!
#suppressPackageStartupMessages(library(pbdMPI))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(pbdML))
suppressPackageStartupMessages(library(pbdIO))
suppressPackageStartupMessages(library(memuse))
init.grid()
a0 <- a <- deltime()

col_classes = c(rep("integer", 8), "character", "integer", "character",
    rep("integer", 5), "character", "character", rep("integer", 4),
    "character", rep("integer", 6))

## local subset of airline data - change to your data location!!
dir <- "/lustre/atlas/scratch/ost/stf006/airline"
air <- comm.fread(dir, verbose=3, colClasses=col_classes)
a <- deltime(a, "T Total comm.fread:")

## variables from the R Journal iodata article. Select for complete cases
##   rebalancing
xy_df <- subset(air, select=c(ArrDelay, DayOfWeek, DepTime, DepDelay, Month))
comm.cat("colnames(xy_df)", colnames(xy_df), "\n", quiet=TRUE)

## subset complete cases
## comm.print(xy_df[1:5, ], all.rank=TRUE)
comm.cat("nrow: ")
comm.cat(nrow(xy_df), " ", all.rank=TRUE, quiet=TRUE)
comm.cat("\n")
xy_df <- xy_df[complete.cases(xy_df), ]
comm.cat("nrow: ")
comm.cat(nrow(xy_df), " ", all.rank=TRUE, quiet=TRUE)
comm.cat("\n")
a <- deltime(a, "complete cases subset:")

## now rebalance after subsettng!
xy_df <- pbdIO:::comm.rebalance.df(xy_df, lo.side="right", type="equal", verbose=1)
a <- deltime(a, "rebalance:")

## separate x and y
x_df <- subset(xy_df, select=c(DayOfWeek, DepTime, DepDelay, Month))
y_df <- subset(xy_df, select=c(ArrDelay))
a <- deltime(a, "separate x and y df:")

## transform some variables
x_df$DayOfWeek <- factor(x_df$DayOfWeek, levels=1:7)
x_df$Month <- factor(x_df$Month, levels=1:12)
x_df$DepTime <- sprintf("%04d", x_df$DepTime)
x_df$DepTime <- as.numeric(substr(x_df$DepTime, 1, 2))*60 +
    as.numeric(substr(x_df$DepTime, 3, 4))
a <- deltime(a, "factors and transformations:")

## create model matrix
form = ~ DayOfWeek + DepTime + DepDelay + Month
x_mm <- model.matrix(form, x_df)
a <- deltime(a, "model matrix:")

## glue x_mm distributed pieces into a ddmatrix
colnames_x_mm <- colnames(x_mm)
comm.cat("colnames_x_mm:", colnames_x_mm, "\n")
dimnames(x_mm) <- NULL
xd_mm <- new("ddmatrix", Data=x_mm, dim=c(allreduce(nrow(x_mm)), ncol(x_mm)),
             ldim=dim(x_mm), bldim=dim(x_mm), ICTXT=2)
## comm.print(submatrix(xd_mm)[1:5, 1:5], all.rank=TRUE)
print(xd_mm)
a <- deltime(a, "xd_mm new ddmatrix:")

## glue y distributed pieces into a ddmatrix
y <- as.matrix(y_df)
dimnames(y) <- NULL
yd <- new("ddmatrix", Data=y, dim=c(allreduce(nrow(y)), 1),
             ldim=dim(y), bldim=dim(y), ICTXT=2)
print(yd)
a <- deltime(a, "y new ddmatrix:")

xd_mm <- as.blockcyclic(xd_mm, bldim=c(2, 2))
yd <- as.blockcyclic(yd, bldim=c(2, 2))
a <- deltime(a, "xd_mm and yd blockcyclic ddmatrix:")

beta <- lm.fit(xd_mm, yd)
coefs <- as.matrix(beta$coefficients)
rownames(coefs) <- colnames_x_mm
comm.print(coefs)
comm.print(names(beta))
a <- deltime(a, "lm.fit:")

xtx <- crossprod(xd_mm)
xty <- crossprod(xd_mm, yd)

beta.coef <- solve(xtx, xty)
beta <- as.matrix(beta.coef)
rownames(beta) <- colnames_x_mm
comm.print(beta)
a <- deltime(a, "solve crossprod:")

xsvd <- svd(xd_mm)
comm.print(xsvd$d)
a <- deltime(a, "svd xd_mm:")


a <- deltime(a0, "T Total time:")
finalize()
##
## Run this demo with
## mpirun -np 32 Rscript -e 'dir <- "your-airline-data-directory"; demo("matrix", package="pbdIO", echo=FALSE)'
##

## TODO Unfinished example code!
#suppressPackageStartupMessages(library(pbdMPI))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(pbdML))
suppressPackageStartupMessages(library(pbdIO))
suppressPackageStartupMessages(library(memuse))
init.grid()
a0 <- a <- deltime()

col_classes = c(rep("integer", 8), "character", "integer", "character",
    rep("integer", 5), "character", "character", rep("integer", 4),
    "character", rep("integer", 6))

## local subset of airline data - change to your data location!!
dir <- "/lustre/atlas/scratch/ost/stf006/airline"
air <- comm.fread(dir, verbose=3, colClasses=col_classes)
a <- deltime(a, "T Total comm.fread:")

## variables from the R Journal iodata article. Select for complete cases
##   rebalancing
xy_df <- subset(air, select=c(ArrDelay, DayOfWeek, DepTime, DepDelay, Month))
comm.cat("colnames(xy_df)", colnames(xy_df), "\n", quiet=TRUE)

## subset complete cases
## comm.print(xy_df[1:5, ], all.rank=TRUE)
comm.cat("nrow: ")
comm.cat(nrow(xy_df), " ", all.rank=TRUE, quiet=TRUE)
comm.cat("\n")
xy_df <- xy_df[complete.cases(xy_df), ]
comm.cat("nrow: ")
comm.cat(nrow(xy_df), " ", all.rank=TRUE, quiet=TRUE)
comm.cat("\n")
a <- deltime(a, "complete cases subset:")

## now rebalance after subsettng!
xy_df <- pbdIO:::comm.rebalance.df(xy_df, lo.side="right", type="equal", verbose=1)
a <- deltime(a, "rebalance:")

## separate x and y
x_df <- subset(xy_df, select=c(DayOfWeek, DepTime, DepDelay, Month))
y_df <- subset(xy_df, select=c(ArrDelay))
a <- deltime(a, "separate x and y df:")

## transform some variables
x_df$DayOfWeek <- factor(x_df$DayOfWeek, levels=1:7)
x_df$Month <- factor(x_df$Month, levels=1:12)
x_df$DepTime <- sprintf("%04d", x_df$DepTime)
x_df$DepTime <- as.numeric(substr(x_df$DepTime, 1, 2))*60 +
    as.numeric(substr(x_df$DepTime, 3, 4))
a <- deltime(a, "factors and transformations:")

## create model matrix
form = ~ DayOfWeek + DepTime + DepDelay + Month
x_mm <- model.matrix(form, x_df)
a <- deltime(a, "model matrix:")

## glue x_mm distributed pieces into a ddmatrix
colnames_x_mm <- colnames(x_mm)
comm.cat("colnames_x_mm:", colnames_x_mm, "\n")
dimnames(x_mm) <- NULL
xd_mm <- new("ddmatrix", Data=x_mm, dim=c(allreduce(nrow(x_mm)), ncol(x_mm)),
             ldim=dim(x_mm), bldim=dim(x_mm), ICTXT=2)
## comm.print(submatrix(xd_mm)[1:5, 1:5], all.rank=TRUE)
print(xd_mm)
a <- deltime(a, "xd_mm new ddmatrix:")

## glue y distributed pieces into a ddmatrix
y <- as.matrix(y_df)
dimnames(y) <- NULL
yd <- new("ddmatrix", Data=y, dim=c(allreduce(nrow(y)), 1),
             ldim=dim(y), bldim=dim(y), ICTXT=2)
print(yd)
a <- deltime(a, "y new ddmatrix:")

xd_mm <- as.blockcyclic(xd_mm, bldim=c(2, 2))
yd <- as.blockcyclic(yd, bldim=c(2, 2))
a <- deltime(a, "xd_mm and yd blockcyclic ddmatrix:")

beta <- lm.fit(xd_mm, yd)
coefs <- as.matrix(beta$coefficients)
rownames(beta) <- colnames_x_mm
comm.print(coefs)
comm.print(names(beta))
a <- deltime(a, "lm.fit:")

beta.coef <- solve(crossprod(xd_mm), crossprod(xd_mm, yd))
beta <- as.matrix(beta.coef)
comm.print(beta)
a <- deltime(a, "solve crossprod:")

xsvd <- svd(xx)
comm.print(xsvd$d)
a <- deltime(a, "svd xx:")


a <- deltime(a0, "T Total time:")
finalize()
##
## Run this demo with
## mpirun -np 32 Rscript -e 'dir <- "your-airline-data-directory"; demo("matrix", package="pbdIO", echo=FALSE)'
##

## TODO Unfinished example code!
#suppressPackageStartupMessages(library(pbdMPI))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(pbdML))
suppressPackageStartupMessages(library(pbdIO))
suppressPackageStartupMessages(library(memuse))
init.grid()
a0 <- a <- deltime()

col_classes = c(rep("integer", 8), "character", "integer", "character",
    rep("integer", 5), "character", "character", rep("integer", 4),
    "character", rep("integer", 6))

## local subset of airline data - change to your data location!!
dir <- "/lustre/atlas/scratch/ost/stf006/airline"
air <- comm.fread(dir, verbose=3, colClasses=col_classes)
a <- deltime(a, "T Total comm.fread:")

## variables from the R Journal iodata article. Select for complete cases
##   rebalancing
xy_df <- subset(air, select=c(ArrDelay, DayOfWeek, DepTime, DepDelay, Month))
comm.cat("colnames(xy_df)", colnames(xy_df), "\n", quiet=TRUE)

## subset complete cases
comm.print(xy_df[1:5, ], all.rank=TRUE)
comm.cat("nrow: ")
comm.cat(nrow(xy_df), all.rank=TRUE, quiet=TRUE)
comm.cat("\n")
xy_df <- xy_df[complete.cases(xy_df), ]
comm.cat("nrow: ")
comm.cat(nrow(xy_df), all.rank=TRUE, quiet=TRUE)
comm.cat("\n")
a <- deltime(a, "complete cases subset:")

## now rebalance after subsettng!
xy_df <- pbdIO:::comm.rebalance.df(xy_df, lo.side="right", type="equal", verbose=1)
a <- deltime(a, "rebalance:")

## separate x and y
x_df <- subset(xy_df, select=c(DayOfWeek, DepTime, DepDelay, Month))
y_df <- subset(xy_df, select=c(ArrDelay))
a <- deltime(a, "separate x and y df:")

## transform some variables
x_df$DayOfWeek <- factor(x_df$DayOfWeek, levels=1:7)
x_df$Month <- factor(x_df$Month, levels=1:12)
x_df$DepTime <- sprintf("%04d", x_df$DepTime)
x_df$DepTime <- as.numeric(substr(x_df$DepTime, 1, 2))*60 +
    as.numeric(substr(x_df$DepTime, 3, 4))
a <- deltime(a, "factors and transformations:")

## create model matrix
form = ~ DayOfWeek + DepTime + DepDelay + Month
x_mm <- model.matrix(form, x_df)
comm.cat(comm.rank(), "class(x_mm)", class(x_mm), "\n", all.rank=TRUE, quiet=TRUE)
## comm.print(x_mm[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "model matrix:")

## glue x_mm distributed pieces into a ddmatrix
colnames_x_mm <- colnames(x_mm)
comm.cat("colnames_x_mm:", colnames_x_mm, "\n")
dimnames(x_mm) <- NULL
xd_mm <- new("ddmatrix", Data=x_mm, dim=c(allreduce(nrow(x_mm)), ncol(x_mm)),
             ldim=dim(x_mm), bldim=dim(x_mm), ICTXT=2)
## comm.print(submatrix(xd_mm)[1:5, 1:5], all.rank=TRUE)
print(xd_mm)
a <- deltime(a, "xd_mm new ddmatrix:")

## glue y distributed pieces into a ddmatrix
y <- as.matrix(y_df)
dimnames(y) <- NULL
yd <- new("ddmatrix", Data=y, dim=c(allreduce(nrow(y)), 1),
             ldim=dim(y), bldim=dim(y), ICTXT=2)
print(yd)
a <- deltime(a, "y new ddmatrix:")

xd_mm <- as.blockcyclic(xd_mm, bldim=c(2, 2))
yd <- as.blockcyclic(yd, bldim=c(2, 2))
a <- deltime(a, "xd_mm and yd blockcyclic ddmatrix:")

beta <- lm.fit(xd_mm, yd)
coefs <- as.matrix(beta$coefficients)
comm.print(coefs)
comm.print(names(beta))
a <- deltime(a, "lm.fit:")

beta.coef <- solve(crossprod(xd_mm), crossprod(xd_mm, yd))
beta <- as.matrix(beta.coef)
comm.print(beta)
a <- deltime(a, "solve crossprod:")

xsvd <- svd(xx)
comm.print(xsvd$d)
a <- deltime(a, "svd xx:")


a <- deltime(a0, "T Total time:")
finalize()
##
## Run this demo with
## mpirun -np 32 Rscript -e 'dir <- "your-airline-data-directory"; demo("matrix", package="pbdIO", echo=FALSE)'
##

## TODO Unfinished example code!
#suppressPackageStartupMessages(library(pbdMPI))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(pbdML))
suppressPackageStartupMessages(library(pbdIO))
suppressPackageStartupMessages(library(memuse))
init.grid()
a0 <- a <- deltime()

col_classes = c(rep("integer", 8), "character", "integer", "character",
    rep("integer", 5), "character", "character", rep("integer", 4),
    "character", rep("integer", 6))

## local subset of airline data - change to your data location!!
dir <- "/lustre/atlas/scratch/ost/stf006/airline"
air <- comm.fread(dir, verbose=3, colClasses=col_classes)
a <- deltime(a, "T Total comm.fread:")

## variables from the R Journal iodata article. Select for complete cases
##   rebalancing
xy_df <- subset(air, select=c(ArrDelay, DayOfWeek, DepTime, DepDelay, Month))
comm.cat("colnames(xy_df)", colnames(xy_df), "\n", quiet=TRUE)

## subset complete cases
comm.print(xy_df[1:5, ], all.rank=TRUE)
comm.cat("nrow: (")
comm.cat(comm.rank(), ",", nrow(xy_df), ") ", all.rank=TRUE, quiet=TRUE)
comm.cat("\n")
xy_df <- xy_df[complete.cases(xy_df), ]
comm.cat("nrow: (")
comm.cat(comm.rank(), ",", nrow(xy_df), ") ", all.rank=TRUE, quiet=TRUE)
comm.cat("\n")
a <- deltime(a, "complete cases subset:")

## now rebalance after subsettng!
xy_df <- pbdIO:::comm.rebalance.df(xy_df, lo.side="right", type="equal", verbose=1)
a <- deltime(a, "rebalance:")

## separate x and y
x_df <- subset(xy_df, select=c(DayOfWeek, DepTime, DepDelay, Month))
y_df <- subset(xy_df, select=c(ArrDelay))
a <- deltime(a, "separate x and y df:")

## transform some variables
x_df$DayOfWeek <- factor(x_df$DayOfWeek, levels=1:7)
x_df$Month <- factor(x_df$Month, levels=1:12)
x_df$DepTime <- sprintf("%04d", x_df$DepTime)
x_df$DepTime <- as.numeric(substr(x_df$DepTime, 1, 2))*60 +
    as.numeric(substr(x_df$DepTime, 3, 4))
a <- deltime(a, "factors and transformations:")

## create model matrix
form = ~ ArrDelay + DayOfWeek + DepTime + DepDelay + Month
x_mm <- model.matrix(form, x_df)
comm.cat(comm.rank(), "class(x_mm)", class(x_mm), "\n", all.rank=TRUE, quiet=TRUE)
comm.print(x_mm[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "model matrix:")

## glue x_mm distributed pieces into a ddmatrix
colnames_x_mm <- colnames(x_mm)
comm.cat("colnames_x_mm:", colnames_x_mm, "\n")
dimnames(x_mm) <- NULL
xd_mm <- new("ddmatrix", Data=x_mm, dim=c(allreduce(nrow(x_mm)), ncol(x_mm)),
             ldim=dim(x_mm), bldim=dim(x_mm), ICTXT=2)
## comm.print(submatrix(xd_mm)[1:5, 1:5], all.rank=TRUE)
print(xd_mm)
a <- deltime(a, "xd_mm new ddmatrix:")

## glue y distributed pieces into a ddmatrix
y <- as.matrix(y_df)
dimnames(y) <- NULL
yd <- new("ddmatrix", Data=y, dim=c(allreduce(nrow(y)), 1),
             ldim=dim(y), bldim=dim(y), ICTXT=2)
print(yd)
a <- deltime(a, "y new ddmatrix:")

## xd_mmbc <- as.blockcyclic(xd_mm, bldim=c(2, 2))
## print(dim(submatrix(xd_mmbc)), all.rank=TRUE)
## a <- deltime(a, "matrix blockcyclic ddmatrix:")

beta <- lm.fit(xd_mm, yd)
coefs <- as.matrix(beta$coefficients)
comm.print(coefs)
comm.print(names(beta))
a <- deltime(a, "lm.fit:")

beta.coef <- solve(crossprod(xd_mm), crossprod(xd_mm, yd))
beta <- as.matrix(beta.coef)
comm.print(beta)
a <- deltime(a, "solve crossprod:")

xsvd <- svd(xx)
comm.print(xsvd$d)
a <- deltime(a, "svd xx:")


a <- deltime(a0, "T Total time:")
finalize()
##
## Run this demo with
## mpirun -np 32 Rscript -e 'dir <- "your-airline-data-directory"; demo("matrix", package="pbdIO", echo=FALSE)'
##

## TODO Unfinished example code!
#suppressPackageStartupMessages(library(pbdMPI))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(pbdML))
suppressPackageStartupMessages(library(pbdIO))
suppressPackageStartupMessages(library(memuse))
init.grid()
a0 <- a <- deltime()

col_classes = c(rep("integer", 8), "character", "integer", "character",
    rep("integer", 5), "character", "character", rep("integer", 4),
    "character", rep("integer", 6))

## local subset of airline data - change to your data location!!
dir <- "/lustre/atlas/scratch/ost/stf006/airline"
air <- comm.fread(dir, verbose=3, colClasses=col_classes)
a <- deltime(a, "T Total comm.fread:")

## for the matrix example, do pca on all data, projecting airports
## into a 2d picture. Take all numerical variables, compute PCA, and
## plot airport labels in the first two pc space.

## select the numeric columns
## comm.cat(comm.rank(), "col.classes(air)", unlist(lapply(air, class)), "\n", quiet=TRUE, all.rank=TRUE)
## airnames <- colnames(air)
## numeric <- unlist(allreduce(sapply(air, is.numeric), op="land"))

## variables from the R Journal iodata article. Select for complete cases
##   rebalancing
air_reg_df <- subset(air, select=c(ArrDelay, DayOfWeek, DepTime, DepDelay, Month))
comm.cat("colnames(air_reg_df)", colnames(air_reg_df), "\n", quiet=TRUE)

## subset complete cases
###!!!### replace with dplyr complete cases
comm.print(air_reg_df[1:5, ], all.rank=TRUE)
comm.cat(comm.rank(), "nrow:", nrow(air_reg_df), "\n", all.rank=TRUE, quiet=TRUE)
air_reg_df <- air_reg_df[complete.cases(air_reg_df), ]
comm.cat(comm.rank(), "nrow:", nrow(air_reg_df), "\n", all.rank=TRUE, quiet=TRUE)
a <- deltime(a, "complete cases subset:")

## now rebalance after subsettng!
air_reg_df <- pbdIO:::comm.rebalance.df(air_reg_df, lo.side="right", type="equal", verbose=3)
a <- deltime(a, "rebalance:")

## from the R Journal iodata article
form = ~ ArrDelay + DayOfWeek + DepTime + DepDelay + Month
## transform some variables
air_reg_df$DayOfWeek <- factor(air_reg_df$DayOfWeek, levels=1:7)
air_reg_df$Month <- factor(air_reg_df$Month, levels=1:12)
air_reg_df$DepTime <- sprintf("%04d", air_reg_df$DepTime)
air_reg_df$DepTime <- as.numeric(substr(air_reg_df$DepTime, 1, 2))*60 +
    as.numeric(substr(air_reg_df$DepTime, 3, 4))
comm.print(air_reg_df[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "factors and transformations:")

amm <- model.matrix(form, air_reg_df)
comm.cat(comm.rank(), "class(amm)", class(amm), "\n", all.rank=TRUE, quiet=TRUE)
comm.print(amm[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "model matrix:")

dimnames(amm) <- NULL
amm.d <- new("ddmatrix", Data=amm,
                 dim=c(allreduce(nrow(amm)), ncol(amm)),
                 ldim=dim(amm), bldim=dim(amm), ICTXT=2)
comm.print(submatrix(amm.d)[1:5, 1:5], all.rank=TRUE)
print(amm.d)
a <- deltime(a, "matrix new ddmatrix:")

amm.dbc <- as.blockcyclic(amm.d, bldim=c(2, 2))
print(dim(submatrix(amm.dbc)), all.rank=TRUE)
a <- deltime(a, "matrix blockcyclic ddmatrix:")

xx <- amm.dbc[, -2]
yy <- amm.dbc[, 2]
comm.print(dim(xx))
comm.print(dim(yy))
a <- deltime(a, "select columns:")

beta <- lm.fit(amm.dbc[, -2], amm.dbc[, 2])
coefs <- as.matrix(beta$coefficients)
comm.print(coefs)
comm.print(names(beta))
a <- deltime(a, "lm.fit:")
### !!! ### singal 11 here on 32 cores of 2 nodes - 12 GB x 10?
beta.coef <- solve(crossprod(xx), crossprod(xx, yy))
beta <- as.matrix(beta.coef)
comm.print(beta)
a <- deltime(a, "solve crossprod:")

xsvd <- svd(xx)
comm.print(xsvd$d)
a <- deltime(a, "svd xx:")

## redy for regression. use column indices to select response etc.

air_cross <- crossprod(amm.dbc)
print(air_cross)
a <- deltime(a, "matrix crossprod ddmatrix:")

library(pbdML)

a <- deltime(a0, "T Total time:")
finalize()
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename = 'catalog_predictions'

catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40,60,80),
                                            nb_iter = 100,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = filename)

# Catalog vs predictions
accuracy <- accuracy0 <- accuracy1 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]])


#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 50, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(WT) * length(K.values)) + 0.5, labels = FALSE, las = 1, pos = -0.02) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, nb.pts, by = length(WT)) + 0.5, labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)

            abline(v = seq(length(WT)+0.5,nb.pts-length(WT)+0.5,by = length(WT)), col = "grey", lty = 2)
            abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
            abline(h = c(1.125,2.375), col = "black", lty = 2)


            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'MW']) + as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt'] + as.numeric(accuracy[[i]][, 'iter'] + as.numeric(accuracy[[i]][, 'pc_rm']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,48), accuracy_mean[, 4][,1] - accuracy_mean[, 4][, 2]+it, seq(1,48), accuracy_mean[, 4][, 1] + accuracy_mean[, 4][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,48), y = accuracy_mean[, 4][, 1]+it, cex = 0.75, pch = 22, col = col[i])
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:
    filename <- 'Multiple_parameters'
    min.tx = 45
    K.values = c(2,4,6,8)
    MW = c(1,3,5)
    WT = c(0,0.3,0.6,1)
    blind = FALSE
    minimum_threshold = 0.3
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/Tanimoto_data.RData")
load("./RData/interactions_source.RData")
suppressMessages(load("./RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
# Format interaction catalogue to fit this table format
    S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
    S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
    }

# setting up the analyses for multiple communities
# Data for communities on which to test the algorithm
    Cm <- unique(interactions_sources[, 'source'])
    communities <- vector("list", length(Cm))
    names(communities) <- Cm

    # Taxa list per community to predict
        for(i in 1:length(communities)) {
            Ci <- which(interactions_sources[, 'source'] == Cm[i])
            S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

            if(length(which(!S1 %in% S0_catalog)) > 0) {
                print('Taxa in C[i] are not all included in taxa list S0')
                break
            }

            communities[[i]] <- S1
        }

# Substracting GloBI interactions for this portion
    Cm.lg <- numeric()
    for(i in 1:length(communities)) {
        Cm.lg <- c(Cm.lg,length(communities[[i]]))
    }

    to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

    Cm <- Cm[-to.delete]
    for(i in rev(to.delete)) {
        communities[[i]] <- NULL
    }
    names(communities) <- Cm

# Setting up lists to store the results
    wt.init <- wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
    wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
    for(i in rev(wt.remove)) {
        similarity.matrices[[i]] <- NULL
    }

    sim.wt <- names(similarity.matrices)
    Tanimoto_analysis <- vector("list",length(sim.wt))
    names(Tanimoto_analysis) <- sim.wt
    for(i in 1:length(sim.wt)) {
        Tanimoto_analysis[[i]] <- vector("list", length(Cm))
        names(Tanimoto_analysis[[i]]) <- Cm
    }

# List to store results of multiple K values
K <- vector("list", length(K.values))
for(i in 1:length(K.values)) {
    K[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- K
names(Tanimoto_analysis) <- K.values
remove(K)

min.wt <- vector("list", length(MW))
for(i in 1:length(MW)) {
    min.wt[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- min.wt
names(Tanimoto_analysis) <- MW
remove(min.wt)

file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
save(x = Tanimoto_analysis, file = file.to.save)

init.time <- Sys.time()
for(n in 1:length(MW)) {
    mw <- MW[n]
    for(m in 1:length(K.values)) {

        # Tanimoto analysis with different weights for different communities
            # Parameters:
                Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
            #   wt  Weight of traits in similarity measurement
            #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
            #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

            # Output:
            #   A vector of sets of resources for each taxon

            for(i in 1:length(WT)){ #1st loop for all types of wt values
                wt <- WT[i]
                pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                for(j in 1:length(Cm)) { #2nd loop for all C[i]
                    S1 <- communities[[j]]
                    S0 <- S0_catalog
                    similarity.matrix <- similarity.matrices[[i]]

                    # Two choices here:
                    #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                    #   2. The analysis takes into account preexisting information already contained in the catalogue

                    # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                    if(blind == TRUE) {
                        for(k in 1:length(S1)) {
                          S0[S1[k], 'resource'] <- ""
                          S0[S1[k], 'non-resource'] <- ""
                        }

                    # 2. Preexisting information kept to inform algorithm
                    } else { # blind == FALSE

                        interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                        # Only modifying those that are loosing data from the catalogue, less time
                            to.change <- numeric()
                            for(k in 1:length(S1)) {
                                to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                            }
                            to.change <- unique(to.change)

                        # Modifying sets of resources and non-resources for taxa in S1
                            interactions <- interactions[to.change, ]
                            rownames(interactions) <- seq(1,nrow(interactions))
                            resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                      resource = interactions[, 'resource'],
                                                                      inter_type = interactions[, 'inter'])

                        # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                            for(k in 1:nrow(resource_set)) {
                              S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                              S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                            }
                        remove(interactions, resource_set, to.change)
                    } #if blind or not blind

                    # Recalculate similarity
                        similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                            S1 = S1,
                                                                            wt = wt,
                                                                            similarity.matrix = similarity.matrix)

                    # Predicting interactions
                        Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                Kr = Kr,
                                                                                S0 = S0,
                                                                                S1 = S1,
                                                                                MW = mw,
                                                                                similarity.matrix = similarity.matrix,
                                                                                minimum_threshold = minimum_threshold)

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(S0, S1, similarity.matrix)
                    setTxtProgressBar(pb, j)
                }#2nd loop for all C[i]

                save(x = Tanimoto_analysis, file = file.to.save)
                remove(wt)

            }#1st loop for all types of wt values
            close(pb)
    }#m
}#n
print(Sys.time() - init.time)
save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))


# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 50, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(WT) * length(K.values)) + 0.5, labels = FALSE, las = 1, pos = -0.02) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, nb.pts, by = length(WT)) + 0.5, labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)

            abline(v = seq(length(WT)+0.5,nb.pts-length(WT)+0.5,by = length(WT)), col = "grey", lty = 2)
            abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
            abline(h = c(1.125,2.375), col = "black", lty = 2)


            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'MW']) + as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,48), accuracy_mean[, 4][,1] - accuracy_mean[, 4][, 2]+it, seq(1,48), accuracy_mean[, 4][, 1] + accuracy_mean[, 4][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,48), y = accuracy_mean[, 4][, 1]+it, cex = 0.75, pch = 22, col = col[i])
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
#!/usr/bin/env RScript
library(ggplot2)

args <- commandArgs(trailingOnly = T)

main <- function()
{
	inputPath <- args[1]
	outputPath <- args[2]
	if (is.na(inputPath))
	{
		stop('Please specify a csv file')
	}

	if (is.na(outputPath))
	{
		stop('Please specify an output file')
	}

	data <- read.csv(inputPath)
	plot <- ggplot(data, aes(x = offset, y = value)) +
		geom_line() +
		labs(x = 'Time (ms)', y = 'GSR (microsiemens)') +
		ylim(c(0, ceiling(max(data$value))))

	ggsave(outputPath, plot)
}

dummy <- main()##
## Run this demo with
## mpirun -np 32 Rscript -e 'dir <- "your-airline-data-directory"; demo("matrix", package="pbdIO", echo=FALSE)'
##

## TODO Unfinished example code!
#suppressPackageStartupMessages(library(pbdMPI))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(pbdML))
suppressPackageStartupMessages(library(pbdIO))
suppressPackageStartupMessages(library(memuse))
init.grid()
a0 <- a <- deltime()

col_classes = c(rep("integer", 8), "character", "integer", "character",
    rep("integer", 5), "character", "character", rep("integer", 4),
    "character", rep("integer", 6))

## local subset of airline data - change to your data location!!
dir <- "/lustre/atlas/scratch/ost/stf006/airline"
air <- comm.fread(dir, verbose=3, colClasses=col_classes)
a <- deltime(a, "T Total comm.fread:")

## for the matrix example, do pca on all data, projecting airports
## into a 2d picture. Take all numerical variables, compute PCA, and
## plot airport labels in the first two pc space.

## select the numeric columns
comm.cat(comm.rank(), "col.classes(air)", unlist(lapply(air, class)), "\n", quiet=TRUE, all.rank=TRUE)
airnames <- colnames(air)
numeric <- unlist(allreduce(sapply(air, is.numeric), op="land"))
comm.cat("numeric\n", quiet=TRUE)
comm.cat("num", as.integer(numeric), "\n", quiet=TRUE)
## variables from the R Journal iodata article. Select for complete cases
##   rebalancing
air_reg_df <- subset(air, select=c(ArrDelay, DayOfWeek, DepTime, DepDelay, Month))
comm.cat("colnames(air_reg_df)", colnames(air_reg_df), "\n", quiet=TRUE)

## subset complete cases
###!!!### replace with dplyr complete cases
comm.print(air_reg_df[1:5, ], all.rank=TRUE)
comm.cat(comm.rank(), "nrow:", nrow(air_reg_df), "\n", all.rank=TRUE, quiet=TRUE)
air_reg_df <- air_reg_df[complete.cases(air_reg_df), ]
comm.cat(comm.rank(), "nrow:", nrow(air_reg_df), "\n", all.rank=TRUE, quiet=TRUE)
a <- deltime(a, "complete cases subset:")

## now rebalance after subsettng!
air_reg_df <- pbdIO:::comm.rebalance.df(air_reg_df, lo.side="right", type="equal", verbose=3)
a <- deltime(a, "rebalance:")

## from the R Journal iodata article
form = ~ ArrDelay + DayOfWeek + DepTime + DepDelay + Month
## transform some variables
air_reg_df$DayOfWeek <- factor(air_reg_df$DayOfWeek, levels=1:7)
air_reg_df$Month <- factor(air_reg_df$Month, levels=1:12)
air_reg_df$DepTime <- sprintf("%04d", air_reg_df$DepTime)
air_reg_df$DepTime <- as.numeric(substr(air_reg_df$DepTime, 1, 2))*60 +
    as.numeric(substr(air_reg_df$DepTime, 3, 4))
comm.print(air_reg_df[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "factors and transformations:")

amm <- model.matrix(form, air_reg_df)
comm.cat(comm.rank(), "class(amm)", class(amm), "\n", all.rank=TRUE, quiet=TRUE)
comm.print(amm[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "model matrix:")

dimnames(amm) <- NULL
amm.d <- new("ddmatrix", Data=amm,
                 dim=c(allreduce(nrow(amm)), ncol(amm)),
                 ldim=dim(amm), bldim=dim(amm), ICTXT=2)
comm.print(submatrix(amm.d)[1:5, 1:5], all.rank=TRUE)
print(amm.d)
a <- deltime(a, "matrix new ddmatrix:")

amm.dbc <- as.blockcyclic(amm.d, bldim=c(2, 2))
print(dim(submatrix(amm.dbc)), all.rank=TRUE)
a <- deltime(a, "matrix blockcyclic ddmatrix:")

xx <- amm.dbc[, -2]
yy <- amm.dbc[, 2]
comm.print(dim(xx))
comm.print(dim(yy))
a <- deltime(a, "select columns:")

beta <- lm.fit(amm.dbc[, -2], amm.dbc[, 2])
coefs <- as.matrix(beta$coefficients)
comm.print(coefs)
comm.print(names(beta))
a <- deltime(a, "lm.fit:")

beta.coef <- solve(crossprod(xx), crossprod(xx, yy))
beta <- as.matrix(beta.coef)
comm.print(beta)
a <- deltime(a, "solve crossprod:")

xsvd <- svd(xx)
comm.print(xsvd$d)
a <- deltime(a, "svd xx:")

## redy for regression. use column indices to select response etc.

air_cross <- crossprod(amm.dbc)
print(air_cross)
a <- deltime(a, "matrix crossprod ddmatrix:")

library(pbdML)

a <- deltime(a0, "T Total time:")
finalize()
#' comm.fread
#'
#' Given a directory, \code{comm.fread()} reads all csv files contained
#' in it in parallel with available resources.
#'
#' @param dir
#' A directory containing the files desired to be read.  The directory
#' should be accessible to all readers.
#' @param pattern
#' The pattern for files desired to be read.
#' @param readers
#' The number of readers.
#' @param verbose
#' Determines the verbosity level. Acceptable values are 0, 1, 2, and 3 for
#' least to most verbosity.
#'
#' @return
#' TODO
#'
#' @examples
#' \dontrun{
#' ### Save code in a file "demo.r" and run with 2 processors by
#' ### SHELL> mpiexec -np 2 Rscript demo.r
#' library(pbdMPI)
#' library(pbdIO)
#'
#' path <- "/tmp/read"
#' comm.print(dir(path))
#' ## [1] "a.csv" "b.csv"
#'
#' X <- comm.fread(path)
#'
#' comm.print(X, all.rank=TRUE)
#' ## COMM.RANK = 0
#' ##    a b c
#' ## 1: 1 2 3
#' ## COMM.RANK = 1
#' ##    a b c
#' ## 1: 2 3 4
#'
#' finalize()
#' }
#'
#' @importFrom data.table fread rbindlist
#'
#' @export
comm.fread <- function(dir, pattern="*.csv$", readers=comm.size(),
                       verbose=0, ...) {
    if (!is.character(dir) || length(dir) != 1 || is.na(dir))
        comm.stop("argument 'dir' must be a string")
    if (!is.character(pattern) || length(pattern) != 1 || is.na(pattern))
        comm.stop("argument 'pattern' must be a string")
    if (!is.numeric(readers) || length(readers) != 1 || is.na(readers))
        comm.stop("argument 'readers' must be an integer")
    if (!(verbose %in% 0:3))
        comm.stop("argument 'verbose' must be 0, 1, 2, or 3")

    if(verbose) a <- deltime()
    files <- file.info(list.files(dir, pattern=pattern, full.names=TRUE))

    if (NROW(files) == 0)
        comm.stop(paste("Directory", dir,
                        "contains no files matching pattern", pattern))

    sizes <- files$size
    my_rank <- comm.rank()
    my_files <- comm.chunk(nrow(files), p=readers, lo.side="right",
                           form="vector")
    comm.print(my_files, all.rank=TRUE)
    if(verbose > 1) for(ifile in my_files)
                      cat(my_rank, rownames(files)[ifile], "\n")

    ## now fread all my_files and bind into one local data.frame
    l <- lapply(rownames(files)[my_files], function(file)
        suppressWarnings(fread(file, showProgress=FALSE, ...)))
    X <- rbindlist(l)

    # TODO if empty? Is length(X) is zero enough?
    ## rank 0 always reads, so it has all attributes. Propagate to NULLs.
    X0 <- bcast(X[0])
    if(length(X) == 0) X <- X0

    if(verbose) a <- deltime(a, "T    component fread time:")

    if(verbose) {
        nrow_have <- unlist(allgather(nrow(X)))
        comm.cat("nrow_have:", nrow_have, "\n")
    }

    X
}

check_sum <- function(X) {
    ## Report variable sums to check input
    my_numeric <- sapply(X, is.numeric)
    Xnumeric <- which(allreduce(my_numeric, op="land"))
    colSums(X[, Xnumeric, with=FALSE], na.rm=TRUE)
}

comm.rebalance.df <- function(X, verbose=0, ...) {
    ## Data frame X has unequal number of rows across ranks. This function
    ##   balances the rows by sending rows from ranks that have too many to
    ##   ranks that have too few.
    ##
    ## TODO makes copies with rbind(). Should this go into copyless C?
    ##
    my_rank <- comm.rank()
    nrow_have <- unlist(allgather(nrow(X)))
    N <- sum(nrow_have)

    ## TODO Three nrow_ vectors can be one with a bit more logic
    nrow_want <- comm.chunk(N, form="number", # type="equal",
                             all.rank=TRUE, ...)
    nrow_send <- pmax(nrow_have - nrow_want, 0)
    nrow_recv <- pmax(nrow_want - nrow_have, 0)
    if(verbose > 1) {
        comm.cat("nrow_have:", nrow_have, "\n")
        comm.cat("nrow_want:", nrow_want, "\n")
        comm.cat("nrow_send:", nrow_send, "\n")
        comm.cat("nrow_recv:", nrow_recv, "\n")
    }

    ## get global numeric column sums for error checking
    if(verbose > 2) before_sums <- check_sum(X)

    while(sum(nrow_send)) {
        recv_i <- 0
        senders <- (1:comm.size())[nrow_send > 0]
        for(proc_send in senders) {
            ## senders and receivers start from 1. Do -1 for rank!
            receivers <- (1:comm.size())[nrow_recv > 0]
            if(recv_i < length(receivers)) {
                recv_i <- recv_i + 1
                count_s <- nrow_send[proc_send]
                count_r <- nrow_recv[receivers[recv_i]]
                count <- min(count_s, count_r)
                if(my_rank + 1 == receivers[recv_i]) {
                    ## receivers and senders are disjoint sets
                    buffer <- matrix(NA, count, ncol(X))
                    buffer <- recv(buffer, rank.source=proc_send - 1)
                    ## can not use irecv because rbind follows!!
                    X <- rbind(X, buffer)
                }
                if(my_rank + 1 == proc_send) {
                    ## but two senders can be sending to same receiver
                    isend(X[1:count, ], rank.dest=receivers[recv_i] - 1)
                    X <- X[-(1:count), ]
                }
                nrow_recv[receivers[recv_i]] <- count_r - count
                nrow_send[proc_send] <- count_s - count
            }
        }
    }

    ## check if global column sums have not changed
    if(verbose > 2) {
        after_sums <- check_sum(X)
        equal <- all.equal(allreduce(before_sums), allreduce(after_sums))
        comm.cat("checksum equal:", equal, "on", ncol(X), "columns\n")
    }

    X
}
##
## Run this demo with
## mpirun -np 32 Rscript -e 'dir <- "your-airline-data-directory"; demo("matrix", package="pbdIO", echo=FALSE)'
##

## TODO Unfinished example code!
#suppressPackageStartupMessages(library(pbdMPI))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(pbdML))
suppressPackageStartupMessages(library(pbdIO))
suppressPackageStartupMessages(library(memuse))
init.grid()
a0 <- a <- deltime()

col_classes = c(rep("integer", 8), "character", "integer", "character",
    rep("integer", 5), "character", "character", rep("integer", 4),
    "character", rep("integer", 6))

## local subset of airline data - change to your data location!!
dir <- "../../R_Thai_Workshop/session-parallel2/data"
air <- comm.fread(dir, verbose=3, colClasses=col_classes)
a <- deltime(a, "T Total comm.fread:")

## for the matrix example, do pca on all data, projecting airports
## into a 2d picture. Take all numerical variables, compute PCA, and
## plot airport labels in the first two pc space.

## select the numeric columns
comm.cat(comm.rank(), "col.classes(air)", unlist(lapply(air, class)), "\n", quiet=TRUE, all.rank=TRUE)
airnames <- colnames(air)
numeric <- unlist(allreduce(sapply(air, is.numeric), op="land"))
comm.cat("numeric\n", quiet=TRUE)
comm.cat("num", as.integer(numeric), "\n", quiet=TRUE)
## variables from the R Journal iodata article. Select for complete cases
##   rebalancing
air_reg_df <- subset(air, select=c(ArrDelay, DayOfWeek, DepTime, DepDelay, Month))
comm.cat("colnames(air_reg_df)", colnames(air_reg_df), "\n", quiet=TRUE)

## subset complete cases
###!!!### replace with dplyr complete cases
comm.print(air_reg_df[1:5, ], all.rank=TRUE)
comm.cat(comm.rank(), "nrow:", nrow(air_reg_df), "\n", all.rank=TRUE, quiet=TRUE)
air_reg_df <- air_reg_df[complete.cases(air_reg_df), ]
comm.cat(comm.rank(), "nrow:", nrow(air_reg_df), "\n", all.rank=TRUE, quiet=TRUE)
a <- deltime(a, "complete cases subset:")

## now rebalance after subsettng!
air_reg_df <- pbdIO:::comm.rebalance.df(air_reg_df, lo.side="right", type="equal", verbose=3)
a <- deltime(a, "rebalance:")

## from the R Journal iodata article
form = ~ ArrDelay + DayOfWeek + DepTime + DepDelay + Month
## transform some variables
air_reg_df$DayOfWeek <- factor(air_reg_df$DayOfWeek, levels=1:7)
air_reg_df$Month <- factor(air_reg_df$Month, levels=1:12)
air_reg_df$DepTime <- sprintf("%04d", air_reg_df$DepTime)
air_reg_df$DepTime <- as.numeric(substr(air_reg_df$DepTime, 1, 2))*60 +
    as.numeric(substr(air_reg_df$DepTime, 3, 4))
comm.print(air_reg_df[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "factors and transformations:")

amm <- model.matrix(form, air_reg_df)
comm.cat(comm.rank(), "class(amm)", class(amm), "\n", all.rank=TRUE, quiet=TRUE)
comm.print(amm[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "model matrix:")

dimnames(amm) <- NULL
amm.d <- new("ddmatrix", Data=amm,
                 dim=c(allreduce(nrow(amm)), ncol(amm)),
                 ldim=dim(amm), bldim=dim(amm), ICTXT=2)
comm.print(submatrix(amm.d)[1:5, 1:5], all.rank=TRUE)
print(amm.d)
a <- deltime(a, "matrix new ddmatrix:")

amm.dbc <- as.blockcyclic(amm.d, bldim=c(2, 2))
print(dim(submatrix(amm.dbc)), all.rank=TRUE)
a <- deltime(a, "matrix blockcyclic ddmatrix:")

xx <- amm.dbc[, -2]
yy <- amm.dbc[, 2]
comm.print(dim(xx))
comm.print(dim(yy))
a <- deltime(a, "select columns:")

beta <- lm.fit(amm.dbc[, -2], amm.dbc[, 2])
coefs <- as.matrix(beta$coefficients)
comm.print(coefs)
comm.print(names(beta))
a <- deltime(a, "lm.fit:")

beta.coef <- solve(crossprod(xx), crossprod(xx, yy))
beta <- as.matrix(beta.coef)
comm.print(beta)
a <- deltime(a, "solve crossprod:")

xsvd <- svd(xx)
comm.print(xsvd$d)
a <- deltime(a, "svd xx:")

## redy for regression. use column indices to select response etc.

air_cross <- crossprod(amm.dbc)
print(air_cross)
a <- deltime(a, "matrix crossprod ddmatrix:")

library(pbdML)

a <- deltime(a0, "T Total time:")
finalize()
foo <- 5
f <- c(5, as.integer(5))
typeof(f)
mode(f)
str(f)
summary(f)

f <- list(5, as.integer(5))
typeof(f)
mode(f)
str(f)

# what about print()?
# look into class() some more
#
explr <- function(x) {
  fs <- c(typeof, mode, class, str, summary, head)
#  lapply(fs, fs, x)
  o <- ""
  for (f in fs) {
    cat("processing\n")
    cat(o, sep = "", quote(f), ": ")
    cat(o, invisible(f(x)))
    cat(o, "\n")
#    print(f(x))
  }
  print(o)
}# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename = 'catalog_predictions'

catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40,60,80),
                                            nb_iter = 100,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = filename)

# Catalog vs predictions
accuracy <- accuracy0 <- accuracy1 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]])


#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=7,height=7)

# Plots
par(mfrow=c(2,2))
# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 1.09)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        # foodwebs <- names(similarity_cons_res_blind[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000088","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
            axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
            # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
            points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
        } #i

        ## Add legend
        if(j == 12) {
            legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        }
} #j
dev.off()
# Run init.r before other scripts
rm(list=ls())
 # for use in R console.
 # set own relevant directory if working in R console, otherwise ignore if in terminal
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "./Script/0-1-Tanimoto_data.r
#           RData <- file = './RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "./Script/0-1-Interactions_sources.r
#           RData <- file = "./RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = './Script/1-Similarity_matrix.r'
#       RData <- file = './RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = './Script/2-1-Tanimoto_analysis.r'
#           RData <- file = './RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = './Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = './RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("./Script/tanimoto.r") # basic tanimoto similarity
source("./Script/tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("./Script/similarity_taxon.r") # similarity matrix for set of taxa
source("./Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("./Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("./Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/consumer_set_of_resource.R")
source("./Script/resource_set_of_consumer.R")
source("./Script/prediction_accuracy.r") #
source("./Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("./Script/serialNext.r") # function to avoid overwriting existing files in temporary analyses folder
source("./Script/eplot.r") # empty plot for figure generation
source("./Script/tanimoto_analysis.r")
source("./Script/catalog_predictions.r") # computing prediction accuracy ~ # taxa in catalog
source("./Script/catalog_predictions_accuracy.r") # accuracy of predictions for accuracy ~ # taxa in catalog

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
#'
#' @export
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".",
                              source_files = list(),
                              settings = SlurmSettings$new()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
                private$settings <- settings
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function(allow_creation_without_input_files = FALSE) {

            if (!allow_creation_without_input_files && length(self$input_files) == 0) {
                stop("Attempting to create slurm job without `input_files`. Pass TRUE to `create` to override.")
            }

            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in c(self$source_files, self$main_file)) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })

            script <- SlurmBashScript$new(container, self$main_file, private$settings)
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        settings = NA,
        find_globals = function() {
            e <- new.env()
            testthat::source_file(self$main_file, e)

            for (file in self$source_files) {
                testthat::source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                if (nglobals == 1) {
                    vars <- "var"
                    t_vars <- "this var"
                } else {
                    vars <- "vars"
                    t_vars <- "these vars"
                }

                cat(paste("Found", nglobals, vars, "to specify:"))
                for (global in globals) {
                    cat(paste("\n    -", global))
                }

                cat(paste("\n\nSet", t_vars, "in the `params` property of your `SlurmJob` instance."))
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
library(ggplot2)
df <- read.csv('sueldos.sysarmy.csv')

rename <- function(df, old, wants) {
  names(df)[names(df)==old] <- wants
  return(df)
}

tukey <- function(data) {
  iqr <- IQR(data$Income)
  firstQ <- quantile(data$Income)[2]
  thirdQ <- quantile(data$Income)[4]
  low <- firstQ - (iqr * 1.5)
  high <- thirdQ + (iqr * 1.5)
  data <- subset(data, Income < high)
  data <- subset(data, Income > low)
  return(data)
}

cleanup <- function(data, handleOutliers) {
  # clean gender.
  data$Gender = ifelse(data$Soy == "Hombre", "M", "F")
  data$Gender = as.factor(data$Gender)

  # rename columns.
  data <- rename(data, "Tengo", "Age")
  data <- rename(data, "Argentina", "Region")
  data <- rename(data, "A..os.de.experiencia", "YearsExperience")
  data <- rename(data, "A..os.en.el.puesto.actual", "YearsCurrentJob")
  data <- rename(data, "Trabajo.de", "JobDescription")
  data <- rename(data, "Tipo.de.contrato", "JobType")
  data <- rename(data, "Qu...tan.conforme.est..s.con.tu.sueldo.", "Happiness")
  data <- rename(data, "Cambiaste.de.empresa.en.los...ltimos.6.meses.", "SwitchedJobsLast6Months")

  # fix region names.
  levels(data$Region)[levels(data$Region) == "Entre R\303\255os"] <- "Entre Rios"
  levels(data$Region)[levels(data$Region) == "Ciudad Aut\303\263noma de Buenos Aires"] <- "CABA"
  levels(data$Region)[levels(data$Region) == "C\303\263rdoba"] <- "Cordoba"
  levels(data$Region)[levels(data$Region) == "Neuqu\303\251n"] <- "Neuquen"
  levels(data$Region)[levels(data$Region) == "R\303\255o Negro"] <- "Rio Negro"
  levels(data$Region)[levels(data$Region) == "Tucum\303\241n"] <- "Tucuman"
  levels(data$Region)[levels(data$Region) == "Provincia de Buenos Aires"] <- "GBA"
  
  # fix age.
  levels(data$Age)[levels(data$Age) == "Menos de 18 a\303\261os"] <- "18-"

  # fix salary.
  data <- rename(data, "Salario.mensual..en.tu.moneda.local.", "Income")
  data$Income <- ifelse(data$Bruto.o.neto. == "Bruto", data$Income, data$Income/0.70)
  data$Bruto.o.neto. = NULL
  
  # fix job switch.
  data$SwitchedJobsLast6Months = ifelse(data$SwitchedJobsLast6Months == "No", 0, 1)

  # remove ficticious data.
  data <- subset(data, Income < 200000)
  data <- subset(data, Income > 1000)
  
  # handle outliers.
  data <- handleOutliers(data)
  
  keep <- c("Age", "Region", "YearsExperience", "YearsCurrentJob", "JobDescription",
            "JobType", "Happiness", "Income", "Gender", "SwitchedJobsLast6Months")
  return(data[keep])
}

all.salaries.hist <- function(df) {
  plot <- ggplot(df, aes(x=Income), ylab="") + 
    geom_histogram(binwidth = 1000, fill="#3399FF", alpha=0.9)
  return(plot)
}

all.salaries.hist.median <- function(df) {
  plot <- all.salaries.hist(df) + 
    geom_vline(aes(xintercept = mean(Income)), linetype="longdash", color="red")
  return(plot)
}

all.salaries.gender = function(df) {
  plot <- ggplot(df, aes(x=Income, fill=Gender), ylab="") + 
    geom_histogram(binwidth = 1000, alpha=0.9)
  return(plot)
}

clean <- cleanup(df, handleOutliers = identity)
write.csv(clean, 'clean.csv', row.names=FALSE)

default.plot <- all.salaries.hist
default.plot(clean)
library(ggplot2)
df <- read.csv('sueldos.sysarmy.csv')

rename <- function(df, old, wants) {
  names(df)[names(df)==old] <- wants
  return(df)
}

# outlier removal functions.
arbitrary <- function(data) {
  data <- subset(data, Income < 120000)
  data <- subset(data, Income > 6000)
  return(data)
}

tukey <- function(data) {
  iqr <- IQR(data$Income)
  firstQ <- quantile(data$Income)[2]
  thirdQ <- quantile(data$Income)[4]
  low <- firstQ - (iqr * 1.5)
  high <- thirdQ + (iqr * 1.5)
  data <- subset(data, Income < high)
  data <- subset(data, Income > low)
  return(data)
}

cleanup <- function(data, removeOutliers) {
  # clean gender.
  data$Gender = ifelse(data$Soy == "Hombre", "M", "F")
  data$Gender = as.factor(data$Gender)

  # rename columns.
  data <- rename(data, "Tengo", "Age")
  data <- rename(data, "Argentina", "Region")
  data <- rename(data, "A..os.de.experiencia", "YearsExperience")
  data <- rename(data, "A..os.en.el.puesto.actual", "YearsCurrentJob")
  data <- rename(data, "Trabajo.de", "JobDescription")
  data <- rename(data, "Tipo.de.contrato", "JobType")
  data <- rename(data, "Qu...tan.conforme.est..s.con.tu.sueldo.", "Happiness")
  data <- rename(data, "Cambiaste.de.empresa.en.los...ltimos.6.meses.", "SwitchedJobsLast6Months")

  # fix region names.
  levels(data$Region)[levels(data$Region) == "Entre R\303\255os"] <- "Entre Rios"
  levels(data$Region)[levels(data$Region) == "Ciudad Aut\303\263noma de Buenos Aires"] <- "CABA"
  levels(data$Region)[levels(data$Region) == "C\303\263rdoba"] <- "Cordoba"
  levels(data$Region)[levels(data$Region) == "Neuqu\303\251n"] <- "Neuquen"
  levels(data$Region)[levels(data$Region) == "R\303\255o Negro"] <- "Rio Negro"
  levels(data$Region)[levels(data$Region) == "Tucum\303\241n"] <- "Tucuman"
  levels(data$Region)[levels(data$Region) == "Provincia de Buenos Aires"] <- "GBA"

  # fix age.
  levels(data$Age)[levels(data$Age) == "Menos de 18 a\303\261os"] <- "18-"

  # fix salary.
  data <- rename(data, "Salario.mensual..en.tu.moneda.local.", "Income")
  data$Income <- ifelse(data$Bruto.o.neto. == "Bruto", data$Income, data$Income/0.70)
  data$Bruto.o.neto. = NULL

  # fix job switch.
  data$SwitchedJobsLast6Months = ifelse(data$SwitchedJobsLast6Months == "No", 0, 1)

  # filter fictitious salaries.
  data <- removeOutliers(data)

  keep <- c("Age", "Region", "YearsExperience", "YearsCurrentJob", "JobDescription",
            "JobType", "Happiness", "Income", "Gender", "SwitchedJobsLast6Months")
  return(data[keep])
}

all.salaries.hist <- function(df) {
  plot <- ggplot(df, aes(x=Income), ylab="") +
    geom_histogram(binwidth = 1000, fill="#3399FF", alpha=0.9)
  return(plot)
}

all.salaries.hist.median <- function(df) {
  plot <- all.salaries.hist(df) +
    geom_vline(aes(xintercept = mean(Income)), linetype="longdash", color="red")
  return(plot)
}

all.salaries.gender = function(df) {
  plot <- ggplot(df, aes(x=Income, fill=Gender), ylab="") +
    geom_histogram(binwidth = 1000, alpha=0.9)
  return(plot)
}

clean <- cleanup(df, removeOutliers = arbitrary)
write.csv(clean, 'clean.csv', row.names=FALSE)

default.plot <- all.salaries.gender
default.plot(clean)
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:
    filename <- 'Multiple_parameters'
    min.tx = 45
    K.values = c(2,4,6,8)
    MW = c(1,3,5)
    WT = c(0,0.3,0.6,1)
    blind = FALSE
    minimum_threshold = 0.3
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/Tanimoto_data.RData")
load("./RData/interactions_source.RData")
suppressMessages(load("./RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
# Format interaction catalogue to fit this table format
    S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
    S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
    }

# setting up the analyses for multiple communities
# Data for communities on which to test the algorithm
    Cm <- unique(interactions_sources[, 'source'])
    communities <- vector("list", length(Cm))
    names(communities) <- Cm

    # Taxa list per community to predict
        for(i in 1:length(communities)) {
            Ci <- which(interactions_sources[, 'source'] == Cm[i])
            S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

            if(length(which(!S1 %in% S0_catalog)) > 0) {
                print('Taxa in C[i] are not all included in taxa list S0')
                break
            }

            communities[[i]] <- S1
        }

# Substracting GloBI interactions for this portion
    Cm.lg <- numeric()
    for(i in 1:length(communities)) {
        Cm.lg <- c(Cm.lg,length(communities[[i]]))
    }

    to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

    Cm <- Cm[-to.delete]
    for(i in rev(to.delete)) {
        communities[[i]] <- NULL
    }
    names(communities) <- Cm

# Setting up lists to store the results
    wt.init <- wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
    wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
    for(i in rev(wt.remove)) {
        similarity.matrices[[i]] <- NULL
    }

    sim.wt <- names(similarity.matrices)
    Tanimoto_analysis <- vector("list",length(sim.wt))
    names(Tanimoto_analysis) <- sim.wt
    for(i in 1:length(sim.wt)) {
        Tanimoto_analysis[[i]] <- vector("list", length(Cm))
        names(Tanimoto_analysis[[i]]) <- Cm
    }

# List to store results of multiple K values
K <- vector("list", length(K.values))
for(i in 1:length(K.values)) {
    K[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- K
names(Tanimoto_analysis) <- K.values
remove(K)

min.wt <- vector("list", length(MW))
for(i in 1:length(MW)) {
    min.wt[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- min.wt
names(Tanimoto_analysis) <- MW
remove(min.wt)

file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
save(x = Tanimoto_analysis, file = file.to.save)

init.time <- Sys.time()
for(n in 1:length(MW)) {
    mw <- MW[n]
    for(m in 1:length(K.values)) {

        # Tanimoto analysis with different weights for different communities
            # Parameters:
                Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
            #   wt  Weight of traits in similarity measurement
            #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
            #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

            # Output:
            #   A vector of sets of resources for each taxon

            for(i in 1:length(WT)){ #1st loop for all types of wt values
                wt <- WT[i]
                pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                for(j in 1:length(Cm)) { #2nd loop for all C[i]
                    S1 <- communities[[j]]
                    S0 <- S0_catalog
                    similarity.matrix <- similarity.matrices[[i]]

                    # Two choices here:
                    #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                    #   2. The analysis takes into account preexisting information already contained in the catalogue

                    # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                    if(blind == TRUE) {
                        for(k in 1:length(S1)) {
                          S0[S1[k], 'resource'] <- ""
                          S0[S1[k], 'non-resource'] <- ""
                        }

                    # 2. Preexisting information kept to inform algorithm
                    } else { # blind == FALSE

                        interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                        # Only modifying those that are loosing data from the catalogue, less time
                            to.change <- numeric()
                            for(k in 1:length(S1)) {
                                to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                            }
                            to.change <- unique(to.change)

                        # Modifying sets of resources and non-resources for taxa in S1
                            interactions <- interactions[to.change, ]
                            rownames(interactions) <- seq(1,nrow(interactions))
                            resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                      resource = interactions[, 'resource'],
                                                                      inter_type = interactions[, 'inter'])

                        # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                            for(k in 1:nrow(resource_set)) {
                              S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                              S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                            }
                        remove(interactions, resource_set, to.change)
                    } #if blind or not blind

                    # Recalculate similarity
                        similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                            S1 = S1,
                                                                            wt = wt,
                                                                            similarity.matrix = similarity.matrix)

                    # Predicting interactions
                        Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                Kr = Kr,
                                                                                S0 = S0,
                                                                                S1 = S1,
                                                                                MW = mw,
                                                                                similarity.matrix = similarity.matrix,
                                                                                minimum_threshold = minimum_threshold)

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(S0, S1, similarity.matrix)
                    setTxtProgressBar(pb, j)
                }#2nd loop for all C[i]

                save(x = Tanimoto_analysis, file = file.to.save)
                remove(wt)

            }#1st loop for all types of wt values
            close(pb)
    }#m
}#n
print(Sys.time() - init.time)
save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))


# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 50, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(WT) * length(K.values)) + 0.5, labels = FALSE, las = 1, pos = -0.02) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, nb.pts, by = length(WT)) + 0.5, labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)

            abline(v = seq(length(WT)+0.5,nb.pts-length(WT)+0.5,by = length(WT)), col = "grey", lty = 2)
            abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
            abline(h = c(1.125,2.375), col = "black", lty = 2)


            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 1, y = 0.15, labels = 'Algorithm', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 1, y = 2.65, labels = 'Catalog', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'MW']) + as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,48), accuracy_mean[, 4][,1] - accuracy_mean[, 4][, 2]+it, seq(1,48), accuracy_mean[, 4][, 1] + accuracy_mean[, 4][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,48), y = accuracy_mean[, 4][, 1]+it, cex = 0.75, pch = 22, col = col[i])
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
context("SlurmJob")


test_that("SlurmJob initializer sets main_file property.",  {
    expect_error(SlurmJob$new())
})
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, settings) {
            private$settings <- settings

            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", basename(main_file), "'"), "], source)")
            loading <- paste("sapply(list.files('./.objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

main_file=$(basename $1)

R CMD BATCH ./sources/$main_file

cp -r * $SLURM_SUBMIT_DIR/output
cd $SLURM_SUBMIT_DIR/output
rm -rf ./input ./sources ./objects"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
#'
#' @export
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".",
                              source_files = list(),
                              settings = SlurmSettings$new()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
                private$settings <- settings
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in c(self$source_files, self$main_file)) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })

            script <- SlurmBashScript$new(container, self$main_file, private$settings)
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        settings = NA,
        find_globals = function() {
            e <- new.env()
            testthat::source_file(self$main_file, e)

            for (file in self$source_files) {
                testthat::source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                if (nglobals == 1) {
                    vars <- "var"
                    t_vars <- "this var"
                } else {
                    vars <- "vars"
                    t_vars <- "these vars"
                }

                cat(paste("Found", nglobals, vars, "to specify:"))
                for (global in globals) {
                    cat(paste("\n    -", global))
                }

                cat(paste("\n\nSet", t_vars, "in the `params` property of your `SlurmJob` instance."))
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
#'
#' @export
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".",
                              source_files = list(),
                              settings = SlurmSettings$new()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
                private$settings <- settings
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in c(self$source_files, self$main_file)) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })

            script <- SlurmBashScript$new(container, self$main_file, private$settings)
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        settings = NA,
        find_globals = function() {
            e <- new.env()
            testthat::source_file(self$main_file, e)

            for (file in self$source_files) {
                testthat::source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                if (nglobals == 1) {
                    vars <- "var"
                    t_vars <- "this var"
                } else {
                    vars <- "vars"
                    t_vars <- "these vars"
                }

                message(paste("Found", nglobals, vars, "to specify:"))
                for (global in globals) {
                    message(paste("    -", global))
                }

                message(paste("\nSet", t_vars, "in the `params` property."))
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, settings) {
            private$settings <- settings

            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", basename(main_file), "'"), "], source)")
            loading <- paste("sapply(list.files('./.objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

# Flatten input directory
mv -r ./input .

main_file=$(basename $1)

R CMD BATCH ./sources/$main_file

cp -r * $SLURM_SUBMIT_DIR/output
cd $SLURM_SUBMIT_DIR/output
rm -rf ./input ./sources ./objects"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' Create an SBATCH option
#'
#' @param key The key for the sbatch option.
#'
#' @return A function that takes a single argument representing
#' the value for the \code{key}.
sbatch_opt <- function(key) {
    return(function(value) {
        return(paste0("--", key, "=", value))
    })
}


#' Test sbatch options for equality.
#'
#' sbatch option equallity is achieved if the keys of the options
#' are the same.
#'
#' @param opt_1 An sbatch option string.
#'
#' @param opt_2 An sbatch option string.
#'
#' @return A boolean value.
sbatch_opts_equal <- function(opt_1, opt_2) {
    return(sbatch_opt_key(opt_1) == sbatch_opt_key(opt_2))
}


#' Insert an sbatch option into a set.
#'
#' @param opt The sbatch option to insert
#'
#' @param opts A set of sbatch options. Default value is the empty
#' set.
#'
#' @return A set with \code{opt} inserted.
sbatch_opts_insert <- function(opt, opts = c()) {
    did_set <- FALSE

    for (i in 1:length(opts)) {
        if (sbatch_opts_equal(opt, opts[i])) {
            opts[i] = opt
            did_set = TRUE
        }
    }

    if(!did_set) {
        opts <- c(opts, opt)
    }

    return(opts)
}


#' Get the key of an sbatch.
#'
#' @param opt An sbatch option string.
#'
#' @return The \code{opt}'s key.
sbatch_opt_key <- function(opt) {
    return(strsplit(opt, "=")[[1]][1])
}


#' A list of sbatch options.
#'
#' The value of each item in the list is a string or a function
#' which takes a string as a parameter, using \code{sbatch_opt}.
#'
#' To ensure proper formatting, the \code{mail_type} option should
#' be set using \code{sbatch_mail_types}. Multiple mail types need
#' to be comma seperated.
#'
#' @export
sbatch_opts <- list (
    begin = sbatch_opt("begin"),
    cpus_per_task = sbatch_opt("cpus-per-task"),
    mail_type = sbatch_opt("mail-type"),
    mail_user = sbatch_opt("mail-user"),
    memory = sbatch_opt("mem"),
    nodes = sbatch_opt("nodes"),
    ouput = sbatch_opt("ouput"),
    time = sbatch_opt("time")
)


#' A list of sbatch mail types.
#'
#' The value of each item in the list is a string representing
#' a mail type option.
#'
#' @export
sbatch_mail_types <- list(
    all = "ALL",
    begin = "BEGIN",
    end = "END",
    fail = "FAIL",
    none = "NONE",
    requeue = "REQUEUE",
    stage_out = "STAGE_OUT",
    time_limit = "TIME_LIMIT",
    time_limit_90 = "TIME_LIMIT_90",
    time_limit_80 = "TIME_LIMIT_80",
    time_limit_50 = "TIME_LIMIT_50"
)
#' Create an SBATCH option
#'
#' @param key The key for the sbatch option.
#'
#' @return A function that takes a single argument representing
#' the value for the \code{key}.
sbatch_opt <- function(key) {
    return(function(value) {
        return(paste0("--", key, "=", value))
    })
}


#' Test sbatch options for equality.
#'
#' sbatch option equallity is achieved if the keys of the options
#' are the same.
#'
#' @param opt_1 An sbatch option string.
#'
#' @param opt_2 An sbatch option string.
#'
#' @return A boolean value.
sbatch_opts_equal <- function(opt_1, opt_2) {
    return(sbatch_opt_key(opt_1) == sbatch_opt_key(opt_2))
}


#' Insert an sbatch option into a set.
#'
#' @param opt The sbatch option to insert
#'
#' @param opts A set of sbatch options. Default value is the empty
#' set.
#'
#' @return A set with \code{opt} inserted.
sbatch_opts_insert <- function(opt, opts = c()) {
    for (i in 1:length(opts)) {
        if (sbatch_opts_equal(opt, opts[i])) {
            opts[i] = opt
        }
    }

    return(opts)
}


#' Get the key of an sbatch.
#'
#' @param opt An sbatch option string.
#'
#' @return The \code{opt}'s key.
sbatch_opt_key <- function(opt) {
    return(strsplit(opt, "=")[[1]][1])
}


#' A list of sbatch options.
#'
#' The value of each item in the list is a string or a function
#' which takes a string as a parameter, using \code{sbatch_opt}.
#'
#' To ensure proper formatting, the \code{mail_type} option should
#' be set using \code{sbatch_mail_types}. Multiple mail types need
#' to be comma seperated.
#'
#' @export
sbatch_opts <- list (
    begin = sbatch_opt("begin"),
    cpus_per_task = sbatch_opt("cpus-per-task"),
    mail_type = sbatch_opt("mail-type"),
    mail_user = sbatch_opt("mail-user"),
    memory = sbatch_opt("mem"),
    nodes = sbatch_opt("nodes"),
    ouput = sbatch_opt("ouput"),
    time = sbatch_opt("time")
)


#' A list of sbatch mail types.
#'
#' The value of each item in the list is a string representing
#' a mail type option.
#'
#' @export
sbatch_mail_types <- list(
    all = "ALL",
    begin = "BEGIN",
    end = "END",
    fail = "FAIL",
    none = "NONE",
    requeue = "REQUEUE",
    stage_out = "STAGE_OUT",
    time_limit = "TIME_LIMIT",
    time_limit_90 = "TIME_LIMIT_90",
    time_limit_80 = "TIME_LIMIT_80",
    time_limit_50 = "TIME_LIMIT_50"
)
#' Create an SBATCH option
#'
#' @param key The key for the sbatch option.
#'
#' @return A function that takes a single argument representing
#' the value for the \code{key}.
sbatch_opt <- function(key) {
    return(function(value) {
        return(paste0("--", key, "=", value))
    })
}


#' Test sbatch options for equality.
#'
#' sbatch option equallity is achieved if the keys of the options
#' are the same.
#'
#' @param opt_1 An sbatch option string.
#'
#' @param opt_2 An sbatch option string.
#'
#' @return A boolean value.
sbatch_opts_equal <- function(opt_1, opt_2) {
    return(sbatch_opt_key(opt_1) == sbatch_opt_key(opt_2))
}


#' Get the key of an sbatch.
#'
#' @param opt An sbatch option string.
#'
#' @return The \code{opt}'s key.
sbatch_opt_key <- function(opt) {
    return(strsplit(opt, "=")[[1]][1])
}


#' A list of sbatch options.
#'
#' The value of each item in the list is a string or a function
#' which takes a string as a parameter, using \code{sbatch_opt}.
#'
#' To ensure proper formatting, the \code{mail_type} option should
#' be set using \code{sbatch_mail_types}. Multiple mail types need
#' to be comma seperated.
#'
#' @export
sbatch_opts <- list (
    begin = sbatch_opt("begin"),
    cpus_per_task = sbatch_opt("cpus-per-task"),
    mail_type = sbatch_opt("mail-type"),
    mail_user = sbatch_opt("mail-user"),
    memory = sbatch_opt("mem"),
    nodes = sbatch_opt("nodes"),
    ouput = sbatch_opt("ouput"),
    time = sbatch_opt("time")
)


#' A list of sbatch mail types.
#'
#' The value of each item in the list is a string representing
#' a mail type option.
#'
#' @export
sbatch_mail_types <- list(
    all = "ALL",
    begin = "BEGIN",
    end = "END",
    fail = "FAIL",
    none = "NONE",
    requeue = "REQUEUE",
    stage_out = "STAGE_OUT",
    time_limit = "TIME_LIMIT",
    time_limit_90 = "TIME_LIMIT_90",
    time_limit_80 = "TIME_LIMIT_80",
    time_limit_50 = "TIME_LIMIT_50"
)
#' minilog.db
#' @param DS
#' @param Y
#' @author Jae Choi
#' @return returns a plot of CPUE data by date along with the predicted line as well as a data.frame with raw data and predicted data
#' @export

  minilog.db = function( DS="", Y=NULL, plotdata=TRUE ){

    minilog.dir = project.datadirectory("bio.snowcrab", "data", "minilog" )
    minilog.rawdata.location = file.path( minilog.dir, "archive" )
    plotdir = project.datadirectory("bio.snowcrab", "data", "minilog", "figures" )

    if (!is.null(Y)) {
      iY = which( Y>=1999 )  # no historical data prior to 1999
      if (length(iY)==0) return ("No data for specified years")
      Y = Y[iY]
    }

    if ( DS %in% c("basedata", "metadata", "load") ) {
      if (DS=="basedata" ){
        flist = list.files(path=minilog.dir, pattern="basedata", full.names=T, recursive=FALSE)
        if (!is.null(Y)) {
          mm = NULL
          for (yy in Y ) {
            ll = grep( yy, flist)
            if (length(ll)==0) return( NULL) # nothing to do
            if (length(ll)>0 ) mm = c( mm, ll)
          }
          if (length(mm) > 0 ) flist= flist[mm]
        }
        out = NULL
        for ( i in flist ) {
          load( i )
          out= rbind( out, basedata )
        }
        return( out )
      }

      if (DS=="metadata" ){
        flist = list.files(path=minilog.dir, pattern="metadata", full.names=T, recursive=FALSE)
        if (!is.null(Y)) {
          mm = NULL
          for (yy in Y ) {
            ll = grep( yy, flist)
            if (length(ll)==0) return( NULL ) # nothing to do
            if (length(ll)>0 ) mm = c( mm, ll)
          }
          if (length(mm) > 0 ) flist= flist[mm]
        }
        out = NULL
        for ( i in flist ) {
          load( i )
          out= rbind( out, metadata )
        }
        return( out )
      }

      # default is to "load"
      dirlist = list.files(path=minilog.rawdata.location, full.names=T, recursive=T)
      oo = grep("backup", dirlist)
      if (length(oo) > 0) {
        backups = dirlist[ oo ]
        dirlist = dirlist[-oo]
      }

      nfiles = length(dirlist)
      filelist = matrix( NA, ncol=3, nrow=nfiles)

      for (f in 1:nfiles) {
        yr = minilogDate( fnMini=dirlist[f] )
        if (is.null(yr) ) next()
        if ( yr %in% Y ) filelist[f,] = c( f, dirlist[f], yr )
      }
      fli = which( !is.na( filelist[,1] ) )
      if ( length(fli) == 0) return( "No files matching the criteria.")

      filelist = filelist[ fli , ]

      set = snowcrab.db( DS="setInitial" )  # set$timestamp is in UTC

      for ( yr in Y ) {
        print(yr)
        fn.meta = file.path( minilog.dir, paste( "minilog", "metadata", yr, "rdata", sep="." ) )
        fn.raw = file.path( minilog.dir, paste( "minilog", "basedata", yr, "rdata", sep="." ) )
        fs = filelist[ which( as.numeric(filelist[,3])==yr ) , 2 ]

        if (length(fs)==0) next()

        basedata = NULL
        metadata = NULL
        for (f in 1:length(fs)) {
          if( yr >= 2014 ) {
            j = load.minilog.rawdata.one.file.per.day( fn=fs[f], f=f, set=set)
          } else {
            j = load.minilog.rawdata( fn=fs[f], f=f, set=set)  # variable naming conventions in the past
          }
          if (is.null(j)) next()
          metadata = rbind( metadata, j$metadata)
          basedata = rbind( basedata, j$basedata)
        }

        # now do a last pass for the "backups" ....
        # incomplete ....
        add.backup.minilogs=FALSE
        if (add.backup.minilogs) {
          stop( "TODO")
          fb = backups[ which( as.numeric(backups[,3])==yr ) , 2 ]
          for (f in 1:length(fb)) {
            j = load.minilog.rawdata.backups( fn=fb[f], f=f, set=set)
            if (is.null(j)) next()
            metadata = rbind( metadata, j$metadata)
            basedata = rbind( basedata, j$basedata)
          }
        }

        save( metadata, file=fn.meta, compress=TRUE )
        save( basedata, file=fn.raw, compress=TRUE )

      }

      minilog.db( DS="set.minilog.lookuptable.redo" )

      return ( minilog.dir )
    }

    # -----------------------------------------------

    if (DS %in% c("stats", "stats.redo" ) ) {

      if (DS %in% c("stats") ){
        flist = list.files(path=minilog.dir, pattern="stats", full.names=T, recursive=FALSE)
        if (!is.null(Y)) {
          mm = NULL
          for (yy in Y ) {
            ll = grep( yy, flist)
            if (length(ll)==0) return(NULL) # nothing to do
            if (length(ll)>0 ) mm = c( mm, ll)
          }
          if (length(mm) > 0 ) flist= flist[mm]
        }
        mini.stat = NULL
        for ( i in flist ) {
          load( i )
          mini.stat = rbind( mini.stat, miniStats )
        }
        mini.meta = minilog.db( DS="metadata", Y=Y )
        res = merge( mini.meta, mini.stat,  by="minilog_uid", all.x=TRUE, all.y=FALSE, sort=FALSE )
        if(any(duplicated(res[,c('trip','set')]))) {
            res = removeDuplicateswithNA(res,cols=c('trip','set'),idvar='dt')
          }
        #res$t0 = as.POSIXct( res$t0, tz="UTC", origin=lubridate::origin )
        #res$t1 = as.POSIXct( res$t1, tz="UTC", origin=lubridate::origin )
        #res$dt = difftime( res$t1, res$t0 )

        return (res)
      }

      # "stats.redo" is the default action

      #      bad.list = c(
      #"minilog.S02112006.9.151.22.14.142",
      #"minilog.S27042001.7.NA.18.7.17",
      #"minilog.S08112008.9.55.NA.NA.55",
      #"minilog.S12102011.12.129.NA.NA.145",
      #"minilog.S18102007.11.226.18.44.198",
      #"minilog.S23102007.6.308.13.28.232",
      #"minilog.S27092007.9.86.NA.NA.87"
      #'minilog.S12071999.1.NA.NA.NA.190',
      #'minilog.S20052000.10.NA.NA.NA.13',
      #'minilog.S19092004.8.389.NA.NA.321',
      #'minilog.S19062000.8.NA.NA.NA.165',
      #'minilog.S07092002.12.NA.NA.NA.245',
      #'minilog.S08092002.10.NA.NA.NA.254',
      #'minilog.S12102002.8.NA.15.59.349',
      #'minilog.S28052002.10.NA.19.30.445',
      #'minilog.S24112009.4.370.NA.NA.276',
      #'minilog.S08092010.3.178.NA.NA.170',
      #'minilog.S21102010.9.341.14.51.252',
      #'minilog.S25092010.8.36.NA.NA.33',
      #'minilog.S27102010.3.918.8.11.423' '
      #      )
      bad.list = NULL
      bad.list = unique( c(bad.list, p$netmensuration.problem ) )

      for ( yr in Y ) {
        print (yr )

        fn = file.path( minilog.dir, paste( "minilog.stats", yr, "rdata", sep=".") )
        mta = miniRAW = miniStats = NULL
        miniRAW = minilog.db( DS="basedata", Y=yr )
        mta = minilog.db( DS="metadata", Y=yr )
        if (is.null(mta) | is.null(miniRAW)) next()

        rid = minilog.db( DS="set.minilog.lookuptable" )
        rid = data.frame( minilog_uid=rid$minilog_uid, stringsAsFactors=FALSE )
        rid = merge( rid, mta, by="minilog_uid", all.x=TRUE, all.y=FALSE )
        rid = rid[ which(rid$yr== yr) ,]
        if (nrow(rid) == 0 ) next()

        for ( i in 1:nrow(rid)  ) {
          #browser()
          id = rid$minilog_uid[i]
          sso.trip = rid$trip[i]
          sso.set = rid$set[i]
          sso.station = rid$station[i]

          Mi = which( miniRAW$minilog_uid == id )
          if (length( Mi) == 0 ) next()
          M = miniRAW[ Mi, ]

          settimestamp= rid$set_timestamp[i]
          time.gate =  list( t0=settimestamp - dminutes(6), t1=settimestamp + dminutes(12) )

          print( paste( i, ":", id) )

          # default, empty container
          res = data.frame(z=NA, t=NA, zsd=NA, tsd=NA, n=NA, t0=NA, t1=NA, dt=NA)

          rii = which( M$timestamp > settimestamp &  (M$timestamp < settimestamp+dminutes(5)) )
          # first estimate in case the following does not work
          if (length(rii) > 30) {
            res$z = mean(M$depth[rii], na.rm=TRUE)
            res$t = mean(M$temperature[rii], na.rm=TRUE)
            res$zsd = sd(M$depth[rii], na.rm=TRUE)
            res$tsd = sd(M$temperature[rii], na.rm=TRUE)
          }

          if (! ( id %in% bad.list ) ) {
            ndat = length( which( !is.na(M$depth) ))
            if (ndat ==0 ) print ("No depth data in minilogs")
            if( ndat < 30 ) {
              miniStats = rbind(miniStats, cbind( minilog_uid=id, res ) )
              next()
            } else {

              bcp = list(id=id, nr=nrow(M), YR=yr, tdif.min=3, tdif.max=11, time.gate=time.gate,
                         depth.min=20, depth.range=c(-25,15), eps.depth = 2 ,
                         smooth.windowsize=5, modal.windowsize=5,
                         noisefilter.trim=0.025, noisefilter.target.r2=0.85, noisefilter.quants=c(0.025, 0.975) )
              bcp = bottom.contact.parameters( bcp ) # add other default parameters .. not specified above
              bc =  NULL
              bc = bottom.contact( x=M, bcp=bcp )

              redo = FALSE
              if ( is.null(bc) ) redo =TRUE
              if ( !is.null(bc) && exists("res", bc)) {
                if ( !is.finite(bc$res$t0 ) || !is.finite(bc$res$t1 ) ) redo = TRUE
              }
              if (redo) {
                 bcp$noisefilter.target.r2=0.8
                 bc = bottom.contact( x=M, bcp=bcp )
                 redo = FALSE
              }

              if ( is.null(bc) ) redo =TRUE
              if ( !is.null(bc) && exists("res", bc)) {
                if ( !is.finite(bc$res$t0 ) || !is.finite(bc$res$t1 ) ) redo = TRUE
              }
              if (redo) {
                 bcp$noisefilter.target.r2=0.75
                 bcp$noisefilter.trim=0.05
                 bcp$noisefilter.quants=c(0.025, 0.975)
                 bc = bottom.contact( x=M, bcp=bcp )
                 redo = FALSE
              }

              if (!is.null(bc) ) {
                if (plotdata) {
                  bottom.contact.plot( bc )
                  plotfn = file.path( plotdir, paste(id, "pdf", sep="." ) )
                  print (plotfn)
                  dev.flush()
                  dev.copy2pdf( file=plotfn )
                }
              }
              if ( !is.null(bc) && !is.null(bc$res) ) {
                res = bc$res
                miniStats = rbind(miniStats, cbind( minilog_uid=id, res ) )
              }
            } #end if dat
          } # end if badlist

        } #end nrow id

        # time needs to be reset as posix as it gets lost with rbind/cbind
        miniStats$minilog_uid =  as.character(miniStats$minilog_uid)
        miniStats$t0 = as.POSIXct(miniStats$t0,origin=lubridate::origin, tz="UTC" )
        miniStats$t1 = as.POSIXct(miniStats$t1,origin=lubridate::origin, tz="UTC")
        miniStats$dt = difftime( miniStats$t1, miniStats$t0 )

        # minidt = miniStats$dt
        # miniStats$dt = NA
        # i = which(!is.na( minidt ) )
        # if (length(i) >0 ) miniStats$dt[i] = minidt[i]

        save( miniStats, file=fn, compress=TRUE )
      } # end for year

      return ( minilog.dir )
    }

    # --------------------------------

    if (DS %in% c("set.minilog.lookuptable", "set.minilog.lookuptable.redo") ) {

      fn = file.path( minilog.dir, "set.minilog.lookuptable.rdata" )

      if (DS=="set.minilog.lookuptable" ) {
        B = NULL
        if ( file.exists( fn) ) load (fn)
        return (B)
      }

      B = minilog.db( DS="metadata" )

      # double check .. should not be necessary .. but in case
      uuid = paste( B$trip, B$set, sep="." )
      dups = which( duplicated( uuid) )

      if (length(dups > 0 ) ) {
        toremove =NULL
        for (i in dups) {
          di = which( uuid == uuid[i] )
          tdiff = difftime( B$set_timestamp[di], B$timestamp[di])
          oo = which.min( abs( tdiff) )
          toremove = c(toremove, di[-oo] )
          print("----")
          print( "Matching based upon closest time stamps")
          print(B[di, ])
          print( "Choosing: ")
          print(B[di[oo], ])
          print("")
          toremove = c(toremove, di[-oo] )
        }
        B = B[ -toremove, ]
      }
      B = B[, c("trip", "set", "minilog_uid" )]
      save(B, file=fn, compress=TRUE )
      return(fn)
    }
	}


suppressMessages(usePackage(ggplot2))
suppressMessages(usePackage(dplyr))
suppressMessages(usePackage(tidyr))
suppressMessages(usePackage(reshape2))
suppressMessages(usePackage(RColorBrewer))
suppressMessages(usePackage(MASS))
suppressMessages(usePackage(speedglm))
suppressMessages(usePackage(boot))
suppressMessages(usePackage(devtools))
suppressMessages(usePackage(psych))

source("./R/get_functions.r")

runTest <- function(cov, dir){
  covtmp <- covdat %>% filter(Cov==cov)
  if(dir=="Up"){
    covdir <- covtmp %>% filter(Est>0)
  } else {
    covdir <- covtmp %>% filter(Est<0)
  }

  dnmstmp <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", substr(chrpfdnm$SEQ, 0, 7)) %in%
    paste0(covdir$Category, "_", covdir$Sequence),]
  if(nrow(dnmstmp)>=5){
    if(cov=="GC"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_gc"
      dnmstmp$GC <- gcCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/output/3bp_10k/full_bin.txt")
      dnmstmp$inside <- ifelse(dnmstmp$GC>=0.55, 1, 0)
    } else if(cov=="TIME"){
      dnmstmp$TIME <- repCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/lymph_rep_time.txt")
      if(dir=="Down"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/late_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME<=-1.25, 1, 0)
      } else if(dir=="Up"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/early_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME>=1.25, 1, 0)
      }
    } else if(cov=="RR"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_rr"
      dnmstmp$RR <- rcrCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/recomb_rate.bed")
      dnmstmp$inside <- ifelse(dnmstmp$RR>=2, 1, 0)
    } else if(cov=="DHS"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/DHS"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="CpGI"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/cpg_islands_sorted"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="LAMIN"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/lamin_B1_LADS2"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else {
      covbase <- paste0("/net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov)
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    }

    obs <- sum(dnmstmp$inside)

    seqs <- unlist(c(covdir$Sequence, lapply(covdir$Sequence, revcomp)))
    write.table(seqs, "/net/bipolar/jedidiah/mutation/seqs.txt", col.names=F, row.names=F, quote=F, sep="\t")

    grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqs.txt ", covbase, ".fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
    system(grepcmd)

    motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

    names(motifcts) <- c("Count", "SEQ")
    motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
    motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
      motifcts$SEQ, motifcts$REVSEQ)
      # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
      # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
    motifcts2 <- motifcts %>%
      group_by(Sequence) %>%
      summarise(Count=sum(Count))
    covdir2 <- merge(covdir, motifcts2, by=c("Sequence"))

    covdir3 <- merge(covdir2, motifdat, by=c("Category", "Sequence"))
    covdir3$exp <- covdir3$Count*covdir3$rel_prop*1.67e-06*1074
    exp <- sum(covdir3$exp)

    total <- nrow(dnmstmp)
    test <- prop.test(c(obs, exp), c(total, total))
    newrow <- data.frame(cov, dir=dir, obs=obs, exp=exp, n=total,
      propobs=test$estimate[1], propexp=test$estimate[2], pval=test$p.value)
    # testdat <- rbind(testdat, newrow)
    newrow
  }
}

motiffile <- "/net/bipolar/jedidiah/mutation/output/7bp_1000k_rates.txt"
motifdat <- read.table(motiffile, header=T, stringsAsFactors=F)
motifdat <- motifdat %>%
  mutate(Category=gsub("cpg_", "", Category2)) %>%
  mutate(Sequence=substr(Sequence, 0, 7)) %>%
  dplyr::select(Category, Sequence, rel_prop)

covdat <- read.table("/net/bipolar/jedidiah/mutation/fa_motifs.txt", header=T, stringsAsFactors=F)
covdat$Category <- gsub("cpg_", "", covdat$Category)
covs <- unique(covdat$Cov)
# covs <- covs[grepl("H3", covs)]
testdat <- data.frame()
covdir <- covdat %>%
  mutate(Dir=ifelse(Est>=0, "Up", "Down")) %>%
  group_by(Cov, Dir) %>%
  summarise(n=n())
for(i in 1:nrow(covdir)){
  cov <- covdir[i,]$Cov
  dir <- covdir[i,]$Dir
  if(covdir[i,]$n > 10){
    row <- runTest(cov, dir)
    testdat <- rbind(testdat, row)
  }
}
suppressMessages(usePackage(ggplot2))
suppressMessages(usePackage(dplyr))
suppressMessages(usePackage(tidyr))
suppressMessages(usePackage(reshape2))
suppressMessages(usePackage(RColorBrewer))
suppressMessages(usePackage(MASS))
suppressMessages(usePackage(speedglm))
suppressMessages(usePackage(boot))
suppressMessages(usePackage(devtools))
suppressMessages(usePackage(psych))

source("./R/get_functions.r")

runTest <- function(cov, dir){
  covtmp <- covdat %>% filter(Cov==cov)
  if(dir=="Up"){
    covdir <- covtmp %>% filter(Est>0)
  } else {
    covdir <- covtmp %>% filter(Est<0)
  }

  dnmstmp <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", substr(chrpfdnm$SEQ, 0, 7) %in%
    paste0(covdir$Category, "_", covdir$Sequence),]
  if(nrow(dnmstmp)>=5){
    if(cov=="GC"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_gc"
      dnmstmp$GC <- gcCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/output/3bp_10k/full_bin.txt")
      dnmstmp$inside <- ifelse(dnmstmp$GC>=0.55, 1, 0)
    } else if(cov=="TIME"){
      dnmstmp$TIME <- repCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/lymph_rep_time.txt")
      if(dir=="Down"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/late_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME<=-1.25, 1, 0)
      } else if(dir=="Up"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/early_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME>=1.25, 1, 0)
      }
    } else if(cov=="RR"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_rr"
      dnmstmp$RR <- rcrCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/recomb_rate.bed")
      dnmstmp$inside <- ifelse(dnmstmp$RR>=2, 1, 0)
    } else if(cov=="DHS"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/DHS"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="CpGI"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/cpg_islands_sorted"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="LAMIN"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/lamin_B1_LADS2"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else {
      covbase <- paste0("/net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov)
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    }

    obs <- sum(dnmstmp$inside)

    seqs <- unlist(c(covdir$Sequence, lapply(covdir$Sequence, revcomp)))
    write.table(seqs, "/net/bipolar/jedidiah/mutation/seqs.txt", col.names=F, row.names=F, quote=F, sep="\t")

    grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqs.txt ", covbase, ".fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
    system(grepcmd)

    motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

    names(motifcts) <- c("Count", "SEQ")
    motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
    motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
      motifcts$SEQ, motifcts$REVSEQ)
      # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
      # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
    motifcts2 <- motifcts %>%
      group_by(Sequence) %>%
      summarise(Count=sum(Count))
    covdir2 <- merge(covdir, motifcts2, by=c("Sequence"))

    covdir3 <- merge(covdir2, motifdat, by=c("Category", "Sequence"))
    covdir3$exp <- covdir3$Count*covdir3$rel_prop*1.67e-06*1074
    exp <- sum(covdir3$exp)

    total <- nrow(dnmstmp)
    test <- prop.test(c(obs, exp), c(total, total))
    newrow <- data.frame(cov, dir=dir, obs=obs, exp=exp, n=total,
      propobs=test$estimate[1], propexp=test$estimate[2], pval=test$p.value)
    # testdat <- rbind(testdat, newrow)
    newrow
  }
}

motiffile <- "/net/bipolar/jedidiah/mutation/output/7bp_1000k_rates.txt"
motifdat <- read.table(motiffile, header=T, stringsAsFactors=F)
motifdat <- motifdat %>%
  mutate(Category=gsub("cpg_", "", Category2)) %>%
  mutate(Sequence=substr(Sequence, 0, 7)) %>%
  dplyr::select(Category, Sequence, rel_prop)

covdat <- read.table("/net/bipolar/jedidiah/mutation/fa_motifs.txt", header=T, stringsAsFactors=F)
covdat$Category <- gsub("cpg_", "", covdat$Category)
covs <- unique(covdat$Cov)
# covs <- covs[grepl("H3", covs)]
testdat <- data.frame()
covdir <- covdat %>%
  mutate(Dir=ifelse(Est>=0, "Up", "Down")) %>%
  group_by(Cov, Dir) %>%
  summarise(n=n())
for(i in 1:nrow(covdir)){
  cov <- covdir[i,]$Cov
  dir <- covdir[i,]$Dir
  if(covdir[i,]$n > 10){
    row <- runTest(cov, dir)
    testdat <- rbind(testdat, row)
  }
}
suppressMessages(usePackage(ggplot2))
suppressMessages(usePackage(dplyr))
suppressMessages(usePackage(tidyr))
suppressMessages(usePackage(reshape2))
suppressMessages(usePackage(RColorBrewer))
suppressMessages(usePackage(MASS))
suppressMessages(usePackage(speedglm))
suppressMessages(usePackage(boot))
suppressMessages(usePackage(devtools))
suppressMessages(usePackage(psych))

source("./R/get_functions.r")

runTest <- function(cov, dir){
  covtmp <- covdat %>% filter(Cov==cov)
  if(dir=="Up"){
    covdir <- covtmp %>% filter(Est>0)
  } else {
    covdir <- covtmp %>% filter(Est<0)
  }

  dnmstmp <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covdir$Category, "_", covdir$Sequence),]
  if(nrow(dnmstmp)>=5){
    if(cov=="GC"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_gc"
      dnmstmp$GC <- gcCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/output/3bp_10k/full_bin.txt")
      dnmstmp$inside <- ifelse(dnmstmp$GC>=0.55, 1, 0)
    } else if(cov=="TIME"){
      dnmstmp$TIME <- repCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/lymph_rep_time.txt")
      if(dir=="Down"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/late_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME<=-1.25, 1, 0)
      } else if(dir=="Up"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/early_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME>=1.25, 1, 0)
      }
    } else if(cov=="RR"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_rr"
      dnmstmp$RR <- rcrCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/recomb_rate.bed")
      dnmstmp$inside <- ifelse(dnmstmp$RR>=2, 1, 0)
    } else if(cov=="DHS"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/DHS"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="CpGI"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/cpg_islands_sorted"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="LAMIN"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/lamin_B1_LADS2"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else {
      covbase <- paste0("/net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov)
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    }

    obs <- sum(dnmstmp$inside)

    seqs <- unlist(c(covdir$Sequence, lapply(covdir$Sequence, revcomp)))
    write.table(seqs, "/net/bipolar/jedidiah/mutation/seqs.txt", col.names=F, row.names=F, quote=F, sep="\t")

    grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqs.txt ", covbase, ".fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
    system(grepcmd)

    motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

    names(motifcts) <- c("Count", "SEQ")
    motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
    motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
      motifcts$SEQ, motifcts$REVSEQ)
      # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
      # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
    motifcts2 <- motifcts %>%
      group_by(Sequence) %>%
      summarise(Count=sum(Count))
    covdir2 <- merge(covdir, motifcts2, by=c("Sequence"))

    covdir3 <- merge(covdir2, motifdat, by=c("Category", "Sequence"))
    covdir3$exp <- covdir3$Count*covdir3$rel_prop*1.67e-06*1074
    exp <- sum(covdir3$exp)

    total <- nrow(dnmstmp)
    test <- prop.test(c(obs, exp), c(total, total))
    newrow <- data.frame(cov, dir=dir, obs=obs, exp=exp, n=total,
      propobs=test$estimate[1], propexp=test$estimate[2], pval=test$p.value)
    # testdat <- rbind(testdat, newrow)
    newrow
  }
}

motiffile <- "/net/bipolar/jedidiah/mutation/output/7bp_1000k_rates.txt"
motifdat <- read.table(motiffile, header=T, stringsAsFactors=F)
motifdat <- motifdat %>%
  mutate(Category=gsub("cpg_", "", Category2)) %>%
  mutate(Sequence=substr(Sequence, 0, 7)) %>%
  dplyr::select(Category, Sequence, rel_prop)

covdat <- read.table("/net/bipolar/jedidiah/mutation/fa_motifs.txt", header=T, stringsAsFactors=F)
covdat$Category <- gsub("cpg_", "", covdat$Category)
covs <- unique(covdat$Cov)
# covs <- covs[grepl("H3", covs)]
testdat <- data.frame()
covdir <- covdat %>%
  mutate(Dir=ifelse(Est>=0, "Up", "Down")) %>%
  group_by(Cov, Dir) %>%
  summarise(n=n())
for(i in 1:nrow(covdir)){
  cov <- covdir[i,]$Cov
  dir <- covdir[i,]$Dir
  if(covdir[i,]$n > 10){
    row <- runTest(cov, dir)
    testdat <- rbind(testdat, row)
  }
}
#' Create an SBATCH option
#'
#' @param key The key for the sbatch option.
#'
#' @return A function that takes a single argument representing
#' the value for the \code{key}.
sbatch_opt <- function(key) {
    return(function(value) {
        return(paste0("--", key, "=", value))
    })
}


#' A list of sbatch options.
#'
#' The value of each item in the list is a string or a function
#' which takes a string as a parameter, using \code{sbatch_opt}.
#'
#' To ensure proper formatting, the \code{mail_type} option should
#' be set using \code{sbatch_mail_types}. Multiple mail types need
#' to be comma seperated.
#'
#' @export
sbatch_opts <- list (
    begin = sbatch_opt("begin"),
    cpus_per_task = sbatch_opt("cpus-per-task"),
    mail_type = sbatch_opt("mail-type"),
    mail_user = sbatch_opt("mail-user"),
    memory = sbatch_opt("mem"),
    nodes = sbatch_opt("nodes"),
    ouput = sbatch_opt("ouput"),
    time = sbatch_opt("time")
)


#' A list of sbatch mail types.
#'
#' The value of each item in the list is a string representing
#' a mail type option.
#'
#' @export
sbatch_mail_types <- list(
    all = "ALL",
    begin = "BEGIN",
    end = "END",
    fail = "FAIL",
    none = "NONE",
    requeue = "REQUEUE",
    stage_out = "STAGE_OUT",
    time_limit = "TIME_LIMIT",
    time_limit_90 = "TIME_LIMIT_90",
    time_limit_80 = "TIME_LIMIT_80",
    time_limit_50 = "TIME_LIMIT_50"
)
suppressMessages(usePackage(ggplot2))
suppressMessages(usePackage(dplyr))
suppressMessages(usePackage(tidyr))
suppressMessages(usePackage(reshape2))
suppressMessages(usePackage(RColorBrewer))
suppressMessages(usePackage(MASS))
suppressMessages(usePackage(speedglm))
suppressMessages(usePackage(boot))
suppressMessages(usePackage(devtools))
suppressMessages(usePackage(psych))

source("./R/get_functions.r")

runTest <- function(cov, dir){
  covtmp <- covdat %>% filter(Cov==cov)
  if(dir=="Up"){
    covdir <- covtmp %>% filter(Est>0)
  } else {
    covdir <- covtmp %>% filter(Est<0)
  }

  dnmstmp <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covdir$Category, "_", covdir$Sequence),]
  if(nrow(dnmstmpup)>=5){
    if(cov=="GC"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_gc"
      dnmstmp$GC <- gcCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/output/3bp_10k/full_bin.txt")
      dnmstmp$inside <- ifelse(dnmstmp$GC>=0.55, 1, 0)
    } else if(cov=="TIME"){
      dnmstmp$TIME <- repCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/lymph_rep_time.txt")
      if(dir=="Down"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/late_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME<=-1.25, 1, 0)
      } else if(dir=="Up"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/early_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME>=1.25, 1, 0)
      }
    } else if(cov=="RR"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_rr"
      dnmstmp$RR <- rcrCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/recomb_rate.bed")
      dnmstmp$inside <- ifelse(dnmstmp$RR>=2, 1, 0)
    } else if(cov=="DHS"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/DHS"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="CpGI"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/cpg_islands_sorted"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="LAMIN"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/lamin_B1_LADS2"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else {
      covbase <- paste0("/net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov)
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    }

    obs <- sum(dnmstmp$inside)

    seqs <- unlist(c(covdir$Sequence, lapply(covdir$Sequence, revcomp)))
    write.table(seqs, "/net/bipolar/jedidiah/mutation/seqs.txt", col.names=F, row.names=F, quote=F, sep="\t")

    grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqs.txt ", covbase, ".fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
    system(grepcmd)

    motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

    names(motifcts) <- c("Count", "SEQ")
    motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
    motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
      motifcts$SEQ, motifcts$REVSEQ)
      # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
      # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
    motifcts2 <- motifcts %>%
      group_by(Sequence) %>%
      summarise(Count=sum(Count))
    covdir2 <- merge(covdir, motifcts2, by=c("Sequence"))

    covdir3 <- merge(covdir2, motifdat, by=c("Category", "Sequence"))
    covdir3$exp <- covdir3$Count*covdir3$rel_prop*1.67e-06*1074
    exp <- sum(covdir3$exp)

    total <- nrow(dnmstmp)
    test <- prop.test(c(obs, exp), c(total, total))
    newrow <- data.frame(cov, dir=dir, obs=obs, exp=exp, n=total,
      propobs=test$estimate[1], propexp=test$estimate[2], pval=test$p.value)
    # testdat <- rbind(testdat, newrow)
    newrow
  }
}

motiffile <- "/net/bipolar/jedidiah/mutation/output/7bp_1000k_rates.txt"
motifdat <- read.table(motiffile, header=T, stringsAsFactors=F)
motifdat <- motifdat %>%
  mutate(Category=gsub("cpg_", "", Category2)) %>%
  mutate(Sequence=substr(Sequence, 0, 7)) %>%
  dplyr::select(Category, Sequence, rel_prop)

covdat <- read.table("/net/bipolar/jedidiah/mutation/fa_motifs.txt", header=T, stringsAsFactors=F)
covdat$Category <- gsub("cpg_", "", covdat$Category)
covs <- unique(covdat$Cov)
# covs <- covs[grepl("H3", covs)]
testdat <- data.frame()
covdir <- covdat %>%
  mutate(Dir=ifelse(Est>=0, "Up", "Down")) %>%
  group_by(Cov, Dir) %>%
  summarise(n=n())
for(i in 1:nrow(covdir)){
  cov <- covdir[i,]$Cov
  dir <- covdir[i,]$Dir
  if(covdir[i,]$n > 10){
    row <- runTest(cov, dir)
    testdat <- rbind(testdat, row)
  }
}
source("./R/get_functions.r")

runTest <- function(cov, dir){
  covtmp <- covdat %>% filter(Cov==cov)
  if(dir=="Up"){
    covdir <- covtmp %>% filter(Est>0)
  } else {
    covdir <- covtmp %>% filter(Est<0)
  }

  dnmstmp <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covdir$Category, "_", covdir$Sequence),]
  if(nrow(dnmstmpup)>=5){
    if(cov=="GC"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_gc"
      dnmstmp$GC <- gcCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/output/3bp_10k/full_bin.txt")
      dnmstmp$inside <- ifelse(dnmstmp$GC>=0.55, 1, 0)
    } else if(cov=="TIME"){
      dnmstmp$TIME <- repCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/lymph_rep_time.txt")
      if(dir=="Down"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/late_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME<=-1.25, 1, 0)
      } else if(dir=="Up"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/early_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME>=1.25, 1, 0)
      }
    } else if(cov=="RR"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_rr"
      dnmstmp$RR <- rcrCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/recomb_rate.bed")
      dnmstmp$inside <- ifelse(dnmstmp$RR>=2, 1, 0)
    } else if(cov=="DHS"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/DHS"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="CpGI"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/cpg_islands_sorted"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="LAMIN"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/lamin_B1_LADS2"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else {
      covbase <- paste0("/net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov)
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    }

    obs <- sum(dnmstmp$inside)

    seqs <- unlist(c(covdir$Sequence, lapply(covdir$Sequence, revcomp)))
    write.table(seqs, "/net/bipolar/jedidiah/mutation/seqs.txt", col.names=F, row.names=F, quote=F, sep="\t")

    grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqs.txt ", covbase, ".fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
    system(grepcmd)

    motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

    names(motifcts) <- c("Count", "SEQ")
    motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
    motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
      motifcts$SEQ, motifcts$REVSEQ)
      # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
      # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
    motifcts2 <- motifcts %>%
      group_by(Sequence) %>%
      summarise(Count=sum(Count))
    covdir2 <- merge(covdir, motifcts2, by=c("Sequence"))

    covdir3 <- merge(covdir2, motifdat, by=c("Category", "Sequence"))
    covdir3$exp <- covdir3$Count*covdir3$rel_prop*1.67e-06*1074
    exp <- sum(covdir3$exp)

    total <- nrow(dnmstmp)
    test <- prop.test(c(obs, exp), c(total, total))
    newrow <- data.frame(cov, dir=dir, obs=obs, exp=exp, n=total,
      propobs=test$estimate[1], propexp=test$estimate[2], pval=test$p.value)
    # testdat <- rbind(testdat, newrow)
    newrow
  }
}

motiffile <- "/net/bipolar/jedidiah/mutation/output/7bp_1000k_rates.txt"
motifdat <- read.table(motiffile, header=T, stringsAsFactors=F)
motifdat <- motifdat %>%
  mutate(Category=gsub("cpg_", "", Category2)) %>%
  mutate(Sequence=substr(Sequence, 0, 7)) %>%
  dplyr::select(Category, Sequence, rel_prop)

covdat <- read.table("/net/bipolar/jedidiah/mutation/fa_motifs.txt", header=T, stringsAsFactors=F)
covdat$Category <- gsub("cpg_", "", covdat$Category)
covs <- unique(covdat$Cov)
# covs <- covs[grepl("H3", covs)]
testdat <- data.frame()
covdir <- covdat %>%
  mutate(Dir=ifelse(Est>=0, "Up", "Down")) %>%
  group_by(Cov, Dir) %>%
  summarise(n=n())
for(i in 1:nrow(covdir)){
  cov <- covdir[i,]$Cov
  dir <- covdir[i,]$Dir
  if(covdir[i,]$n > 10){
    row <- runTest(cov, dir)
    testdat <- rbind(testdat, row)
  }
}
source("./get_functions.r")

runTest <- function(cov, dir){
  covtmp <- covdat %>% filter(Cov==cov)
  if(dir=="Up"){
    covdir <- covtmp %>% filter(Est>0)
  } else {
    covdir <- covtmp %>% filter(Est<0)
  }

  dnmstmp <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covdir$Category, "_", covdir$Sequence),]
  if(nrow(dnmstmpup)>=5){
    if(cov=="GC"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_gc"
      dnmstmp$GC <- gcCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/output/3bp_10k/full_bin.txt")
      dnmstmp$inside <- ifelse(dnmstmp$GC>=0.55, 1, 0)
    } else if(cov=="TIME"){
      dnmstmp$TIME <- repCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/lymph_rep_time.txt")
      if(dir=="Down"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/late_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME<=-1.25, 1, 0)
      } else if(dir=="Up"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/early_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME>=1.25, 1, 0)
      }
    } else if(cov=="RR"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_rr"
      dnmstmp$RR <- rcrCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/recomb_rate.bed")
      dnmstmp$inside <- ifelse(dnmstmp$RR>=2, 1, 0)
    } else if(cov=="DHS"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/DHS"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="CpGI"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/cpg_islands_sorted"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="LAMIN"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/lamin_B1_LADS2"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else {
      covbase <- paste0("/net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov)
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    }

    obs <- sum(dnmstmp$inside)

    seqs <- unlist(c(covdir$Sequence, lapply(covdir$Sequence, revcomp)))
    write.table(seqs, "/net/bipolar/jedidiah/mutation/seqs.txt", col.names=F, row.names=F, quote=F, sep="\t")

    grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqs.txt ", covbase, ".fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
    system(grepcmd)

    motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

    names(motifcts) <- c("Count", "SEQ")
    motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
    motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
      motifcts$SEQ, motifcts$REVSEQ)
      # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
      # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
    motifcts2 <- motifcts %>%
      group_by(Sequence) %>%
      summarise(Count=sum(Count))
    covdir2 <- merge(covdir, motifcts2, by=c("Sequence"))

    covdir3 <- merge(covdir2, motifdat, by=c("Category", "Sequence"))
    covdir3$exp <- covdir3$Count*covdir3$rel_prop*1.67e-06*1074
    exp <- sum(covdir3$exp)

    total <- nrow(dnmstmp)
    test <- prop.test(c(obs, exp), c(total, total))
    newrow <- data.frame(cov, dir=dir, obs=obs, exp=exp, n=total,
      propobs=test$estimate[1], propexp=test$estimate[2], pval=test$p.value)
    # testdat <- rbind(testdat, newrow)
    newrow
  }
}

motiffile <- "/net/bipolar/jedidiah/mutation/output/7bp_1000k_rates.txt"
motifdat <- read.table(motiffile, header=T, stringsAsFactors=F)
motifdat <- motifdat %>%
  mutate(Category=gsub("cpg_", "", Category2)) %>%
  mutate(Sequence=substr(Sequence, 0, 7)) %>%
  dplyr::select(Category, Sequence, rel_prop)

covdat <- read.table("/net/bipolar/jedidiah/mutation/fa_motifs.txt", header=T, stringsAsFactors=F)
covdat$Category <- gsub("cpg_", "", covdat$Category)
covs <- unique(covdat$Cov)
# covs <- covs[grepl("H3", covs)]
testdat <- data.frame()
covdir <- covdat %>%
  mutate(Dir=ifelse(Est>=0, "Up", "Down")) %>%
  group_by(Cov, Dir) %>%
  summarise(n=n())
for(i in 1:nrow(covdir)){
  cov <- covdir[i,]$Cov
  dir <- covdir[i,]$Dir
  if(covdir[i,]$n > 10){
    row <- runTest(cov, dir)
    testdat <- rbind(testdat, row)
  }
}
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:
    filename <- 'Multiple_parameters'
    min.tx = 45
    K.values = c(2,4,6,8)
    MW = c(1,3,5)
    WT = c(0,0.3,0.6,1)
    blind = FALSE
    minimum_threshold = 0.3
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/Tanimoto_data.RData")
load("./RData/interactions_source.RData")
suppressMessages(load("./RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
# Format interaction catalogue to fit this table format
    S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
    S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
    }

# setting up the analyses for multiple communities
# Data for communities on which to test the algorithm
    Cm <- unique(interactions_sources[, 'source'])
    communities <- vector("list", length(Cm))
    names(communities) <- Cm

    # Taxa list per community to predict
        for(i in 1:length(communities)) {
            Ci <- which(interactions_sources[, 'source'] == Cm[i])
            S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

            if(length(which(!S1 %in% S0_catalog)) > 0) {
                print('Taxa in C[i] are not all included in taxa list S0')
                break
            }

            communities[[i]] <- S1
        }

# Substracting GloBI interactions for this portion
    Cm.lg <- numeric()
    for(i in 1:length(communities)) {
        Cm.lg <- c(Cm.lg,length(communities[[i]]))
    }

    to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

    Cm <- Cm[-to.delete]
    for(i in rev(to.delete)) {
        communities[[i]] <- NULL
    }
    names(communities) <- Cm

# Setting up lists to store the results
    wt.init <- wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
    wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
    for(i in rev(wt.remove)) {
        similarity.matrices[[i]] <- NULL
    }

    sim.wt <- names(similarity.matrices)
    Tanimoto_analysis <- vector("list",length(sim.wt))
    names(Tanimoto_analysis) <- sim.wt
    for(i in 1:length(sim.wt)) {
        Tanimoto_analysis[[i]] <- vector("list", length(Cm))
        names(Tanimoto_analysis[[i]]) <- Cm
    }

# List to store results of multiple K values
K <- vector("list", length(K.values))
for(i in 1:length(K.values)) {
    K[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- K
names(Tanimoto_analysis) <- K.values
remove(K)

min.wt <- vector("list", length(MW))
for(i in 1:length(MW)) {
    min.wt[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- min.wt
names(Tanimoto_analysis) <- MW
remove(min.wt)

file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
save(x = Tanimoto_analysis, file = file.to.save)

init.time <- Sys.time()
for(n in 1:length(MW)) {
    mw <- MW[n]
    for(m in 1:length(K.values)) {

        # Tanimoto analysis with different weights for different communities
            # Parameters:
                Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
            #   wt  Weight of traits in similarity measurement
            #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
            #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

            # Output:
            #   A vector of sets of resources for each taxon

            for(i in 1:length(WT)){ #1st loop for all types of wt values
                wt <- WT[i]
                pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                for(j in 1:length(Cm)) { #2nd loop for all C[i]
                    S1 <- communities[[j]]
                    S0 <- S0_catalog
                    similarity.matrix <- similarity.matrices[[i]]

                    # Two choices here:
                    #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                    #   2. The analysis takes into account preexisting information already contained in the catalogue

                    # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                    if(blind == TRUE) {
                        for(k in 1:length(S1)) {
                          S0[S1[k], 'resource'] <- ""
                          S0[S1[k], 'non-resource'] <- ""
                        }

                    # 2. Preexisting information kept to inform algorithm
                    } else { # blind == FALSE

                        interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                        # Only modifying those that are loosing data from the catalogue, less time
                            to.change <- numeric()
                            for(k in 1:length(S1)) {
                                to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                            }
                            to.change <- unique(to.change)

                        # Modifying sets of resources and non-resources for taxa in S1
                            interactions <- interactions[to.change, ]
                            rownames(interactions) <- seq(1,nrow(interactions))
                            resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                      resource = interactions[, 'resource'],
                                                                      inter_type = interactions[, 'inter'])

                        # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                            for(k in 1:nrow(resource_set)) {
                              S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                              S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                            }
                        remove(interactions, resource_set, to.change)
                    } #if blind or not blind

                    # Recalculate similarity
                        similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                            S1 = S1,
                                                                            wt = wt,
                                                                            similarity.matrix = similarity.matrix)

                    # Predicting interactions
                        Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                Kr = Kr,
                                                                                S0 = S0,
                                                                                S1 = S1,
                                                                                MW = mw,
                                                                                similarity.matrix = similarity.matrix,
                                                                                minimum_threshold = minimum_threshold)

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(S0, S1, similarity.matrix)
                    setTxtProgressBar(pb, j)
                }#2nd loop for all C[i]

                save(x = Tanimoto_analysis, file = file.to.save)
                remove(wt)

            }#1st loop for all types of wt values
            close(pb)
    }#m
}#n
print(Sys.time() - init.time)
save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))


# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=7,height=7)
# Plots
par(mfrow=c(2,2))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 50)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(WT) * length(K.values)), labels = FALSE, las = 1, pos = -0.02) #MW
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, nb.pts, by = length(WT)), labels = FALSE, las = 1, pos = 1.02) #wt
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = (nb.pts + 0.02))
            abline(v = seq(length(WT)+0.5,nb.pts-length(WT)+0.5,by = length(WT)), col = "grey", lty = 2)
            abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2), font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2), font = 1, cex = 0.75)

        # for(i in 1:length(accuracy)) {
        for(i in 2) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'MW']) + as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,48), accuracy_mean[, 4][,1] - accuracy_mean[, 4][, 2], seq(1,48), accuracy_mean[, 4][, 1] + accuracy_mean[, 4][, 2], length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,48), y = accuracy_mean[, 4][, 1], cex = 0.75, pch = 22, col = col[i])
        } #i

        # ## Add legend
        # if(j == 12) {
        #     legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j
dev.off()
#' SlurmSettings R6 object.
#'
#' An interface to SBATCH settings.
#'
#' @export
SlurmSettings <- R6::R6Class("SlurmSettings",
    public = list(
        nodes = NA,
        cpus_per_task = NA,
        time = NA,
        memory = NA,
        mail_to = NA,
        mail_type = NA,
        initialize = function(nodes = 1, cpus_per_task = 12,
                              time = "00:30:00", memory = "16g",
                              mail_to = NA, mail_type = "all") {
            self$nodes <- nodes
            self$cpus_per_task <- cpus_per_task
            self$time <- time
            self$memory <- memory

            if (!is.na(mail_to) && !is.na(mail_type)) {
                self$mail_to <- mail_to
                self$mail_type <- mail_type
            }
        },
        sbatch_comments = function() {
            sb <- "#SBATCH --"
            sb_nodes <- paste0(sb, "nodes=", self$nodes)
            sb_cpus_per_task <- paste0(sb, "cpus-per-task=",
                                       self$cpus_per_task)
            sb_time <- paste0(sb, "time=", self$time)
            sb_memory <- paste0(sb, "mem=", self$memory)

            comments <- paste(sb_nodes, sb_cpus_per_task, sb_time,
                              sb_memory, "#SBATCH -o R_job.o%j", sep = "\n")

            if (!is.na(self$mail_to)) {
                sb_mail_to <- paste0(sb, "mail-user=", self$mail_to)
                sb_mail_type <- paste0(sb, "mail-type=", self$mail_type)

                comments <- paste(comments, sb_mail_type, sb_mail_to, sep = "\n")
            }

            return(comments)
        }
    )
)
#' SlurmSettings R6 object.
#'
#' An interface to SBATCH settings.
#'
#' @export
SlurmSettings <- R6::R6Class("SlurmSettings",
    public = list(
        nodes = NA,
        cpus_per_task = NA,
        time = NA,
        memory = NA,
        mail_to = NA,
        mail_type = NA,
        initialize = function(nodes = 1, cpus_per_task = 12,
                              time = "00:30:00", memory = "16g",
                              mail_to = NA, mail_type = "all") {
            self$nodes <- nodes
            self$cpus_per_task <- cpus_per_task
            self$time <- time
            self$memory <- memory

            if (!is.na(self$mail_to) && !is.na(self$mail_type)) {
                self$mail_to <- mail_to
                self$mail_type <- mail_type
            }
        },
        sbatch_comments = function() {
            sb <- "#SBATCH --"
            sb_nodes <- paste0(sb, "nodes=", self$nodes)
            sb_cpus_per_task <- paste0(sb, "cpus-per-task=",
                                       self$cpus_per_task)
            sb_time <- paste0(sb, "time=", self$time)
            sb_memory <- paste0(sb, "mem=", self$memory)

            comments <- paste(sb_nodes, sb_cpus_per_task, sb_time,
                              sb_memory, "#SBATCH -o R_job.o%j", sep = "\n")

            if (!is.na(self$mail_to)) {
                sb_mail_to <- paste0(sb, "mail-user=", self$mail_to)
                sb_mail_type <- paste0(sb, "mail-type=", self$mail_type)

                comments <- paste(comments, sb_mail_type, sb_mail_to, sep = "\n")
            }

            return(commments)
        }
    )
)
## Author(s): Kalle von Feilitzen, Fredric J & Martin Hjelmare

# Gain calculation script
# Run with "Rscript path/to/script/gain.r path/to/working/dir/
# path/to/histogram-csv-filebase path/to/initialgains/csv-file"
# from linux command line.
# Repeat for each well.

# Gain calculation script
setwd(commandArgs(TRUE)[1])
filebase <- commandArgs(TRUE)[2]
# Initial gain values used
initialgains <- read.csv(commandArgs(TRUE)[3])$gain
gain <- list()
bins <- list()
gains <- list()
oks <- list()

green <- 11;    # 11 images
blue <- 18;     # 7 images
yellow <- 25;   # 7 images
red <- 32;      # 7 images
channel <- vector()
channel_name <- vector()
channel <- append(channel, rep(green, green-length(channel)))
channel_name <- append(channel_name, rep('green', green-length(channel_name)))
channel <- append(channel, rep(blue, blue-length(channel)))
channel_name <- append(channel_name, rep('blue', blue-length(channel_name)))
channel <- append(channel, rep(yellow, yellow-length(channel)))
channel_name <- append(channel_name, rep('yellow', yellow-length(channel_name)))
channel <- append(channel, rep(red, red-length(channel)))
channel_name <- append(channel_name, rep('red', red-length(channel_name)))
channels <- unique(channel)


for (i in 1:(length(channels))) {
  bins[[i]] <- vector()
  gains[[i]] <- vector()
  oks[[i]] <- vector()
}

# Create curve and function for each individual well
for (i in 1:32) {
  # Read histogram CSV file
  csvfile <- paste(filebase, "C", sprintf("%02d", i-1), ".ome.csv", sep="")
  csv <- read.csv(csvfile)
  csv1 <- csv[csv$count>0 & csv$bin>0,]
  bin1 <- csv1$bin
  count1 <- csv1$count
  # Only use values in interval 10-100
  binmax <- tail(csv$bin, n=1)
  # Find the max bin holding pixels
  binmax_count <- tail(bin1, n=1)
  # Remove data that is outside the interesting range
  csv2 <- csv[csv$count <= 100 & csv$count >= 10 & csv$bin < binmax & csv$bin > binmax_count-175,]
  bin2 <- csv2$bin
  count2 <- csv2$count
  # Plot values
  test <- 0
  png(filename=paste(filebase, "C", sprintf("%02d", i-1), ".ome.png", sep = ""))
  if (length(bin1) > 0) {
    plot(count1, bin1, log="xy")
  }
  # Fit curve
  sink("/dev/null")	# Suppress output
  curv <- tryCatch(nls(bin2 ~ A*count2^B, start=list(A = 1000, B=-1), trace=T),
                   warning=function(e) NULL,
                   error=function(e) NULL)
  sink()
  if (!is.null(curv)) {
    # Plot curve
    lines(count2, fitted.values(curv), lwd=2, col="green")
    # Find function and save gain value
    func <- function(val, A=coef(curv)[1], B=coef(curv)[2]) {A*val^B}
    B <- coef(curv)[2]
    chn <- which(channels==channel[i])
    bins[[chn]] <- append(bins[[chn]], func(2))	# 2 is close to 0 but safer
    gains[[chn]] <- append(gains[[chn]], initialgains[i])
    # curv is only ok if B is less than 0
    oks[[chn]] <- append(oks[[chn]], B < 0)
  }
  dev.off()
}

# Create curve and function for each channel (multiple wells)
for (i in 1:(length(channels))) {
  bins_c <- bins[[i]]
  gains_c <- gains[[i]]
  oks_c <- oks[[i]]
  png(filename=paste(filebase,
                     channel_name[channels[i]],
                     "_gain.png",
                     sep = ""))
  if (length(bins_c) >= 3) {
    plot(bins_c, gains_c)
    # Remove values not making an upward trend and above bin=600 (Martin Hjelmare)
    point.connected <- 0
    point.start <- 1
    point.end <- 1
    for (m in 1:(length(bins_c)-1)) {
      if (!oks_c[m]) {
        break
      }
      for (n in (m+1):length(bins_c)) {
        if(oks_c[n] & bins_c[n] <= 600 & bins_c[n] >= bins_c[n-1]) {
          if((n-m+1) > point.connected) {
            point.connected <- n-m+1
            point.start <- m
            point.end <- n
          }
        }
        else {
          break
        }
      }
    }
    bins_c <- bins_c[point.start:point.end]
    gains_c <- gains_c[point.start:point.end]
  }
  gain[[i]] <- round(initialgains[channels[i]])
  if (length(bins_c) >= 3) {
    # Fit curve
    sink("/dev/null")	# Suppress output
    curv2 <- tryCatch(nls(gains_c ~ C*bins_c^D,
                          start=list(C = 1, D=1),
                          trace=T),
                      warning=function(e) NULL,
                      error=function(e) NULL)
    sink()
    # Find function
    if (!is.null(curv2)) {
      func2 <- function(val, A=coef(curv2)[1], B=coef(curv2)[2]) {A*val^B}
      lines(bins_c, fitted.values(curv2), lwd=2, col="green")
      abline(v=binmax)
      gain[[i]] <- round(min(func2(binmax), gain[[i]]))
    }
  }
  dev.off()
}
cat(paste(gain[[1]], gain[[2]], gain[[3]], gain[[4]]))
#' SlurmSettings R6 object.
#'
#' An interface to SBATCH settings.
#'
#' @export
SlurmSettings <- R6::R6Class("SlurmSettings",
    public = list(
        nodes = NA,
        cpus_per_task = NA,
        time = NA,
        memory = NA,
        initialize = function(nodes = 1, cpus_per_task = 12,
                              time = "00:30:00", memory = "16g") {
            self$nodes <- nodes
            self$cpus_per_task <- cpus_per_task
            self$time <- time
            self$memory <- memory
        },
        sbatch_comments = function() {
            sb <- "#SBATCH --"
            sb_nodes <- paste0(sb, "nodes=", self$nodes)
            sb_cpus_per_task <- paste0(sb, "cpus-per-task=",
                                       self$cpus_per_task)
            sb_time <- paste0(sb, "time=", self$time)
            sb_memory <- paste0(sb, "mem=", self$memory)
            return(paste(sb_nodes, sb_cpus_per_task, sb_time,
                         sb_memory, "#SBATCH -o R_job.o%j", sep = "\n"))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file) {
            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file)
        }
    ),
    private = list(
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", basename(main_file), "'"), "], source)")
            loading <- paste("sapply(list.files('./.objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat(sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

# Flatten input directory
mv -r ./input .

main_file=$(basename $1)

R CMD BATCH ./sources/$main_file

cp -r * $SLURM_SUBMIT_DIR/output
cd $SLURM_SUBMIT_DIR/output
rm -rf ./input ./sources ./objects"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", basename(main_file), "'"), "], source)")
            loading <- paste("sapply(list.files('./.objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat(sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

# Flatten input directory
mv -r ./input .

main_file=$(basename $1)

R CMD BATCH ./sources/$main_file

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", basename(main_file), "'"), "], source)")
            loading <- paste("sapply(list.files('./.objects'), load)")
            running_main <- "main()"

            cat(sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

# Flatten input directory
mv -r ./input .

main_file=$(basename $1)

R CMD BATCH ./sources/$main_file

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources')[!(",
                              paste0("'", main_file, "'"),
                              "%in% list.files('./sources'))], source)")
            loading <- paste("sapply(list.files('./.objects'), load)")
            running_main <- "main()"

            cat(sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

# Flatten input directory
mv -r ./input .

main_file=$(basename $1)

R CMD BATCH ./sources/$main_file

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            name <- paste0("job_", private$rand_alphanumeric())
            dir <- paste(getwd(), dir, name, sep = "/")
            self$dir <- dir

            for (sub_dir in c("/input", "/output", "/sources", "/.objects")) {
                dir.create(paste0(dir, sub_dir), recursive = TRUE,
                           showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (!is.na(value)) {
                obj_dir <- paste0(self$dir, "/.objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        add_source = function(file) {
            if (file.exists(file)) {
                source_dir <- paste0(self$dir, "/sources")
                system(paste("cp -r", file, source_dir))
            } else {
                stop("Source file does not exist.")
            }
        },
        add_input = function(file) {
            if (file.exists(file)) {
                input_dir <- paste0(self$dir, "/input")
                system(paste("cp -r", file, input_dir))
            } else {
                stop("Source file does not exist.")
            }
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            name <- paste0("job_", private$rand_alphanumeric())
            dir <- paste(getwd(), dir, name, sep = "/")
            self$dir <- dir

            for (sub_dir in c("/input", "/output", "/sources", "/.objects")) {
                dir.create(paste0(dir, sub_dir), recursive = TRUE,
                           showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (!is.na(value)) {
                obj_dir <- paste0(self$dir, "/.objects")
                rdata <- paste0(name, ".Rdata")
                save(value, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        add_source = function(file) {
            if (file.exists(file)) {
                source_dir <- paste0(self$dir, "/sources")
                system(paste("cp -r", file, source_dir))
            } else {
                stop("Source file does not exist.")
            }
        },
        add_input = function(file) {
            if (file.exists(file)) {
                input_dir <- paste0(self$dir, "/input")
                system(paste("cp -r", file, input_dir))
            } else {
                stop("Source file does not exist.")
            }
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources')[!(",
                              paste0("'", main_file, "'"),
                              "%in% list.files('./sources'))], source)")
            loading <- paste("sapply(list.files('./.objects'), load)")
            running_main <- "main()"

            cat(sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

# Flatten input directory
mv -r ./input .

R CMD BATCH ./sources/$1

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources')[!(",
                              paste0("'", main_file, "'"),
                              "%in% list.files('./sources'))], source)")
            loading <- paste("sapply(list.files('./.objects'), load)")
            running_main <- "main()"

            cat(sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

R CMD BATCH ./source/$1

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
#'
#' @export
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in c(self$source_files, self$main_file)) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })

            script <- SlurmBashScript$new(container, self$main_file)
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            testthat::source_file(self$main_file, e)

            for (file in self$source_files) {
                testthat::source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources')[!(",
                              paste0("'", main_file, "'"),
                              "%in% list.files('./sources'))], source)")
            loading <- paste("sapply(list.files('./.objects'), load)")
            running_main <- "main()"

            cat(sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

R CMD BATCH ./source/$1

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("sbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in c(self$source_files, self$main_file)) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })

            script <- SlurmBashScript$new(container, self$main_file)
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(self$main_file, e)

            for (file in self$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$write_slurm_script(container$dir)
            private$write_slurm_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        write_slurm_script = function(dir) {
            contents <- "
#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./source ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

R CMD BATCH ./source/$1

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("sbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in c(self$source_files, self$main_file)) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })

            script <- SlurmBashScript$new(container, main_file)
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(self$main_file, e)

            for (file in self$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$write_slurm_script(container$dir)
            private$write_slurm_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        write_slurm_script = function(dir) {
            contents <- "
#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./source ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

R CMD BATCH $1

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("sbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = "*") {
            private$write_slurm_script(container$dir)
        }
    ),
    private = list(
        write_slurm_script = function(dir) {
            contents <- "
#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./source ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

R CMD BATCH $1

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in c(self$source_files, self$main_file)) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(self$main_file, e)

            for (file in self$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in self$source_files) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(self$main_file, e)

            for (file in self$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        container = NULL,
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in self$source_files) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }

                self$container <- container
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(self$main_file, e)

            for (file in self$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        container = NULL,
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in private$source_files) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }

                self$container <- container
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        container = NULL,
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        add_input_files = function(files) {
            for (file in c(files)) {
                if (!file.exists(file)) {
                    warning("Input file does not exist.")
                }
            }

            input_files <- c(input_files, files)
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in private$source_files) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }

                self$container <- container
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        container = NULL,
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        add_input_files = function(files) {
            for (file in c(files)) {
                if (!file.exists(file)) {
                    warning("Input file does not exist.")
                }
            }

            input_files <- c(input_files, files)
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            container <- SlurmContainer$new(container_location)

            for (name in names(self$params)) {
                container$add_object(name, self$params[[name]])
            }

            for (file in private$source_files) {
                container$add_source(file)
            }

            for (file in self$input_files) {
                container$add_input(file)
            }

            self$container <- container
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            name <- paste0("job_", private$rand_alphanumeric())
            dir <- paste(getwd(), dir, name, sep = "/")
            self$dir <- dir

            for (sub_dir in c("/input", "/ouput", "/sources", "/.objects")) {
                dir.create(paste0(dir, sub_dir), recursive = TRUE,
                           showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            obj_dir <- paste0(self$dir, "/.objects")
            rdata <- paste0(name, ".Rdata")
            save(value, file = paste(obj_dir, rdata, sep = "/"))
        },
        add_source = function(file) {
            if (file.exists(file)) {
                source_dir <- paste0(self$dir, "/sources")
                system(paste("cp", file, source_dir))
            } else {
                warning("Source file does not exist.")
            }
        },
        add_input = function(file) {
            if (file.exists(file)) {
                input_dir <- paste0(self$dir, "/input")
                system(paste("cp", file, input_dir))
            } else {
                warning("Source file does not exist.")
            }
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        container = NULL,
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()

                self$container <- SlurmContainer$new(container_location)
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        add_input_files = function(files) {
            for (file in c(files)) {
                if (!file.exists(file)) {
                    warning("Input file does not exist.")
                }
            }

            input_files <- c(input_files, files)
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            for (name in names(self$params)) {
                self$container$add_object(name, self$params[[name]])
            }

            for (file in private$source_files) {
                self$container$add_source(file)
            }

            for (file in self$input_files) {
                self$container$add_input(file)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            name <- paste0("job_", private$rand_alphanumeric())
            dir <- paste(getwd(), dir, name, sep = "/")
            self$dir <- dir

            for (sub_dir in c("/input", "/ouput", "/sources", "/.objects")) {
                dir.create(paste0(dir, sub_dir), recursive = TRUE,
                           showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            obj_dir <- paste0(self$dir, "/.objects")
            rdata <- paste0(name, ".Rdata")
            save(value, paste(obj_dir, rdata, sep = "/"))
        },
        add_source = function(file) {
            if (file.exists(file)) {
                source_dir <- paste0(self$dir, "/source")
                system(paste("cp", file, source_dir))
            } else {
                warning("Source file does not exist.")
            }
        },
        add_input = function(file) {
            if (file.exists(file)) {
                input_dir <- paste0(self$dir, "/input")
                system(paste("cp", file, input_dir))
            } else {
                warning("Source file does not exist.")
            }
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        container = NULL,
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()

                self$container <- SlurmContainer$new(container_location)
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        add_input_files = function(files) {
            for (file in c(files)) {
                if (!file.exists(file)) {
                    warning("Input file does not exist.")
                }
            }

            input_files <- c(input_files, files)
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            for (name in names(self$params)) {
                self$container$add_object(name, self$params[[name]])
            }

            # Copy source files to sources directory
            for (file in private$source_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/sources"))
                system(cmd)
            }

            # Copy input files to input directory
            for (file in self$input_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/input"))
                system(cmd)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            name <- paste0("job_", private$rand_alphanumeric())
            dir <- paste(getwd(), dir, name, sep = "/")
            self$dir <- dir

            for (sub_dir in c("/input", "/ouput", "/sources", "/.objects")) {
                dir.create(paste0(dir, sub_dir), recursive = TRUE,
                           showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            obj_dir <- paste0(self$dir, "/.objects")
            rdata <- paste0(name, ".Rdata")
            save(value, paste(obj_dir, rdata, sep = "/"))
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        container = NULL,
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()

                self$container <- SlurmContainer$new(container_location)
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        add_input_files = function(files) {
            for (file in c(files)) {
                if (!file.exists(file)) {
                    warning("Input file does not exist.")
                }
            }

            input_files <- c(input_files, files)
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            objects_dir <- paste(private$base_dir, ".objects", sep = "/")

            for (param in names(self$params)) {
                value <- self$params[[param]]
                rdata <- paste(objects_dir, paste0(param, ".RData"), sep = "/")
                save(value, file = rdata)
            }

            # Copy source files to sources directory
            for (file in private$source_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/sources"))
                system(cmd)
            }

            # Copy input files to input directory
            for (file in self$input_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/input"))
                system(cmd)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            name <- paste0("job_", private$rand_alphanumeric())
            dir <- paste(getwd(), dir, name, sep = "/")
            self$dir <- dir

            for (sub_dir in c("/input", "/ouput", "/sources", "/.objects")) {
                dir.create(paste0(dir, sub_dir), recursive = TRUE,
                           showWarnings = FALSE)
            }
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        add_input_files = function(files) {
            for (file in c(files)) {
                if (!file.exists(file)) {
                    warning("Input file does not exist.")
                }
            }

            input_files <- c(input_files, files)
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            private$generate_container()
            objects_dir <- paste(private$base_dir, ".objects", sep = "/")

            for (param in names(self$params)) {
                value <- self$params[[param]]
                rdata <- paste(objects_dir, paste0(param, ".RData"), sep = "/")
                save(value, file = rdata)
            }

            # Copy source files to sources directory
            for (file in private$source_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/sources"))
                system(cmd)
            }

            # Copy input files to input directory
            for (file in self$input_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/input"))
                system(cmd)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        },
        generate_container = function() {
            private$base_dir <- paste0(private$base_dir, "/job")
            bd <- paste0(private$base_dir, "/")
            dir.create(paste0(bd, "input"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "output"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "sources"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, ".objects"), recursive = TRUE, showWarnings = FALSE)

        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        add_input_files = function(files) {
            for (file in c(files)) {
                if (!file.exists(file)) {
                    warning("Input file does not exist.")
                }
            }

            input_files <- c(input_files, files)
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            private$generate_container()
            objects_dir <- paste(private$base_dir, ".objects", sep = "/")

            for (param in names(self$params)) {
                value <- self$params[[param]]
                rdata <- paste(objects_dir, paste0(param, ".RData"), sep = "/")
                save(value, file = rdata)
            }

            # Copy source files to sources directory
            for (file in private$source_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/sources"))
                system(cmd)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        },
        generate_container = function() {
            private$base_dir <- paste0(private$base_dir, "/job")
            bd <- paste0(private$base_dir, "/")
            dir.create(paste0(bd, "input"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "output"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "sources"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, ".objects"), recursive = TRUE, showWarnings = FALSE)

        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        stop("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            private$generate_container()
            objects_dir <- paste(private$base_dir, ".objects", sep = "/")

            for (param in names(self$params)) {
                value <- self$params[[param]]
                rdata <- paste(objects_dir, paste0(param, ".RData"), sep = "/")
                save(value, file = rdata)
            }

            # Copy source files to sources directory
            for (file in private$source_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/sources"))
                system(cmd)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        },
        generate_container = function() {
            private$base_dir <- paste0(private$base_dir, "/job")
            bd <- paste0(private$base_dir, "/")
            dir.create(paste0(bd, "input"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "output"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "sources"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, ".objects"), recursive = TRUE, showWarnings = FALSE)

        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file
                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            private$generate_container()
            objects_dir <- paste(private$base_dir, ".objects", sep = "/")

            for (param in names(self$params)) {
                value <- self$params[[param]]
                rdata <- paste(objects_dir, paste0(param, ".RData"), sep = "/")
                save(value, file = rdata)
            }

            # Copy source files to sources directory
            for (file in private$source_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/sources"))
                system(cmd)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        },
        generate_container = function() {
            private$base_dir <- paste0(private$base_dir, "/job")
            bd <- paste0(private$base_dir, "/")
            dir.create(paste0(bd, "input"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "output"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "sources"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, ".objects"), recursive = TRUE, showWarnings = FALSE)

        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file
                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            private$generate_container()
            objects_dir <- paste(private$base_dir, ".objects", sep = "/")

            for (param in names(self$params)) {
                value <- self$params[[param]]
                rdata <- paste(objects_dir, paste0(param, ".RData"), sep = "/")
                save(value, file = rdata)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        },
        generate_container = function() {
            private$base_dir <- paste0(private$base_dir, "/job")
            bd <- paste0(private$base_dir, "/")
            dir.create(paste0(bd, "input"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "output"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, ".objects"), recursive = TRUE, showWarnings = FALSE)

        }
    )
)
#' NOAARequest R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        main_file = NULL,
        params = list(),
        initialize = function(main_file, source_files = list()) {
            if (!missing(main_file)) {
                self$main_file <- main_file
                private$source_files = source_files

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        }
    ),
    private = list(
        globals = list(),
        source_files = list(),
        find_globals = function() {
            e <- new.env()
            source_file(self$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' NOAARequest R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        main_file = NULL,
        params = list(),
        initialize = function(main_file, source_files = list()) {
            if (!missing(main_file)) {
                self$main_file <- main_file
                private$source_files = source_files

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        }
    ),
    private = list(
        globals = list(),
        source_files = list(),
        find_globals = function() {
            e <- new.env()
            source_file(self$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify."))
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            private$globals = globals
            self$params = globals
        }
    )
)
# Given a campaign finance report ID number from the FEC's website, will download that data, analyze it, and save it as CSVs.
# Consists of two functions: fecgrabber() and fecanalyzer().
# fecgrabber() takes as input a title and an ID.
# It will download the specified report, and clean it up.
# The title should be descriptive and precise, such as "LewisQ1". It should not include any characters such as spaces, dashes or periods that could confuse either R or your file system.
# The ID number can be obtained from the Filings page on a candidate's FEC page, under the View/Download column. It is the numeric part of a string such as "FEC-1061533" — so, in this case, the ID would be 1061533.
# Sample function call: fecgrabber("LewisQ1",1061533)
# It will create a folder in your working directory with a name equal to the title you called the function with, and in it create two CSVs: full data for receipts (1) and expenses (2).
# It then calls fecanalyzer() using the output.
# fecanalyzer() takes as input a title, a table with receipts data and a table with expenditures data. 
# Will be run automatically as part of fecgrabber(). Can also be called manually, in which case the receipts and expenditures data should be specified by reference to data frames in R. It does not include any read.csv() calls to load from the disk; this will have to be done manually.
# fecanalyzer() will output in the console quick overall fundraising summary numbers, but these are incidental to this script. The script is designed to do more in-depth analysis; for basic summary data see the FEC's summaries.
# It will also create a folder in your working directory with a name equal to the title you called the function with, if this doesn't already exist, and in it create six CSVs: Fundraising summarized by (1) states, (2) cities, (3) occupation and (4) employer, and expenses summarized by (5) purpose and (6) recipient.
# FEC reports often contain lots of unclean artifacts — typos, unusual methods of recording data, etc. This won't catch that stuff, so always check your outputs. If you catch issues, you can fix them manually and then call fecanalyzer() to re-run the analysis on the clean data.
# This code drops all contributions from "Actblue", a conduit PAC that often shows up as double entries in FEC reports. If your data should not exclude Actblue, comment out line 47.
# Code by David H. Montgomery for the Pioneer Press.

library(RCurl)
library(dplyr)

fecgrabber <- function(title,id) {
    tmp <- read.table( # Load the FEC file from the web
        textConnection(
            getURL(
                paste0("http://docquery.fec.gov/dcdev/posted/",id,".fec")
            )
        ),
        sep = "\034",
        quote = "\"",
        skip = 2, # Skip the useless header lines
        fill = TRUE, # Fill in blank cells to avoid tons of errors
        stringsAsFactors= FALSE,
        colClasses = c(rep("character",20),"numeric","numeric",rep("character",3))
    )
    tmp$V20 <- as.Date(tmp$V20,"%Y%m%d") # Convert dates from character to date format
    receipts <- subset(tmp, grepl("SA", V1)) # Extract receipt data to a new data frame
    expenses <- subset(tmp, grepl("SB", V1)) # Extract expenses data to a new data frame
    
    # Process Receipts table
    
    receipts <- receipts[,c(1,6:9,13:18,20:25)] # Drop unneeded receipts columns
    colnames(receipts) <- c("Code","Type","Name","Lastname","Firstname","Address","PO Box","City","State","ZIP","Elex","Date","Contrib","To Date","Memo","Employer","Job") # Label receipts columns
    receipts <- receipts[receipts$Code != "SA13A",] # Drop self-funding
    for (i in 1:nrow(receipts)) { if(receipts[i,3] == "") {receipts[i,3] <- paste0(receipts[i,4],", ",receipts[i,5]) }} # Fill in full names
    for (i in 1:nrow(receipts)) { if(receipts[i,7] != "") {receipts[i,6] <- paste(receipts[i,6],receipts[i,7]) }} # Fill in full addresses
    receipts <- receipts[,-c(4,5,7)] # Drop newly superfluous columns
    receipts <- receipts[receipts$Name != "Actblue",] # Remove ActBlue contributions
    
    # Process Expenses table
    
    expenses <- expenses[,c(1,6:9,13:18,20:21,23)] # Drop unneeded expenses columns
    colnames(expenses) <- c("Code","Type","Name","Lastname","Firstname","Address","PO Box","City","State","ZIP","Elex","Date","Amount","Expense") # Label expenses columns
    for (i in 1:nrow(expenses)) { if(expenses[i,3] == "") {expenses[i,3] <- paste0(expenses[i,4],", ",expenses[i,5]) }} # Fill in full names
    for (i in 1:nrow(expenses)) { if(expenses[i,7] != "") {expenses[i,6] <- paste(expenses[i,6],expenses[i,7]) }} # Fill in full addresses
    expenses <- expenses[,-c(4,5,7)] # Drop newly superfluous columns

	# Save contents to disk.
	if (!dir.exists(title)) {dir.create(title)} # If it doesn't exist, create a directory named after the specified title.
	setwd(title) # Move to the new directory
	# Save the receipts and expenses tables as CSVs
	write.csv(receipts,paste0(title,"receipts.csv"), row.names =F)
	write.csv(expenses,paste0(title,"expenses.csv"), row.names = F)
	setwd("..") # Return to the original working directory.
	fecanalyzer(title,receipts,expenses) # Call the supporting function fecanalyzer() with the outputs from fecgrabber().
}
		
	
# Supporting function that takes data frames as formatted by fecgrabber() and extracts some interesting information from them.

fecanalyzer <- function(title, raised, spent) {	
    # The top states of origin for donations in the report.      
	a <- raised %>% group_by(State) %>% summarise(Total = sum(Contrib)) %>% arrange(desc(Total)) %>% mutate(Percent = Total / sum(Total, na.rm=T))

	# The top cities of origin for donations in the report.	
	b <- raised %>% group_by(City, State) %>% na.omit() %>% summarise(Total = sum(Contrib)) %>% arrange(desc(Total)) %>% ungroup() %>% mutate (Percent = Total / sum(Total, na.rm=T))
	
	# The top occupations listed by donors in the report.
	c <- raised %>% group_by(Job) %>% summarise(Total = sum(Contrib)) %>% arrange(desc(Total)) %>% mutate(Percent = Total / sum(Total, na.rm=T))
	
	# The top employers listed by donors in the report.
	d <- raised %>% group_by(Employer) %>% summarise(Total = sum(Contrib)) %>% arrange(desc(Total)) %>% mutate(Percent = Total / sum(Total, na.rm=T))
	
	# The top types of expense in the report.
	e <- spent %>% group_by(Expense) %>% summarise(Total = sum(Amount)) %>% arrange(desc(Total)) %>% mutate(Percent = Total / sum(Total, na.rm=T))

	# The top recipients of expenses in the report.
	f <- spent %>% group_by(Name) %>% summarise(Total = sum(Amount)) %>% arrange(desc(Total)) %>% mutate(Percent = Total / sum(Total, na.rm=T))
	
	if (!dir.exists(title)) {dir.create(title)} # If it doesn't exist, create a directory named after the specified title.
	setwd(title) # Move to the directory in question
	# Save the six data frames just calcualted as CSVs, with filenames based on your title.
	write.csv(a,paste0(title,"-in-states.csv"), row.names =F)
	write.csv(b,paste0(title,"-in-cities.csv"), row.names =F)
	write.csv(c,paste0(title,"-in-jobs.csv"), row.names =F)
	write.csv(d,paste0(title,"-in-employers.csv"), row.names =F)
	write.csv(e,paste0(title,"-out-expenses.csv"), row.names =F)
	write.csv(f,paste0(title,"-out-recipients.csv"), row.names =F)
	setwd("..") # Return to the original working directory.
	
	# Create a new global variable, called [title].fec: a list containing the six data frames, so you can call them in R for quick analysis.
	assign(paste0(title,".fec"),list("Top States" = a,"Top Cities" = b,"Top Jobs" = c,"Top Employers" = d, "Top Expenses" = e, "Top Recipients" = f), envir = .GlobalEnv) 
	rm(a,b,c,d,e,f) # Clean up the old data frames.
	
	# Print basic summary data into the console.
	print(paste0("Total raised: $",sum(raised$Contrib, na.rm=T)))
	print(paste0("Total spent: $",sum(spent$Amount, na.rm=T)))
}
#' Remove points from a scatter plot where density is really high
#' @param x x-coordinates vector
#' @param y y-coordinates vector
#' @param resolution number of partitions for the x and y-dimensions.
#' @param max.per.cell maximum number of points per x-y partition.
#' @return index into the points that omits points from x-y partitions
#' so that each has at most \code{max.per.cell} points.
scatter.thinning <- function(x,y,resolution=100,max.per.cell=100) {
    x.cell <- floor((resolution-1)*(x - min(x,na.rm=T))/diff(range(x,na.rm=T))) + 1
    y.cell <- floor((resolution-1)*(y - min(y,na.rm=T))/diff(range(y,na.rm=T))) + 1
    z.cell <- x.cell * resolution + y.cell
    frequency.table <- table(z.cell)
    frequency <- rep(0,max(z.cell, na.rm=T))
    frequency[as.integer(names(frequency.table))] <- frequency.table
    f.cell <- frequency[z.cell]
    
    big.cells <- length(which(frequency > max.per.cell))
    sort(c(which(f.cell <= max.per.cell),
           sample(which(f.cell > max.per.cell),
                  size=big.cells * max.per.cell, replace=F)),
         decreasing=F)
}

#' QQ plot for EWAS
#'
#' @param ewas.object Return object from \code{\link{meffil.ewas()}}.
#' @param sig.threshold P-value threshold for significance (Default: 1e-7).
#' @param sig.color Color for points corresponding to significant tests (Default: "red").
#' @param title Title for the plot (Default: "QQ plot").
#' @param xlab Label for the x-axis (Default: -log_10(expected p-values)).
#' @param ylab Label for the y-axis (Default: -log_10(observed p-values)).
#' @param lambda.method Method for calculating genomic inflation lambda.
#' Valid values are "median" or "regression" (Default: "median").
#' @return List of \code{\link{ggplot}} for each analysis in \code{ewas.object}.
#' @export
meffil.ewas.qq.plot <- function(ewas.object,
                                sig.threshold=1e-7,
                                sig.color="red",
                                title="QQ plot",
                                xlab=bquote(-log[10]("expected p-values")),
                                ylab=bquote(-log[10]("observed p-values")),
                                lambda.method="median") {
    stopifnot(is.ewas.object(ewas.object))
    
    sapply(names(ewas.object$analyses), function(name) {
        p.values <- sort(ewas.object$analyses[[name]]$table$p.value, decreasing=T)
        p.values[which(p.values < .Machine$double.xmin)] <- .Machine$double.xmin
        stats <- data.frame(is.sig=p.values < sig.threshold,
                            expected=-log(sort(ppoints(p.values),decreasing=T),10),
                            observed=-log(p.values, 10))
        lambda <- qq.lambda(p.values[which(p.values > sig.threshold)],
                            method=lambda.method)

        label.x <- min(stats$expected) + diff(range(stats$expected))*0.1
        label.y <- min(stats$expected) + diff(range(stats$observed))*0.9

        lambda.label <- paste("lambda == ", format(lambda$estimate,digits=3),
                              "%+-%", format(lambda$se, digits=3),
                              "~(", lambda.method, ")", sep="")

        selection.idx <- scatter.thinning(stats$observed, stats$expected,
                                          resolution=100, max.per.cell=100)

        lim <- range(c(0, stats$expected, stats$observed))
        sig.threshold <- format(sig.threshold, digits=3)
        
        (ggplot(stats[selection.idx,], aes(x=expected, y=observed)) + 
         geom_abline(intercept = 0, slope = 1, colour="black") +              
         geom_point(aes(colour=factor(sign(is.sig)))) +
         scale_colour_manual(values=c("black", "red"),
                             name="Significant",
                             breaks=c("0","1"),
                             labels=c(paste("p-value >", sig.threshold),
                                 paste("p-value <", sig.threshold))) +
         annotate(geom="text", x=label.x, y=label.y, hjust=0,
                  label=lambda.label,
                  parse=T) +
         xlim(lim) + ylim(lim) + 
         xlab(xlab) + ylab(ylab) +
         coord_fixed() +
         ggtitle(paste(title, ": ", name, sep="")))
     }, simplify=F)     
}

qq.lambda <- function(p.values, method="median", B=100) {
    stopifnot(method %in% c("median","regression"))
    p.values <- na.omit(p.values)
    observed <- qchisq(p.values, df=1, lower.tail = FALSE)
    observed <- sort(observed)
    expected <- qchisq(ppoints(length(observed)), df=1, lower.tail=FALSE)
    expected <- sort(expected)

    lambda <- se <- NA
    if (method == "median")  {
        lambda <- median(observed)/qchisq(0.5, df=1)
        boot.medians <- sapply(1:B, function(i) median(sample(observed, replace=T)))
        se <- sd(boot.medians/qchisq(0.5,df=1))
    } else if (method == "regression") {
        coef.table <- summary(lm(observed ~ 0 + expected))$coeff
        lambda <- coef.table["expected","Estimate"]
        se <- coef.table["expected", "Std. Error"]
    }
    list(method=method, estimate=lambda, se=se)
}

#' Manhattan plot for EWAS
#'
#' @param ewas.object Return object from \code{\link{meffil.ewas()}}.
#' @param sig.threshold P-value threshold for significance (Default: 1e-7).
#' @param title Title for the plot (Default: "Manhattan plot").
#' @return \code{\link{ggplot}} showing the Manhattan plot. 
#' @export
meffil.ewas.manhattan.plot <- function(ewas.object, sig.threshold=1e-7,
                                       title="Manhattan plot") {
    stopifnot(is.ewas.object(ewas.object))
    
    chromosomes <- paste("chr", c(1:22, "X","Y"), sep="")
    sapply(names(ewas.object$analyses), function(name) {
        stats <- ewas.object$analyses[[name]]$table
        stats$chromosome <- factor(as.character(stats$chromosome), levels=chromosomes)
        stats$chr.colour <- 0
        stats$chr.colour[stats$chromosomes %in% chromosomes[seq(1,length(chromosomes),2)]] <- 1
        p.values <- stats$p.value
        p.values[which(p.values < .Machine$double.xmin)] <- .Machine$double.xmin
        stats$stat <- -log(p.values,10) * sign(stats$coefficient)

        stats <- stats[order(stats$stat, decreasing=T),]

        chromosome.lengths <- sapply(chromosomes, function(chromosome)
                                     max(stats$position[which(stats$chromosome == chromosome)]))
        chromosome.lengths <- as.numeric(chromosome.lengths)
        chromosome.starts <- c(1,cumsum(chromosome.lengths)+1)
        names(chromosome.starts) <- c(chromosomes, "NA")
        stats$global <- stats$position + chromosome.starts[stats$chromosome] - 1

        selection.idx <- scatter.thinning(stats$global, stats$stat,
                                          resolution=100, max.per.cell=100)
        
        (ggplot(stats[selection.idx,], aes(x=position, y=stat)) +
         geom_point(aes(colour=chr.colour)) +
         facet_grid(. ~ chromosome, space="free_x", scales="free_x") +
         theme(strip.text.x = element_text(angle = 90)) +
         guides(colour=FALSE) +
         labs(x="Position",
              y=bquote(-log[10]("p-value") * sign(beta))) +             
         geom_hline(yintercept=log(sig.threshold,10), colour="red") +
         geom_hline(yintercept=-log(sig.threshold,10), colour="red") +
         theme(axis.text.x = element_blank(), axis.ticks.x = element_blank()) +
         ggtitle(paste(title, ": ", name, sep=""))) 
    }, simplify=F)        
}


#' Scatter plots for a CpG site in an EWAS
#'
#' @param ewas.object Return object from \code{\link{meffil.ewas()}}.
#' @param cpg CpG site to plot.
#' @param title Title of the plot (Default: \code{cpg}).
#' @param beta Matrix of methylation levels used to create the \code{ewas.object}.
#' @param \code{\link{ggplot}} object showing the scatterplots of DNA methylation vs the variable of interest
#' in the EWAS.  Each plot corresponds to a covariate set.
#' Methylation levels are in fact residuals from fitting a model with DNA methylation and the covariates.
#' 
#' @export
meffil.ewas.cpg.plot <- function(ewas.object, cpg, beta, title=cpg) {
    stopifnot(is.ewas.object(ewas.object))
    stopifnot(is.matrix(beta) && cpg %in% rownames(beta))
    
    variable <- ewas.object$variable
    
    lapply(names(ewas.object$analyses), function(name) {
        ewas <- ewas.object$analyses[[name]]        

        if (!all(rownames(ewas$design) %in% colnames(beta)))
            stop("EWAS samples do not match those in the beta argument (methylation matrix)")
        methylation <- beta[cpg,rownames(ewas$design)]

        covariates <- subset(data.frame(ewas$design), select=c(-variable,-intercept))
        if (ncol(covariates) == 0)
            covariates <- NULL
        cpg.plot(methylation, variable, covariates, title=paste(name, ": ", title, sep=""))
    })
}

cpg.plot <- function(methylation, variable, covariates=NULL, title="") {
    ## remove missing values
    idx <- which(!is.na(methylation) & !is.na(variable))
    if (length(idx) < 3) {
        warning("Not enough data points to plot CpG methylation.")
        return(NULL)
    }
    methylation <- methylation[idx]
    variable <- variable[idx]
    
    ## linear model fit
    if (is.null(covariates)) {
        fit <- lm(methylation ~ variable)
        base <- lm(methylation ~ 1)
    }
    else {
        covariates <- covariates[idx,,drop=F]
        fit <- lm(methylation ~ variable + ., data=covariates)
        base <- lm(methylation ~ ., data=covariates)
    }
    p.value.lm <- anova(fit,base)[2,"Pr(>F)"]

    stats.desc <- paste("variable\np[lm]= ", format(p.value.lm, digits=3), sep="")
                        
    has.betareg <- all(c("lmtest", "betareg") %in% rownames(installed.packages()))
    if (has.betareg) {
        require("betareg")
        require("lmtest")
        ## beta regression model fit
        if (is.null(covariates)) {
            fit <- betareg(methylation ~ variable)
            base <- betareg(methylation ~ 1)
        }
        else {
            fit <- betareg(methylation ~ variable + ., data=covariates)
            base <- betareg(methylation ~ ., data=covariates)
        }
        p.value.beta <- lrtest(fit, base)[2,"Pr(>Chisq)"]

        stats.desc <- paste(stats.desc, "; p[beta] = ", format(p.value.beta, digits=3), sep="")
    }
    if (!is.null(covariates))
        methylation <- residuals(base)

    ## plot
    data <- data.frame(methylation=methylation, variable=variable)
    if (is.factor(variable) || length(unique(variable)) <= 20) {
        data$variable <- as.factor(data$variable)
        p <- (ggplot(data, aes(x=variable, y=methylation)) +
              geom_boxplot())
    } else {
        p <- (ggplot(data, aes(x=variable, y=methylation)) +
              geom_point() + geom_smooth(method=lm))
    }

    (p + ggtitle(title) +
     xlab(stats.desc) + ylab("DNA methylation"))
}
##predefined_condition_begin
# setwd("h:/temp")  
#   
# data<-read.table("Z:/Shared/Labs/Brown,J/tiger/20160509_brown_3436/star_genetable/result/B3436_gene.count",row.names=1, header=T, check.names=F)
# 
# taskName<-'B3436'
# showLabelInPCA<-1
# showDEGeneCluster<-0
# pvalue<-0.05
# foldChange<-2
# minMedianInGroup<-5
# addCountOne<-0
# 
# comparisons=list(
#   "CAPTISOL_vs_FED" = c("CAPTISOL_vs_FED.design", "FED", "CAPTISOL")
# ) 
#
##predefined_condition_end

library("DESeq2")
library("heatmap3")
library("lattice")
library("reshape")
library("ggplot2")
library("grid")
library("scales")
library("reshape2")
library("VennDiagram")
library("RColorBrewer")

##Solving node stack overflow problem start###
#when there are too many genes, drawing dendrogram may failed due to node stack overflow,
#It could be solved by forcing stats:::plotNode to be run as interpreted code rather then byte-compiled code via a nasty hack.
#http://stackoverflow.com/questions/16559250/error-in-heatmap-2-gplots/25877485#25877485

# Convert a byte-compiled function to an interpreted-code function 
unByteCode <- function(fun)
{
  FUN <- eval(parse(text=deparse(fun)))
  environment(FUN) <- environment(fun)
  FUN
}

# Replace function definition inside of a locked environment **HACK** 
assignEdgewise <- function(name, env, value)
{
  unlockBinding(name, env=env)
  assign( name, envir=env, value=value)
  lockBinding(name, env=env)
  invisible(value)
}

# Replace byte-compiled function in a locked environment with an interpreted-code
# function
unByteCodeAssign <- function(fun)
{
  name <- gsub('^.*::+','', deparse(substitute(fun)))
  FUN <- unByteCode(fun)
  retval <- assignEdgewise(name=name,
                           env=environment(FUN),
                           value=FUN
  )
  invisible(retval)
}

# Use the above functions to convert stats:::plotNode to interpreted-code:
unByteCodeAssign(stats:::plotNode)

# Now raise the interpreted code recursion limit (you may need to adjust this,
#  decreasing if it uses to much memory, increasing if you get a recursion depth error ).
options(expressions=5e4)

##Solving node stack overflow problem end###

hmcols <- colorRampPalette(c("green", "black", "red"))(256)

drawHCA<-function(prefix, rldselect, ispaired, designData, conditionColors, gnames){
  htfile<-paste0(prefix, "_DESeq2-vsd-heatmap.png")
  cat("saving HCA to ", htfile, "\n")
  genecount<-nrow(rldselect)
  if(genecount > 2){
    png(filename=htfile, width=3000, height =3000, res=300)
    cexCol = max(1.0, 0.2 + 1/log10(ncol(rldselect)))
    if(ispaired){
      htColors<-rainbow(length(unique(designData$Paired)))
      gsColors<-as.matrix(data.frame(Group=conditionColors, Sample=htColors[designData$Paired]))
    }else{
      gsColors = conditionColors;
    }
    heatmap3(rldselect, 
             col = hmcols, 
             ColSideColors = gsColors, 
             margins=c(12,5), 
             scale="r", 
             dist=dist, 
             labRow=NA,
             main=paste0("Hierarchical Cluster Using ", genecount, " Genes"),  
             cexCol=cexCol, 
             useRaster=FALSE,
             legendfun=function() showLegend(legend=paste0("Group ", gnames), col=c("red","blue"),cex=1.0,x="center"))
    dev.off()
  }
}

drawPCA<-function(prefix, rldmatrix, showLabelInPCA, designData, conditionColors){
  #filename<-paste0(prefix, "_DESeq2-vsd-pca.png")
  filename<-paste0(prefix, "_DESeq2-vsd-pca.pdf")
  genecount<-nrow(rldmatrix)
  if(genecount > 2){
    cat("saving PCA to ", filename, "\n")
    #png(filename=filename, width=3000, height=3000, res=300) # 10 X 10 inches
    pdf(filename, width=10, height=10)
    pca<-prcomp(t(rldmatrix))
    supca<-summary(pca)$importance
    pcadata<-data.frame(pca$x)
    pcalabs=paste0(colnames(pcadata), "(", round(supca[2,] * 100), "%)")
    pcadata["sample"]<-row.names(pcadata)
    
    if(showLabelInPCA){
      g <- ggplot(pcadata, aes(x=PC1, y=PC2, label=sample)) + 
        geom_text(vjust=-0.6, size=4) +
        geom_point(col=conditionColors, size=4) + 
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) +
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) + 
        xlab(pcalabs[1]) + ylab(pcalabs[2])
    }else{
      g <- ggplot(pcadata, aes(x=PC1, y=PC2)) + 
        geom_point(col=conditionColors, size=4) + 
        labs(color = "Group") +
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) + 
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) +
        xlab(pcalabs[1]) + ylab(pcalabs[2]) + 
        theme(legend.position="top")
    }
    
    print(g)
    dev.off()
  }
}

#for volcano plot
reverselog_trans <- function(base = exp(1)) {
  trans <- function(x) -log(x, base)
  inv <- function(x) base^(-x)
  trans_new(paste0("reverselog-", format(base)), trans, inv, 
            log_breaks(base = base), 
            domain = c(1e-100, Inf))
}

data<-data[,colnames(data) != "Feature_length"]
colClass<-sapply(data, class)
countNotNumIndex<-which(colClass!="numeric" & colClass!="integer")
if (length(countNotNumIndex)==0) {
  index<-1;
  indecies<-c()
} else {
  index<-max(countNotNumIndex)+1
  indecies<-c(1:(index-1))
}

countData<-data[,c(index:ncol(data))]
countData[is.na(countData)] <- 0
countData<-round(countData)

if(addCountOne){
  countData<-countData+1
}

comparisonNames=names(comparisons)
comparisonName=comparisonNames[1]

dir.create("details", showWarnings = FALSE)

pairedspearman<-list()
resultAllOut<-data
resultAllOutVar<-c("log2FoldChange","pvalue","padj")
for(comparisonName in comparisonNames){
  str(comparisonName)
  designFile=comparisons[[comparisonName]][1]
  gnames=comparisons[[comparisonName]][2:3]
  designData<-read.table(designFile, sep="\t", header=T)
  designData$Condition<-factor(designData$Condition, levels=gnames)
  
  if(ncol(designData) >= 3){
    cat("Data with covariances!\n")
  }else{
    cat("Data without covariances!\n")
  }
  if (any(colnames(designData)=="Paired")) {
	  ispaired<-TRUE
	  cat("Paired Data!\n")
  }else{
	  ispaired<-FALSE
	  cat("Not Paired Data!\n")
  }
  temp<-apply(designData,2,function(x) length(unique(x)))
  if (any(temp==1)) {
	  cat(paste0("Factors with only 1 level in design matrix: ",colnames(designData)[which(temp==1)],"\n"))
	  cat("They will be removed")
	  cat("\n")
	  designData<-designData[,which(temp!=1)]
  }
  temp<-apply(designData[,-1,drop=F],2,rank)
  if (length(unique(rowSums(temp)))==1 | identical(temp[,1],temp[,-1])) {
	  cat(paste0("The model matrix is not full rank, so the model cannot be fit as specified"))
	  cat("\n")
	  cat("Only Condition variable will be kept.")
	  cat("\n")
	  designData<-designData[,which(colnames(designData)%in% c("Sample","Condition"))]
  }
  
  comparisonData<-countData[,colnames(countData) %in% as.character(designData$Sample),drop=F]
  if(ncol(comparisonData) != nrow(designData)){
	message=paste0("Data not matched, there are ", nrow(designData), " samples in design file ", designFile, " but ", ncol(comparisonData), " samples in data ")
	warning(message)
	writeLines(message,paste0(comparisonName,".error"))
	next
  }
  comparisonData<-comparisonData[,as.character(designData$Sample)]
  
  prefix<-comparisonName
  curdata<-data
  if(minMedianInGroup > 0){
    conds<-unique(designData$Condition)
    data1<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[1]]]
    data2<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[2]]]
    med1<-apply(data1, 1, median) >= minMedianInGroup
    med2<-apply(data2, 1, median) >= minMedianInGroup
    med<-med1 | med2
    comparisonData<-comparisonData[med,]
    cat(nrow(comparisonData), " genes with minimum median count in group larger or equals than ", minMedianInGroup, "\n")
    
    if (nrow(comparisonData)==0) {
		message=paste0("Error: 0 Genes can be used in DESeq2 analysis in comparison ",comparisonName," \n")
		warning(message)
		writeLines(message,paste0(comparisonName,".error"))
      next;
    }
    
    prefix<-paste0(comparisonName, "_min", minMedianInGroup)
    curdata<-data[med,]
  }
  
  if(ispaired){
    pairedSamples = unique(designData$Paired)
    
    spcorr<-unlist(lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      cor(comparisonData[,samples[1]],comparisonData[,samples[2]],method="spearman")
    }))
    
    
    sptable<-data.frame(Name=pairedSamples, Spcorr=spcorr)
    write.csv(sptable, file=paste0(prefix, "_Spearman.csv"), row.names=FALSE)
    
    lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      log2c1<-log2(comparisonData[,samples[1]]+1)
      log2c2<-log2(comparisonData[,samples[2]]+1)
      png(paste0("details/", prefix, "_Spearman_", pairedSamples[x], ".png"), width=2000, height=2000, res=300)
      plot(log2c1, log2c2, xlab=paste0(samples[1], " [log2(Count + 1)]"), ylab=paste0(samples[2], " [log2(Count + 1)]"))
      text(3,15,paste0("SpearmanCorr=", sprintf("%0.3f", spcorr[x])))
      dev.off()
    })
    
    pairedspearman[[comparisonName]]<-spcorr
  }
  
  notEmptyData<-apply(comparisonData, 1, max) > 0
  comparisonData<-comparisonData[notEmptyData,]
  curdata<-curdata[notEmptyData,]
  
  if(ispaired){
    colnames(comparisonData)<-unlist(lapply(c(1:ncol(comparisonData)), function(i){paste0(designData$Paired[i], "_", colnames(comparisonData)[i])}))
  }
  rownames(designData)<-colnames(comparisonData)
  conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
  
  write.csv(comparisonData, file=paste0(prefix, ".csv"))
  
  #some basic graph
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                             colData = designData,
                             design = ~1)
  
  colnames(dds)<-colnames(comparisonData)
  
  #draw density graph
  rldmatrix<-as.matrix(log2(counts(dds,normalized=FALSE) + 1))
  rsdata<-melt(rldmatrix)
  colnames(rsdata)<-c("Gene", "Sample", "log2Count")
  png(filename=paste0(prefix, "_DESeq2-log2-density.png"), width=4000, height=3000, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  width=max(4000, ncol(rldmatrix) * 40 + 1000)
  height=max(3000, ncol(rldmatrix) * 40)
  png(filename=paste0(prefix, "_DESeq2-log2-density-individual.png"), width=width, height=height, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + facet_wrap(~Sample, scales = "free") + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  
  #varianceStabilizingTransformation
  
  allDesignData<-designData
  allComparisonData<-comparisonData
  
  excludedSample<-c()
  zeronumbers<-apply(comparisonData, 2, function(x){sum(x==0)})
  zeronumbers<-names(zeronumbers[order(zeronumbers)])
  percent10<-max(1, round(length(zeronumbers) * 0.1))
  
  removed<-0
  
  excludedCountFile<-paste0(prefix, "_DESeq2-exclude-count.csv")
  excludedDesignFile<-paste0(prefix, "_DESeq2-exclude-design.csv")
  if(file.exists(excludedCountFile)){
    file.remove(excludedCountFile)
  }
  if(file.exists(excludedDesignFile)){
    file.remove(excludedDesignFile)
  }
  
  fitType<-"parametric"
  while(1){
    #varianceStabilizingTransformation
    vsdres<-try(vsd <- varianceStabilizingTransformation(dds, blind=TRUE,fitType=fitType))
    if(class(vsdres) == "try-error" && grepl("every gene contains at least one zero", vsdres[1])){
      removed<-removed+1
      keptNumber<-length(zeronumbers) - percent10 * removed
      keptSample<-zeronumbers[1:keptNumber]
      excludedSample<-zeronumbers[(keptNumber+1):length(zeronumbers)]
      
      comparisonData<-comparisonData[, colnames(comparisonData) %in% keptSample]
      designData<-designData[rownames(designData) %in% keptSample,]
      dds=DESeqDataSetFromMatrix(countData = comparisonData,
                                 colData = designData,
                                 design = ~1)
      
      colnames(dds)<-colnames(comparisonData)
    } else if (class(vsdres) == "try-error" && grepl("newsplit: out of vertex space", vsdres[1])) {
		message=paste0("Warning: varianceStabilizingTransformation function can't run. fitType was set to local to try again")
		warning(message)
		fitType<-"mean"
		writeLines(message,paste0(comparisonName,".error"))
	} else{
      conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
      break
    }
  }
  if (nrow(comparisonData)<=1) {
	  message=paste0("Error: All genes in ",comparisonName," has at least one 0 value. Can't do DESeq2.")
	  warning(message)
	  writeLines(message,paste0(comparisonName,".error"))
	  next;
  }
  
  if(length(excludedSample) > 0){
    excludedCountData<-allComparisonData[,colnames(allComparisonData) %in% excludedSample]
    write.csv(file=excludedCountFile, excludedCountData)
    excludedDesignData<-allDesignData[rownames(allDesignData) %in% excludedSample,]
    write.csv(file=excludedDesignFile, excludedDesignData)
  }
  
  assayvsd<-assay(vsd)
  write.csv(assayvsd, file=paste0(prefix, "_DESeq2-vsd.csv"))
  
  vsdiqr<-apply(assayvsd, 1, IQR)
  assayvsd<-assayvsd[order(vsdiqr, decreasing=T),]
  
  rldmatrix=as.matrix(assayvsd)
  
  #draw pca graph
  drawPCA(paste0(prefix,"_geneAll"), rldmatrix, showLabelInPCA, designData, conditionColors)
  
  #draw heatmap
  #drawHCA(paste0(prefix,"_gene500"), rldmatrix[1:min(500, nrow(rldmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  drawHCA(paste0(prefix,"_geneAll"), rldmatrix, ispaired, designData, conditionColors, gnames)
  
  #different expression analysis
  designFormula=as.formula(paste0("~",paste0(c(colnames(designData)[-c(1:2)],"Condition"),collapse="+")))
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                               colData = designData,
                               design = designFormula)
  
  dds <- DESeq(dds,fitType=fitType)
  res<-results(dds,cooksCutoff=FALSE)
  
  cat("DESeq2 finished.\n")
  
  select<-(!is.na(res$padj)) & (res$padj<pvalue) & ((res$log2FoldChange >= log2(foldChange)) | (res$log2FoldChange <= -log2(foldChange)))
  
  if(length(indecies) > 0){
    inddata<-curdata[,indecies,drop=F]
    tbb<-cbind(inddata, comparisonData, res)
  }else{
    tbb<-cbind(comparisonData, res)
  }
  tbb$FoldChange<-2^tbb$log2FoldChange
  tbbselect<-tbb[select,,drop=F]
  tbbAllOut<-as.data.frame(tbb[,resultAllOutVar,drop=F])
  tbbAllOut$Significant<-select
  colnames(tbbAllOut)<-paste0(colnames(tbbAllOut)," (",comparisonName,")")
  resultAllOut<-cbind(resultAllOut,tbbAllOut[row.names(resultAllOut),])

  tbb<-tbb[order(tbb$padj),,drop=F]
  write.csv(as.data.frame(tbb),paste0(prefix, "_DESeq2.csv"))
  
  tbbselect<-tbbselect[order(tbbselect$padj),,drop=F]
  write.csv(as.data.frame(tbbselect),paste0(prefix, "_DESeq2_sig.csv"))
  
  if("Feature_gene_name" %in% colnames(tbb)){
    write.table(tbb[,c("Feature_gene_name", "stat"),drop=F],paste0(prefix, "_DESeq2_GSEA.rnk"),row.names=F,col.names=F,sep="\t", quote=F)
    write.table(tbbselect[,c("Feature_gene_name"),drop=F], paste0(prefix, "_DESeq2_sig_genename.txt"),row.names=F,col.names=F,sep="\t", quote=F)
  }

  if(showDEGeneCluster){
    siggenes<-rownames(rldmatrix) %in% rownames(tbbselect)
    
    nonDEmatrix<-rldmatrix[!siggenes,,drop=F]
    DEmatrix<-rldmatrix[siggenes,,drop=F]
    
    drawPCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, ispaired, designData, conditionColors, gnames)
    
    drawPCA(paste0(prefix,"_geneDE"),DEmatrix , showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneDE"),DEmatrix , ispaired, designData, conditionColors, gnames)
    #drawHCA(paste0(prefix,"_gene500NotDE"), nonDEmatrix[1:min(500, nrow(nonDEmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  }
  
  #Top 25 Significant genes barplot
  sigDiffNumber<-nrow(tbbselect)
  if (sigDiffNumber>0) {
    if (sigDiffNumber>25) {
      print(paste0("More than 25 genes were significant. Only the top 25 genes will be used in barplot"))
      diffResultSig<-tbbselect[order(tbbselect$padj)[1:25],]
    } else {
      diffResultSig<-tbbselect
    }
    if("Feature_gene_name" %in% colnames(diffResultSig)){
      diffResultSig$Name<-as.character(diffResultSig$Feature_gene_name)
    }else{
      diffResultSig$Name<-sapply(strsplit(row.names(diffResultSig),";"),function(x) x[1])
    }
    diffResultSig$Name <- factor(diffResultSig$Name, levels=diffResultSig$Name[order(diffResultSig$log2FoldChange)])
    diffResultSig<-as.data.frame(diffResultSig)
    
    png(filename=paste0(prefix, "_DESeq2_sig_barplot.png"), width=3000, height=3000, res=300)
    #	  pdf(paste0(prefix,"_DESeq2_sig_barplot.pdf"))
    p<-ggplot(diffResultSig,aes(x=Name,y=log2FoldChange,order=log2FoldChange))+geom_bar(stat="identity")+
      coord_flip()+
      #			geom_abline(slope=0,intercept=1,colour="red",linetype = 2)+
      scale_y_continuous(name=bquote(log[2]~Fold~Change))+
      theme(axis.text = element_text(colour = "black"))
    print(p)
    dev.off()
  } else {
    print(paste0("No gene with adjusted p value less than ",pvalue," and fold change larger than ",foldChange))
  }
  
  #volcano plot
  changeColours<-c(grey="grey",blue="blue",red="red")
  diffResult<-as.data.frame(tbb)
  diffResult$log10BaseMean<-log10(diffResult$baseMean)
  diffResult$colour<-"grey"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange>=log2(foldChange))]<-"red"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange<=-log2(foldChange))]<-"blue"
  png(filename=paste0(prefix, "_DESeq2_volcanoPlot.png"), width=3000, height=3000, res=300)
  #  pdf(paste0(prefix,"_DESeq2_volcanoPlot.pdf"))
  p<-ggplot(diffResult,aes(x=log2FoldChange,y=padj))+
    geom_point(aes(size=log10BaseMean,colour=colour))+
    scale_color_manual(values=changeColours,guide = FALSE)+
    scale_y_continuous(trans=reverselog_trans(10),name=bquote(Adjusted~p~value))+
    scale_x_continuous(name=bquote(log[2]~Fold~Change))+
    geom_hline(yintercept = 1,colour="grey",linetype = "dotted")+
    geom_vline(xintercept = 0,colour="grey",linetype = "dotted")+
    guides(size=guide_legend(title=bquote(log[10]~Base~Mean)))+
    theme_bw()+
    scale_size(range = c(3, 7))+
    theme(axis.text = element_text(colour = "black",size=30),
			axis.title = element_text(size=30),
			legend.text= element_text(size=30),
			legend.title= element_text(size=30))
  print(p)
  dev.off()
}

#write a file with all information
write.csv(resultAllOut,paste0(taskName, "_DESeq2.csv"))

if(length(pairedspearman) > 0){
  #draw pca graph
  filename<-ifelse(minMedianInGroup > 0, paste0("spearman_min", minMedianInGroup, ".png"), "spearman.png")
  png(filename=filename, width=1000 * length(pairedspearman), height=2000, res=300)
  boxplot(pairedspearman)
  dev.off()
}

#Venn for all significant genes
allSigNameList<-list()
allSigDirectionList<-list()
for(comparisonName in comparisonNames){
	if (minMedianInGroup > 0) {
		prefix<-paste0(comparisonName, "_min", minMedianInGroup)
	} else {
		prefix<-comparisonName
	}
	sigFile<-paste0(prefix, "_DESeq2_sig.csv")
	if (file.exists(sigFile)) {
		sigTable<-read.csv(sigFile,header=TRUE,as.is=TRUE)
		if (nrow(sigTable)>0) {
			allSigNameList[[comparisonName]]<-sigTable[,1]
			allSigDirectionList[[comparisonName]]<-sign(sigTable$log2FoldChange)
		} else {
			warning(paste0("No significant genes in ",comparisonName))
#		allSigNameList[[comparisonName]]<-""
		}
	}
}

#Do venn if length between 2-5
if (length(allSigNameList)>=2 & length(allSigNameList)<=5) {
	venn.diagram1<-function (x, filename, height = 3000, width = 3000, resolution = 500, 
			units = "px", compression = "lzw", na = "stop", main = NULL, 
			sub = NULL, main.pos = c(0.5, 1.05), main.fontface = "plain", 
			main.fontfamily = "serif", main.col = "black", main.cex = 1, 
			main.just = c(0.5, 1), sub.pos = c(0.5, 1.05), sub.fontface = "plain", 
			sub.fontfamily = "serif", sub.col = "black", sub.cex = 1, 
			sub.just = c(0.5, 1), category.names = names(x), force.unique = TRUE,
			fill=NA,
			...) 
	{
		if (is.na(fill[1])) {
			if (length(x)==5) {
				fill = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3")
			} else if (length(x)==4) {
				fill = c("dodgerblue", "goldenrod1",  "seagreen3", "orchid3")
			} else if (length(x)==3) {
				fill = c("dodgerblue", "goldenrod1", "seagreen3")
			} else if (length(x)==2) {
				fill = c("dodgerblue", "goldenrod1")
			}
		}
		if (force.unique) {
			for (i in 1:length(x)) {
				x[[i]] <- unique(x[[i]])
			}
		}
		if ("none" == na) {
			x <- x
		}
		else if ("stop" == na) {
			for (i in 1:length(x)) {
				if (any(is.na(x[[i]]))) {
					stop("NAs in dataset", call. = FALSE)
				}
			}
		}
		else if ("remove" == na) {
			for (i in 1:length(x)) {
				x[[i]] <- x[[i]][!is.na(x[[i]])]
			}
		}
		else {
			stop("Invalid na option: valid options are \"none\", \"stop\", and \"remove\"")
		}
		if (0 == length(x) | length(x) > 5) {
			stop("Incorrect number of elements.", call. = FALSE)
		}
		if (1 == length(x)) {
			list.names <- category.names
			if (is.null(list.names)) {
				list.names <- ""
			}
			grob.list <- VennDiagram::draw.single.venn(area = length(x[[1]]), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else if (2 == length(x)) {
			grob.list <- VennDiagram::draw.pairwise.venn(area1 = length(x[[1]]), 
					area2 = length(x[[2]]), cross.area = length(intersect(x[[1]], 
									x[[2]])), category = category.names, ind = FALSE, 
					fill=fill,
					...)
		}
		else if (3 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			list.names <- category.names
			nab <- intersect(A, B)
			nbc <- intersect(B, C)
			nac <- intersect(A, C)
			nabc <- intersect(nab, C)
			grob.list <- VennDiagram::draw.triple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), n12 = length(nab), 
					n23 = length(nbc), n13 = length(nac), n123 = length(nabc), 
					category = list.names, ind = FALSE, list.order = 1:3, 
					fill=fill,
					...)
		}
		else if (4 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n34 <- intersect(C, D)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n134 <- intersect(n13, D)
			n234 <- intersect(n23, D)
			n1234 <- intersect(n123, D)
			grob.list <- VennDiagram::draw.quad.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					n12 = length(n12), n13 = length(n13), n14 = length(n14), 
					n23 = length(n23), n24 = length(n24), n34 = length(n34), 
					n123 = length(n123), n124 = length(n124), n134 = length(n134), 
					n234 = length(n234), n1234 = length(n1234), category = list.names, 
					ind = FALSE, fill=fill,...)
		}
		else if (5 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			E <- x[[5]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n15 <- intersect(A, E)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n25 <- intersect(B, E)
			n34 <- intersect(C, D)
			n35 <- intersect(C, E)
			n45 <- intersect(D, E)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n125 <- intersect(n12, E)
			n134 <- intersect(n13, D)
			n135 <- intersect(n13, E)
			n145 <- intersect(n14, E)
			n234 <- intersect(n23, D)
			n235 <- intersect(n23, E)
			n245 <- intersect(n24, E)
			n345 <- intersect(n34, E)
			n1234 <- intersect(n123, D)
			n1235 <- intersect(n123, E)
			n1245 <- intersect(n124, E)
			n1345 <- intersect(n134, E)
			n2345 <- intersect(n234, E)
			n12345 <- intersect(n1234, E)
			grob.list <- VennDiagram::draw.quintuple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					area5 = length(E), n12 = length(n12), n13 = length(n13), 
					n14 = length(n14), n15 = length(n15), n23 = length(n23), 
					n24 = length(n24), n25 = length(n25), n34 = length(n34), 
					n35 = length(n35), n45 = length(n45), n123 = length(n123), 
					n124 = length(n124), n125 = length(n125), n134 = length(n134), 
					n135 = length(n135), n145 = length(n145), n234 = length(n234), 
					n235 = length(n235), n245 = length(n245), n345 = length(n345), 
					n1234 = length(n1234), n1235 = length(n1235), n1245 = length(n1245), 
					n1345 = length(n1345), n2345 = length(n2345), n12345 = length(n12345), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else {
			stop("Invalid size of input object")
		}
		if (!is.null(sub)) {
			grob.list <- add.title(gList = grob.list, x = sub, pos = sub.pos, 
					fontface = sub.fontface, fontfamily = sub.fontfamily, 
					col = sub.col, cex = sub.cex)
		}
		if (!is.null(main)) {
			grob.list <- add.title(gList = grob.list, x = main, pos = main.pos, 
					fontface = main.fontface, fontfamily = main.fontfamily, 
					col = main.col, cex = main.cex)
		}
		grid.newpage()
		grid.draw(grob.list)
		return(1)
#	return(grob.list)
	}
	makeColors<-function(n,colorNames="Set1") {
		maxN<-brewer.pal.info[colorNames,"maxcolors"]
		if (n<=maxN) {
			colors<-brewer.pal(n, colorNames)
		} else {
			colors<-colorRampPalette(brewer.pal(maxN, colorNames))(n)
		}
		return(colors)
	}
	colors<-makeColors(length(allSigNameList))
	png(paste0(taskName,"_significantVenn.png"),res=300,height=2000,width=2000)
	venn.diagram1(allSigNameList,cex=2,cat.cex=2,cat.col=colors,fill=colors)
	dev.off()
}
#Do heatmap significant genes if length larger or equal than 2
if (length(allSigNameList)>=2) {
	temp<-cbind(unlist(allSigNameList),unlist(allSigDirectionList))
	colnames(temp)<-c("Gene","Direction")
	temp<-cbind(temp,comparisonName=rep(names(allSigNameList),sapply(allSigNameList,length)))
	temp<-data.frame(temp)
	dataForFigure<-temp
	#geting dataForFigure order in figure
	temp$Direction<-as.integer(as.character(temp$Direction))
	temp<-acast(temp, Gene~comparisonName ,value.var="Direction")
	temp<-temp[do.call(order, data.frame(temp)),]
	maxNameChr<-max(nchar(row.names(temp)))
	if (maxNameChr>70) {
		row.names(temp)<-substr(row.names(temp),0,70)
		dataForFigure$Gene<-substr(dataForFigure$Gene,0,70)
		warning(paste0("The gene names were too long (",maxNameChr,"). Only first 70 letters were kept."))
	}
	dataForFigure$Gene<-factor(dataForFigure$Gene,levels=row.names(temp))
	
	width=max(2500, 60 * length(unique(dataForFigure$comparisonName)))
	height=max(2000, 40 * length(unique(dataForFigure$Gene)))
	png(paste0(taskName,"_significantHeatmap.png"),res=300,height=height,width=width)
	g<-ggplot(dataForFigure, aes(comparisonName, Gene))+
			geom_tile(aes(fill=Direction), color="white") +
			scale_fill_manual(values=c("light green", "red")) +
			theme(axis.text.x = element_text(angle=90, vjust=0.5, size=11, hjust=0.5, face="bold"),
					axis.text.y = element_text(size=11, face="bold")) +
			coord_equal()
	print(g)
	dev.off()
}


#readFile = "CR_Y_TBX5_peaks.broadPeak.bed.reads" 
#singlePdf = 0 
#inputFile = "CR_Y_TBX5_peaks.broadPeak.bed.depth" 
#outputFile = "" 
#facet<-0
#drawLine<-1

library("reshape2")
library("ggplot2")

data<-read.table(inputFile, sep="\t", header=T, stringsAsFactors = F)

if(exists("readFile")){
  sampleReads<-read.table(readFile, sep="\t", header=T, row.names=1, as.is = T)
  totalReads<-sampleReads[, 1]
  names(totalReads)<-rownames(sampleReads)
  for(sample in rownames(sampleReads)){
    data[,sample] = data[,sample] * 1000000 / totalReads[sample]
  }
}

if(exists("cnvrFile")){
  cnvr<-read.table(cnvrFile, sep="\t", header=T, stringsAsFactors = F, row.names=4)
  refs<-rownames(sampleReads)[! rownames(sampleReads) %in% colnames(cnvr)]
  
  colors<-c("green", "darkblue", "lightblue", "black", colorRampPalette(c("yellow", "red"))(11))
  names(colors)<-c("REF","CN0", "CN1", "CN2", "CN3", "CN4", "CN5", "CN6", "CN7", "CN8", "CN16", "CN32", "CN64")
  
  #no_sig<-c("CN1","CN2","CN3","REF")
  no_sig<-c("CN2","REF")
}

files<-unique(data$File)

if(singlePdf){
  pdf(outputFile, onefile = T)
}

x<-files[2]
for(x in files){
  cat(x, "\n")
  
  if(exists("cnvrFile")){
    tmpcnv<-cnvr[x, c(4:ncol(cnvr))]
    tmpcnv[,refs] <- "REF"
    tmpcnv<-t(tmpcnv)
    
    curcnv<-as.character(tmpcnv[,1])
    names(curcnv) <- row.names(tmpcnv)
    
    if(length(curcnv[! (curcnv %in% no_sig)]) == 0){
      next
    }
  }
  
  curdata<-data[data$File==x,]
  
  title<-paste0(x, " (", curdata$Chr[1], ":", min(curdata$Position),"-",max(curdata$Position),")")
  
  mdata<-melt(curdata, id=c("Chr", "Position", "File"))
  colnames(mdata)<-c("Chr", "Position", "File", "Sample", "Depth")
  
  if(facet){
    height=max(2000, 400+300 * length(unique(mdata$Sample)))
    if(exists("cnvrFile")){
      mdata$Color<-as.character(curcnv[as.character(mdata$Sample)])
      g<-ggplot(mdata, aes(x=Position, y=Depth))
      if(drawLine){
        g <- g + geom_line(aes(color = Color), size=0.8)
      }else{
        g <- g + geom_point(aes(color = Color), size=0.8)
      }
      g<-g + scale_colour_manual(name="CNV", values = colors)
    }else{
      g<-ggplot(mdata, aes(x=Position, y=Depth))
      if(drawLine){
        g<-g+geom_line(aes(color = Sample), size=0.8, show.legend = F)
      }else{
        g<-g+geom_point(aes(color = Sample), size=0.8, show.legend = F)
      }
    }
    g <- g + xlab(unique(data$chr)) + 
      ylab("Reads per million total reads") +
      ggtitle(x) +
      facet_wrap( ~ Sample, ncol=1) +
      theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
  }
  else{
    height=2000
    if(exists("cnvrFile")){
      mdata$Color<-as.character(curcnv[as.character(mdata$Sample)])
      g<-ggplot(mdata, aes(x=Position, y=Depth, group=Sample))
      if(drawLine){
        g <- g + geom_line(aes(color = Color), size=0.8)
      }else{
        g <- g + geom_point(aes(color = Color), size=0.8)
      }
      g<-g+scale_colour_manual(name="CNV", values = colors)
    }else{
      g<-ggplot(mdata, aes(x=Position, y=Depth, group=Sample))
      if(drawLine){
        g <- g + geom_line(aes(color = Sample), size=0.8, show.legend = T)
      }else{
        g <- g + geom_point(aes(color = Sample), size=0.8, show.legend = T)
      }
    }
    
    g <- g + xlab(data$chr[1]) + 
      ylab("Reads per million total reads") +
      ggtitle(title) +
      theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
  }
  if(singlePdf){
    print(g)
  }else{
    png(paste0(x, ".png"), width=2000, height=height, res=300)
    print(g)
    dev.off()
  }
}

if(singlePdf){
  dev.off()
}
#################################################################################
### CALIBRATION CHECKING SCRIPT
### The goal here is to take a DIMA that contains calibration data, grab those data, and serve up information on how the observers compare on the major calibration indicators
### A lot of things are defined as values before they're called so that this can be altered as needed and to add hooks for a Shiny implementation
## Reporting out on the following indicators
## LPI : Foliar Cover, Bare Soil, Litter, Basal Cover, Rock Fragments, Vegetation Heights (by woody/herbaceous and height classes)
## Gap Intercept : Gap counts and proprtion of plot in gaps (by size classes)
#################################################################################

#################################################################################
### BASIC CONFIGURATION #########################################################
#################################################################################
## Getting the packages
require(RODBC)
require(dplyr)

# Filepath to find the DIMA
path.read <- "C:/Users/username/Documents/Projects/"
# DIMA filename
name.dima <- "training__calibration_DIMA_4.1.mdb"
# Filepath to write out the .csv of calibration results
path.write <- "C:/Users/username/Documents/Projects/"
# Filename for the .csv that you want to write out the results in
filename.output <- "calibration_results.csv"
#################################################################################

#################################################################################
### SETTING CALIBRATION TOLERANCES ##############################################
#################################################################################
## In the end, we need everyone to be within tolerances, which is ±5% from the mean for anything reported in percentages and ±2 on the species counts
## I'm still defining them as values in a list in case we want to let people set different tolerances eventually

## Initialize the tolerances list
tolerances <- list()

## LPI tolerances
# These four are the tolerance for (maximum observed percent on plot - minimum observed percent on plot)
tolerances$lpi$foliar.percent.range <- 10
tolerances$lpi$baresoil.percent.range <- 10
tolerances$lpi$basalcover.percent.range <- 10
tolerances$lpi$rockfragments.percent.range <- 10
# These four are maximum tolerance in abs(individual's observed percentage - mean plot percentage)
tolerances$lpi$foliar.percent <- tolerances$lpi$foliar.percent.range/2
tolerances$lpi$baresoil.percent <- tolerances$lpi$baresoil.percent.range/2
tolerances$lpi$basalcover.percent <- tolerances$lpi$basalcover.percent.range/2
tolerances$lpi$rockfragments.percent <- tolerances$lpi$rockfragments.percent.range/2
# Tolerance for (maximum observed count within a height class - minimum observed count within a height class)
tolerances$lpi$heights.count.range <- 4
# Tolerance for abs(individual's observed count within a height class - mean observed count on plot within a height class)
tolerances$lpi$heights.count <- tolerances$lpi$heights.count.range/2
# The breaking points in cm for the height classes. The upper bound is inclusive on each, e.g. <=50, >50 & <=200, >200
tolerances$lpi$heights.breaks <- c(50, 200, 500)



## Gap tolerances
tolerances$gaps$gap.pct.range <- 10
tolerances$gaps$gap.percent <- tolerances$gaps$gap.pct.range/2
## The breaking points in cm for the gap classes. For the first gap class, the check is inclusive, e.g. >= 25 & <=50
## For other gaps, the check is inclusive on the high end, e.g. >50 & <=100
## For the largest gap class, the upper limit is unbound, e.g. >200
tolerances$gaps$gap.breaks <- c(25, 50, 100, 200)
# gap.count is currently unused
tolerances$gaps$gap.count <- 2
#################################################################################


#################################################################################
### PULLING THE DATA FROM A DATABASE ############################################
#################################################################################
## Specify the DIMA filepath
dima.location <- paste(path.read, name.dima, sep = "/")

## Initialize our queries list
queries <- list()

## SQL query for getting a table of all LPI hits by layer with recorder, observer,, heights and species for heights by woody and herbaceous, point location on line,
## point number on line, line, plot, site, and date
queries$lpi <- "SELECT joinSitePlotLine.SiteID, joinSitePlotLine.PlotID, joinSitePlotLine.PlotKey, joinSitePlotLine.LineID, tblLPIHeader.FormDate, tblLPIHeader.Observer, tblLPIHeader.Recorder, tblLPIDetail.PointLoc, tblLPIDetail.PointNbr, tblLPIDetail.TopCanopy, tblLPIDetail.Lower1, tblLPIDetail.Lower2, tblLPIDetail.Lower3, tblLPIDetail.Lower4, tblLPIDetail.SoilSurface, tblLPIDetail.HeightWoody, tblLPIDetail.SpeciesWoody, tblLPIDetail.HeightHerbaceous, tblLPIDetail.SpeciesHerbaceous
FROM joinSitePlotLine INNER JOIN (tblLPIHeader LEFT JOIN tblLPIDetail ON tblLPIHeader.RecKey = tblLPIDetail.RecKey) ON joinSitePlotLine.LineKey = tblLPIHeader.LineKey;"

## SQL query for getting a table of gaps with observer, recorder, line, plot,site, and date
queries$gaps <- "SELECT joinSitePlotLine.SiteID, joinSitePlotLine.PlotID, joinSitePlotLine.PlotKey, joinSitePlotLine.LineID, tblGapHeader.FormDate, tblGapHeader.Observer, tblGapHeader.Recorder, tblGapDetail.Gap, tblGapHeader.LineLengthAmount
FROM joinSitePlotLine INNER JOIN (tblGapHeader INNER JOIN tblGapDetail ON tblGapHeader.RecKey = tblGapDetail.RecKey) ON joinSitePlotLine.LineKey = tblGapHeader.LineKey;"


## Let's get some tables extracted from the specified DIMA!
## Initialize the lists to keep all our data frames in
lpi <- list()
gaps <- list()

## Note that I'm using the function odbcConnectAccess2007() because I have 64-bit R and 64-bit Access installed. If your Access install is 32-bit, use odbcConnectAccess() in 32-bit R
## I also never trust factored fields to work with functions that I want to use, so I avoid them in the first place
## This is just connecting to the database and running the SQL queries then storing the results
lpi$raw <- odbcConnectAccess2007(dima.location) %>% sqlQuery(., queries$lpi, stringsAsFactors = F)
gaps$raw <- odbcConnectAccess2007(dima.location) %>% sqlQuery(., queries$gaps, stringsAsFactors = F)
odbcCloseAll()

## The line length is in meters, but we need cm, so we'll quickly do that
gaps$raw$LineLengthAmount <- gaps$raw$LineLengthAmount*100

## We also want the plot keys to be strings, not numeric values
lpi$raw$PlotKey <- as.character(lpi$raw$PlotKey)
gaps$raw$PlotKey <- as.character(gaps$raw$PlotKey)

## We'll set up some objects we can use to populate options in the Shiny tool that maybe will one day be built
sites.plots <- rbind(gaps$raw[,c("SiteID", "PlotID", "PlotKey")], lpi$raw[,c("SiteID", "PlotID", "PlotKey")]) %>% unique()
observers.all <- c(gaps$raw$Observer, lpi$raw$Observer) %>% unique()

## If you want to see your options for the calibration PlotKey, Plot-, and SiteID, use this
# sites.plots %>% View()

## Where's the calibration data? Specify the SiteID and the PlotID, although all we really need is the key
## This was originally—naively—written to use a combination of the Site- and PlotIDs on a one-at-a-time basis
## We've moved onto a loop that'll look at all the plots in a database using the plotkeys that were found
calibration.SiteID <- "Canyonlands Calibration"
calibration.PlotID <- "Calibration: NWDO"
## Humans struggle with reliably typing out a plot key, so let's just extract it based on the friendlier Site- and PlotIDs
calibration.PlotKey <- sites.plots$PlotKey[sites.plots$SiteID == calibration.SiteID & sites.plots$PlotID == calibration.PlotID]
#################################################################################


#################################################################################
### KICKING OFF THE LOOP THAT'LL ITERATE THROUGH ALL PLOTS ######################
#################################################################################
## For general purposes, we need to make a final data table that has calibration information for every plot
## in the database instead of just one at a time. So, we'll loop through each of the plot keys in turn and
## mash together the results from the data associated to each key.
## Obviously, the conclusion to this needs to come at the end of all the calibration work, so if you comment this
## out make sure you also comment out that section

## This is predicated on the assumption that the database contains only calibration plots. If there's just one calibration
## plot, just make sure it's set up above. If you have multiple calibration plots, let this do its thing and then
## just filter/subset at the end of it all. Your life will be much better for it.

for (i in seq_along(sites.plots$PlotKey)){
  calibration.PlotKey <- sites.plots$PlotKey[i]
  
## I'm aware that this is slow and inelegant, but the script was written assuming a single plot and this is much easier
## than working to rewrite to do calculations without looping and it's not that much data, really
#################################################################################
  
  
  
#################################################################################
### CALIBRATION CHECKING FOR LPI ################################################
#################################################################################
## The indicators being evaluated are Foliar Cover, Bare Soil, Litter, Basal Cover, Rock Fragments, Vegetation Heights (by woody/herbaceous and height classes)
## This is currently set up so that it'll work regardless of how many lines were read

## Create a data frame of just the LPI data from the calibration plot so we can get to work looking at it
## This first line is from the dark times when we didn't use plot keys
# lpi$calibration.raw <- lpi$raw %>% subset(SiteID == calibration.SiteID) %>% subset(PlotID == calibration.PlotID)
lpi$calibration.raw <- lpi$raw %>% subset(PlotKey == calibration.PlotKey)
## Add in some extra variables so we can calculate the indicators relatively painlessly. Normally I wouldn't do this, but summarize() is fighting me and this should make it possible
## First up is to add a 1 to all observations where the top canopy hit isn't a "None" so that we can find the sum to know how many foliar hits there were
lpi$calibration.raw$foliar.cover[lpi$calibration.raw$TopCanopy != "None"] <- 1
## Likewise, do the same sort of thing to all the points where there's a species code at the soil surface, which here is just anywhere where a standard non-vegetative code was not found
surface.codes <- c("S", "LC", "M", "D", "W", "CY", "EL", "R", "GR", "CB", "ST", "BY", "BR")
lpi$calibration.raw$basal.cover[!(lpi$calibration.raw$SoilSurface %in% surface.codes)] <- 1
## And a variable for if the last hit was a rock of some sort that wasn't bedrock because that's not a "rock fragment"
lpi$calibration.raw$rock.fragments[lpi$calibration.raw$SoilSurface %in% surface.codes[8:12]] <- 1
## One for bare ground. Assume it's true and then invalidate it wherever the surface code isn't S or CY, the top code isn't None, or there's anything in Lower1:Lower4. Clunky, but effective
lpi$calibration.raw$bare.soil <- 1
lpi$calibration.raw$bare.soil[!(lpi$calibration.raw$SoilSurface %in% c("S", "CY"))] <- 0
lpi$calibration.raw$bare.soil[lpi$calibration.raw$TopCanopy != "None"] <- 0
lpi$calibration.raw$bare.soil[lpi$calibration.raw$Lower1 != ""] <- 0
lpi$calibration.raw$bare.soil[lpi$calibration.raw$Lower2 != ""] <- 0
lpi$calibration.raw$bare.soil[lpi$calibration.raw$Lower3 != ""] <- 0
lpi$calibration.raw$bare.soil[lpi$calibration.raw$Lower4 != ""] <- 0

## The NAs were a complete nightmare to deal with, so I turned them into -1s. After this next bit I'll turn them back
lpi$calibration.raw$HeightWoody[is.na(lpi$calibration.raw$HeightWoody)] <- -1
lpi$calibration.raw$HeightHerbaceous[is.na(lpi$calibration.raw$HeightHerbaceous)] <- -1

## Adding in the height classes for woody and herbaceous.
for (n in seq_along(tolerances$lpi$heights.breaks)){
  ## For the first loop, we're checking for plants shorter than or equal to the first height break
  if (n == min(seq_along(tolerances$lpi$heights.breaks))){
    # That !is.na() wrapped around the logical statement is because for some reason it was returning a vector of TRUE and NA instead of TRUE and FALSE
    lpi$calibration.raw[lpi$calibration.raw$HeightWoody <= tolerances$lpi$heights.breaks[n] &
                           lpi$calibration.raw$HeightWoody > 0,
                        paste0("woody.0.", tolerances$lpi$heights.breaks[n])] <- 1
    lpi$calibration.raw[lpi$calibration.raw$HeightHerbaceous <= tolerances$lpi$heights.breaks[n] &
                          lpi$calibration.raw$HeightHerbaceous > 0,
                        paste0("herbaceous.0.", tolerances$lpi$heights.breaks[n])] <- 1
  ## The last loop will just look for anything larger than the last height break
  } else if (n == max(seq_along(tolerances$lpi$heights.breaks))){
    lpi$calibration.raw[lpi$calibration.raw$HeightWoody > tolerances$lpi$heights.breaks[n-1] &
                          lpi$calibration.raw$HeightWoody <= tolerances$lpi$heights.breaks[n] &
                          lpi$calibration.raw$HeightWoody > 0,
                        paste0("woody.", tolerances$lpi$heights.breaks[n-1]+1, ".", tolerances$lpi$heights.breaks[n])] <- 1
    lpi$calibration.raw[lpi$calibration.raw$HeightHerbaceous > tolerances$lpi$heights.breaks[n-1] &
                          lpi$calibration.raw$Heightherbaceous <= tolerances$lpi$heights.breaks[n],
                        paste0("herbaceous.", tolerances$lpi$heights.breaks[n-1]+1, ".", tolerances$lpi$heights.breaks[n])] <- 1
    lpi$calibration.raw[lpi$calibration.raw$HeightWoody > tolerances$lpi$heights.breaks[n] &
                          lpi$calibration.raw$HeightWoody > 0,
                        paste0("woody.", tolerances$lpi$heights.breaks[n] + 1)] <- 1
    lpi$calibration.raw[lpi$calibration.raw$HeightHerbaceous > tolerances$lpi$heights.breaks[n],
                        paste0("herbaceous.", tolerances$lpi$heights.breaks[n] + 1)] <- 1
  ## All other loops will find plants greater than the previous height break AND shorter than or equal to the current one
  } else {
    lpi$calibration.raw[lpi$calibration.raw$HeightWoody > tolerances$lpi$heights.breaks[n-1] &
                          lpi$calibration.raw$HeightWoody <= tolerances$lpi$heights.breaks[n] &
                          lpi$calibration.raw$HeightWoody > 0,
                        paste0("woody.", tolerances$lpi$heights.breaks[n-1]+1, ".", tolerances$lpi$heights.breaks[n])] <- 1
    lpi$calibration.raw[lpi$calibration.raw$HeightHerbaceous > tolerances$lpi$heights.breaks[n-1] &
                          lpi$calibration.raw$Heightherbaceous <= tolerances$lpi$heights.breaks[n],
                        paste0("herbaceous.", tolerances$lpi$heights.breaks[n-1]+1, ".", tolerances$lpi$heights.breaks[n])] <- 1
  }
}

## Restoring the NAs so that we can tell that there weren't values there
lpi$calibration.raw$HeightWoody[lpi$calibration.raw$HeightWoody == -1] <- NA
lpi$calibration.raw$HeightHerbaceous[lpi$calibration.raw$HeightHerbaceous == -1] <- NA

## Storing the column names we just generated for future reference
tolerances$lpi$heights.classes <- tail(colnames(lpi$calibration.raw), (length(tolerances$lpi$heights.breaks) + 1)*2)


## Taking those raw data and converting them into the various indicators we want for each observer, specifically: percent total foliar cover, percent bare soil, percent basal cover, percent rock fragments,
## and the woody and herbaceous heights by height classes
lpi$calibration <- lpi$calibration.raw %>% group_by(Observer, SiteID, PlotID, PlotKey) %>%
  summarize(records.lpi = n(),
            foliar.hits = sum(foliar.cover, na.rm = T),
            basal.hits = sum(basal.cover, na.rm = T),
            rock.frag.hits = sum(rock.fragments, na.rm = T),
            bare.soil.hits = sum(bare.soil, na.rm = T))

for (n in seq_along(tolerances$lpi$heights.classes)){
  lpi$calibration <- lpi$calibration.raw %>% group_by(Observer, SiteID, PlotID, PlotKey) %>%
    summarize_(paste0("sum(", tolerances$lpi$heights.classes[n], ", na.rm = T)")) %>%
    merge(y = ., x = lpi$calibration, all = T)
  colnames(lpi$calibration)[length(colnames(lpi$calibration))] <- paste0(tolerances$lpi$heights.classes[n], ".count")
}

## Calculating percentages for the appropriate indicators
lpi$calibration <- lpi$calibration %>% mutate(foliar.cover.pct = 100*(foliar.hits/records.lpi),
                                              basal.cover.pct = 100*(basal.hits/records.lpi),
                                              rock.fragments.pct = 100*(rock.frag.hits/records.lpi),
                                              bare.soil.pct = 100*(bare.soil.hits/records.lpi))

## Now to add in the min and max for each indicator
lpi$calibration <- lpi$calibration %>% mutate(foliar.cover.pct.min = min(foliar.cover.pct),
                                              basal.cover.pct.min = min(basal.cover.pct),
                                              rock.fragments.pct.min = min(rock.fragments.pct),
                                              bare.soil.pct.min = min(bare.soil.pct),
                                              foliar.cover.pct.max = max(foliar.cover.pct),
                                              basal.cover.pct.max = max(basal.cover.pct),
                                              rock.fragments.pct.max = max(rock.fragments.pct),
                                              bare.soil.pct.max = max(bare.soil.pct))

for (n in seq_along(tolerances$lpi$heights.classes)){
  lpi$calibration <- lpi$calibration %>% mutate_(paste0("min(",tolerances$lpi$heights.classes[n],".count)"),
                                                 paste0("max(",tolerances$lpi$heights.classes[n],".count)"),
                                                 paste0("max(",tolerances$lpi$heights.classes[n],".count) - min(",tolerances$lpi$heights.classes[n],".count)"))
  colnames(lpi$calibration)[tail(seq_along(colnames(lpi$calibration)), 3)] <- c(paste0(tolerances$lpi$heights.classes[n], ".count.min"),
                                                                                paste0(tolerances$lpi$heights.classes[n], ".count.max"),
                                                                                paste0(tolerances$lpi$heights.classes[n], ".count.range"))
}


## And now to add the calibrated-or-not logical values!
lpi$calibration$foliar.cover.calibrated <- (lpi$calibration$foliar.cover.pct.max - lpi$calibration$foliar.cover.pct.min) <= tolerances$lpi$foliar.percent.range
lpi$calibration$basal.cover.calibrated <- (lpi$calibration$basal.cover.pct.max - lpi$calibration$basal.cover.pct.min) <= tolerances$lpi$basalcover.percent.range
lpi$calibration$bare.soil.calibrated <- (lpi$calibration$bare.soil.pct.max - lpi$calibration$bare.soil.pct.min) <= tolerances$lpi$baresoil.percent.range
lpi$calibration$rock.fragments.calibrated <- (lpi$calibration$rock.fragments.pct.max - lpi$calibration$rock.fragments.pct.min) <= tolerances$lpi$rockfragments.percent.range

for (n in seq_along(tolerances$lpi$heights.classes)){
  lpi$calibration[,paste0(tolerances$lpi$heights.classes[n], ".calibrated")] <- lpi$calibration[, paste0(tolerances$lpi$heights.classes[n], ".count.range")] <= tolerances$lpi$heights.count.range
}
#################################################################################

#################################################################################
### CALIBRATION CHECKING FOR GAPS ###############################################
#################################################################################
## The indicator being evaluated percentage of line[s] in gaps of of size classes defined by the values in tolerances$gaps$gap.breaks.
## Additionally, the gap count for each size class is included
## This is currently set up so that it'll work regardless of how many lines were read or number of gap classes

## Subset to just the data from the calibration plot
## This used to use a combination of Site- and PlotID, but much more reasonably, if less readably, now uses plot keys
# gaps$calibration.raw <- gaps$raw %>% subset(SiteID == calibration.SiteID) %>% subset(PlotID == calibration.PlotID)
## It also omits all rows with NA values, so just be aware
gaps$calibration.raw <- gaps$raw %>% subset(PlotKey == calibration.PlotKey) %>% na.omit()

## Writing in variables to keep track of what size class these belong to
## These are generalized so that no matter what the gap breaks are or how many size classes they result in, you should get the appropriate
## number of columns with intelligible names
for (n in seq_along(tolerances$gaps$gap.breaks)){
  # This evaluates for the first gap class, which is inclusive of the lower bounding cm value and the upper
  if (n == min(seq_along(tolerances$gaps$gap.breaks))){
    # This is the standard situation for the smallest gap class, but it only applies if there's more than one gap class
    if (length(tolerances$gaps$gap.breaks) > 1){
      # This creates a column with the name of "gap.[lowerbound].[upperbound]" and writes a 1 into it in every row where the size of the gap is both >= the lowest bound and <= the next break
      gaps$calibration.raw[gaps$calibration.raw$Gap >= tolerances$gaps$gap.breaks[n] & gaps$calibration.raw$Gap <= tolerances$gaps$gap.breaks[n+1], paste("gap", tolerances$gaps$gap.breaks[n], tolerances$gaps$gap.breaks[n+1], sep = ".")] <- 1
      # Otherwise, if for some reason there's only one size class, this will handle that situation
    } else {
      gaps$calibration.raw[gaps$calibration.raw$Gap >= tolerances$gaps$gap.breaks[n], paste("gap", tolerances$gaps$gap.breaks[n], sep = ".")] <- 1
    }
    # This evaluates the largest gap class, which has no upper bound on size and is not inclusive on the lower bound
  } else if (n == max(seq_along(tolerances$gaps$gap.breaks))){
    gaps$calibration.raw[gaps$calibration.raw$Gap > tolerances$gaps$gap.breaks[n], paste("gap", tolerances$gaps$gap.breaks[n] + 1, sep = ".")] <- 1
    # This evaluates all other gap classes, which are inclusive only on the upper bound   
  } else {
    gaps$calibration.raw[gaps$calibration.raw$Gap > tolerances$gaps$gap.breaks[n] & gaps$calibration.raw$Gap <= tolerances$gaps$gap.breaks[n+1], paste("gap", tolerances$gaps$gap.breaks[n], tolerances$gaps$gap.breaks[n+1] + 1, sep = ".")] <- 1
  }
}

## Just going to store the resulting gap classes' column names for future reference. They're the only ones with "gap." in them at this point
## Basically every loop after this takes advantage of this vector because it's so useful
tolerances$gaps$gap.classes <- colnames(gaps$calibration.raw)[grep("gap.", colnames(gaps$calibration.raw))]

## Counting gaps and finding their sums. This was the quick-and-dirty solution where I just filtered by the classes and kept merging them into the same calibration data frame
for (n in seq_along(tolerances$gaps$gap.classes)){
  ## As ever, we want to do something different on the first pass because we're creating gaps.calibration here, but with later passes we'll merge
  if (n == min(seq_along(tolerances$gaps$gap.classes))){
    ## Step one is to group the data by an observer on the plot
    gaps$calibration <- gaps$calibration.raw %>% group_by(Observer, SiteID, PlotID, PlotKey) %>%
      ## Then we use filter_() to get only the rows where the currently-being-evaluated gap class was recorded
      ## I guess that filter_() lets us pass strings as arguments whereas filter() doesn't, so we can create a string of "[column name] == 1"
      ## to use as our evaluations statement
      filter_(paste0(tolerances$gaps$gap.classes[n], "==", 1)) %>%
      ## Finish off with summarizing the number of gaps and the sum of the gaps' lengths in that size class, with appropriate but still ambiguously-named columns
      summarize(count = n(), cm.sum = sum(Gap, na.rm = T))
    ## Renaming those columns because doing it inside the summarize() was too hard to implement. Frankly this isn't much easier, but at least it works
    ## The grep() is looking for a column that exactly matches the string provided. "^" indicates that that's the start of the string and "$" is the end
    ## so "^count$" will only return the index of "count" but not "counts" or "account"
    colnames(gaps$calibration)[grep("^count$", colnames(gaps$calibration))] <- paste0(tolerances$gaps$gap.classes[n], ".count")
    colnames(gaps$calibration)[grep("^cm.sum$", colnames(gaps$calibration))] <- paste0(tolerances$gaps$gap.classes[n], ".cm.sum")
    ## And on any subsequent passes, we do the same thing, but merge in so as to not overwrite
  } else {
    gaps$calibration <- gaps$calibration.raw %>% group_by(Observer, SiteID, PlotID, PlotKey) %>%
      filter_(paste0(tolerances$gaps$gap.classes[n], "==", 1)) %>%
      summarize(count = n(), cm.sum = sum(Gap, na.rm = T)) %>%
      ## The only difference from above is that this line merges because gaps$calibration already has data in it
      merge (x = ., y = gaps$calibration, all = T)
    colnames(gaps$calibration)[grep("^count$", colnames(gaps$calibration))] <- paste0(tolerances$gaps$gap.classes[n], ".count")
    colnames(gaps$calibration)[grep("^cm.sum$", colnames(gaps$calibration))] <- paste0(tolerances$gaps$gap.classes[n], ".cm.sum")
  }
}

## Adding in the line lengths on a per-observer basis in case they maybe read different lengths even though they shouldn't
gaps$calibration <- gaps$calibration.raw %>% group_by(Observer, SiteID, PlotID, PlotKey) %>% summarize(length.total.cm = first(LineLengthAmount)) %>% merge (x = ., y = gaps$calibration, all = T)

## We've got NAs, but those are really 0s because this data frame is restricted to observers who completed gap forms, so let's change them
gaps$calibration <- gaps$calibration %>% replace(., is.na(.), 0)

## We need the minimum and maximum gap counts and percent in each gap class
for (n in seq_along(tolerances$gaps$gap.classes)){
  gaps$calibration[,paste0(tolerances$gaps$gap.classes[n], ".pct.max")] <- 100*max(gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".cm.sum")]/gaps$calibration$length.total.cm)
  gaps$calibration[,paste0(tolerances$gaps$gap.classes[n], ".pct.min")] <- 100*min(gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".cm.sum")]/gaps$calibration$length.total.cm)
  gaps$calibration[,paste0(tolerances$gaps$gap.classes[n], ".count.max")] <- max(gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".count")])
  gaps$calibration[,paste0(tolerances$gaps$gap.classes[n], ".count.min")] <- min(gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".count")])
}

## Now we'll add the percent of length and the mean percent of length in each gap class and mean count
for (n in seq_along(tolerances$gaps$gap.classes)){
  gaps$calibration <-  gaps$calibration %>% mutate_(paste0("100*(", tolerances$gaps$gap.classes[n], ".cm.sum/length.total.cm)"),
                                                    paste0("100*(mean(", tolerances$gaps$gap.classes[n], ".cm.sum, na.rm = T)/length.total.cm)"),
                                                    paste0(" mean(", tolerances$gaps$gap.classes[n], ".count, na.rm = T)")
  )
  ## So, I can't be bothered to fight naming mutate_() columns anymore. This takes the last three column names in the data frame
  ## using the tail() function to get the indices for them in the vector from colnames() and uses those to rename them with the same paste0()
  ## results that I couldn't get working in the mutate_()
  colnames(gaps$calibration)[tail(seq_along(colnames(gaps$calibration)), 3)] <- c(paste0(tolerances$gaps$gap.classes[n], ".pct"), paste0(tolerances$gaps$gap.classes[n], ".pct.mean"), paste0(tolerances$gaps$gap.classes[n], ".count.mean"))
}

## Final step is to decide if they're calibrated or not.
for (n in seq_along(tolerances$gaps$gap.classes)){
  gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".pct.calibrated")] <- (gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".pct.max")] - gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".pct.min")]) <= tolerances$gaps$gap.pct.range
  gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".count.calibrated")] <- (gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".count.max")] - gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".count.min")]) <= tolerances$gaps$gap.count
}
#################################################################################

#################################################################################
### CONCLUDING THE LOOP THAT'LL ITERATE THROUGH ALL PLOTS #######################
#################################################################################
## And now we wrap up the loop set in motion above. This will result in a single data frame output that contains all the calibration
## information for each observer by plot.

## On the first trip through the loop, it just creates calibration.results
  if (i == 1){
    calibration.results <- merge(lpi$calibration, gaps$calibration, all = T)
    ## On subsequent loops, the calibration.results data frame exists, so the new plot's results are just appended to avoid overwriting
  } else {
    calibration.results <- merge(lpi$calibration, gaps$calibration, all = T) %>% rbind(., calibration.results)
  }
}

#################################################################################


#################################################################################
### COMBINING AND WRITING CALIBRATION RESULTS ###################################
#################################################################################
### COMBINING AND WRITING CALIBRATION RESULTS
## So, now there're two data frames—one for LPI and one for gaps—but we want them combined and written out
## This needs to be uncommented to combine things if you aren't using the whole-database loop!
## calibration.results <- merge(lpi$calibration, gaps$calibration, all = T)
write.csv(calibration.results, paste(path.write, filename.output, sep = "/"))

#################################################################################
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
filename = 'similarity_cons_res_blind'
similarity_cons_res <- tanimoto_analysis(min.tx = 45,
                                        K.values = 8,
                                        MW = 1,
                                        WT =  c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1),
                                        minimum_threshold = 0.3,
                                        filename = filename)

# Catalog vs predictions
load("./RData/interactions_source.RData")
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = similarity_cons_res, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = similarity_cons_res, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = similarity_cons_res)

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=7,height=7)

# Plots
par(mfrow=c(2,2))
# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 1.09)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        # foodwebs <- names(similarity_cons_res_blind[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000088","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
            axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
            # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
            points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
        } #i

        ## Add legend
        if(j == 12) {
            legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        }
} #j
dev.off()
no.extension <- function(filename) { 
  if (substr(filename, nchar(filename), nchar(filename))==".") { 
    return(substr(filename, 1, nchar(filename)-1)) 
  } else { 
    no.extension(substr(filename, 1, nchar(filename)-1)) 
  } 
}


extract.ages <- function(file = NULL, replicates = 1, cutoff = NULL, random = TRUE){

if (is.null(file)) 
    stop("you must enter a filename or a character string\n")

rnd <- random
q <- cutoff
dat1 <- read.table(file, header=T, stringsAsFactors=F, row.names=NULL, sep="\t", strip.white=T)
fname <- no.extension(basename(file))
outfile <- paste(dirname(file), "/", fname, "_PyRate.py", sep="")

dat1[,1] <- gsub("[[:blank:]]{1,}","_", dat1[,1])

if (replicates > 1){
	rnd <- TRUE
}

if (any(is.na(dat1[,1:4]))){
	stop("the input file contains missing data in species names, status or ages)\n")
}

if (!is.null(q)){
		dat <- dat1[!(dat1[,4] - dat1[,3] >= q),]
	} else { 
		dat <- dat1 
}

if (length(dat) == 5){
	colnames(dat) <- c("Species", "Status", "min_age", "max_age", "trait")	
	} else {
	colnames(dat) <- c("Species", "Status", "min_age", "max_age")
}

dat$new_age <- "NA"
splist <- unique(dat[,c(1,2)])[order(unique(dat[,c(1,2)][,1])),]


if (any(is.element(splist$Species[splist$Status == "extant"], splist$Species[splist$Status == "extinct"]))){
	print(intersect(splist$Species[splist$Status == "extant"], splist$Species[splist$Status == "extinct"]))
	stop("at least one species is listed as both extinct and extant\n")
}

cat("#!/usr/bin/env python", "from numpy import * ", "",  file=outfile, sep="\n")

for (j in 1:replicates){
	times <- list()
	cat ("\nreplicate", j)
	
	dat[dat$min_age == 0,3] <- 0.001
	
	if (any(dat[,4] < dat[,3])){
		cat("\nWarning: the min age is older than the max age for at least one record\n")
		cat ("\nlines:",1+as.numeric(which(dat[,4] < dat[,3])),sep=" ")
	}
	
	if (isTRUE(rnd)){
			dat$new_age <- round(runif(length(dat[,1]), min=apply(dat[,3:4],FUN=min,1), max=apply(dat[,3:4],FUN=max,1)), digits=6)
		} else {
			for (i in 1:length(dat[,1])){
				dat$new_age[i] <- mean(c(dat[i,3], dat[i,4]))
			}				
		}

	dat2 <- subset(dat, select=c("Species","new_age"))
	taxa <- sort(unique(dat2$Species))

	for (n in 1:length(taxa)){
		times[[n]] <- dat2$new_age[dat2$Species == taxa[n]]
		if (toupper(splist$Status[splist$Species == taxa[n]]) == toupper("extant")){
			times[[n]] <- append(times[[n]], "0", after=length(times[[n]]))
		}
	}

	dat3 <- matrix(data=NA, nrow=length(times), ncol=max(sapply(times, length)))
	rownames(dat3) <- taxa

	for (p in 1:length(times)){
		dat3[p,1:length(times[[p]])] <- times[[p]]
	}

	cat(noquote(sprintf("\ndata_%s=[", j)), file=outfile, append=TRUE)

	for (n in 1:(length(taxa)-1)){
		rec <- paste(dat3[n,!is.na(dat3[n,])], collapse=",")
		cat(noquote(sprintf("array([%s]),", rec)), file=outfile, append=TRUE, sep="\n")
	}

	n <- n+1
	rec <- paste(dat3[n,!is.na(dat3[n,])], collapse=",")
	cat(noquote(sprintf("array([%s])", rec)), file=outfile, append=TRUE, sep="\n")

	cat("]", "", file=outfile, append=TRUE, sep="\n")
}


data_sets <- ""
names <- ""

if (replicates > 1){
	for (j in 1:(replicates-1)) {
		data_sets <- paste(data_sets, noquote(sprintf("data_%s,", j)))
		names <- paste(names, noquote(sprintf(" '%s_%s',", fname,j)))
		}

	data_sets <- paste(data_sets, noquote(sprintf("data_%s", j+1)))
	names <- paste(names, noquote(sprintf(" '%s_%s',", fname,j+1)))
} else {
	data_sets <- "data_1"
	names <- noquote(sprintf(" '%s_1'", fname))	
}

cat(noquote(sprintf("d=[%s]", data_sets)), noquote(sprintf("names=[%s]", names)), "def get_data(i): return d[i]", "def get_out_name(i): return  names[i]", file=outfile, append=TRUE, sep="\n")


tax_names <- paste(taxa, collapse="','")
cat(noquote(sprintf("taxa_names=['%s']", tax_names)), "def get_taxa_names(): return taxa_names", file=outfile, append=TRUE, sep="\n")


if ("trait" %in% colnames(dat)){
	datBM <- dat[,1]
	splist$Trait <- NA
	for (n in 1:length(splist[,1])){
		splist$Trait[n] <- mean(dat$trait[datBM == splist[n,1]], na.rm=T)
	}
	s1 <- "\ntrait1=array(["
	BM <- gsub("NaN|NA", "nan", toString(splist$Trait))
	s2 <- "])\ntraits=[trait1]\ndef get_continuous(i): return traits[i]"
	STR <- paste(s1,BM,s2)
	cat(STR, file=outfile, append=TRUE, sep="\n")
}

splistout <- paste(dirname(file), "/", fname, "_SpeciesList.txt", sep="")
lookup <- as.data.frame(taxa)
lookup$status  <- "extinct"

write.table(splist, file=splistout, sep="\t", row.names=F, quote=F)
cat("\n\nPyRate input file was saved in: ", sprintf("%s", outfile), "\n\n")

}


fit.prior <- function(file = NULL, lineage = "root_age"){

require(fitdistrplus)

if (is.null(file)){
    stop("You must enter a valid filename.\n")
	}

dat <- read.table(file, header=T, stringsAsFactors=F, row.names=NULL, sep="\t")
fname <- no.extension(basename(file))
outfile <- paste(dirname(file), "/", lineage, "_Prior.txt", sep="")

lineage2 <- paste(lineage,"_TS", sep="")
if (!is.element(lineage2, colnames(dat))){
	stop("Lineage not found, please check your input.\n")
	}

time <- dat[,which(names(dat) == lineage2)]
time2 <- time-(min(time)-0.01)
gamm <- fitdist(time2, distr="gamma", method = "mle")$estimate 

cat("Lineage: ", lineage, "; Shape: ", gamm[1], "; Scale: ", 1/gamm[2], "; Offset: ", min(time), sep="", file=outfile, append=FALSE)
}




extract.ages.pbdb <- function(file = NULL,sep=",", extant_species = c(), replicates = 1, cutoff = NULL, random = TRUE){
	print("This function is currently being tested - caution with the results!")
	tbl = read.table(file=file,h=T,sep=sep,stringsAsFactors =F)
	new_tbl = NULL # ADD EXTANT SPECIES
	
	for (i in 1:dim(tbl)[1]){
		if (tbl$accepted_name[i] %in% extant_species){
			status="extant"
		}else{status="extinct"}
		species_name = gsub(" ", "_", tbl$accepted_name[i])
		new_tbl = rbind(new_tbl,c(species_name,status,tbl$min_ma[i],tbl$max_ma[i]))
	}
	colnames(new_tbl) = c("Species","Status","min_age","max_age")
	
	output_file = file.path(dirname(file),strsplit(basename(file), "\\.")[[1]][1])
	output_file = paste(output_file,".txt",sep="")
	write.table(file=output_file,new_tbl,quote=F,row.names = F,sep="\t")
	extract.ages(file=output_file,replicates = replicates, cutoff = cutoff, random = random)
}



                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
#        list12 <- stocklistperiod[period, 2][[1]]
#        for (i in 1:max) {
#            print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
#        }
        for (i in 1:max) {
            id <- list11$id[i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
            }
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), rise, list11$id[[i]]))
        }
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
                                        #    list12 <- stocklistperiod[period, 2][[1]]
                                        #
                                        #    len <- nrow(list12)
                                        #    len <- len + 1

                                        #    for (i in 1:max) {
                                        #        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
                                        #    }

                                        #    len <- nrow(list11)
                                        #    len <- len + 1

        len <- nrow(list11)
        len <- len + 1
        for (i in 1:max) {
            id <- list11$id[len - i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
            }
            
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), rise, list11$id[[len - i]]))
        }
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, mynames, topbottom, periodtext, maindate, olddate, days) {
    dev.new()
    colours <- rainbow(topbottom)
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE, col = colours[i], pch = i)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o", lty = i, col = colours[i], pch = i)
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(mynames[1]))
        legend(1, g_range[2], mynames, cex=0.8, lty=1:6, pch=1:25, col=colours) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (type == pricetype) {
        return (df$price)
    }
    if (type == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    normalize <- 0
    if (length(ids) > 1) {
        if (periodtext == "price") {
            normalize <- 1
        }
        if (periodtext == "index") {
            normalize <- 1
        }
    }
    
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, pricetype)
        perioddata[["text"]] <- pairs
        perioddatamap[["price"]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, indextype)
        perioddata[["text"]] <- pairs
        perioddatamap[["index"]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    dayset <- list()
    ls <- list()
    mynames <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        if (normalize == 1) {
                            str("minmax")
                            str(l)
                            mymin <- abs(min(l))
                            mymax <- abs(max(l))
                            if (mymin > mymax) {
                                mymax <- mymin
                            }
                            for (j in 1:length(l)) {
                                l[j] <- l[j] * 100 / mymax;
                            }
                            str(l)
                        }
                        
                        dayset <- append(dayset, bigretl[[2]])
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        mynames[c] <- df$name
                    }
                }
            }
        }
    }
    daynames <- names(dayset)
    olddate <- min(daynames)
    newdate <- max(daynames)
    displaychart(ls, mynames, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
#        list12 <- stocklistperiod[period, 2][[1]]
#        for (i in 1:max) {
#            print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
#        }
        for (i in 1:max) {
            id <- list11$id[i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
            }
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), rise, list11$id[[i]]))
        }
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, mynames, topbottom, periodtext, maindate, olddate, days) {
    dev.new()
    colours <- rainbow(topbottom)
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE, col = colours[i], pch = i)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o", lty = i, col = colours[i], pch = i)
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(mynames[1]))
        legend(1, g_range[2], mynames, cex=0.8, lty=1:6, pch=1:25, col=colours) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (type == pricetype) {
        return (df$price)
    }
    if (type == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    normalize <- 0
    if (length(ids) > 1) {
        if (periodtext == "price") {
            normalize <- 1
        }
        if (periodtext == "index") {
            normalize <- 1
        }
    }
    
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, pricetype)
        perioddata[["text"]] <- pairs
        perioddatamap[["price"]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, indextype)
        perioddata[["text"]] <- pairs
        perioddatamap[["index"]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    dayset <- list()
    ls <- list()
    mynames <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        if (normalize == 1) {
                            str("minmax")
                            str(l)
                            mymin <- abs(min(l))
                            mymax <- abs(max(l))
                            if (mymin > mymax) {
                                mymax <- mymin
                            }
                            for (j in 1:length(l)) {
                                l[j] <- l[j] * 100 / mymax;
                            }
                            str(l)
                        }
                        
                        dayset <- append(dayset, bigretl[[2]])
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        mynames[c] <- df$name
                    }
                }
            }
        }
    }
    daynames <- names(dayset)
    olddate <- min(daynames)
    newdate <- max(daynames)
    displaychart(ls, mynames, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

#setwd("/scratch/cqs/shengq1/dnaseq/2110/cnmops/result")
#sample_names <- c(
#"2110_JP_01"
#,"2110_JP_02"
#,"2110_JP_03"
#,"2110_JP_04"
#,"2110_JP_05"
#,"2110_JP_06"
#,"2110_JP_07"
#,"2110_JP_08"
#,"2110_JP_09"
#,"2110_JP_10"
#,"2110_JP_11"
#,"2110_JP_12"
#,"2110_JP_13"
#,"2110_JP_14"
#,"2110_JP_15"
#,"2110_JP_16"
#)
#bam_files <- c(
#"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-1_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-2_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-3_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-4_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-5_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-6_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-7_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-8_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-9_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-10_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-11_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-12_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-13_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-14_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-15_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-16_realigned_recal_rmdup.sorted.bam"
#)
#hasbed<-1
#bedfile<-"/scratch/cqs/lij17/cnv/SureSelect_XT_Human_All_Exon_V4_withoutchr_withoutY_lite.bed"
#prefix<-"2110"
#callfile<-"2110.call"
#pairmode<-"paired"
#parallel<-8
#refnames<-c()

library(GenomicRanges)

if(hasbed){
  segments <- read.table(bedfile, sep="\t", as.is=TRUE, header=T)
  gr <- GRanges(segments[,1], IRanges(segments[,2], segments[,3]))
  gr <- reduce(gr)
  sort(gr, ignore.strand=TRUE)
}    

library(cn.mops)
library(DNAcopy)
resfile<-paste0(prefix, "_resCNMOPS.cnmops.Rdata")

if(length(refnames) > 0){
  insample<-sample_names %in% refnames
  REFNames<-sample_names[insample]
  REFFiles<-bam_files[insample]
  SAMNames<-sample_names[!insample]
  SAMFiles<-bam_files[!insample]
  if(hasbed){
    segfile<-paste0(prefix, "_getSegmentReadCountsFromBAM_ref.Rdata")
    if(file.exists(segfile)){
      load(segfile)
    }else{
      refdata <- getSegmentReadCountsFromBAM(REFFiles, GR=gr, sampleNames=REFNames, mode=pairmode, parallel=parallel)
      samdata <- getSegmentReadCountsFromBAM(SAMFiles, GR=gr, sampleNames=SAMNames, mode=pairmode, parallel=parallel)
      save(refdata, samdata, file=segfile)
    }
  }else{
    countfile<-paste0(prefix, "_getReadCountsFromBAM_ref.Rdata")
    if(file.exists(countfile)){
      load(countfile)
    }else{
      refdata <- getReadCountsFromBAM(REFFiles, sampleNames=REFNames, mode=pairmode, parallel=parallel)
      samdata <- getReadCountsFromBAM(SAMFiles, sampleNames=SAMNames, mode=pairmode, parallel=parallel)
      save(refdata, samdata, file=countfile)
    }
  }
  resCNMOPS<-referencecn.mops(cases=samdata, 
                              controls=refdata, 
                              upperThreshold=0.5, 
                              lowerThreshold=-0.5,
                              segAlgorithm="fast")
  resCNMOPS<-calcIntegerCopyNumbers(resCNMOPS)
}else{
  if(hasbed){
    segfile<-paste0(prefix, "_getSegmentReadCountsFromBAM.Rdata")
    if(file.exists(segfile)){
      load(segfile)
    }else{
      x <- getSegmentReadCountsFromBAM(bam_files, GR=gr, sampleNames=sample_names, mode=pairmode, parallel=parallel)
      save(refx, samx, file=segfile)
    }
    resCNMOPS<-exomecn.mops(x, upperThreshold=0.5, lowerThreshold=-0.5)
    resCNMOPS<-calcIntegerCopyNumbers(resCNMOPS)
  }else{
    countfile<-paste0(prefix, "_getReadCountsFromBAM.Rdata")
    if(file.exists(countfile)){
      load(countfile)
    }else{
      x <- getReadCountsFromBAM(bam_files, sampleNames=sample_names, mode=pairmode)
      save(x, file=countfile)
    }
    resCNMOPS <- cn.mops(x) 
    resCNMOPS <- calcIntegerCopyNumbers(resCNMOPS)
  }
}

#load(resfile)
save(resCNMOPS, file=resfile)

d<-as.data.frame(cnvs(resCNMOPS))
d[,"type"]<-apply(d,1,function(x){
  if(as.numeric(x["median"]) < 0){
    return ("DELETION")
  }else{
    return ("DUPLICATION")
  }
})

# locus<-data.frame(Title=paste0(d$sampleName, " ~ ", d$seqnames, ":", d$start, "-", d$end, " ~ ", d$type),
#                   Filename=paste0(d$sampleName, "_", d$seqnames, "_", d$start, "_", d$end, ".png"))

d<-d[order(d[,"sampleName"], as.numeric(d[,"seqnames"]), as.numeric(d[,"start"])),]
write.table(d, file=callfile,sep="\t",col.names=T,row.names=F,quote=F)

locus<-d[,c("seqnames", "start", "end")]
locus$name<-paste0(d$seqnames, "_", d$start, "_", d$end, "_", d$CN, "_", d$sampleName)
locus<-locus[order(d$seqnames, d$start),]
write.table(locus, file=paste0(prefix, ".call.bed"), sep="\t", col.names=F, row.names=F,quote=F)

cnvr<- data.frame(seqnames=seqnames(resCNMOPS@cnvr),
                  starts=start(resCNMOPS@cnvr)-1,
                  ends=end(resCNMOPS@cnvr),
                  file=paste(seqnames(resCNMOPS@cnvr), start(resCNMOPS@cnvr)-1, end(resCNMOPS@cnvr), sep="_") )
cnvr<-data.frame(cbind(cnvr, elementMetadata(resCNMOPS@cnvr)))
write.table(file=paste0(prefix, ".cnvr.tsv"), cnvr, sep="\t" ,row.names=F, quote=F)

# dir.create("images", showWarnings = FALSE)
# 
# index<-9
# for(index in c(1:nrow(locus))){
#   png(filename=paste0("images/", locus$Filename[index]), width=2000, height=2000, res=300)
#   plot(resCNMOPS, which=index, toFile=TRUE)
#   grid.text(locus$Title[index], y=0.98)
#   dev.off()
# }
                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
#        list12 <- stocklistperiod[period, 2][[1]]
#        for (i in 1:max) {
#            print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
#        }
        for (i in 1:max) {
            id <- list11$id[i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
            }
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), rise, list11$id[[i]]))
        }
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, mynames, topbottom, periodtext, maindate, olddate, days) {
    dev.new()
    colours <- rainbow(topbottom)
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE, col = colours[i], pch = i)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o", lty = i, col = colours[i], pch = i)
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(mynames[1]))
        legend(1, g_range[2], mynames, cex=0.8, lty=1:6, pch=1:25, col=colours) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (type == pricetype) {
        return (df$price)
    }
    if (type == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    normalize <- 0
    if (length(ids) > 0) {
        if (periodtext == "price") {
            normalize <- 1
        }
        if (periodtext == "index") {
            normalize <- 1
        }
    }
    
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, pricetype)
        perioddata[["text"]] <- pairs
        perioddatamap[["price"]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, indextype)
        perioddata[["text"]] <- pairs
        perioddatamap[["index"]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    dayset <- list()
    ls <- list()
    mynames <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        if (normalize == 1) {
                            str("minmax")
                            str(l)
                            mymin <- abs(min(l))
                            mymax <- abs(max(l))
                            if (mymin > mymax) {
                                mymax <- mymin
                            }
                            for (j in 1:length(l)) {
                                l[j] <- l[j] * 100 / mymax;
                            }
                            str(l)
                        }
                        
                        dayset <- append(dayset, bigretl[[2]])
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        mynames[c] <- df$name
                    }
                }
            }
        }
    }
    daynames <- names(dayset)
    olddate <- min(daynames)
    newdate <- max(daynames)
    displaychart(ls, mynames, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

# The functions require rchart-helper.R preloaded

# getQ2TimelapsePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getQ2TimelapsePlot = function(data, names, colors, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    dateFactors = list()
    for (i in 1:length(data)) {
        dateFactors[[i]] = as.factor(data[[i]]$date)
        boxplot = boxplot(data[[i]]$x ~ dateFactors[[i]],
                          data=data.frame(dateFactors[[i]], data[[i]]$x), plot=FALSE)
        stats = setNames(as.data.frame(boxplot$stats), nm=NULL)

        # Timpstamp in miliseconds
        unixTimestamps =
            1000 * as.numeric(as.POSIXct(sort(unique(data[[i]]$date)),
                                         origin="1970-01-01"))
        statsMedian = rbind(setNames(unixTimestamps, nm=NULL), stats[3,])
        statsQ2 = rbind(setNames(unixTimestamps, nm=NULL), stats[c(2, 4),])

        series[[2 * (i - 1) + 1]] =
            list(name=names[i], data=statsMedian, zIndex=1, color=colors[i],
                 marker=list(fillColor="white", lineWidth=2, lineColor=colors[i]))
        series[[2 * i]] = list(name="50th quartile", data=statsQ2, zIndex=0,
                 type="arearange", color=colors[i], lineWidth=0, linkedTo=":previous", fillOpacity=0.3)
    }

    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=list(text=yLabel), min=0)
    chart$set(series=series)
    return(chart)
}

# Helper for creating histogram
getBinItemList = function(data, businesses, interval=100) {
    binItemList = c()
    currentBin = interval
    maxBin = max(data$count) + interval
    while (currentBin < maxBin) {
        items = filter(data, currentBin - interval <= count & count < currentBin)
        binItemList = c(binItemList,
                        paste("< ", currentBin, "<br>",
                              paste(items$name, collapse="<br>, ")))
        currentBin = currentBin + interval
    }
    return(binItemList)
}

# getStackedHistogram
# data[[]]$x
getStackedHistogram = function(data, names, xLabel, interval=100, logScale=FALSE, logBase=exp(1), normalize=FALSE, colors = c("#7cb5ec", "#000000")) {
    series = list()
    plotLines = list()
    for (i in 1:length(data)){
        x = data[[i]]$x

        plotLines[[i * 2 - 1]] =
            list(color=colors[i],
                 value=mean(x),
                 width=2,
                 label=list(text="mean", style=list(color=colors[i]), verticalAlign="middle"))
        plotLines[[i * 2]] =
            list(color=colors[i],
                 value=median(x),
                 dashStyle="dash",
                 width=2,
                 label=list(text="median", style=list(color=colors[i]), verticalAlign="middle"))

        maxBin = max(data[[i]]$x)
        minBin = min(data[[i]]$x)
        actualInterval = interval

        if (logScale) {
            x = log(x + 1, base=logBase)
            maxBin = log(maxBin + 1, base=logBase)
            minBin = log(minBin + 1, base=logBase)
            actualInterval = log(interval, base=logBase)
        }
        histogram = hist(x, breaks=seq(minBin, maxBin + actualInterval, actualInterval), plot=FALSE)
        histNames = getBinItemList(data[[i]], interval=actualInterval)

        nBins = min(length(histogram$breaks), length(histogram$counts))
        counts = histogram$counts[1:nBins]
        if (normalize) {
            counts = counts / nrow(data[[i]])
        }
        breaks = c(histogram$breaks[2:nBins], histogram$breaks[nBins] + actualInterval)
        bins = getValues(
            breaks,
            counts,
            name=histNames)
        series[[i]] = list(name=names[i], data=bins)
    }
   
    chart <- Highcharts$new()
    chart$chart(type="column")
    chart$plotOptions(
        column="{ grouping: false, pointPadding: 0, borderWidth: 0, groupPadding: 0, shadow: false}")
    chart$xAxis(title=paste("{text: '", xLabel, "'}", sep=""),
                plotLines=plotLines)
    yLabel = "frequency"
    if (normalize) {
        yLabel = paste(yLabel, "(normalized)")
    }
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""))
    chart$set(series=series)
    return(chart)
}

# getTimelapseLinePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getTimelapseLinePlot = function(data, names, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    for (i in 1:length(data)){
        timelapseValues = getTimelapseValues(
            as.POSIXlt(strptime(as.character(data[[i]]$date), "%Y-%m-%d", tz=timezone)),
            data[[i]]$x)
        series[[i]] = list(name=names[i], data=timelapseValues)
    }


    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""), gridLineColor="#FFFFFF")
    chart$set(series=series)
    return(chart)
}


# Difference-in-difference plot
diffInDiffPlot <- function(data,
                     idCol,
                     xCol,
                     yLabel="change",
                     periodNames=NULL
                     ) {
    dataChart <- Highcharts$new()
    ids = unique(data[, idCol])
    numPeriod = 0
    for (i in 1:length(ids)) {
        current = data[data[, idCol] == ids[i],]
        numPeriod = nrow(current)
        name = current[1,]$name
        x = seq(0, numPeriod - 1, 1)
        y = current[, xCol]
        z = current[, xCol]
        
        seriesData = getValues(x, y, z, name)
        visible = TRUE
        dataChart$series(name=name,
                         data=seriesData,
                         showInLegend=TRUE,
                         visible=visible)
    }
    if (is.null(periodNames)) {
        periodNames = paste("period", x)
    }
    dataChart$xAxis(categories=periodNames)
    dataChart$yAxis(title=list(text=yLabel), gridLineColor="#FFFFFF")
    dataChart$legend(align="right", verticalAlign="top", layout="vertical")
    dataChart$tooltip(pointFormat=getPointFormat(y=yLabel, z=xCol))
    return (dataChart)
}


                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
#        list12 <- stocklistperiod[period, 2][[1]]
#        for (i in 1:max) {
#            print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
#        }
        for (i in 1:max) {
            id <- list11$id[i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
            }
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), rise, list11$id[[i]]))
        }
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, mynames, topbottom, periodtext, maindate, olddate, days) {
    dev.new()
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(mynames[1]))
        legend(1, g_range[2], mynames, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (type == pricetype) {
        return (df$price)
    }
    if (type == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    normalize <- 0
    if (length(ids) > 0) {
        if (periodtext == "price") {
            normalize <- 1
        }
        if (periodtext == "index") {
            normalize <- 1
        }
    }
    
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, pricetype)
        perioddata[["text"]] <- pairs
        perioddatamap[["price"]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, indextype)
        perioddata[["text"]] <- pairs
        perioddatamap[["index"]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    dayset <- list()
    ls <- list()
    mynames <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        if (normalize == 1) {
                            str("minmax")
                            str(l)
                            mymin <- abs(min(l))
                            mymax <- abs(max(l))
                            if (mymin > mymax) {
                                mymax <- mymin
                            }
                            for (j in 1:length(l)) {
                                l[j] <- l[j] * 100 / mymax;
                            }
                            str(l)
                        }
                        
                        dayset <- append(dayset, bigretl[[2]])
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        mynames[c] <- df$name
                    }
                }
            }
        }
    }
    daynames <- names(dayset)
    olddate <- min(daynames)
    newdate <- max(daynames)
    displaychart(ls, mynames, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
#        list12 <- stocklistperiod[period, 2][[1]]
#        for (i in 1:max) {
#            print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
#        }
        for (i in 1:max) {
            id <- list11$id[i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
            }
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), rise, list11$id[[i]]))
        }
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, mynames, topbottom, periodtext, maindate, olddate, days) {
    dev.new()
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(mynames[1]))
        legend(1, g_range[2], mynames, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (type == pricetype) {
        return (df$price)
    }
    if (type == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    normalize <- 0
    if (length(ids) > 0) {
        if (periodtext == "price") {
            normalize <- 1
        }
        if (periodtext == "index") {
            normalize <- 1
        }
    }
    
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, pricetype)
        perioddata[["text"]] <- pairs
        perioddatamap[["price"]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, indextype)
        perioddata[["text"]] <- pairs
        perioddatamap[["index"]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    ls <- list()
    mynames <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        if (normalize == 1) {
                            str("minmax")
                            str(l)
                            mymin <- abs(min(l))
                            mymax <- abs(max(l))
                            if (mymin > mymax) {
                                mymax <- mymin
                            }
                            for (j in 1:length(l)) {
                                l[j] <- l[j] * 100 / mymax;
                            }
                            str(l)
                        }
                        
                        dayset <- bigretl[[2]]
                        daynames <- names(dayset)
                        olddate <- min(daynames)
                        newdate <- max(daynames)
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        mynames[c] <- df$name
                    }
                }
            }
        }
    }
    displaychart(ls, mynames, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

REBOL [
    System: "REBOL [R3] Language Interpreter and Run-time Environment"
    Title: "REBOL 3 Mezzanine: File Related"
    Rights: {
        Copyright 2012 REBOL Technologies
        REBOL is a trademark of REBOL Technologies
    }
    License: {
        Licensed under the Apache License, Version 2.0
        See: http://www.apache.org/licenses/LICENSE-2.0
    }
]


clean-path: function [
    "Returns new directory path with `//` `.` and `..` processed."
    file [file! url! string!]
    /only
        "Do not prepend current directory"
    /dir
        "Add a trailing / if missing"
][
    case [
        any [only not file? file] [file: copy file]
        #"/" = first file [
            ++ file
            out: next what-dir
            while [
                all [
                    #"/" = first file
                    f: find/tail out #"/"
                ]
            ][
                ++ file
                out: f
            ]
            file: append clear out file
        ]
        true [file: append what-dir file]
    ]

    if all [dir not dir? file] [append file #"/"]

    out: make type-of file length file ; same datatype
    cnt: 0 ; back dir counter

    parse reverse file [
        some [
            ;pp: (?? pp)
            "../" (++ cnt)
            | "./"
            | #"/" (if any [not file? file #"/" <> last out] [append out #"/"])
            | copy f [to #"/" | to end] (
                either cnt > 0 [
                    -- cnt
                ][
                    unless find ["" "." ".."] to string! f [append out f]
                ]
            )
        ]
    ]

    if all [#"/" = last out | #"/" <> last file] [remove back tail out]
    reverse out
]


input: function [
    {Inputs a string from the console. New-line character is removed.}
    return: [string!]
;   /hide
;       "Mask input with a * character"
][
    if any [
        not port? system/ports/input
        not open? system/ports/input
    ][
        system/ports/input: open [scheme: 'console]
    ]

    line: to-string read system/ports/input
    trim/with line newline
    line
]


ask: function [
    "Ask the user for input."
    return: [string!]
    question [any-series!]
        "Prompt to user"
    /hide
        "mask input with *"
][
    prin question
    trim either hide [input/hide] [input]
]


confirm: function [
    "Confirms a user choice."
    return: [logic!]
    question [any-series!]
        "Prompt to user"
    /with
    choices [string! block!]
][
    if all [block? choices | 2 < length choices] [
        cause-error 'script 'invalid-arg mold choices
    ]

    response: ask question

    unless with [choices: [["y" "yes"] ["n" "no"]]]

    case [
        empty? choices [true]
        string? choices [find?/match response choices]
        2 > length choices [find?/match response first choices]
        find? first choices response [true]
        find? second choices response [false]
    ]
]


list-dir: procedure [
    "Print contents of a directory (ls)."
    'path [<end> file! word! path! string!]
        "Accepts %file, :variables, and just words (as dirs)"
    /l "Line of info format"
    /f "Files only"
    /d "Dirs only"
;   /t "Time order"
    /r "Recursive"
    /i "Indent"
        indent
][
    indent: default ""

    save-dir: what-dir

    unless file? save-dir [
        fail ["No directory listing protocol registered for" save-dir]
    ]

    switch type-of :path [
        _ [] ; Stay here
        :file! [change-dir path]
        :string! [change-dir to-rebol-file path]
        :word! :path! [change-dir to-file path]
    ]

    if r [l: true]
    unless l [l: make string! 62] ; approx width    
    
    if not (files: attempt [read %./]) [
        print ["Not found:" :path]
        change-dir save-dir
        leave
    ]
    
    for-each file files [
        if any [
            all [f | dir? file]
            all [d | not dir? file]
        ][continue]

        either string? l [
            append l file
            append/dup l #" " 15 - remainder length l 15
            if greater? length l 60 [print l clear l]
        ][
            info: get query file
            change info second split-path info/1
            printf [indent 16 -8 #" " 24 #" " 6] info
            if all [r | dir? file] [
                list-dir/l/r/i :file join indent "    "
            ]
        ]
    ]
    
    if all [string? l | not empty? l] [print l]
    
    change-dir save-dir
]


undirize: function [
    {Returns a copy of the path with any trailing "/" removed.}
    return: [file! string! url!]
    path [file! string! url!]
][
    path: copy path
    if #"/" = last path [clear back tail path]
    path
]


in-dir: function [
    "Evaluate a block while in a directory."
    return: [<opt> any-value!]
    dir [file!]
        "Directory to change to (changed back after)"
    block [block!]
        "Block to evaluate"
][
    old-dir: what-dir
    change-dir dir

    ; You don't want the block to be done if the change-dir fails, for safety.

    also do block change-dir old-dir
]


to-relative-file: function [
    "Returns relative portion of a file if in subdirectory, original if not."
    return: [file! string!]
    file [file! string!]
        "File to check (local if string!)"
    /no-copy
        "Don't copy, just reference"
    /as-rebol
        "Convert to REBOL-style filename if not"
    /as-local
        "Convert to local-style filename if not"
][
    either string? file [ ; Local file
        ; Note: to-local-file drops trailing / in R2, not in R3
        ; if tmp: find/match file to-local-file what-dir [file: next tmp]
        file: any [find/match file to-local-file what-dir | file]
        if as-rebol [
            file: to-rebol-file file
            no-copy: true
        ]
    ][
        file: any [find/match file what-dir | file]
        if as-local [
            file: to-local-file file
            no-copy: true
        ]
    ]

    unless no-copy [file: copy file]
    
    file
]
#' Calibrate oli images to TM images
#'
#' Calibrate oli images to TM images using linear regression
#' @param oliwrs2dir character. oli WRS-2 scene directory path
#' @param tmwrs2dir character. TM WRS-2 scene directory path
#' @import raster
#' @import MASS
#' @export


olical_single = function(oli_file, tm_file, overwrite=F){
  
  get_intersection = function(files){
    int = intersect(extent(raster(files[1])),extent(raster(files[2])))
    if(length(files) >= 3){for(i in 3:length(files))int = intersect(extent(raster(files[i])), int)}
    return(int)
  }
  
  predict_oli_index = function(tbl, outsampfile){  
    
    #create a multivariable linear model
    model = rlm(refsamp ~ b2samp + b3samp + b4samp + b5samp + b6samp + b7samp, data=tbl) #
    
    tbl$singlepred = round(predict(model))
    write.csv(tbl, outsampfile, row.names=F)
    
    #plot the regression
    r = cor(tbl$refsamp, tbl$singlepred)
    coef = rlm(tbl$refsamp ~ tbl$singlepred)
    
    pngout = sub("samp.csv", "plot.png",outsampfile)
    png(pngout,width=700, height=700)
    title = paste(tbl$index[1],"linear regression: slope =",paste(signif(coef$coefficients[2], digits=3),",",sep=""),
                  "y Intercept =",paste(round(coef$coefficients[1], digits=3),",",sep=""),
                  "r =",signif(r, digits=3))
    plot(x=tbl$singlepred,y=tbl$refsamp,
         main=title,
         xlab=paste(tbl$oli_img[1],tbl$index[1]),
         ylab=paste(tbl$ref_img[1],tbl$index[1]))
    abline(coef = coef$coefficients, col="red")  
    dev.off()
    
    #return the information
    coef_tbl = data.frame(rbind(model$coefficients))
    cnames = c("yint","b2c","b3c","b4c","b5c","b6c","b7c")
    colnames(coef_tbl) = cnames
    tbls = list(coef_tbl,tbl)
    return(tbls)
  }

  #define the filenames
  oli_sr_file = oli_file
  oli_mask_file = sub("l8sr.tif", "cloudmask.tif", oli_sr_file)
  ref_tc_file = tm_file
  ref_tca_file = sub("tc", "tca", ref_tc_file)
  ref_mask_file = sub("tc", "cloudmask", ref_tc_file)
  
  #make new directory
  dname = dirname(oli_sr_file)
  oliimgid = substr(basename(oli_sr_file),1,16)
  outdir = file.path(substr(dname,1,nchar(dname)-12),"calibration", oliimgid)  #-5
  dir.create(outdir, showWarnings = F, recursive=T)
  
  #check to see if single cal has already been run
  files = list.files(outdir)
  thesefiles = c("tca_cal_plot.png","tcb_cal_plot.png","tcg_cal_plot.png","tcw_cal_plot.png",
                 "tca_cal_samp.csv","tcb_cal_samp.csv","tcg_cal_samp.csv","tcw_cal_samp.csv")
  results = rep(NA,length(thesefiles))
  for(i in 1:length(results)){
    test = grep(thesefiles[i], files)
    results[i] = length(test) > 0
  }
  if(all(results) == T & overwrite == F){return(0)}
  
  
  #load files as raster
  oli_sr_img = brick(oli_sr_file)
  oli_mask_img = raster(oli_mask_file)
  ref_tc_img = brick(ref_tc_file)
  ref_tca_img  = raster(ref_tca_file)
  ref_mask_img = raster(ref_mask_file)
  
  #align the extents
  extent(oli_sr_img)  = alignExtent(oli_sr_img, ref_tc_img, snap="near")
  extent(oli_mask_img) = alignExtent(oli_mask_img, ref_tc_img, snap="near")
  extent(ref_tc_img)   = alignExtent(ref_tc_img, ref_tc_img, snap="near")
  extent(ref_tca_img)  = alignExtent(ref_tca_img, ref_tc_img, snap="near")
  extent(ref_mask_img) = alignExtent(ref_mask_img, ref_tc_img, snap="near")
  
  #crop the images to their intersection
  int = get_intersection(c(oli_mask_file,ref_mask_file))
  oli_b5_img = crop(subset(oli_sr_img,5),int)
  ref_tca_img = crop(ref_tca_img,int)
  oli_mask_img = crop(oli_mask_img,int)
  ref_mask_img = crop(ref_mask_img,int)
  
  #make a composite mask

  oli_mask_v = as.vector(oli_mask_img)
  ref_mask_v = as.vector(ref_mask_img)

  mask = oli_mask_v*ref_mask_v #make composite mask
  oli_mask_v = ref_mask_v = 0 # save memory
  
  #load oli and etm+ bands
  oli_b5_v = as.vector(oli_b5_img)
  ref_tca_v = as.vector(ref_tca_img)
  
  dif = oli_b5_v - ref_tca_v #find the difference
  oli_b5_v = ref_tca_v = 0 #save memory
  nas = which(mask == 0) #find the bads in the mask
  dif[nas] = NA #set the bads in the dif to NA so they are not included in the calc of mean and stdev
  stdv = sd(dif, na.rm=T) #get stdev of difference
  center = mean(dif, na.rm=T) #get the mean difference
  dif = dif < (center+stdv*2) & dif > (center-stdv*2) #find the pixels that are not that different
    
  
  goods = which(dif == 1)
  if(length(goods) < 20000){return(0)}
  
  #random sample
  samp = sample(1:length(goods), 20000)
  samp = goods[samp]
  sampxy = xyFromCell(oli_mask_img, samp)
  
  #save memory
  mask = 0
  
  #extract the sample pixels from the bands
  olisamp = extract(subset(oli_sr_img, 2:7), sampxy)
  tcsamp = extract(ref_tc_img, sampxy)
  tcasamp = extract(ref_tca_img, sampxy)
  
  #make sure the values are good for running regression on (diversity)
  unib2samp = length(unique(olisamp[,1]))
  unib3samp = length(unique(olisamp[,2]))
  unib4samp = length(unique(olisamp[,3]))
  unib5samp = length(unique(olisamp[,4]))
  unib6samp = length(unique(olisamp[,5]))
  unib7samp = length(unique(olisamp[,6]))
  
  unitcbsamp = length(unique(tcsamp[,1]))
  unitcgsamp = length(unique(tcsamp[,2]))
  unitcwsamp = length(unique(tcsamp[,3]))
  unitcasamp = length(unique(tcasamp))
  
  
  if(unib2samp < 15 | unib3samp < 15 | unib4samp < 15 | unib5samp < 15 | unib6samp < 15 | 
     unib7samp < 15 | unitcbsamp < 15 | unitcgsamp < 15 | unitcwsamp < 15 | unitcasamp < 15){return()}
  
  olibname = basename(oli_sr_file)
  refbname = basename(ref_tc_file)
  refabname = basename(ref_tca_file)
  
  tcb_tbl = data.frame(olibname,refbname,"tcb",sampxy,tcsamp[,1],olisamp)
  tcg_tbl = data.frame(olibname,refbname,"tcg",sampxy,tcsamp[,2],olisamp)
  tcw_tbl = data.frame(olibname,refbname,"tcw",sampxy,tcsamp[,3],olisamp)
  tca_tbl = data.frame(olibname,refabname,"tca",sampxy,tcasamp,olisamp)
  
  tcb_tbl = tcb_tbl[complete.cases(tcb_tbl),]
  tcg_tbl = tcg_tbl[complete.cases(tcg_tbl),]
  tcw_tbl = tcw_tbl[complete.cases(tcw_tbl),]
  tca_tbl = tca_tbl[complete.cases(tca_tbl),]
  
  cnames = c("oli_img","ref_img","index","x","y","refsamp","b2samp","b3samp","b4samp","b5samp","b6samp","b7samp") 
  colnames(tcb_tbl) = cnames
  colnames(tcg_tbl) = cnames
  colnames(tcw_tbl) = cnames
  colnames(tca_tbl) = cnames
  
  #predict the indices
  #TCB
  outsampfile = file.path(outdir,paste(oliimgid,"_tcb_cal_samp.csv",sep=""))
  model = predict_oli_index(tcb_tbl, outsampfile)
  bcoef = model[[1]]
  bsamp = model[[2]]
  br = cor(bsamp$refsamp, bsamp$singlepred)
  
  #TCG
  outsampfile = file.path(outdir,paste(oliimgid,"_tcg_cal_samp.csv",sep=""))
  model = predict_oli_index(tcg_tbl, outsampfile)
  gcoef = model[[1]]
  gsamp = model[[2]]
  gr = cor(gsamp$refsamp, gsamp$singlepred)
  
  #TCW
  outsampfile = file.path(outdir,paste(oliimgid,"_tcw_cal_samp.csv",sep=""))
  model = predict_oli_index(tcw_tbl, outsampfile)
  wcoef = model[[1]]
  wsamp = model[[2]]
  wr = cor(wsamp$refsamp, wsamp$singlepred)
  
  #TCA
  outsampfile = file.path(outdir,paste(oliimgid,"_tca_cal_samp.csv",sep=""))
  model = predict_oli_index(tca_tbl, outsampfile)
  acoef = model[[1]]
  asamp = model[[2]]
  ar = cor(asamp$refsamp, asamp$singlepred)
  
  #write out the coef files
  tcbinfo = data.frame(oli_file=olibname, ref_file=refbname, index="tcb", bcoef, r=br)
  tcginfo = data.frame(oli_file=olibname, ref_file=refbname, index="tcg", gcoef, r=gr)
  tcwinfo = data.frame(oli_file=olibname, ref_file=refbname, index="tcw", wcoef, r=wr)
  tcainfo = data.frame(oli_file=olibname, ref_file=refabname, index="tca", acoef, r=ar)
  
  tcbcoefoutfile = file.path(outdir,paste(oliimgid,"_tcb_cal_coef.csv",sep=""))
  tcgcoefoutfile = file.path(outdir,paste(oliimgid,"_tcg_cal_coef.csv",sep=""))
  tcwcoefoutfile = file.path(outdir,paste(oliimgid,"_tcw_cal_coef.csv",sep=""))
  tcacoefoutfile = file.path(outdir,paste(oliimgid,"_tca_cal_coef.csv",sep=""))
  
  write.csv(tcbinfo, tcbcoefoutfile, row.names=F)
  write.csv(tcginfo, tcgcoefoutfile, row.names=F)
  write.csv(tcwinfo, tcwcoefoutfile, row.names=F)
  write.csv(tcainfo, tcacoefoutfile, row.names=F)
}
#' Calibrate OLI images to TM images
#'
#' Calibrate OLI images to TM images using linear regression
#' @param oliwrs2dir character. oli WRS-2 scene directory path
#' @param tmwrs2dir character. TM WRS-2 scene directory path
#' @param cores numeric. Number of cores to process with options: 1 or 2
#' @export


olical = function(oliwrs2dir, tmwrs2dir, cores=2, overwrite=overwrite){  
  
  olifiles = list.files(oliwrs2dir, "l8sr.tif", recursive=T, full.names=T)
  tmfiles = list.files(tmwrs2dir, "tc.tif", recursive=T, full.names=T)
  
  #pull out oli and tm year
  olibase = basename(olifiles)
  oliyears = substr(olibase, 10, 13)
  tmbase = basename(tmfiles)   
  tmyears = substr(tmbase, 10, 13)
  tmyearday = as.numeric(substr(tmbase, 10, 16))
  
  #get overlapping oli/etm+ years
  oliuni = unique(oliyears)
  notintm = oliuni %in% tmyears
  if(sum(notintm) < 2){stop("There is not at least one year of overlapping images between OLI and ETM+ to calibrate on")}
  theseoli = which(oliyears %in% tmyears == T)
  olifilessub = olifiles[theseoli]
  olibase = olibase[theseoli]
  oliyears = oliyears[theseoli]
  oliyearday = as.numeric(substr(olibase, 10, 16))
  
  match = data.frame(oli=olifilessub, etm=NA, stringsAsFactors=FALSE)
  for(i in 1:length(olifilessub)){
    closest = order(abs(oliyearday[i]-tmyearday))[1]
    match$etm[i] = tmfiles[closest]
  }
  
  #do single pair modeling
  print("...single image pair modeling")
  if(cores==2){
    cl = makeCluster(cores)
    registerDoParallel(cl)
    cfun <- function(a, b) NULL
    o = foreach(i=1:length(olifilessub), .combine="cfun",.packages="LandsatLinkr") %dopar% olical_single(match$oli[i], match$etm[i], overwrite=overwrite) #
    stopCluster(cl)
  } else {for(i in 1:length(olifilessub)){olical_single(match$oli[i], match$etm[i], overwrite=overwrite)}}
  
  #do aggregated modeling
  caldir = file.path(oliwrs2dir,"calibration")
  print("...aggregate image pair modeling")
  cal_oli_tc_aggregate_model(caldir,overwrite=overwrite)
  
  #predict tc and tca from aggregate model
  calagdir = file.path(caldir,"aggregate_model")
  bcoef = as.numeric(read.csv(file.path(calagdir,"tcb_cal_aggregate_coef.csv"))[1,3:8])
  gcoef = as.numeric(read.csv(file.path(calagdir,"tcg_cal_aggregate_coef.csv"))[1,3:8])
  wcoef = as.numeric(read.csv(file.path(calagdir,"tcw_cal_aggregate_coef.csv"))[1,3:8])
  
  print("...applying model to all oli images")
  for(i in 1:length(olifiles)){olisr2tc(olifiles[i],bcoef,gcoef,wcoef,"apply",overwrite=overwrite)}
}
#' Calibrate OLI images to TM images
#'
#' Calibrate OLI images to TM images using linear regression
#' @param oliwrs2dir character. oli WRS-2 scene directory path
#' @param tmwrs2dir character. TM WRS-2 scene directory path
#' @param cores numeric. Number of cores to process with options: 1 or 2
#' @export


olical = function(oliwrs2dir, tmwrs2dir, cores=2, overwrite=overwrite){  
  
  olifiles = list.files(oliwrs2dir, "l8sr.tif", recursive=T, full.names=T)
  tmfiles = list.files(tmwrs2dir, "tc.tif", recursive=T, full.names=T)
  
  #pull out oli and tm year
  olibase = basename(olifiles)
  oliyears = substr(olibase, 10, 13)
  tmbase = basename(tmfiles)   
  tmyears = substr(tmbase, 10, 13)
  tmyearday = as.numeric(substr(tmbase, 10, 16))
  
  #get overlapping oli/etm+ years
  oliuni = unique(oliyears)
  notintm = oliuni %in% tmyears
  if(sum(notintm) < 2){stop("There is not at least one year of overlapping images between OLI and ETM+ to calibrate on")}
  theseoli = which(oliyears %in% tmyears == T)
  olifilessub = olifiles[theseoli]
  olibase = olibase[theseoli]
  oliyears = oliyears[theseoli]
  oliyearday = as.numeric(substr(olibase, 10, 16))
  
  len = length(olifilessub)
  match = data.frame(oli=olifilessub, etm=NA, stringsAsFactors=FALSE)
  for(i in 1:len){
    closest = order(abs(oliyearday[i]-tmyearday))[1]
    match$etm[i] = tmfiles[closest]
  }
  
  #do single pair modeling
  print("...single image pair modeling")
  if(cores==2){
    cl = makeCluster(cores)
    registerDoParallel(cl)
    cfun <- function(a, b) NULL
    o = foreach(i=1:len, .combine="cfun",.packages="LandsatLinkr") %dopar% olical_single(match$oli[i], match$etm[i], overwrite=overwrite) #
    stopCluster(cl)
  } else {for(i in 1:len){olical_single(match$oli[i], match$etm[i], overwrite=overwrite)}}
  
  #do aggregated modeling
  caldir = file.path(oliwrs2dir,"calibration")
  print("...aggregate image pair modeling")
  cal_oli_tc_aggregate_model(caldir,overwrite=overwrite)
  
  #predict tc and tca from aggregate model
  calagdir = file.path(caldir,"aggregate_model")
  bcoef = as.numeric(read.csv(file.path(calagdir,"tcb_cal_aggregate_coef.csv"))[1,3:8])
  gcoef = as.numeric(read.csv(file.path(calagdir,"tcg_cal_aggregate_coef.csv"))[1,3:8])
  wcoef = as.numeric(read.csv(file.path(calagdir,"tcw_cal_aggregate_coef.csv"))[1,3:8])
  
  print("...applying model to all oli images")
  for(i in 1:len){olisr2tc(olifiles[i],bcoef,gcoef,wcoef,"apply",overwrite=overwrite)}
}
#' Calibrate MSS images to TM images
#'
#' Calibrate MSS images to TM images using linear regression
#' @param msswrs2dir character. MSS WRS-2 scene directory path
#' @param tmwrs2dir character. TM WRS-2 scene directory path
#' @import raster
#' @import MASS
#' @export


msscal_single = function(mss_file, tm_file){
  
  get_intersection = function(files){
    int = intersect(extent(raster(files[1])),extent(raster(files[2])))
    if(length(files) >= 3){for(i in 3:length(files))int = intersect(extent(raster(files[i])), int)}
    return(int)
  }
  
  predict_mss_index = function(tbl, outsampfile){  
    #create a multivariable linear model
    model = rlm(refsamp ~ b1samp + b2samp + b3samp + b4samp, data=tbl) #tbl replaced final 1/22/2016
    
    tbl$singlepred = round(predict(model))
    write.csv(tbl, outsampfile, row.names=F)
    
    #plot the regression
    r = cor(tbl$refsamp, tbl$singlepred)
    coef = rlm(tbl$refsamp ~ tbl$singlepred)
    
    pngout = sub("samp.csv", "plot.png",outsampfile)
    png(pngout,width=700, height=700)
    title = paste(tbl$index[1],"linear regression: slope =",paste(signif(coef$coefficients[2], digits=3),",",sep=""),
                  "y Intercept =",paste(round(coef$coefficients[1], digits=3),",",sep=""),
                  "r =",signif(r, digits=3))
    plot(x=tbl$singlepred,y=tbl$refsamp, #tbl replaced final 1/22/2016
         main=title,
         xlab=paste(tbl$mss_img[1],tbl$index[1]),
         ylab=paste(tbl$ref_img[1],tbl$index[1]))   
    abline(coef = coef$coefficients, col="red")  
    dev.off()
    
    coef_tbl = data.frame(rbind(model$coefficients))
    cnames = c("yint","b1c","b2c","b3c","b4c")
    colnames(coef_tbl) = cnames
    tbls = list(coef_tbl,tbl)
    return(tbls)
  }
  
  #define the filenames
  mss_sr_file = mss_file
  mss_mask_file = sub("dos_sr_30m.tif", "cloudmask_30m.tif", mss_sr_file)
  ref_tc_file = tm_file
  ref_tca_file = sub("tc", "tca", ref_tc_file)
  ref_mask_file = sub("tc", "cloudmask", ref_tc_file)
  
  #make new directory
  dname = dirname(mss_sr_file)
  mssimgid = substr(basename(mss_sr_file),1,16)
  outdir = file.path(substr(dname,1,nchar(dname)-12),"calibration", mssimgid)  #-5
  dir.create(outdir, showWarnings = F, recursive=T)
  
  #load files as raster
  mss_sr_img = brick(mss_sr_file)
  mss_mask_img = raster(mss_mask_file)
  ref_tc_img = brick(ref_tc_file)
  ref_tca_img  = raster(ref_tca_file)
  ref_mask_img = raster(ref_mask_file)
  
  #align the extents
  extent(mss_sr_img)  = alignExtent(mss_sr_img, ref_tc_img, snap="near")
  extent(mss_mask_img) = alignExtent(mss_mask_img, ref_tc_img, snap="near")
  extent(ref_tc_img)   = alignExtent(ref_tc_img, ref_tc_img, snap="near")
  extent(ref_tca_img)  = alignExtent(ref_tca_img, ref_tc_img, snap="near")
  extent(ref_mask_img) = alignExtent(ref_mask_img, ref_tc_img, snap="near")
  
  #crop the images to their intersection
  int = get_intersection(c(mss_sr_file,mss_mask_file,ref_tc_file,ref_tca_file,ref_mask_file))
  mss_sr_img = crop(mss_sr_img,int)
  mss_mask_img = crop(mss_mask_img,int)
  ref_tc_img = crop(ref_tc_img,int)
  ref_tca_img = crop(ref_tca_img,int)
  ref_mask_img = crop(ref_mask_img,int)
  
  #make a composite mask
  mss_mask_v = as.vector(mss_mask_img)
  ref_mask_v = as.vector(ref_mask_img)
  mask = mss_mask_v*ref_mask_v
  mss_mask_v = ref_mask_v = 0 # save memory
  
  goods = which(mask == 1)
  if(length(goods) < 20000){return()}
  
  #random sample
  samp = sample(1:length(goods), 20000)
  samp = goods[samp]
  sampxy = xyFromCell(mss_mask_img, samp) #added on 1/22/2016
  
  #save memory
  mask = 0
  
  msssamp = extract(mss_sr_img, sampxy)
  tcsamp = extract(ref_tc_img, sampxy)
  tcasamp = extract(ref_tca_img, sampxy)
  
  #make sure the values are good for running regression on (diversity)
  unib1samp = length(unique(msssamp[,1]))
  unib2samp = length(unique(msssamp[,2]))
  unib3samp = length(unique(msssamp[,3]))
  unib4samp = length(unique(msssamp[,4]))
  
  unitcbsamp = length(unique(tcsamp[,1]))
  unitcgsamp = length(unique(tcsamp[,2]))
  unitcwsamp = length(unique(tcsamp[,3]))
  unitcasamp = length(unique(tcasamp))
  
  
  #if(unib1samp < 15 | unib2samp < 15 | unib3samp < 15 | unib4samp < 15 ){return()}
  if(unib1samp < 15 | unib2samp < 15 | unib3samp < 15 | unib4samp < 15 |
     unitcbsamp < 15 | unitcgsamp < 15 | unitcwsamp < 15 | unitcasamp < 15){return()}
  
  mssbname = basename(mss_sr_file)
  refbname = basename(ref_tc_file)
  refabname = basename(ref_tca_file)
  
  tcb_tbl = data.frame(mssbname,refbname,"tcb",sampxy,tcsamp[,1],msssamp)
  tcg_tbl = data.frame(mssbname,refbname,"tcg",sampxy,tcsamp[,2],msssamp)
  tcw_tbl = data.frame(mssbname,refbname,"tcw",sampxy,tcsamp[,3],msssamp)
  tca_tbl = data.frame(mssbname,refabname,"tca",sampxy,tcasamp,msssamp)
  
  tcb_tbl = tcb_tbl[complete.cases(tcb_tbl),]
  tcg_tbl = tcg_tbl[complete.cases(tcg_tbl),]
  tcw_tbl = tcw_tbl[complete.cases(tcw_tbl),]
  tca_tbl = tca_tbl[complete.cases(tca_tbl),]
  
  cnames = c("mss_img","ref_img","index","x","y","refsamp","b1samp","b2samp","b3samp","b4samp") 
  colnames(tcb_tbl) = cnames
  colnames(tcg_tbl) = cnames
  colnames(tcw_tbl) = cnames
  colnames(tca_tbl) = cnames
  
  outsampfile = file.path(outdir,paste(mssimgid,"_tcb_cal_samp.csv",sep=""))
  model = predict_mss_index(tcb_tbl, outsampfile)
  bcoef = model[[1]]
  bsamp = model[[2]]
  br = cor(bsamp$refsamp, bsamp$singlepred)
  
  outsampfile = file.path(outdir,paste(mssimgid,"_tcg_cal_samp.csv",sep=""))
  model = predict_mss_index(tcg_tbl, outsampfile)
  gcoef = model[[1]]
  gsamp = model[[2]]
  gr = cor(gsamp$refsamp, gsamp$singlepred)
  
  outsampfile = file.path(outdir,paste(mssimgid,"_tcw_cal_samp.csv",sep=""))
  model = predict_mss_index(tcw_tbl, outsampfile)
  wcoef = model[[1]]
  wsamp = model[[2]]
  wr = cor(wsamp$refsamp, wsamp$singlepred)
  
  #TCA
  outsampfile = file.path(outdir,paste(mssimgid,"_tca_cal_samp.csv",sep=""))
  model = predict_mss_index(tca_tbl, outsampfile)
  acoef = model[[1]]
  asamp = model[[2]]
  ar = cor(asamp$refsamp, asamp$singlepred)
  
  tcbinfo = data.frame(mss_file=mssbname, ref_file=refbname, index="tcb", bcoef, r=br)
  tcginfo = data.frame(mss_file=mssbname, ref_file=refbname, index="tcg", gcoef, r=gr)
  tcwinfo = data.frame(mss_file=mssbname, ref_file=refbname, index="tcw", wcoef, r=wr)
  tcainfo = data.frame(mss_file=mssbname, ref_file=refabname, index="tca", acoef, r=ar)
  
  tcbcoefoutfile = file.path(outdir,paste(mssimgid,"_tcb_cal_coef.csv",sep=""))
  tcgcoefoutfile = file.path(outdir,paste(mssimgid,"_tcg_cal_coef.csv",sep=""))
  tcwcoefoutfile = file.path(outdir,paste(mssimgid,"_tcw_cal_coef.csv",sep=""))
  tcacoefoutfile = file.path(outdir,paste(mssimgid,"_tca_cal_coef.csv",sep=""))
  
  write.csv(tcbinfo, tcbcoefoutfile, row.names=F)
  write.csv(tcginfo, tcgcoefoutfile, row.names=F)
  write.csv(tcwinfo, tcwcoefoutfile, row.names=F)
  write.csv(tcainfo, tcacoefoutfile, row.names=F)
}
#' Composite images 
#'
#' Composite images
#' @param msswrs1dir character. list of mss wrs1 directory paths
#' @param msswrs2dir character. list of mss wrs2 directory paths
#' @param tmwrs2dir character. list of tm wrs2 directory path
#' @param index character. spectral index to make composites for. options: "tca", "tcb", "tcg", "tcw"
#' @param outdir character. path to output directory
#' @param runname character. unique name for the composite set
#' @param useareafile character. path to usearea file
#' @param doyears ??? what years to composite
#' @param order character. how to order the images options "sensor_and_doy" and "doy"
#' @param overlap character. how to deal with overlapping images. options: "mean"
#' @import raster
#' @import gdalUtils
#' @import plyr
#' @export


mixel = function(msswrs1dir,msswrs2dir,tmwrs2dir,oliwrs2dir,index,outdir,runname,useareafile,doyears="all",order="none",overlap="mean",startday,endday,yearadj=0){
  
  mixel_find = function(files, refimg){
    info = matrix(ncol = 4, nrow=length(files))
    print("Getting image extents")
    for(i in 1:length(files)){ 
      print(i)
      img = raster(files[i])
      ext = extent(img)
      info[i,1] = ext@xmin
      info[i,2] = ext@xmax
      info[i,3] = ext@ymin
      info[i,4] = ext@ymax
    }
    
    text = extent(raster(refimg))  
    these = which(info[,3] < text@ymax & info[,4] > text@ymin & info[,2] > text@xmin & info[,1] < text@xmax) 
    goods = files[these]
    return(goods)
  }
  
  mixel_mask = function(imgfile, useareafile, index){ #search,
    print(paste("...cloud masking:",basename(imgfile)))
    if(index == "tca" | index == "tcb"){band=1}
    if(index == "tcg"){band=2}
    if(index == "tcw"){band=3}
    
    sensor = substr(basename(imgfile), 1,2)
    if(sensor == "LM"){maskbit = "_cloudmask_30m.tif"} else {maskbit = "_cloudmask.tif"}
    
    maskfile = file.path(dirname(imgfile), paste(substr(basename(imgfile),1,16),maskbit,sep=""))
    img = raster(imgfile, band=band)
    mask = raster(maskfile)
    NAvalue(mask) = 0 #make 0 in the mask
    refimg = raster(useareafile)
    
    imgex = alignExtent(img, refimg, snap="near")
    maskex = alignExtent(mask, refimg, snap="near")
    extent(img) = imgex
    extent(mask) = maskex
    
    overlap = intersect(img, mask)
    mask = crop(mask, overlap)
    img = crop(img, overlap)
    
    img = img*mask
    return(img)
  }
  
  change_envi_to_bsq = function(file){
    envifilename = sub("bsq","envi",file)
    envixmlfile = paste(envifilename,".aux.xml",sep="")
    bsqxmlfile = sub("envi","bsq",envixmlfile)
    file.rename(envifilename,file)
    file.rename(envixmlfile,bsqxmlfile)
  }
  
  mixel_composite = function(outdir, imginfosub, runname, index, order, useareafile, overlap, yearadj){

    #outdir= mssdir 
    #imginfosub = mssdf

    uniyears = sort(unique(imginfosub$compyear))
    
    #for all the unique year make a composite
    for(i in 1:length(uniyears)){
      print(paste("working on year:", uniyears[i]))
      these = which(imginfosub$compyear == uniyears[i])
      theseimgs = imginfosub$file[these]

      if(order == "none"){theseimgs = theseimgs}

      len = length(theseimgs)
      #mask all the images in a year
      for(m in 1:len){
        mergeit = ifelse(m == 1, "r1", paste(mergeit,",r",m, sep=""))
        dothis = paste("r",m,"=mixel_mask(theseimgs[",m,"], useareafile, index)", sep="") 
        eval(parse(text=dothis))
      }
      
      #select a mosaic method
      if(overlap == "order"){mergeit = paste("newimg = merge(",mergeit,")", sep="")} else
      if(overlap == "mean"){mergeit = paste("newimg = mosaic(",mergeit,",fun=mean,na.rm=T)", sep="")} else
      if(overlap == "median"){mergeit = paste("newimg = mosaic(",mergeit,",fun=median,na.rm=T)", sep="")} else
      if(overlap == "max"){mergeit = paste("newimg = mosaic(",mergeit,",fun=max,na.rm=T)", sep="")} else
      if(overlap == "min"){mergeit = paste("newimg = mosaic(",mergeit,",fun=min,na.rm=T)", sep="")}
      
      #run the merge function
      print(paste("...merging files using ", overlap, ":",sep=""))
      for(h in 1:len){print(paste("......",basename(theseimgs[h]),sep=""))}
      if(len == 1){newimg = r1} else {eval(parse(text=mergeit))} #only run merge it if there are multiple files to merge
      
      #name the new file
      yearlabel = as.character(as.numeric(uniyears[i])+yearadj)
      newbase = paste(yearlabel,"_",runname,"_",index,"_composite.bsq", sep="")
      outimgfile = file.path(outdir,newbase)
      outtxtfile = sub("composite.bsq", "composite_img_list.csv", outimgfile)
      theseimgs = data.frame(theseimgs)
      colnames(theseimgs) = "File"
      write.csv(theseimgs, file=outtxtfile, row.names = F)
      
      #load in the usearea file and crop/extend the new image to it
      refimg = raster(useareafile)
      newimg = round(crop(newimg, refimg))
      newimg = extend(newimg, refimg, value=NA)

      #set NA values to 0 for use
      refimg = refimg != 0 # set all values not equal to 0 to 1 and 0 to 0 - NA can still be in there, it will be set to 0 in the final img
      refimg = refimg * newimg #set all 0's in the usearea file to 0 in the img file - if NA are in the usearea file, they will be transfered to img and then set to 0 in the final img
      newimg[is.na(newimg)] = 0 #set all NA to 0

      #write out the new image
      projection(newimg) = set_projection(files[1])
      writeRaster(newimg, outimgfile, format="ENVI", datatype = "INT2S",overwrite=T)
      change_envi_to_bsq(outimgfile)
    
      #clean the temp directory      
      delete_temp_files()
    }
  }
  
  delete_temp_files = function(){
    tempdir = dirname(rasterTmpFile())
    tempfiles = list.files(tempdir,full.names=T)
    unlink(tempfiles)
  }
  
  find_files = function(dir, search){
    if(length(which(is.na(dir) == T)) > 0){return(vector())} else{
      imgdir = normalizePath(file.path(dir,"images"),winslash="/")
      files = vector()
      for(i in 1:length(imgdir)){
        print(paste("finding files in: ",imgdir))
        files = c(files,list.files(imgdir[i], search, recursive=T, full.names=T))
      }
      if(length(files)==0){stop(
          paste("There were no tasselled cap files found in this directory: ",imgdir[i],".
          Make sure that you provided the correct scene head directory path and that all processing
          steps up to compositing have been completed. MSS directories should contain
          files with the extension 'tc_30m.tif' and 'tca_30m.tif', and TM/ETM+ and OLI 'tc.tif' and 'tca.tif'.
          A valid scene head directory path should look like this mock example: 'C:/mock/landsat/wrs2/045030'.
          The program will then append 'images' to the path and search recursively in that directory. If
          you wish to continue without this directory, re-run the compositing call and don't add this directory.",sep="")
        )
      } else{
        return(files)
      }
    }
  }
  
  combine_overlapping_senors = function(ref_files, dep_files){
    thesetm = which(basename(ref_files) %in% basename(dep_files))
    ref_files_sort = sort(ref_files[thesetm])
    thesemss = which(basename(dep_files) %in% basename(ref_files))
    dep_files_sort = sort(dep_files[thesemss])
    len = length(dep_files_sort)
    if(len > 0){
      for(i in 1:len){
        print(paste("...",i,"/",len,sep=""))
        depimg= raster(dep_files_sort[i])
        refimg= raster(ref_files_sort[i])
        NAvalue(depimg) = 0
        NAvalue(refimg) = 0
        newimg = mosaic(depimg,refimg, fun="mean", na.rm=T)
        newimg[is.na(newimg)] = 0
        projection(newimg) = set_projection(files[1])
        
        outimgfile = file.path(outdir,basename(dep_files_sort[i]))
        writeRaster(newimg, outimgfile, format="ENVI", datatype = "INT2S",overwrite=T)
        change_envi_to_bsq(outimgfile)
        
        delete_temp_files()
      }
    }
  }
  
  
  pixel_level_offset = function(ref_files, dep_files, outdir, sensor, projfile, runname){
    
    #find overlapping years
    theseref = which(basename(ref_files) %in% basename(dep_files))
    thesedep = which(basename(dep_files) %in% basename(ref_files))
    lendep = length(thesedep)
    lenref = length(theseref)
    if(lenref == 0 | lendep == 0 | lenref != lendep){return()} # get out if there are no matching files - no overlap
    
    print(paste("calculating pixel-level offset for: ",sensor," composites",sep=""))
    
    #sort the files to make sure they are in the same order
    ref_files_sort = sort(ref_files[theseref])
    dep_files_sort = sort(dep_files[thesedep])
    
    #find the mean pixel-wise difference between dependent and reference images
    for(i in 1:lendep){
      print(paste("...",basename(dep_files_sort[i]),sep=""))
      refimg = raster(ref_files_sort[i])
      depimg = raster(dep_files_sort[i])
      NAvalue(refimg) = 0
      NAvalue(depimg) = 0
      
      dif = refimg - depimg #get the difference 
      denom = !is.na(dif) #get the cells that are not NA after difference
      dif[is.na(dif)] = 0 #set the difference NA values to 0
      
      #make the sum difference and denominator layers
      if(i == 1){ #if i is one then start the layers
        difsum = dif
        denomsum = denom
      } else{ #else sum the layers
        difsum = sum(difsum, dif, na.rm=T)
        denomsum = sum(denomsum, denom, na.rm=T)
      }
    }
    print("...calculating mean pixel-level offset")
    meandiforig = round(difsum/denomsum) #mean the mean for the time series
    meandiforig[is.na(meandiforig)] = 0 #make division by 0 set to 0 instead of NA - there will be no correction for these pixels

    #figure out parts of file names
    if(sensor == "mss"){offsetdir = file.path(outdir,"mss_offset");deprunname="lm"; refrunname="lt"; meandiffilebname = "mss_mean_dif.bsq"}
    if(sensor == "oli"){offsetdir = file.path(outdir,"oli_offset");deprunname="lc"; refrunname="le"; meandiffilebname = "oli_mean_dif.bsq"}
    
    #write out the mean pixel-wise difference file
    dir.create(offsetdir, recursive=T, showWarnings=F)
    projection(meandiforig) = set_projection(projfile)
    meandiffile = file.path(offsetdir,meandiffilebname)
    writeRaster(meandiforig, meandiffile, format="ENVI", datatype = "INT2S",overwrite=T)
    change_envi_to_bsq(meandiffile)
    
    #write out the frequency file
    projection(denomsum) = set_projection(projfile)
    denomsumfile = file.path(dirname(meandiffile),"overlap_frequency.bsq")
    writeRaster(denomsum, denomsumfile, format="ENVI", datatype="INT2S",overwrite=T)
    change_envi_to_bsq(denomsumfile)
    
    #move files around
    for(i in 1:lendep){
      from_dep_files = list.files(dirname(dep_files_sort[1]),substr(basename(dep_files_sort[i]),1,4), full.names = T)
      from_ref_files = list.files(dirname(ref_files_sort[1]),substr(basename(ref_files_sort[i]),1,4), full.names = T)
      to_dep_files = file.path(offsetdir,sub(paste("_",runname,"_",sep=""),paste("_",deprunname,"_",sep=""),basename(from_dep_files)))
      to_ref_files = file.path(offsetdir,sub(paste("_",runname,"_",sep=""),paste("_",refrunname,"_",sep=""),basename(from_ref_files)))
      
      file.copy(from_dep_files, to_dep_files)
      file.copy(from_ref_files, to_ref_files)
    }
    
    #adjust the dep images
    print("...adjusting images by mean pixel-level offset:")
    for(i in 1:length(dep_files)){
      print(paste("......",basename(dep_files[i]),sep=""))
      img = raster(dep_files[i])
      NAvalue(img) = 0
      
      meandiforig = raster(meandiffile) #need to load this each time because delete_temp_files() gets called at the end of each loop - if this file is big it is held in the temp directory and will be deleted
      img = img + meandiforig
      img[is.na(img)] = 0
      
      #write out the new image
      projection(img) = set_projection(projfile)
      
      #delete the old .bsq files - keep the "img_list.csv" files
      allfiles = list.files(dirname(dep_files[i]),substr(basename(dep_files[i]),1,nchar(basename(dep_files[i]))-4),full.names=T)
      allfiles = grep("img_list.csv", allfiles, invert=T, value=T) #keep the "img_list.csv" files
      unlink(allfiles)
      writeRaster(img, dep_files[i], format="ENVI", datatype="INT2S",overwrite=T)
      change_envi_to_bsq(dep_files[i])
      
      delete_temp_files()
    }
  }
  
  #check for leap year
  leapyear = function(year){
    return(((year %% 4 == 0) & (year %% 100 != 0)) | (year %% 400 == 0))
  }
  
  #create decimal year day
  decyearday = function(year,day){
    num = ifelse(leapyear(year) == T, 366, 365)
    return(year+day/num)
  }
  
  #create decimal day
  decday = function(day){
    num = ifelse(day == 366, 366, 365)
    return(day/num)
  }

  #########################################################################
  #########################################################################
  #########################################################################
  print(paste("working on index:",index))
  
  #create some search terms depending on index
  if(index == "tca"){msssearch="tca_30m.tif$"; tmsearch="tca.tif$"; olisearch="tca.tif$"}
  if(index == "tcb"){msssearch="tc_30m.tif$"; tmsearch="tc.tif$"; olisearch="tc.tif$"}
  if(index == "tcg"){msssearch="tc_30m.tif$"; tmsearch="tc.tif$"; olisearch="tc.tif$"}
  if(index == "tcw"){msssearch="tc_30m.tif$"; tmsearch="tc.tif$"; olisearch="tc.tif$"}
  
  #find the files
  msswrs1files = find_files(msswrs1dir, msssearch)
  msswrs2files = find_files(msswrs2dir, msssearch)
  tmwrs2files = find_files(tmwrs2dir, tmsearch)
  oliwrs2files = find_files(oliwrs2dir, olisearch)
  
  #put all the files together in a vector and check to make sure the files intersect the useareafile, if not they will be excluded
  files = c(msswrs1files,msswrs2files,tmwrs2files,oliwrs2files)
  
  #find files that intersect the usearea file
  files = mixel_find(files, useareafile)
  if(length(files)==0){stop("There were no files in the given directories that intersect the provided 'usearea file'.
                            Make sure that you provided the correct file, checked that it actually overlaps the scenes you 
                            specified for compositing, and that the projection is the same as the images.")}
  
  
  #create a table with info on the files
  imginfo = data.frame(file = as.character(files))
  imginfo$file = as.character(imginfo$file)
  bname = basename(imginfo$file)
  imginfo$year = substr(bname, 10, 13)
  imginfo$day = substr(bname, 14,16)
  imginfo$sensor = substr(bname, 1,2)
  imginfo$compyear = imginfo$decdate = NA
  for(i in 1:nrow(imginfo)){imginfo$decdate[i] = decyearday(as.numeric(imginfo$year[i]),as.numeric(imginfo$day[i]))}
  
  #figure out the dec year day range that is good
  #uniyears = as.numeric(sort(unique(imginfo$year)))
  uniyears = 1972:as.numeric(format(Sys.Date(),'%Y'))
  
  if(doyears != "all"){uniyears = uniyears[match(doyears,uniyears)]}

  decstart = decday(startday)
  decend = decday(endday)
  dif = ifelse(decstart > decend, (1-decstart)+decend, decend - decstart)
  start = uniyears+decstart
  end = start+dif
  yearsdf = data.frame(uniyears,start,end)
  
  #figure out which images are in the composite date range, get rif of ones that aren't
  for(i in 1:nrow(yearsdf)){
    these = which(imginfo$decdate >= yearsdf$start[i] & imginfo$decdate <= yearsdf$end[i])
    imginfo$compyear[these] = yearsdf$uniyears[i]
  }
  imginfo = na.omit(imginfo)
  if(nrow(imginfo)==0){stop("There were no files in the given directories that intersect the provided start and end year-of-day bounds.
                            Make sure that you provided the correct limits and check that there are actually image files that intersect 
                            the specified date range.")}
  
  
  #make composites
  mssdir = file.path(outdir,"mss")
  tmdir = file.path(outdir,"tm")
  olidir = file.path(outdir,"oli")
  
  #pull out files by sensor
  mssdf = imginfo[imginfo$sensor == "LM",]
  tmetmdf = imginfo[imginfo$sensor == "LT" | imginfo$sensor == "LE",]
  olidf = imginfo[imginfo$sensor == "LC",]
  
  #create annual composites for all sensors
  if(nrow(mssdf) != 0){
    dir.create(mssdir, recursive=T, showWarnings=F)
    mixel_composite(mssdir, mssdf, runname=runname,index=index, order=order, useareafile=useareafile, overlap=overlap, yearadj=yearadj)
  }
  if(nrow(tmetmdf) != 0){
    dir.create(tmdir, recursive=T, showWarnings=F)
    mixel_composite(tmdir, tmetmdf, runname=runname,index=index, order=order, useareafile=useareafile, overlap=overlap, yearadj=yearadj)
  }
  if(nrow(olidf) != 0){
    dir.create(olidir, recursive=T, showWarnings=F)
    mixel_composite(olidir, olidf, runname=runname,index=index, order=order, useareafile=useareafile, overlap=overlap, yearadj=yearadj)
  }
  
  #deal with the overlapping composites
  msscompfiles = list.files(mssdir, ".bsq$", recursive=T, full.names=T)
  tmcompfiles = list.files(tmdir, ".bsq$", recursive=T, full.names=T)
  olicompfiles = list.files(olidir, ".bsq$", recursive=T, full.names=T)
  
  pixel_level_offset(ref_files=tmcompfiles, dep_files=msscompfiles, outdir=outdir, sensor="mss", projfile=files[1], runname=runname)
  pixel_level_offset(ref_files=tmcompfiles, dep_files=olicompfiles, outdir=outdir, sensor="oli", projfile=files[1], runname=runname)
  
  
  print("dealing with any temporally overlapping MSS/TM composites")
  combine_overlapping_senors(tmcompfiles, msscompfiles)
  
  print("dealing with any temporally overlapping ETM+/OLI composites")
  combine_overlapping_senors(tmcompfiles, olicompfiles)
  
  
  #rename files
  print("directory and file organization/cleaning")
  imglists = list.files(outdir, paste(runname,"_",index,"_composite_img_list.csv",sep=""), recursive=T, full.names=T)
  imglistyears = substr(basename(imglists),1,4)
  uniimglistyears = unique(imglistyears)
  for(i in 1:length(uniimglistyears)){
    outname = file.path(outdir,paste(uniimglistyears[i],"_",runname,"_",index,"_composite_img_list.csv", sep=""))
    theseones = which(imglistyears %in% uniimglistyears[i])
    for(l in 1:length(theseones)){
      if(l == 1){
        alllimglist = read.csv(imglists[theseones[l]], stringsAsFactors=F)$File
      } else{
        alllimglist = c(alllimglist, read.csv(imglists[theseones[l]], stringsAsFactors=F)$File)
      }
    }
    alllimglist = data.frame(File = alllimglist)
    write.csv(alllimglist, outname, row.names = F)
  }
  
  #move files
  msstmolifiles = c(msscompfiles, tmcompfiles, olicompfiles)
  finalfiles = file.path(outdir, basename(msstmolifiles))
  for(i in 1:length(finalfiles)){
    check = file.exists(finalfiles[i])
    if(check == F){
      year = substr(basename(finalfiles[i]), 1, 4)
      files = list.files(dirname(msstmolifiles[i]), year, full.names=T)
      file.rename(files, file.path(outdir, basename(files)))
    }
  }
  
  #clean up
  unlink(c(mssdir,tmdir,olidir), recursive=T)
  
  #make the final stack
  print("making final annual composite stack")
  bname = paste(runname,"_",index,"_composite_stack.bsq", sep="")
  bands = sort(list.files(outdir, "composite.bsq$", full.names=T))
  fullnametif = file.path(outdir,bname)
  fullnamevrt = change_extension("bsq", "vrt", fullnametif)
  gdalbuildvrt(gdalfile=bands, output.vrt = fullnamevrt, separate=T) #, tr=c(reso,reso)
  gdal_translate(src_dataset=fullnamevrt, dst_dataset=fullnametif, of = "ENVI") #, co="INTERLEAVE=BAND"
  unlink(fullnamevrt)
}


#' Calibrate MSS imagery to TM and make cloud-free composites 
#'
#' Calibrate MSS imagery to TM and make cloud-free composites   
#' @param msswrs1dir character. mss wrs1 directory path
#' @param msswrs2dir character. mss wrs2 directory path
#' @param tmwrs2dir character. tm wrs2 directory path
#' @param index character. spectral index to make composites for. options: "tca", "tcb", "tcg", "tcw"
#' @param outdir character. path to output directory
#' @param runname character. unique name for the composite set
#' @param useareafile character. path to usearea file
#' @param doyears ??? what years to composite
#' @param order character. how to order the images options "sensor_and_doy", "doy", and "none"
#' @param overlap character. how to deal with overlapping images. options: "mean"
#' @param cores numeric. Number of cores to process with options: 1 or 2
#' @param process numeric. integer or vector specifying which processes to run: 1=msscal, 2=mixel
#' @import foreach
#' @import doParallel
#' @export


calibrate_and_composite = function(msswrs1dir,msswrs2dir,tmwrs2dir,oliwrs2dir,index,outdir,runname,useareafile,doyears="all",order="none",overlap="mean", cores=2, process, overwrite=F ,startday, endday, yearadj){
  
  #msscal
  if(1 %in% process ==T){
    #resample MSS
    print("Resampling MSS reflectance and cloudmask images")
    msswrs1srfiles = list.files(msswrs1dir, "dos_sr.tif", recursive=T, full.names=T)
    msswrs1cloudfiles = list.files(msswrs1dir, "cloudmask.tif", recursive=T, full.names=T)
    msswrs2srfiles = list.files(msswrs2dir, "dos_sr.tif", recursive=T, full.names=T)
    msswrs2cloudfiles = list.files(msswrs2dir, "cloudmask.tif", recursive=T, full.names=T)
    files = c(msswrs1srfiles,msswrs1cloudfiles,msswrs2srfiles,msswrs2cloudfiles)
    #cores=2
    if(cores == 2){
      print("...in parallel")
      cl = makeCluster(cores)
      registerDoParallel(cl)
      o = foreach(i=1:length(files), .combine="c",.packages="LandsatLinkr") %dopar% mss_resample(files[i], overwrite=F) #hardwired to not overwrite
      stopCluster(cl)
    } else {for(i in 1:length(files)){o = mss_resample(files[i], overwrite=F)}} #hardwired to not overwrite
    
    
    print("Running msscal")
    t=proc.time()
    msscal(msswrs1dir, msswrs2dir, tmwrs2dir, cores=cores)
    print(proc.time()-t)
  }
  
  #olical
  if(2 %in% process ==T){
    print("Running olical")
    t=proc.time()
    olical(oliwrs2dir, tmwrs2dir, cores=cores, overwrite=overwrite)
    print(proc.time()-t)
  }

  #mixel
  if(3 %in% process ==T){
    print("Running mixel")
    t=proc.time()
    if(index == "all"){
      index = c("tca", "tcb", "tcg", "tcw")
      outdir = c(file.path(outdir,"tca"),file.path(outdir,"tcb"),file.path(outdir,"tcg"),file.path(outdir,"tcw"))
      for(i in 1:length(index)){mixel(msswrs1dir,msswrs2dir,tmwrs2dir,oliwrs2dir,index[i],outdir[i],runname,useareafile,doyears="all",order="none",overlap=overlap, startday=startday, endday=endday, yearadj=yearadj)} #overlap="mean"
    } else {
      outdir = file.path(outdir,index)
      mixel(msswrs1dir,msswrs2dir,tmwrs2dir,oliwrs2dir,index,outdir,runname,useareafile,doyears="all",order="none",overlap=overlap, startday=startday, endday=endday, yearadj=yearadj) #overlap="mean"
    }
    print(proc.time()-t)
  }  
}##predefined_condition_begin
# setwd("h:/temp")  
#   
# data<-read.table("Z:/Shared/Labs/Brown,J/tiger/20160509_brown_3436/star_genetable/result/B3436_gene.count",row.names=1, header=T, check.names=F)
# 
# taskName<-'B3436'
# showLabelInPCA<-1
# showDEGeneCluster<-0
# pvalue<-0.05
# foldChange<-2
# minMedianInGroup<-5
# addCountOne<-0
# 
# comparisons=list(
#   "CAPTISOL_vs_FED" = c("CAPTISOL_vs_FED.design", "FED", "CAPTISOL")
# ) 
#
##predefined_condition_end

library("DESeq2")
library("heatmap3")
library("lattice")
library("reshape")
library("ggplot2")
library("grid")
library("scales")
library("reshape2")
library("VennDiagram")

##Solving node stack overflow problem start###
#when there are too many genes, drawing dendrogram may failed due to node stack overflow,
#It could be solved by forcing stats:::plotNode to be run as interpreted code rather then byte-compiled code via a nasty hack.
#http://stackoverflow.com/questions/16559250/error-in-heatmap-2-gplots/25877485#25877485

# Convert a byte-compiled function to an interpreted-code function 
unByteCode <- function(fun)
{
  FUN <- eval(parse(text=deparse(fun)))
  environment(FUN) <- environment(fun)
  FUN
}

# Replace function definition inside of a locked environment **HACK** 
assignEdgewise <- function(name, env, value)
{
  unlockBinding(name, env=env)
  assign( name, envir=env, value=value)
  lockBinding(name, env=env)
  invisible(value)
}

# Replace byte-compiled function in a locked environment with an interpreted-code
# function
unByteCodeAssign <- function(fun)
{
  name <- gsub('^.*::+','', deparse(substitute(fun)))
  FUN <- unByteCode(fun)
  retval <- assignEdgewise(name=name,
                           env=environment(FUN),
                           value=FUN
  )
  invisible(retval)
}

# Use the above functions to convert stats:::plotNode to interpreted-code:
unByteCodeAssign(stats:::plotNode)

# Now raise the interpreted code recursion limit (you may need to adjust this,
#  decreasing if it uses to much memory, increasing if you get a recursion depth error ).
options(expressions=5e4)

##Solving node stack overflow problem end###

hmcols <- colorRampPalette(c("green", "black", "red"))(256)

drawHCA<-function(prefix, rldselect, ispaired, designData, conditionColors, gnames){
  htfile<-paste0(prefix, "_DESeq2-vsd-heatmap.png")
  cat("saving HCA to ", htfile, "\n")
  genecount<-nrow(rldselect)
  if(genecount > 2){
    png(filename=htfile, width=3000, height =3000, res=300)
    cexCol = max(1.0, 0.2 + 1/log10(ncol(rldselect)))
    if(ispaired){
      htColors<-rainbow(length(unique(designData$Paired)))
      gsColors<-as.matrix(data.frame(Group=conditionColors, Sample=htColors[designData$Paired]))
    }else{
      gsColors = conditionColors;
    }
    heatmap3(rldselect, 
             col = hmcols, 
             ColSideColors = gsColors, 
             margins=c(12,5), 
             scale="r", 
             dist=dist, 
             labRow=NA,
             main=paste0("Hierarchical Cluster Using ", genecount, " Genes"),  
             cexCol=cexCol, 
             useRaster=FALSE,
             legendfun=function() showLegend(legend=paste0("Group ", gnames), col=c("red","blue"),cex=1.0,x="center"))
    dev.off()
  }
}

drawPCA<-function(prefix, rldmatrix, showLabelInPCA, designData, conditionColors){
  #filename<-paste0(prefix, "_DESeq2-vsd-pca.png")
  filename<-paste0(prefix, "_DESeq2-vsd-pca.pdf")
  genecount<-nrow(rldmatrix)
  if(genecount > 2){
    cat("saving PCA to ", filename, "\n")
    #png(filename=filename, width=3000, height=3000, res=300) # 10 X 10 inches
    pdf(filename, width=10, height=10)
    pca<-prcomp(t(rldmatrix))
    supca<-summary(pca)$importance
    pcadata<-data.frame(pca$x)
    pcalabs=paste0(colnames(pcadata), "(", round(supca[2,] * 100), "%)")
    pcadata["sample"]<-row.names(pcadata)
    
    if(showLabelInPCA){
      g <- ggplot(pcadata, aes(x=PC1, y=PC2, label=sample)) + 
        geom_text(vjust=-0.6, size=4) +
        geom_point(col=conditionColors, size=4) + 
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) +
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) + 
        xlab(pcalabs[1]) + ylab(pcalabs[2])
    }else{
      g <- ggplot(pcadata, aes(x=PC1, y=PC2)) + 
        geom_point(col=conditionColors, size=4) + 
        labs(color = "Group") +
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) + 
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) +
        xlab(pcalabs[1]) + ylab(pcalabs[2]) + 
        theme(legend.position="top")
    }
    
    print(g)
    dev.off()
  }
}

#for volcano plot
reverselog_trans <- function(base = exp(1)) {
  trans <- function(x) -log(x, base)
  inv <- function(x) base^(-x)
  trans_new(paste0("reverselog-", format(base)), trans, inv, 
            log_breaks(base = base), 
            domain = c(1e-100, Inf))
}

data<-data[,colnames(data) != "Feature_length"]
colClass<-sapply(data, class)
countNotNumIndex<-which(colClass!="numeric" & colClass!="integer")
if (length(countNotNumIndex)==0) {
  index<-1;
  indecies<-c()
} else {
  index<-max(countNotNumIndex)+1
  indecies<-c(1:(index-1))
}

countData<-data[,c(index:ncol(data))]
countData[is.na(countData)] <- 0
countData<-round(countData)

if(addCountOne){
  countData<-countData+1
}

comparisonNames=names(comparisons)
comparisonName=comparisonNames[1]

dir.create("details", showWarnings = FALSE)

pairedspearman<-list()
resultAllOut<-data
resultAllOutVar<-c("log2FoldChange","pvalue","padj")
for(comparisonName in comparisonNames){
  str(comparisonName)
  designFile=comparisons[[comparisonName]][1]
  gnames=comparisons[[comparisonName]][2:3]
  designData<-read.table(designFile, sep="\t", header=T)
  designData$Condition<-factor(designData$Condition, levels=gnames)
  
  if(ncol(designData) >= 3){
    cat("Data with covariances!\n")
  }else{
    cat("Data without covariances!\n")
  }
  if (any(colnames(designData)=="Paired")) {
	  ispaired<-TRUE
	  cat("Paired Data!\n")
  }else{
	  ispaired<-FALSE
	  cat("Not Paired Data!\n")
  }
  temp<-apply(designData,2,function(x) length(unique(x)))
  if (any(temp==1)) {
	  cat(paste0("Factors with only 1 level in design matrix: ",colnames(designData)[which(temp==1)],"\n"))
	  cat("They will be removed")
	  cat("\n")
	  designData<-designData[,which(temp!=1)]
  }
  temp<-apply(designData[,-1,drop=F],2,rank)
  if (length(unique(rowSums(temp)))==1 | identical(temp[,1],temp[,-1])) {
	  cat(paste0("The model matrix is not full rank, so the model cannot be fit as specified"))
	  cat("\n")
	  cat("Only Condition variable will be kept.")
	  cat("\n")
	  designData<-designData[,which(colnames(designData)%in% c("Sample","Condition"))]
  }
  
  comparisonData<-countData[,colnames(countData) %in% as.character(designData$Sample),drop=F]
  if(ncol(comparisonData) != nrow(designData)){
	message=paste0("Data not matched, there are ", nrow(designData), " samples in design file ", designFile, " but ", ncol(comparisonData), " samples in data ")
	warning(message)
	writeLines(message,paste0(comparisonName,".error"))
	next
  }
  comparisonData<-comparisonData[,as.character(designData$Sample)]
  
  prefix<-comparisonName
  curdata<-data
  if(minMedianInGroup > 0){
    conds<-unique(designData$Condition)
    data1<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[1]]]
    data2<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[2]]]
    med1<-apply(data1, 1, median) >= minMedianInGroup
    med2<-apply(data2, 1, median) >= minMedianInGroup
    med<-med1 | med2
    comparisonData<-comparisonData[med,]
    cat(nrow(comparisonData), " genes with minimum median count in group larger or equals than ", minMedianInGroup, "\n")
    
    if (nrow(comparisonData)==0) {
		message=paste0("Error: 0 Genes can be used in DESeq2 analysis in comparison ",comparisonName," \n")
		warning(message)
		writeLines(message,paste0(comparisonName,".error"))
      next;
    }
    
    prefix<-paste0(comparisonName, "_min", minMedianInGroup)
    curdata<-data[med,]
  }
  
  if(ispaired){
    pairedSamples = unique(designData$Paired)
    
    spcorr<-unlist(lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      cor(comparisonData[,samples[1]],comparisonData[,samples[2]],method="spearman")
    }))
    
    
    sptable<-data.frame(Name=pairedSamples, Spcorr=spcorr)
    write.csv(sptable, file=paste0(prefix, "_Spearman.csv"), row.names=FALSE)
    
    lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      log2c1<-log2(comparisonData[,samples[1]]+1)
      log2c2<-log2(comparisonData[,samples[2]]+1)
      png(paste0("details/", prefix, "_Spearman_", pairedSamples[x], ".png"), width=2000, height=2000, res=300)
      plot(log2c1, log2c2, xlab=paste0(samples[1], " [log2(Count + 1)]"), ylab=paste0(samples[2], " [log2(Count + 1)]"))
      text(3,15,paste0("SpearmanCorr=", sprintf("%0.3f", spcorr[x])))
      dev.off()
    })
    
    pairedspearman[[comparisonName]]<-spcorr
  }
  
  notEmptyData<-apply(comparisonData, 1, max) > 0
  comparisonData<-comparisonData[notEmptyData,]
  curdata<-curdata[notEmptyData,]
  
  if(ispaired){
    colnames(comparisonData)<-unlist(lapply(c(1:ncol(comparisonData)), function(i){paste0(designData$Paired[i], "_", colnames(comparisonData)[i])}))
  }
  rownames(designData)<-colnames(comparisonData)
  conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
  
  write.csv(comparisonData, file=paste0(prefix, ".csv"))
  
  #some basic graph
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                             colData = designData,
                             design = ~1)
  
  colnames(dds)<-colnames(comparisonData)
  
  #draw density graph
  rldmatrix<-as.matrix(log2(counts(dds,normalized=FALSE) + 1))
  rsdata<-melt(rldmatrix)
  colnames(rsdata)<-c("Gene", "Sample", "log2Count")
  png(filename=paste0(prefix, "_DESeq2-log2-density.png"), width=4000, height=3000, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  width=max(4000, ncol(rldmatrix) * 40 + 1000)
  height=max(3000, ncol(rldmatrix) * 40)
  png(filename=paste0(prefix, "_DESeq2-log2-density-individual.png"), width=width, height=height, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + facet_wrap(~Sample, scales = "free") + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  
  #varianceStabilizingTransformation
  
  allDesignData<-designData
  allComparisonData<-comparisonData
  
  excludedSample<-c()
  zeronumbers<-apply(comparisonData, 2, function(x){sum(x==0)})
  zeronumbers<-names(zeronumbers[order(zeronumbers)])
  percent10<-max(1, round(length(zeronumbers) * 0.1))
  
  removed<-0
  
  excludedCountFile<-paste0(prefix, "_DESeq2-exclude-count.csv")
  excludedDesignFile<-paste0(prefix, "_DESeq2-exclude-design.csv")
  if(file.exists(excludedCountFile)){
    file.remove(excludedCountFile)
  }
  if(file.exists(excludedDesignFile)){
    file.remove(excludedDesignFile)
  }
  
  fitType<-"parametric"
  while(1){
    #varianceStabilizingTransformation
    vsdres<-try(vsd <- varianceStabilizingTransformation(dds, blind=TRUE,fitType=fitType))
    if(class(vsdres) == "try-error" && grepl("every gene contains at least one zero", vsdres[1])){
      removed<-removed+1
      keptNumber<-length(zeronumbers) - percent10 * removed
      keptSample<-zeronumbers[1:keptNumber]
      excludedSample<-zeronumbers[(keptNumber+1):length(zeronumbers)]
      
      comparisonData<-comparisonData[, colnames(comparisonData) %in% keptSample]
      designData<-designData[rownames(designData) %in% keptSample,]
      dds=DESeqDataSetFromMatrix(countData = comparisonData,
                                 colData = designData,
                                 design = ~1)
      
      colnames(dds)<-colnames(comparisonData)
    } else if (class(vsdres) == "try-error" && grepl("newsplit: out of vertex space", vsdres[1])) {
		message=paste0("Warning: varianceStabilizingTransformation function can't run. fitType was set to local to try again")
		warning(message)
		fitType<-"mean"
		writeLines(message,paste0(comparisonName,".error"))
	} else{
      conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
      break
    }
  }
  if (nrow(comparisonData)<=1) {
	  message=paste0("Error: All genes in ",comparisonName," has at least one 0 value. Can't do DESeq2.")
	  warning(message)
	  writeLines(message,paste0(comparisonName,".error"))
	  next;
  }
  
  if(length(excludedSample) > 0){
    excludedCountData<-allComparisonData[,colnames(allComparisonData) %in% excludedSample]
    write.csv(file=excludedCountFile, excludedCountData)
    excludedDesignData<-allDesignData[rownames(allDesignData) %in% excludedSample,]
    write.csv(file=excludedDesignFile, excludedDesignData)
  }
  
  assayvsd<-assay(vsd)
  write.csv(assayvsd, file=paste0(prefix, "_DESeq2-vsd.csv"))
  
  vsdiqr<-apply(assayvsd, 1, IQR)
  assayvsd<-assayvsd[order(vsdiqr, decreasing=T),]
  
  rldmatrix=as.matrix(assayvsd)
  
  #draw pca graph
  drawPCA(paste0(prefix,"_geneAll"), rldmatrix, showLabelInPCA, designData, conditionColors)
  
  #draw heatmap
  #drawHCA(paste0(prefix,"_gene500"), rldmatrix[1:min(500, nrow(rldmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  drawHCA(paste0(prefix,"_geneAll"), rldmatrix, ispaired, designData, conditionColors, gnames)
  
  #different expression analysis
  designFormula=as.formula(paste0("~",paste0(c(colnames(designData)[-c(1:2)],"Condition"),collapse="+")))
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                               colData = designData,
                               design = designFormula)
  
  dds <- DESeq(dds,fitType=fitType)
  res<-results(dds,cooksCutoff=FALSE)
  
  cat("DESeq2 finished.\n")
  
  select<-(!is.na(res$padj)) & (res$padj<pvalue) & ((res$log2FoldChange >= log2(foldChange)) | (res$log2FoldChange <= -log2(foldChange)))
  
  if(length(indecies) > 0){
    inddata<-curdata[,indecies,drop=F]
    tbb<-cbind(inddata, comparisonData, res)
  }else{
    tbb<-cbind(comparisonData, res)
  }
  tbb$FoldChange<-2^tbb$log2FoldChange
  tbbselect<-tbb[select,,drop=F]
  tbbAllOut<-as.data.frame(tbb[,resultAllOutVar,drop=F])
  tbbAllOut$Significant<-select
  colnames(tbbAllOut)<-paste0(colnames(tbbAllOut)," (",comparisonName,")")
  resultAllOut<-cbind(resultAllOut,tbbAllOut[row.names(resultAllOut),])

  tbb<-tbb[order(tbb$padj),,drop=F]
  write.csv(as.data.frame(tbb),paste0(prefix, "_DESeq2.csv"))
  
  tbbselect<-tbbselect[order(tbbselect$padj),,drop=F]
  write.csv(as.data.frame(tbbselect),paste0(prefix, "_DESeq2_sig.csv"))
  
  if("Feature_gene_name" %in% colnames(tbb)){
    write.table(tbb[,c("Feature_gene_name", "stat"),drop=F],paste0(prefix, "_DESeq2_GSEA.rnk"),row.names=F,col.names=F,sep="\t", quote=F)
    write.table(tbbselect[,c("Feature_gene_name"),drop=F], paste0(prefix, "_DESeq2_sig_genename.txt"),row.names=F,col.names=F,sep="\t", quote=F)
  }

  if(showDEGeneCluster){
    siggenes<-rownames(rldmatrix) %in% rownames(tbbselect)
    
    nonDEmatrix<-rldmatrix[!siggenes,,drop=F]
    DEmatrix<-rldmatrix[siggenes,,drop=F]
    
    drawPCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, ispaired, designData, conditionColors, gnames)
    
    drawPCA(paste0(prefix,"_geneDE"),DEmatrix , showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneDE"),DEmatrix , ispaired, designData, conditionColors, gnames)
    #drawHCA(paste0(prefix,"_gene500NotDE"), nonDEmatrix[1:min(500, nrow(nonDEmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  }
  
  #Top 25 Significant genes barplot
  sigDiffNumber<-nrow(tbbselect)
  if (sigDiffNumber>0) {
    if (sigDiffNumber>25) {
      print(paste0("More than 25 genes were significant. Only the top 25 genes will be used in barplot"))
      diffResultSig<-tbbselect[order(tbbselect$padj)[1:25],]
    } else {
      diffResultSig<-tbbselect
    }
    if("Feature_gene_name" %in% colnames(diffResultSig)){
      diffResultSig$Name<-as.character(diffResultSig$Feature_gene_name)
    }else{
      diffResultSig$Name<-sapply(strsplit(row.names(diffResultSig),";"),function(x) x[1])
    }
    diffResultSig$Name <- factor(diffResultSig$Name, levels=diffResultSig$Name[order(diffResultSig$log2FoldChange)])
    diffResultSig<-as.data.frame(diffResultSig)
    
    png(filename=paste0(prefix, "_DESeq2_sig_barplot.png"), width=3000, height=3000, res=300)
    #	  pdf(paste0(prefix,"_DESeq2_sig_barplot.pdf"))
    p<-ggplot(diffResultSig,aes(x=Name,y=log2FoldChange,order=log2FoldChange))+geom_bar(stat="identity")+
      coord_flip()+
      #			geom_abline(slope=0,intercept=1,colour="red",linetype = 2)+
      scale_y_continuous(name=bquote(log[2]~Fold~Change))+
      theme(axis.text = element_text(colour = "black"))
    print(p)
    dev.off()
  } else {
    print(paste0("No gene with adjusted p value less than ",pvalue," and fold change larger than ",foldChange))
  }
  
  #volcano plot
  changeColours<-c(grey="grey",blue="blue",red="red")
  diffResult<-as.data.frame(tbb)
  diffResult$log10BaseMean<-log10(diffResult$baseMean)
  diffResult$colour<-"grey"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange>=log2(foldChange))]<-"red"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange<=-log2(foldChange))]<-"blue"
  png(filename=paste0(prefix, "_DESeq2_volcanoPlot.png"), width=3000, height=3000, res=300)
  #  pdf(paste0(prefix,"_DESeq2_volcanoPlot.pdf"))
  p<-ggplot(diffResult,aes(x=log2FoldChange,y=padj))+
    geom_point(aes(size=log10BaseMean,colour=colour))+
    scale_color_manual(values=changeColours,guide = FALSE)+
    scale_y_continuous(trans=reverselog_trans(10),name=bquote(Adjusted~p~value))+
    scale_x_continuous(name=bquote(log[2]~Fold~Change))+
    geom_hline(yintercept = 1,colour="grey",linetype = "dotted")+
    geom_vline(xintercept = 0,colour="grey",linetype = "dotted")+
    guides(size=guide_legend(title=bquote(log[10]~Base~Mean)))+
    theme_bw()+
    scale_size(range = c(3, 7))+
    theme(axis.text = element_text(colour = "black",size=30),
			axis.title = element_text(size=30),
			legend.text= element_text(size=30),
			legend.title= element_text(size=30))
  print(p)
  dev.off()
}

#write a file with all information
write.csv(resultAllOut,paste0(taskName, "_DESeq2.csv"))

if(length(pairedspearman) > 0){
  #draw pca graph
  filename<-ifelse(minMedianInGroup > 0, paste0("spearman_min", minMedianInGroup, ".png"), "spearman.png")
  png(filename=filename, width=1000 * length(pairedspearman), height=2000, res=300)
  boxplot(pairedspearman)
  dev.off()
}

#Venn for all significant genes
allSigNameList<-list()
allSigDirectionList<-list()
for(comparisonName in comparisonNames){
	if (minMedianInGroup > 0) {
		prefix<-paste0(comparisonName, "_min", minMedianInGroup)
	} else {
		prefix<-comparisonName
	}
	sigFile<-paste0(prefix, "_DESeq2_sig.csv")
	if (file.exists(sigFile)) {
		sigTable<-read.csv(sigFile,header=TRUE,as.is=TRUE)
		if (nrow(sigTable)>0) {
			allSigNameList[[comparisonName]]<-sigTable[,1]
			allSigDirectionList[[comparisonName]]<-sign(sigTable$log2FoldChange)
		} else {
			warning(paste0("No significant genes in ",comparisonName))
#		allSigNameList[[comparisonName]]<-""
		}
	}
}

#Do venn if length between 2-5
if (length(allSigNameList)>=2 & length(allSigNameList)<=5) {
	venn.diagram1<-function (x, filename, height = 3000, width = 3000, resolution = 500, 
			units = "px", compression = "lzw", na = "stop", main = NULL, 
			sub = NULL, main.pos = c(0.5, 1.05), main.fontface = "plain", 
			main.fontfamily = "serif", main.col = "black", main.cex = 1, 
			main.just = c(0.5, 1), sub.pos = c(0.5, 1.05), sub.fontface = "plain", 
			sub.fontfamily = "serif", sub.col = "black", sub.cex = 1, 
			sub.just = c(0.5, 1), category.names = names(x), force.unique = TRUE,
			fill=NA,
			...) 
	{
		if (is.na(fill)) {
			if (length(x)==5) {
				fill = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3")
			} else if (length(x)==4) {
				fill = c("dodgerblue", "goldenrod1",  "seagreen3", "orchid3")
			} else if (length(x)==3) {
				fill = c("dodgerblue", "goldenrod1", "seagreen3")
			} else if (length(x)==2) {
				fill = c("dodgerblue", "goldenrod1")
			}
		}
		if (force.unique) {
			for (i in 1:length(x)) {
				x[[i]] <- unique(x[[i]])
			}
		}
		if ("none" == na) {
			x <- x
		}
		else if ("stop" == na) {
			for (i in 1:length(x)) {
				if (any(is.na(x[[i]]))) {
					stop("NAs in dataset", call. = FALSE)
				}
			}
		}
		else if ("remove" == na) {
			for (i in 1:length(x)) {
				x[[i]] <- x[[i]][!is.na(x[[i]])]
			}
		}
		else {
			stop("Invalid na option: valid options are \"none\", \"stop\", and \"remove\"")
		}
		if (0 == length(x) | length(x) > 5) {
			stop("Incorrect number of elements.", call. = FALSE)
		}
		if (1 == length(x)) {
			list.names <- category.names
			if (is.null(list.names)) {
				list.names <- ""
			}
			grob.list <- VennDiagram::draw.single.venn(area = length(x[[1]]), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else if (2 == length(x)) {
			grob.list <- VennDiagram::draw.pairwise.venn(area1 = length(x[[1]]), 
					area2 = length(x[[2]]), cross.area = length(intersect(x[[1]], 
									x[[2]])), category = category.names, ind = FALSE, 
					fill=fill,
					...)
		}
		else if (3 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			list.names <- category.names
			nab <- intersect(A, B)
			nbc <- intersect(B, C)
			nac <- intersect(A, C)
			nabc <- intersect(nab, C)
			grob.list <- VennDiagram::draw.triple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), n12 = length(nab), 
					n23 = length(nbc), n13 = length(nac), n123 = length(nabc), 
					category = list.names, ind = FALSE, list.order = 1:3, 
					fill=fill,
					...)
		}
		else if (4 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n34 <- intersect(C, D)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n134 <- intersect(n13, D)
			n234 <- intersect(n23, D)
			n1234 <- intersect(n123, D)
			grob.list <- VennDiagram::draw.quad.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					n12 = length(n12), n13 = length(n13), n14 = length(n14), 
					n23 = length(n23), n24 = length(n24), n34 = length(n34), 
					n123 = length(n123), n124 = length(n124), n134 = length(n134), 
					n234 = length(n234), n1234 = length(n1234), category = list.names, 
					ind = FALSE, fill=fill,...)
		}
		else if (5 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			E <- x[[5]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n15 <- intersect(A, E)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n25 <- intersect(B, E)
			n34 <- intersect(C, D)
			n35 <- intersect(C, E)
			n45 <- intersect(D, E)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n125 <- intersect(n12, E)
			n134 <- intersect(n13, D)
			n135 <- intersect(n13, E)
			n145 <- intersect(n14, E)
			n234 <- intersect(n23, D)
			n235 <- intersect(n23, E)
			n245 <- intersect(n24, E)
			n345 <- intersect(n34, E)
			n1234 <- intersect(n123, D)
			n1235 <- intersect(n123, E)
			n1245 <- intersect(n124, E)
			n1345 <- intersect(n134, E)
			n2345 <- intersect(n234, E)
			n12345 <- intersect(n1234, E)
			grob.list <- VennDiagram::draw.quintuple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					area5 = length(E), n12 = length(n12), n13 = length(n13), 
					n14 = length(n14), n15 = length(n15), n23 = length(n23), 
					n24 = length(n24), n25 = length(n25), n34 = length(n34), 
					n35 = length(n35), n45 = length(n45), n123 = length(n123), 
					n124 = length(n124), n125 = length(n125), n134 = length(n134), 
					n135 = length(n135), n145 = length(n145), n234 = length(n234), 
					n235 = length(n235), n245 = length(n245), n345 = length(n345), 
					n1234 = length(n1234), n1235 = length(n1235), n1245 = length(n1245), 
					n1345 = length(n1345), n2345 = length(n2345), n12345 = length(n12345), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else {
			stop("Invalid size of input object")
		}
		if (!is.null(sub)) {
			grob.list <- add.title(gList = grob.list, x = sub, pos = sub.pos, 
					fontface = sub.fontface, fontfamily = sub.fontfamily, 
					col = sub.col, cex = sub.cex)
		}
		if (!is.null(main)) {
			grob.list <- add.title(gList = grob.list, x = main, pos = main.pos, 
					fontface = main.fontface, fontfamily = main.fontfamily, 
					col = main.col, cex = main.cex)
		}
		grid.newpage()
		grid.draw(grob.list)
		return(1)
#	return(grob.list)
	}
	png(paste0(taskName,"_significantVenn.png"),res=300,height=2000,width=2000)
	venn.diagram1(allSigNameList)
	dev.off()
}
#Do heatmap significant genes if length larger or equal than 2
if (length(allSigNameList)>=2) {
	temp<-cbind(unlist(allSigNameList),unlist(allSigDirectionList))
	colnames(temp)<-c("Gene","Direction")
	temp<-cbind(temp,comparisonName=rep(names(allSigNameList),sapply(allSigNameList,length)))
	temp<-data.frame(temp)
	dataForFigure<-temp
	#geting dataForFigure order in figure
	temp$Direction<-as.integer(as.character(temp$Direction))
	temp<-acast(temp, Gene~comparisonName ,value.var="Direction")
	temp<-temp[do.call(order, data.frame(temp)),]
	maxNameChr<-max(nchar(row.names(temp)))
	if (maxNameChr>70) {
		row.names(temp)<-substr(row.names(temp),0,70)
		dataForFigure$Gene<-substr(dataForFigure$Gene,0,70)
		warning(paste0("The gene names were too long (",maxNameChr,"). Only first 70 letters were kept."))
	}
	dataForFigure$Gene<-factor(dataForFigure$Gene,levels=row.names(temp))
	
	width=max(2500, 60 * length(unique(dataForFigure$comparisonName)))
	height=max(2000, 40 * length(unique(dataForFigure$Gene)))
	png(paste0(taskName,"_significantHeatmap.png"),res=300,height=height,width=width)
	g<-ggplot(dataForFigure, aes(comparisonName, Gene))+
			geom_tile(aes(fill=Direction), color="white") +
			scale_fill_manual(values=c("light green", "red")) +
			theme(axis.text.x = element_text(angle=90, vjust=0.5, size=11, hjust=0.5, face="bold"),
					axis.text.y = element_text(size=11, face="bold")) +
			coord_equal()
	print(g)
	dev.off()
}


options(max.print = 1000L)

print.data.frame = function (x, ..., digits = NULL, quote = FALSE, right = TRUE,
                             row.names = TRUE) {
    if (! isTRUE(all.equal(rownames(x), as.character(seq_len(nrow(x))))))
        x = tibble::rownames_to_column(x)
    print(dplyr::tbl_df(x))
}
##predefined_condition_begin
# setwd("h:/temp")  
#   
# data<-read.table("Z:/Shared/Labs/Brown,J/tiger/20160509_brown_3436/star_genetable/result/B3436_gene.count",row.names=1, header=T, check.names=F)
# 
# taskName<-'B3436'
# showLabelInPCA<-1
# showDEGeneCluster<-0
# pvalue<-0.05
# foldChange<-2
# minMedianInGroup<-5
# addCountOne<-0
# 
# comparisons=list(
#   "CAPTISOL_vs_FED" = c("CAPTISOL_vs_FED.design", "FED", "CAPTISOL")
# ) 
#
##predefined_condition_end

library("DESeq2")
library("heatmap3")
library("lattice")
library("reshape")
library("ggplot2")
library("grid")
library("scales")
library("reshape2")
library("VennDiagram")

##Solving node stack overflow problem start###
#when there are too many genes, drawing dendrogram may failed due to node stack overflow,
#It could be solved by forcing stats:::plotNode to be run as interpreted code rather then byte-compiled code via a nasty hack.
#http://stackoverflow.com/questions/16559250/error-in-heatmap-2-gplots/25877485#25877485

# Convert a byte-compiled function to an interpreted-code function 
unByteCode <- function(fun)
{
  FUN <- eval(parse(text=deparse(fun)))
  environment(FUN) <- environment(fun)
  FUN
}

# Replace function definition inside of a locked environment **HACK** 
assignEdgewise <- function(name, env, value)
{
  unlockBinding(name, env=env)
  assign( name, envir=env, value=value)
  lockBinding(name, env=env)
  invisible(value)
}

# Replace byte-compiled function in a locked environment with an interpreted-code
# function
unByteCodeAssign <- function(fun)
{
  name <- gsub('^.*::+','', deparse(substitute(fun)))
  FUN <- unByteCode(fun)
  retval <- assignEdgewise(name=name,
                           env=environment(FUN),
                           value=FUN
  )
  invisible(retval)
}

# Use the above functions to convert stats:::plotNode to interpreted-code:
unByteCodeAssign(stats:::plotNode)

# Now raise the interpreted code recursion limit (you may need to adjust this,
#  decreasing if it uses to much memory, increasing if you get a recursion depth error ).
options(expressions=5e4)

##Solving node stack overflow problem end###

hmcols <- colorRampPalette(c("green", "black", "red"))(256)

drawHCA<-function(prefix, rldselect, ispaired, designData, conditionColors, gnames){
  htfile<-paste0(prefix, "_DESeq2-vsd-heatmap.png")
  cat("saving HCA to ", htfile, "\n")
  genecount<-nrow(rldselect)
  if(genecount > 2){
    png(filename=htfile, width=3000, height =3000, res=300)
    cexCol = max(1.0, 0.2 + 1/log10(ncol(rldselect)))
    if(ispaired){
      htColors<-rainbow(length(unique(designData$Paired)))
      gsColors<-as.matrix(data.frame(Group=conditionColors, Sample=htColors[designData$Paired]))
    }else{
      gsColors = conditionColors;
    }
    heatmap3(rldselect, 
             col = hmcols, 
             ColSideColors = gsColors, 
             margins=c(12,5), 
             scale="r", 
             dist=dist, 
             labRow=NA,
             main=paste0("Hierarchical Cluster Using ", genecount, " Genes"),  
             cexCol=cexCol, 
             useRaster=FALSE,
             legendfun=function() showLegend(legend=paste0("Group ", gnames), col=c("red","blue"),cex=1.0,x="center"))
    dev.off()
  }
}

drawPCA<-function(prefix, rldmatrix, showLabelInPCA, designData, conditionColors){
  #filename<-paste0(prefix, "_DESeq2-vsd-pca.png")
  filename<-paste0(prefix, "_DESeq2-vsd-pca.pdf")
  genecount<-nrow(rldmatrix)
  if(genecount > 2){
    cat("saving PCA to ", filename, "\n")
    #png(filename=filename, width=3000, height=3000, res=300) # 10 X 10 inches
    pdf(filename, width=10, height=10)
    pca<-prcomp(t(rldmatrix))
    supca<-summary(pca)$importance
    pcadata<-data.frame(pca$x)
    pcalabs=paste0(colnames(pcadata), "(", round(supca[2,] * 100), "%)")
    pcadata["sample"]<-row.names(pcadata)
    
    if(showLabelInPCA){
      g <- ggplot(pcadata, aes(x=PC1, y=PC2, label=sample)) + 
        geom_text(vjust=-0.6, size=4) +
        geom_point(col=conditionColors, size=4) + 
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) +
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) + 
        xlab(pcalabs[1]) + ylab(pcalabs[2])
    }else{
      g <- ggplot(pcadata, aes(x=PC1, y=PC2)) + 
        geom_point(col=conditionColors, size=4) + 
        labs(color = "Group") +
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) + 
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) +
        xlab(pcalabs[1]) + ylab(pcalabs[2]) + 
        theme(legend.position="top")
    }
    
    print(g)
    dev.off()
  }
}

#for volcano plot
reverselog_trans <- function(base = exp(1)) {
  trans <- function(x) -log(x, base)
  inv <- function(x) base^(-x)
  trans_new(paste0("reverselog-", format(base)), trans, inv, 
            log_breaks(base = base), 
            domain = c(1e-100, Inf))
}

isDataNumeric = unlist(lapply(data[1,], function(x){is.numeric(x)}))
if (any(isDataNumeric)) {
  index = 1
  while(!all(isDataNumeric[index:ncol(data)])){
    index = index + 1
  }
} else {
  cat("Error: No numeric data found for DESeq2 \n")
  quit(save="yes")
}

if(index > 1){
  indecies<-c(1:(index-1))
}else{
  indecies<-c()
}
countData<-data[,c(index:ncol(data))]

countData[is.na(countData)] <- 0

if(addCountOne){
  countData<-round(countData)+1
}

comparisonNames=names(comparisons)
comparisonName=comparisonNames[1]

dir.create("details", showWarnings = FALSE)

pairedspearman<-list()
resultAllOut<-data
resultAllOutVar<-c("log2FoldChange","pvalue","padj")
for(comparisonName in comparisonNames){
  str(comparisonName)
  designFile=comparisons[[comparisonName]][1]
  gnames=comparisons[[comparisonName]][2:3]
  designData<-read.table(designFile, sep="\t", header=T)
  designData$Condition<-factor(designData$Condition, levels=gnames)
  
  if(ncol(designData) >= 3){
    cat("Data with covariances!\n")
  }else{
    cat("Data without covariances!\n")
  }
  if (any(colnames(designData)=="Paired")) {
	  ispaired<-TRUE
	  cat("Paired Data!\n")
  }else{
	  ispaired<-FALSE
	  cat("Not Paired Data!\n")
  }
  temp<-apply(designData,2,function(x) length(unique(x)))
  if (any(temp==1)) {
	  cat(paste0("Factors with only 1 level in design matrix: ",colnames(designData)[which(temp==1)],"\n"))
	  cat("They will be removed")
	  cat("\n")
	  designData<-designData[,which(temp!=1)]
  }
  temp<-apply(designData[,-1,drop=F],2,rank)
  if (length(unique(rowSums(temp)))==1 | identical(temp[,1],temp[,-1])) {
	  cat(paste0("The model matrix is not full rank, so the model cannot be fit as specified"))
	  cat("\n")
	  cat("Only Condition variable will be kept.")
	  cat("\n")
	  designData<-designData[,which(colnames(designData)%in% c("Sample","Condition"))]
  }
  
  comparisonData<-countData[,colnames(countData) %in% as.character(designData$Sample),drop=F]
  if(ncol(comparisonData) != nrow(designData)){
	message=paste0("Data not matched, there are ", nrow(designData), " samples in design file ", designFile, " but ", ncol(comparisonData), " samples in data ")
	warning(message)
	writeLines(message,paste0(comparisonName,".error"))
	next
  }
  comparisonData<-comparisonData[,as.character(designData$Sample)]
  
  prefix<-comparisonName
  curdata<-data
  if(minMedianInGroup > 0){
    conds<-unique(designData$Condition)
    data1<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[1]]]
    data2<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[2]]]
    med1<-apply(data1, 1, median) >= minMedianInGroup
    med2<-apply(data2, 1, median) >= minMedianInGroup
    med<-med1 | med2
    comparisonData<-comparisonData[med,]
    cat(nrow(comparisonData), " genes with minimum median count in group larger or equals than ", minMedianInGroup, "\n")
    
    if (nrow(comparisonData)==0) {
		message=paste0("Error: 0 Genes can be used in DESeq2 analysis in comparison ",comparisonName," \n")
		warning(message)
		writeLines(message,paste0(comparisonName,".error"))
      next;
    }
    
    prefix<-paste0(comparisonName, "_min", minMedianInGroup)
    curdata<-data[med,]
  }
  
  if(ispaired){
    pairedSamples = unique(designData$Paired)
    
    spcorr<-unlist(lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      cor(comparisonData[,samples[1]],comparisonData[,samples[2]],method="spearman")
    }))
    
    
    sptable<-data.frame(Name=pairedSamples, Spcorr=spcorr)
    write.csv(sptable, file=paste0(prefix, "_Spearman.csv"), row.names=FALSE)
    
    lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      log2c1<-log2(comparisonData[,samples[1]]+1)
      log2c2<-log2(comparisonData[,samples[2]]+1)
      png(paste0("details/", prefix, "_Spearman_", pairedSamples[x], ".png"), width=2000, height=2000, res=300)
      plot(log2c1, log2c2, xlab=paste0(samples[1], " [log2(Count + 1)]"), ylab=paste0(samples[2], " [log2(Count + 1)]"))
      text(3,15,paste0("SpearmanCorr=", sprintf("%0.3f", spcorr[x])))
      dev.off()
    })
    
    pairedspearman[[comparisonName]]<-spcorr
  }
  
  notEmptyData<-apply(comparisonData, 1, max) > 0
  comparisonData<-comparisonData[notEmptyData,]
  curdata<-curdata[notEmptyData,]
  
  if(ispaired){
    colnames(comparisonData)<-unlist(lapply(c(1:ncol(comparisonData)), function(i){paste0(designData$Paired[i], "_", colnames(comparisonData)[i])}))
  }
  rownames(designData)<-colnames(comparisonData)
  conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
  
  write.csv(comparisonData, file=paste0(prefix, ".csv"))
  
  #some basic graph
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                             colData = designData,
                             design = ~1)
  
  colnames(dds)<-colnames(comparisonData)
  
  #draw density graph
  rldmatrix<-as.matrix(log2(counts(dds,normalized=FALSE) + 1))
  rsdata<-melt(rldmatrix)
  colnames(rsdata)<-c("Gene", "Sample", "log2Count")
  png(filename=paste0(prefix, "_DESeq2-log2-density.png"), width=4000, height=3000, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  width=max(4000, ncol(rldmatrix) * 40 + 1000)
  height=max(3000, ncol(rldmatrix) * 40)
  png(filename=paste0(prefix, "_DESeq2-log2-density-individual.png"), width=width, height=height, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + facet_wrap(~Sample, scales = "free") + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  
  #varianceStabilizingTransformation
  
  allDesignData<-designData
  allComparisonData<-comparisonData
  
  excludedSample<-c()
  zeronumbers<-apply(comparisonData, 2, function(x){sum(x==0)})
  zeronumbers<-names(zeronumbers[order(zeronumbers)])
  percent10<-max(1, round(length(zeronumbers) * 0.1))
  
  removed<-0
  
  excludedCountFile<-paste0(prefix, "_DESeq2-exclude-count.csv")
  excludedDesignFile<-paste0(prefix, "_DESeq2-exclude-design.csv")
  if(file.exists(excludedCountFile)){
    file.remove(excludedCountFile)
  }
  if(file.exists(excludedDesignFile)){
    file.remove(excludedDesignFile)
  }
  
  fitType<-"parametric"
  while(1){
    #varianceStabilizingTransformation
    vsdres<-try(vsd <- varianceStabilizingTransformation(dds, blind=TRUE,fitType=fitType))
    if(class(vsdres) == "try-error" && grepl("every gene contains at least one zero", vsdres[1])){
      removed<-removed+1
      keptNumber<-length(zeronumbers) - percent10 * removed
      keptSample<-zeronumbers[1:keptNumber]
      excludedSample<-zeronumbers[(keptNumber+1):length(zeronumbers)]
      
      comparisonData<-comparisonData[, colnames(comparisonData) %in% keptSample]
      designData<-designData[rownames(designData) %in% keptSample,]
      dds=DESeqDataSetFromMatrix(countData = comparisonData,
                                 colData = designData,
                                 design = ~1)
      
      colnames(dds)<-colnames(comparisonData)
    } else if (class(vsdres) == "try-error" && grepl("newsplit: out of vertex space", vsdres[1])) {
		message=paste0("Warning: varianceStabilizingTransformation function can't run. fitType was set to local to try again")
		warning(message)
		fitType<-"mean"
		writeLines(message,paste0(comparisonName,".error"))
	} else{
      conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
      break
    }
  }
  if (nrow(comparisonData)<=1) {
	  message=paste0("Error: All genes in ",comparisonName," has at least one 0 value. Can't do DESeq2.")
	  warning(message)
	  writeLines(message,paste0(comparisonName,".error"))
	  next;
  }
  
  if(length(excludedSample) > 0){
    excludedCountData<-allComparisonData[,colnames(allComparisonData) %in% excludedSample]
    write.csv(file=excludedCountFile, excludedCountData)
    excludedDesignData<-allDesignData[rownames(allDesignData) %in% excludedSample,]
    write.csv(file=excludedDesignFile, excludedDesignData)
  }
  
  assayvsd<-assay(vsd)
  write.csv(assayvsd, file=paste0(prefix, "_DESeq2-vsd.csv"))
  
  vsdiqr<-apply(assayvsd, 1, IQR)
  assayvsd<-assayvsd[order(vsdiqr, decreasing=T),]
  
  rldmatrix=as.matrix(assayvsd)
  
  #draw pca graph
  drawPCA(paste0(prefix,"_geneAll"), rldmatrix, showLabelInPCA, designData, conditionColors)
  
  #draw heatmap
  #drawHCA(paste0(prefix,"_gene500"), rldmatrix[1:min(500, nrow(rldmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  drawHCA(paste0(prefix,"_geneAll"), rldmatrix, ispaired, designData, conditionColors, gnames)
  
  #different expression analysis
  designFormula=as.formula(paste0("~",paste0(c(colnames(designData)[-c(1:2)],"Condition"),collapse="+")))
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                               colData = designData,
                               design = designFormula)
  
  dds <- DESeq(dds,fitType=fitType)
  res<-results(dds,cooksCutoff=FALSE)
  
  cat("DESeq2 finished.\n")
  
  select<-(!is.na(res$padj)) & (res$padj<pvalue) & ((res$log2FoldChange >= log2(foldChange)) | (res$log2FoldChange <= -log2(foldChange)))
  
  if(length(indecies) > 0){
    inddata<-curdata[,indecies,drop=F]
    tbb<-cbind(inddata, comparisonData, res)
  }else{
    tbb<-cbind(comparisonData, res)
  }
  tbb$FoldChange<-2^tbb$log2FoldChange
  tbbselect<-tbb[select,,drop=F]
  tbbAllOut<-as.data.frame(tbb[,resultAllOutVar,drop=F])
  tbbAllOut$Significant<-select
  colnames(tbbAllOut)<-paste0(colnames(tbbAllOut)," (",comparisonName,")")
  resultAllOut<-cbind(resultAllOut,tbbAllOut[row.names(resultAllOut),])

  tbb<-tbb[order(tbb$padj),,drop=F]
  write.csv(as.data.frame(tbb),paste0(prefix, "_DESeq2.csv"))

  if("Feature_gene_name" %in% colnames(tbb)){
    gsea<-tbb[,c("Feature_gene_name", "stat"),drop=F]
    write.table(gsea,paste0(prefix, "_DESeq2_GSEA.rnk"),row.names=F,col.names=F,sep="\t", quote=F)
  }

  tbbselect<-tbbselect[order(tbbselect$padj),,drop=F]
  write.csv(as.data.frame(tbbselect),paste0(prefix, "_DESeq2_sig.csv"))
  
  if(showDEGeneCluster){
    siggenes<-rownames(rldmatrix) %in% rownames(tbbselect)
    
    nonDEmatrix<-rldmatrix[!siggenes,,drop=F]
    DEmatrix<-rldmatrix[siggenes,,drop=F]
    
    drawPCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, ispaired, designData, conditionColors, gnames)
    
    drawPCA(paste0(prefix,"_geneDE"),DEmatrix , showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneDE"),DEmatrix , ispaired, designData, conditionColors, gnames)
    #drawHCA(paste0(prefix,"_gene500NotDE"), nonDEmatrix[1:min(500, nrow(nonDEmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  }
  
  #Top 25 Significant genes barplot
  sigDiffNumber<-nrow(tbbselect)
  if (sigDiffNumber>0) {
    if (sigDiffNumber>25) {
      print(paste0("More than 25 genes were significant. Only the top 25 genes will be used in barplot"))
      diffResultSig<-tbbselect[order(tbbselect$padj)[1:25],]
    } else {
      diffResultSig<-tbbselect
    }
    if("Feature_gene_name" %in% colnames(diffResultSig)){
      diffResultSig$Name<-as.character(diffResultSig$Feature_gene_name)
    }else{
      diffResultSig$Name<-sapply(strsplit(row.names(diffResultSig),";"),function(x) x[1])
    }
    diffResultSig$Name <- factor(diffResultSig$Name, levels=diffResultSig$Name[order(diffResultSig$log2FoldChange)])
    diffResultSig<-as.data.frame(diffResultSig)
    
    png(filename=paste0(prefix, "_DESeq2_sig_barplot.png"), width=3000, height=3000, res=300)
    #	  pdf(paste0(prefix,"_DESeq2_sig_barplot.pdf"))
    p<-ggplot(diffResultSig,aes(x=Name,y=log2FoldChange,order=log2FoldChange))+geom_bar(stat="identity")+
      coord_flip()+
      #			geom_abline(slope=0,intercept=1,colour="red",linetype = 2)+
      scale_y_continuous(name=bquote(log[2]~Fold~Change))+
      theme(axis.text = element_text(colour = "black"))
    print(p)
    dev.off()
  } else {
    print(paste0("No gene with adjusted p value less than ",pvalue," and fold change larger than ",foldChange))
  }
  
  #volcano plot
  changeColours<-c(grey="grey",blue="blue",red="red")
  diffResult<-as.data.frame(tbb)
  diffResult$log10BaseMean<-log10(diffResult$baseMean)
  diffResult$colour<-"grey"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange>=log2(foldChange))]<-"red"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange<=-log2(foldChange))]<-"blue"
  png(filename=paste0(prefix, "_DESeq2_volcanoPlot.png"), width=3000, height=3000, res=300)
  #  pdf(paste0(prefix,"_DESeq2_volcanoPlot.pdf"))
  p<-ggplot(diffResult,aes(x=log2FoldChange,y=padj))+
    geom_point(aes(size=log10BaseMean,colour=colour))+
    scale_color_manual(values=changeColours,guide = FALSE)+
    scale_y_continuous(trans=reverselog_trans(10),name=bquote(Adjusted~p~value))+
    scale_x_continuous(name=bquote(log[2]~Fold~Change))+
    geom_hline(yintercept = 1,colour="grey",linetype = "dotted")+
    geom_vline(xintercept = 0,colour="grey",linetype = "dotted")+
    guides(size=guide_legend(title=bquote(log[10]~Base~Mean)))+
    theme_bw()+
    scale_size(range = c(3, 7))+
    theme(axis.text = element_text(colour = "black",size=30),
			axis.title = element_text(size=30),
			legend.text= element_text(size=30),
			legend.title= element_text(size=30))
  print(p)
  dev.off()
}

#write a file with all information
write.csv(resultAllOut,paste0(taskName, "_DESeq2.csv"))

if(length(pairedspearman) > 0){
  #draw pca graph
  filename<-ifelse(minMedianInGroup > 0, paste0("spearman_min", minMedianInGroup, ".png"), "spearman.png")
  png(filename=filename, width=1000 * length(pairedspearman), height=2000, res=300)
  boxplot(pairedspearman)
  dev.off()
}

#Venn for all significant genes
allSigNameList<-list()
allSigDirectionList<-list()
for(comparisonName in comparisonNames){
	if (minMedianInGroup > 0) {
		prefix<-paste0(comparisonName, "_min", minMedianInGroup)
	} else {
		prefix<-comparisonName
	}
	sigFile<-paste0(prefix, "_DESeq2_sig.csv")
	if (file.exists(sigFile)) {
		sigTable<-read.csv(sigFile,header=TRUE,as.is=TRUE)
		if (nrow(sigTable)>0) {
			allSigNameList[[comparisonName]]<-sigTable[,1]
			allSigDirectionList[[comparisonName]]<-sign(sigTable$log2FoldChange)
		} else {
			warning(paste0("No significant genes in ",comparisonName))
#		allSigNameList[[comparisonName]]<-""
		}
	}
}

#Do venn if length between 2-5
if (length(allSigNameList)>=2 & length(allSigNameList)<=5) {
	venn.diagram1<-function (x, filename, height = 3000, width = 3000, resolution = 500, 
			units = "px", compression = "lzw", na = "stop", main = NULL, 
			sub = NULL, main.pos = c(0.5, 1.05), main.fontface = "plain", 
			main.fontfamily = "serif", main.col = "black", main.cex = 1, 
			main.just = c(0.5, 1), sub.pos = c(0.5, 1.05), sub.fontface = "plain", 
			sub.fontfamily = "serif", sub.col = "black", sub.cex = 1, 
			sub.just = c(0.5, 1), category.names = names(x), force.unique = TRUE,
			fill=NA,
			...) 
	{
		if (is.na(fill)) {
			if (length(x)==5) {
				fill = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3")
			} else if (length(x)==4) {
				fill = c("dodgerblue", "goldenrod1",  "seagreen3", "orchid3")
			} else if (length(x)==3) {
				fill = c("dodgerblue", "goldenrod1", "seagreen3")
			} else if (length(x)==2) {
				fill = c("dodgerblue", "goldenrod1")
			}
		}
		if (force.unique) {
			for (i in 1:length(x)) {
				x[[i]] <- unique(x[[i]])
			}
		}
		if ("none" == na) {
			x <- x
		}
		else if ("stop" == na) {
			for (i in 1:length(x)) {
				if (any(is.na(x[[i]]))) {
					stop("NAs in dataset", call. = FALSE)
				}
			}
		}
		else if ("remove" == na) {
			for (i in 1:length(x)) {
				x[[i]] <- x[[i]][!is.na(x[[i]])]
			}
		}
		else {
			stop("Invalid na option: valid options are \"none\", \"stop\", and \"remove\"")
		}
		if (0 == length(x) | length(x) > 5) {
			stop("Incorrect number of elements.", call. = FALSE)
		}
		if (1 == length(x)) {
			list.names <- category.names
			if (is.null(list.names)) {
				list.names <- ""
			}
			grob.list <- VennDiagram::draw.single.venn(area = length(x[[1]]), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else if (2 == length(x)) {
			grob.list <- VennDiagram::draw.pairwise.venn(area1 = length(x[[1]]), 
					area2 = length(x[[2]]), cross.area = length(intersect(x[[1]], 
									x[[2]])), category = category.names, ind = FALSE, 
					fill=fill,
					...)
		}
		else if (3 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			list.names <- category.names
			nab <- intersect(A, B)
			nbc <- intersect(B, C)
			nac <- intersect(A, C)
			nabc <- intersect(nab, C)
			grob.list <- VennDiagram::draw.triple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), n12 = length(nab), 
					n23 = length(nbc), n13 = length(nac), n123 = length(nabc), 
					category = list.names, ind = FALSE, list.order = 1:3, 
					fill=fill,
					...)
		}
		else if (4 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n34 <- intersect(C, D)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n134 <- intersect(n13, D)
			n234 <- intersect(n23, D)
			n1234 <- intersect(n123, D)
			grob.list <- VennDiagram::draw.quad.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					n12 = length(n12), n13 = length(n13), n14 = length(n14), 
					n23 = length(n23), n24 = length(n24), n34 = length(n34), 
					n123 = length(n123), n124 = length(n124), n134 = length(n134), 
					n234 = length(n234), n1234 = length(n1234), category = list.names, 
					ind = FALSE, fill=fill,...)
		}
		else if (5 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			E <- x[[5]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n15 <- intersect(A, E)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n25 <- intersect(B, E)
			n34 <- intersect(C, D)
			n35 <- intersect(C, E)
			n45 <- intersect(D, E)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n125 <- intersect(n12, E)
			n134 <- intersect(n13, D)
			n135 <- intersect(n13, E)
			n145 <- intersect(n14, E)
			n234 <- intersect(n23, D)
			n235 <- intersect(n23, E)
			n245 <- intersect(n24, E)
			n345 <- intersect(n34, E)
			n1234 <- intersect(n123, D)
			n1235 <- intersect(n123, E)
			n1245 <- intersect(n124, E)
			n1345 <- intersect(n134, E)
			n2345 <- intersect(n234, E)
			n12345 <- intersect(n1234, E)
			grob.list <- VennDiagram::draw.quintuple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					area5 = length(E), n12 = length(n12), n13 = length(n13), 
					n14 = length(n14), n15 = length(n15), n23 = length(n23), 
					n24 = length(n24), n25 = length(n25), n34 = length(n34), 
					n35 = length(n35), n45 = length(n45), n123 = length(n123), 
					n124 = length(n124), n125 = length(n125), n134 = length(n134), 
					n135 = length(n135), n145 = length(n145), n234 = length(n234), 
					n235 = length(n235), n245 = length(n245), n345 = length(n345), 
					n1234 = length(n1234), n1235 = length(n1235), n1245 = length(n1245), 
					n1345 = length(n1345), n2345 = length(n2345), n12345 = length(n12345), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else {
			stop("Invalid size of input object")
		}
		if (!is.null(sub)) {
			grob.list <- add.title(gList = grob.list, x = sub, pos = sub.pos, 
					fontface = sub.fontface, fontfamily = sub.fontfamily, 
					col = sub.col, cex = sub.cex)
		}
		if (!is.null(main)) {
			grob.list <- add.title(gList = grob.list, x = main, pos = main.pos, 
					fontface = main.fontface, fontfamily = main.fontfamily, 
					col = main.col, cex = main.cex)
		}
		grid.newpage()
		grid.draw(grob.list)
		return(1)
#	return(grob.list)
	}
	png(paste0(taskName,"_significantVenn.png"),res=300,height=2000,width=2000)
	venn.diagram1(allSigNameList)
	dev.off()
}
#Do heatmap significant genes if length larger or equal than 2
if (length(allSigNameList)>=2) {
	temp<-cbind(unlist(allSigNameList),unlist(allSigDirectionList))
	colnames(temp)<-c("Gene","Direction")
	temp<-cbind(temp,comparisonName=rep(names(allSigNameList),sapply(allSigNameList,length)))
	temp<-data.frame(temp)
	dataForFigure<-temp
	#geting dataForFigure order in figure
	temp$Direction<-as.integer(as.character(temp$Direction))
	temp<-acast(temp, Gene~comparisonName ,value.var="Direction")
	temp<-temp[do.call(order, data.frame(temp)),]
	maxNameChr<-max(nchar(row.names(temp)))
	if (maxNameChr>70) {
		row.names(temp)<-substr(row.names(temp),0,70)
		dataForFigure$Gene<-substr(dataForFigure$Gene,0,70)
		warning(paste0("The gene names were too long (",maxNameChr,"). Only first 70 letters were kept."))
	}
	dataForFigure$Gene<-factor(dataForFigure$Gene,levels=row.names(temp))
	
	width=max(2500, 60 * length(unique(dataForFigure$comparisonName)))
	height=max(2000, 40 * length(unique(dataForFigure$Gene)))
	png(paste0(taskName,"_significantHeatmap.png"),res=300,height=height,width=width)
	g<-ggplot(dataForFigure, aes(comparisonName, Gene))+
			geom_tile(aes(fill=Direction), color="white") +
			scale_fill_manual(values=c("light green", "red")) +
			theme(axis.text.x = element_text(angle=90, vjust=0.5, size=11, hjust=0.5, face="bold"),
					axis.text.y = element_text(size=11, face="bold")) +
			coord_equal()
	print(g)
	dev.off()
}


##predefined_condition_begin
# setwd("h:/temp")  
#   
# data<-read.table("Z:/Shared/Labs/Brown,J/tiger/20160509_brown_3436/star_genetable/result/B3436_gene.count",row.names=1, header=T, check.names=F)
# 
# taskName<-'B3436'
# showLabelInPCA<-1
# showDEGeneCluster<-0
# pvalue<-0.05
# foldChange<-2
# minMedianInGroup<-5
# addCountOne<-0
# 
# comparisons=list(
#   "CAPTISOL_vs_FED" = c("CAPTISOL_vs_FED.design", "FED", "CAPTISOL")
# ) 
#
##predefined_condition_end

library("DESeq2")
library("heatmap3")
library("lattice")
library("reshape")
library("ggplot2")
library("grid")
library("scales")
library("reshape2")
library("VennDiagram")

##Solving node stack overflow problem start###
#when there are too many genes, drawing dendrogram may failed due to node stack overflow,
#It could be solved by forcing stats:::plotNode to be run as interpreted code rather then byte-compiled code via a nasty hack.
#http://stackoverflow.com/questions/16559250/error-in-heatmap-2-gplots/25877485#25877485

# Convert a byte-compiled function to an interpreted-code function 
unByteCode <- function(fun)
{
  FUN <- eval(parse(text=deparse(fun)))
  environment(FUN) <- environment(fun)
  FUN
}

# Replace function definition inside of a locked environment **HACK** 
assignEdgewise <- function(name, env, value)
{
  unlockBinding(name, env=env)
  assign( name, envir=env, value=value)
  lockBinding(name, env=env)
  invisible(value)
}

# Replace byte-compiled function in a locked environment with an interpreted-code
# function
unByteCodeAssign <- function(fun)
{
  name <- gsub('^.*::+','', deparse(substitute(fun)))
  FUN <- unByteCode(fun)
  retval <- assignEdgewise(name=name,
                           env=environment(FUN),
                           value=FUN
  )
  invisible(retval)
}

# Use the above functions to convert stats:::plotNode to interpreted-code:
unByteCodeAssign(stats:::plotNode)

# Now raise the interpreted code recursion limit (you may need to adjust this,
#  decreasing if it uses to much memory, increasing if you get a recursion depth error ).
options(expressions=5e4)

##Solving node stack overflow problem end###

hmcols <- colorRampPalette(c("green", "black", "red"))(256)

drawHCA<-function(prefix, rldselect, ispaired, designData, conditionColors, gnames){
  htfile<-paste0(prefix, "_DESeq2-vsd-heatmap.png")
  cat("saving HCA to ", htfile, "\n")
  genecount<-nrow(rldselect)
  if(genecount > 2){
    png(filename=htfile, width=3000, height =3000, res=300)
    cexCol = max(1.0, 0.2 + 1/log10(ncol(rldselect)))
    if(ispaired){
      htColors<-rainbow(length(unique(designData$Paired)))
      gsColors<-as.matrix(data.frame(Group=conditionColors, Sample=htColors[designData$Paired]))
    }else{
      gsColors = conditionColors;
    }
    heatmap3(rldselect, 
             col = hmcols, 
             ColSideColors = gsColors, 
             margins=c(12,5), 
             scale="r", 
             dist=dist, 
             labRow=NA,
             main=paste0("Hierarchical Cluster Using ", genecount, " Genes"),  
             cexCol=cexCol, 
             useRaster=FALSE,
             legendfun=function() showLegend(legend=paste0("Group ", gnames), col=c("red","blue"),cex=1.0,x="center"))
    dev.off()
  }
}

drawPCA<-function(prefix, rldmatrix, showLabelInPCA, designData, conditionColors){
  #filename<-paste0(prefix, "_DESeq2-vsd-pca.png")
  filename<-paste0(prefix, "_DESeq2-vsd-pca.pdf")
  genecount<-nrow(rldmatrix)
  if(genecount > 2){
    cat("saving PCA to ", filename, "\n")
    #png(filename=filename, width=3000, height=3000, res=300) # 10 X 10 inches
    pdf(filename, width=10, height=10)
    pca<-prcomp(t(rldmatrix))
    supca<-summary(pca)$importance
    pcadata<-data.frame(pca$x)
    pcalabs=paste0(colnames(pcadata), "(", round(supca[2,] * 100), "%)")
    pcadata["sample"]<-row.names(pcadata)
    
    if(showLabelInPCA){
      g <- ggplot(pcadata, aes(x=PC1, y=PC2, label=sample)) + 
        geom_text(vjust=-0.6, size=4) +
        geom_point(col=conditionColors, size=4) + 
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) +
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) + 
        xlab(pcalabs[1]) + ylab(pcalabs[2])
    }else{
      g <- ggplot(pcadata, aes(x=PC1, y=PC2)) + 
        geom_point(col=conditionColors, size=4) + 
        labs(color = "Group") +
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) + 
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) +
        xlab(pcalabs[1]) + ylab(pcalabs[2]) + 
        theme(legend.position="top")
    }
    
    print(g)
    dev.off()
  }
}

#for volcano plot
reverselog_trans <- function(base = exp(1)) {
  trans <- function(x) -log(x, base)
  inv <- function(x) base^(-x)
  trans_new(paste0("reverselog-", format(base)), trans, inv, 
            log_breaks(base = base), 
            domain = c(1e-100, Inf))
}

isDataNumeric = unlist(lapply(data[1,], function(x){is.numeric(x)}))
if (any(isDataNumeric)) {
  index = 1
  while(!all(isDataNumeric[index:ncol(data)])){
    index = index + 1
  }
} else {
  cat("Error: No numeric data found for DESeq2 \n")
  quit(save="yes")
}

if(index > 1){
  indecies<-c(1:(index-1))
}else{
  indecies<-c()
}
countData<-data[,c(index:ncol(data))]

countData[is.na(countData)] <- 0

if(addCountOne){
  countData<-round(countData)+1
}

comparisonNames=names(comparisons)
comparisonName=comparisonNames[1]

dir.create("details", showWarnings = FALSE)

pairedspearman<-list()
resultAllOut<-data
resultAllOutVar<-c("log2FoldChange","pvalue","padj")
for(comparisonName in comparisonNames){
  str(comparisonName)
  designFile=comparisons[[comparisonName]][1]
  gnames=comparisons[[comparisonName]][2:3]
  designData<-read.table(designFile, sep="\t", header=T)
  designData$Condition<-factor(designData$Condition, levels=gnames)
  
  if(ncol(designData) >= 3){
    cat("Data with covariances!\n")
  }else{
    cat("Data without covariances!\n")
  }
  if (any(colnames(designData)=="Paired")) {
	  ispaired<-TRUE
	  cat("Paired Data!\n")
  }else{
	  ispaired<-FALSE
	  cat("Not Paired Data!\n")
  }
  temp<-apply(designData,2,function(x) length(unique(x)))
  if (any(temp==1)) {
	  cat(paste0("Factors with only 1 level in design matrix: ",colnames(designData)[which(temp==1)],"\n"))
	  cat("They will be removed")
	  cat("\n")
	  designData<-designData[,which(temp!=1)]
  }
  temp<-apply(designData[,-1,drop=F],2,rank)
  if (length(unique(rowSums(temp)))==1 | identical(temp[,1],temp[,-1])) {
	  cat(paste0("The model matrix is not full rank, so the model cannot be fit as specified"))
	  cat("\n")
	  cat("Only Condition variable will be kept.")
	  cat("\n")
	  designData<-designData[,which(colnames(designData)%in% c("Sample","Condition"))]
  }
  
  comparisonData<-countData[,colnames(countData) %in% as.character(designData$Sample),drop=F]
  if(ncol(comparisonData) != nrow(designData)){
	message=paste0("Data not matched, there are ", nrow(designData), " samples in design file ", designFile, " but ", ncol(comparisonData), " samples in data ")
	warning(message)
	writeLines(message,paste0(comparisonName,".error"))
	next
  }
  comparisonData<-comparisonData[,as.character(designData$Sample)]
  
  prefix<-comparisonName
  curdata<-data
  if(minMedianInGroup > 0){
    conds<-unique(designData$Condition)
    data1<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[1]]]
    data2<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[2]]]
    med1<-apply(data1, 1, median) >= minMedianInGroup
    med2<-apply(data2, 1, median) >= minMedianInGroup
    med<-med1 | med2
    comparisonData<-comparisonData[med,]
    cat(nrow(comparisonData), " genes with minimum median count in group larger or equals than ", minMedianInGroup, "\n")
    
    if (nrow(comparisonData)==0) {
		message=paste0("Error: 0 Genes can be used in DESeq2 analysis in comparison ",comparisonName," \n")
		warning(message)
		writeLines(message,paste0(comparisonName,".error"))
      next;
    }
    
    prefix<-paste0(comparisonName, "_min", minMedianInGroup)
    curdata<-data[med,]
  }
  
  if(ispaired){
    pairedSamples = unique(designData$Paired)
    
    spcorr<-unlist(lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      cor(comparisonData[,samples[1]],comparisonData[,samples[2]],method="spearman")
    }))
    
    
    sptable<-data.frame(Name=pairedSamples, Spcorr=spcorr)
    write.csv(sptable, file=paste0(prefix, "_Spearman.csv"), row.names=FALSE)
    
    lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      log2c1<-log2(comparisonData[,samples[1]]+1)
      log2c2<-log2(comparisonData[,samples[2]]+1)
      png(paste0("details/", prefix, "_Spearman_", pairedSamples[x], ".png"), width=2000, height=2000, res=300)
      plot(log2c1, log2c2, xlab=paste0(samples[1], " [log2(Count + 1)]"), ylab=paste0(samples[2], " [log2(Count + 1)]"))
      text(3,15,paste0("SpearmanCorr=", sprintf("%0.3f", spcorr[x])))
      dev.off()
    })
    
    pairedspearman[[comparisonName]]<-spcorr
  }
  
  notEmptyData<-apply(comparisonData, 1, max) > 0
  comparisonData<-comparisonData[notEmptyData,]
  curdata<-curdata[notEmptyData,]
  
  if(ispaired){
    colnames(comparisonData)<-unlist(lapply(c(1:ncol(comparisonData)), function(i){paste0(designData$Paired[i], "_", colnames(comparisonData)[i])}))
  }
  rownames(designData)<-colnames(comparisonData)
  conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
  
  write.csv(comparisonData, file=paste0(prefix, ".csv"))
  
  #some basic graph
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                             colData = designData,
                             design = ~1)
  
  colnames(dds)<-colnames(comparisonData)
  
  #draw density graph
  rldmatrix<-as.matrix(log2(counts(dds,normalized=FALSE) + 1))
  rsdata<-melt(rldmatrix)
  colnames(rsdata)<-c("Gene", "Sample", "log2Count")
  png(filename=paste0(prefix, "_DESeq2-log2-density.png"), width=4000, height=3000, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  width=max(4000, ncol(rldmatrix) * 40 + 1000)
  height=max(3000, ncol(rldmatrix) * 40)
  png(filename=paste0(prefix, "_DESeq2-log2-density-individual.png"), width=width, height=height, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + facet_wrap(~Sample, scales = "free") + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  
  #varianceStabilizingTransformation
  
  allDesignData<-designData
  allComparisonData<-comparisonData
  
  excludedSample<-c()
  zeronumbers<-apply(comparisonData, 2, function(x){sum(x==0)})
  zeronumbers<-names(zeronumbers[order(zeronumbers)])
  percent10<-max(1, round(length(zeronumbers) * 0.1))
  
  removed<-0
  
  excludedCountFile<-paste0(prefix, "_DESeq2-exclude-count.csv")
  excludedDesignFile<-paste0(prefix, "_DESeq2-exclude-design.csv")
  if(file.exists(excludedCountFile)){
    file.remove(excludedCountFile)
  }
  if(file.exists(excludedDesignFile)){
    file.remove(excludedDesignFile)
  }
  
  fitType<-"parametric"
  while(1){
    #varianceStabilizingTransformation
    vsdres<-try(vsd <- varianceStabilizingTransformation(dds, blind=TRUE,fitType=fitType))
    if(class(vsdres) == "try-error" && grepl("every gene contains at least one zero", vsdres[1])){
      removed<-removed+1
      keptNumber<-length(zeronumbers) - percent10 * removed
      keptSample<-zeronumbers[1:keptNumber]
      excludedSample<-zeronumbers[(keptNumber+1):length(zeronumbers)]
      
      comparisonData<-comparisonData[, colnames(comparisonData) %in% keptSample]
      designData<-designData[rownames(designData) %in% keptSample,]
      dds=DESeqDataSetFromMatrix(countData = comparisonData,
                                 colData = designData,
                                 design = ~1)
      
      colnames(dds)<-colnames(comparisonData)
    } else if (class(vsdres) == "try-error" && grepl("newsplit: out of vertex space", vsdres[1])) {
		message=paste0("Warning: varianceStabilizingTransformation function can't run. fitType was set to local to try again")
		warning(message)
		fitType<-"mean"
		writeLines(message,paste0(comparisonName,".error"))
	} else{
      conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
      break
    }
  }
  if (nrow(comparisonData)<=1) {
	  message=paste0("Error: All genes in ",comparisonName," has at least one 0 value. Can't do DESeq2.")
	  warning(message)
	  writeLines(message,paste0(comparisonName,".error"))
	  next;
  }
  
  if(length(excludedSample) > 0){
    excludedCountData<-allComparisonData[,colnames(allComparisonData) %in% excludedSample]
    write.csv(file=excludedCountFile, excludedCountData)
    excludedDesignData<-allDesignData[rownames(allDesignData) %in% excludedSample,]
    write.csv(file=excludedDesignFile, excludedDesignData)
  }
  
  assayvsd<-assay(vsd)
  write.csv(assayvsd, file=paste0(prefix, "_DESeq2-vsd.csv"))
  
  vsdiqr<-apply(assayvsd, 1, IQR)
  assayvsd<-assayvsd[order(vsdiqr, decreasing=T),]
  
  rldmatrix=as.matrix(assayvsd)
  
  #draw pca graph
  drawPCA(paste0(prefix,"_geneAll"), rldmatrix, showLabelInPCA, designData, conditionColors)
  
  #draw heatmap
  #drawHCA(paste0(prefix,"_gene500"), rldmatrix[1:min(500, nrow(rldmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  drawHCA(paste0(prefix,"_geneAll"), rldmatrix, ispaired, designData, conditionColors, gnames)
  
  #different expression analysis
  designFormula=as.formula(paste0("~",paste0(c(colnames(designData)[-c(1:2)],"Condition"),collapse="+")))
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                               colData = designData,
                               design = designFormula)
  
  dds <- DESeq(dds,fitType=fitType)
  res<-results(dds,cooksCutoff=FALSE)
  
  cat("DESeq2 finished.\n")
  
  select<-(!is.na(res$padj)) & (res$padj<pvalue) & ((res$log2FoldChange >= log2(foldChange)) | (res$log2FoldChange <= -log2(foldChange)))
  
  if(length(indecies) > 0){
    inddata<-curdata[,indecies,drop=F]
    tbb<-cbind(inddata, comparisonData, res)
  }else{
    tbb<-cbind(comparisonData, res)
  }
  tbb$FoldChange<-2^tbb$log2FoldChange
  tbbselect<-tbb[select,,drop=F]
  tbbAllOut<-as.data.frame(tbb[,resultAllOutVar,drop=F])
  tbbAllOut$Significant<-select
  colnames(tbbAllOut)<-paste0(colnames(tbbAllOut)," (",comparisonName,")")
  resultAllOut<-cbind(resultAllOut,tbbAllOut[row.names(resultAllOut),])

  tbb<-tbb[order(tbb$padj),,drop=F]
  write.csv(as.data.frame(tbb),paste0(prefix, "_DESeq2.csv"))

  if("Feature_gene_name" %in% colnames(tbb)){
    gsea<-tbb[,c("Feature_gene_name", "stat"),drop=F]
    write.table(gsea,paste0(prefix, "_DESeq2_GSEA.rnk"),row.names=F,col.names=F,sep="\t")
  }

  tbbselect<-tbbselect[order(tbbselect$padj),,drop=F]
  write.csv(as.data.frame(tbbselect),paste0(prefix, "_DESeq2_sig.csv"))
  
  if(showDEGeneCluster){
    siggenes<-rownames(rldmatrix) %in% rownames(tbbselect)
    
    nonDEmatrix<-rldmatrix[!siggenes,,drop=F]
    DEmatrix<-rldmatrix[siggenes,,drop=F]
    
    drawPCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, ispaired, designData, conditionColors, gnames)
    
    drawPCA(paste0(prefix,"_geneDE"),DEmatrix , showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneDE"),DEmatrix , ispaired, designData, conditionColors, gnames)
    #drawHCA(paste0(prefix,"_gene500NotDE"), nonDEmatrix[1:min(500, nrow(nonDEmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  }
  
  #Top 25 Significant genes barplot
  sigDiffNumber<-nrow(tbbselect)
  if (sigDiffNumber>0) {
    if (sigDiffNumber>25) {
      print(paste0("More than 25 genes were significant. Only the top 25 genes will be used in barplot"))
      diffResultSig<-tbbselect[order(tbbselect$padj)[1:25],]
    } else {
      diffResultSig<-tbbselect
    }
    if("Feature_gene_name" %in% colnames(diffResultSig)){
      diffResultSig$Name<-as.character(diffResultSig$Feature_gene_name)
    }else{
      diffResultSig$Name<-sapply(strsplit(row.names(diffResultSig),";"),function(x) x[1])
    }
    diffResultSig$Name <- factor(diffResultSig$Name, levels=diffResultSig$Name[order(diffResultSig$log2FoldChange)])
    diffResultSig<-as.data.frame(diffResultSig)
    
    png(filename=paste0(prefix, "_DESeq2_sig_barplot.png"), width=3000, height=3000, res=300)
    #	  pdf(paste0(prefix,"_DESeq2_sig_barplot.pdf"))
    p<-ggplot(diffResultSig,aes(x=Name,y=log2FoldChange,order=log2FoldChange))+geom_bar(stat="identity")+
      coord_flip()+
      #			geom_abline(slope=0,intercept=1,colour="red",linetype = 2)+
      scale_y_continuous(name=bquote(log[2]~Fold~Change))+
      theme(axis.text = element_text(colour = "black"))
    print(p)
    dev.off()
  } else {
    print(paste0("No gene with adjusted p value less than ",pvalue," and fold change larger than ",foldChange))
  }
  
  #volcano plot
  changeColours<-c(grey="grey",blue="blue",red="red")
  diffResult<-as.data.frame(tbb)
  diffResult$log10BaseMean<-log10(diffResult$baseMean)
  diffResult$colour<-"grey"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange>=log2(foldChange))]<-"red"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange<=-log2(foldChange))]<-"blue"
  png(filename=paste0(prefix, "_DESeq2_volcanoPlot.png"), width=3000, height=3000, res=300)
  #  pdf(paste0(prefix,"_DESeq2_volcanoPlot.pdf"))
  p<-ggplot(diffResult,aes(x=log2FoldChange,y=padj))+
    geom_point(aes(size=log10BaseMean,colour=colour))+
    scale_color_manual(values=changeColours,guide = FALSE)+
    scale_y_continuous(trans=reverselog_trans(10),name=bquote(Adjusted~p~value))+
    scale_x_continuous(name=bquote(log[2]~Fold~Change))+
    geom_hline(yintercept = 1,colour="grey",linetype = "dotted")+
    geom_vline(xintercept = 0,colour="grey",linetype = "dotted")+
    guides(size=guide_legend(title=bquote(log[10]~Base~Mean)))+
    theme_bw()+
    scale_size(range = c(3, 7))+
    theme(axis.text = element_text(colour = "black",size=30),
			axis.title = element_text(size=30),
			legend.text= element_text(size=30),
			legend.title= element_text(size=30))
  print(p)
  dev.off()
}

#write a file with all information
write.csv(resultAllOut,paste0(taskName, "_DESeq2.csv"))

if(length(pairedspearman) > 0){
  #draw pca graph
  filename<-ifelse(minMedianInGroup > 0, paste0("spearman_min", minMedianInGroup, ".png"), "spearman.png")
  png(filename=filename, width=1000 * length(pairedspearman), height=2000, res=300)
  boxplot(pairedspearman)
  dev.off()
}

#Venn for all significant genes
allSigNameList<-list()
allSigDirectionList<-list()
for(comparisonName in comparisonNames){
	if (minMedianInGroup > 0) {
		prefix<-paste0(comparisonName, "_min", minMedianInGroup)
	} else {
		prefix<-comparisonName
	}
	sigFile<-paste0(prefix, "_DESeq2_sig.csv")
	if (file.exists(sigFile)) {
		sigTable<-read.csv(sigFile,header=TRUE,as.is=TRUE)
		if (nrow(sigTable)>0) {
			allSigNameList[[comparisonName]]<-sigTable[,1]
			allSigDirectionList[[comparisonName]]<-sign(sigTable$log2FoldChange)
		} else {
			warning(paste0("No significant genes in ",comparisonName))
#		allSigNameList[[comparisonName]]<-""
		}
	}
}

#Do venn if length between 2-5
if (length(allSigNameList)>=2 & length(allSigNameList)<=5) {
	venn.diagram1<-function (x, filename, height = 3000, width = 3000, resolution = 500, 
			units = "px", compression = "lzw", na = "stop", main = NULL, 
			sub = NULL, main.pos = c(0.5, 1.05), main.fontface = "plain", 
			main.fontfamily = "serif", main.col = "black", main.cex = 1, 
			main.just = c(0.5, 1), sub.pos = c(0.5, 1.05), sub.fontface = "plain", 
			sub.fontfamily = "serif", sub.col = "black", sub.cex = 1, 
			sub.just = c(0.5, 1), category.names = names(x), force.unique = TRUE,
			fill=NA,
			...) 
	{
		if (is.na(fill)) {
			if (length(x)==5) {
				fill = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3")
			} else if (length(x)==4) {
				fill = c("dodgerblue", "goldenrod1",  "seagreen3", "orchid3")
			} else if (length(x)==3) {
				fill = c("dodgerblue", "goldenrod1", "seagreen3")
			} else if (length(x)==2) {
				fill = c("dodgerblue", "goldenrod1")
			}
		}
		if (force.unique) {
			for (i in 1:length(x)) {
				x[[i]] <- unique(x[[i]])
			}
		}
		if ("none" == na) {
			x <- x
		}
		else if ("stop" == na) {
			for (i in 1:length(x)) {
				if (any(is.na(x[[i]]))) {
					stop("NAs in dataset", call. = FALSE)
				}
			}
		}
		else if ("remove" == na) {
			for (i in 1:length(x)) {
				x[[i]] <- x[[i]][!is.na(x[[i]])]
			}
		}
		else {
			stop("Invalid na option: valid options are \"none\", \"stop\", and \"remove\"")
		}
		if (0 == length(x) | length(x) > 5) {
			stop("Incorrect number of elements.", call. = FALSE)
		}
		if (1 == length(x)) {
			list.names <- category.names
			if (is.null(list.names)) {
				list.names <- ""
			}
			grob.list <- VennDiagram::draw.single.venn(area = length(x[[1]]), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else if (2 == length(x)) {
			grob.list <- VennDiagram::draw.pairwise.venn(area1 = length(x[[1]]), 
					area2 = length(x[[2]]), cross.area = length(intersect(x[[1]], 
									x[[2]])), category = category.names, ind = FALSE, 
					fill=fill,
					...)
		}
		else if (3 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			list.names <- category.names
			nab <- intersect(A, B)
			nbc <- intersect(B, C)
			nac <- intersect(A, C)
			nabc <- intersect(nab, C)
			grob.list <- VennDiagram::draw.triple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), n12 = length(nab), 
					n23 = length(nbc), n13 = length(nac), n123 = length(nabc), 
					category = list.names, ind = FALSE, list.order = 1:3, 
					fill=fill,
					...)
		}
		else if (4 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n34 <- intersect(C, D)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n134 <- intersect(n13, D)
			n234 <- intersect(n23, D)
			n1234 <- intersect(n123, D)
			grob.list <- VennDiagram::draw.quad.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					n12 = length(n12), n13 = length(n13), n14 = length(n14), 
					n23 = length(n23), n24 = length(n24), n34 = length(n34), 
					n123 = length(n123), n124 = length(n124), n134 = length(n134), 
					n234 = length(n234), n1234 = length(n1234), category = list.names, 
					ind = FALSE, fill=fill,...)
		}
		else if (5 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			E <- x[[5]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n15 <- intersect(A, E)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n25 <- intersect(B, E)
			n34 <- intersect(C, D)
			n35 <- intersect(C, E)
			n45 <- intersect(D, E)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n125 <- intersect(n12, E)
			n134 <- intersect(n13, D)
			n135 <- intersect(n13, E)
			n145 <- intersect(n14, E)
			n234 <- intersect(n23, D)
			n235 <- intersect(n23, E)
			n245 <- intersect(n24, E)
			n345 <- intersect(n34, E)
			n1234 <- intersect(n123, D)
			n1235 <- intersect(n123, E)
			n1245 <- intersect(n124, E)
			n1345 <- intersect(n134, E)
			n2345 <- intersect(n234, E)
			n12345 <- intersect(n1234, E)
			grob.list <- VennDiagram::draw.quintuple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					area5 = length(E), n12 = length(n12), n13 = length(n13), 
					n14 = length(n14), n15 = length(n15), n23 = length(n23), 
					n24 = length(n24), n25 = length(n25), n34 = length(n34), 
					n35 = length(n35), n45 = length(n45), n123 = length(n123), 
					n124 = length(n124), n125 = length(n125), n134 = length(n134), 
					n135 = length(n135), n145 = length(n145), n234 = length(n234), 
					n235 = length(n235), n245 = length(n245), n345 = length(n345), 
					n1234 = length(n1234), n1235 = length(n1235), n1245 = length(n1245), 
					n1345 = length(n1345), n2345 = length(n2345), n12345 = length(n12345), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else {
			stop("Invalid size of input object")
		}
		if (!is.null(sub)) {
			grob.list <- add.title(gList = grob.list, x = sub, pos = sub.pos, 
					fontface = sub.fontface, fontfamily = sub.fontfamily, 
					col = sub.col, cex = sub.cex)
		}
		if (!is.null(main)) {
			grob.list <- add.title(gList = grob.list, x = main, pos = main.pos, 
					fontface = main.fontface, fontfamily = main.fontfamily, 
					col = main.col, cex = main.cex)
		}
		grid.newpage()
		grid.draw(grob.list)
		return(1)
#	return(grob.list)
	}
	png(paste0(taskName,"_significantVenn.png"),res=300,height=2000,width=2000)
	venn.diagram1(allSigNameList)
	dev.off()
}
#Do heatmap significant genes if length larger or equal than 2
if (length(allSigNameList)>=2) {
	temp<-cbind(unlist(allSigNameList),unlist(allSigDirectionList))
	colnames(temp)<-c("Gene","Direction")
	temp<-cbind(temp,comparisonName=rep(names(allSigNameList),sapply(allSigNameList,length)))
	temp<-data.frame(temp)
	dataForFigure<-temp
	#geting dataForFigure order in figure
	temp$Direction<-as.integer(as.character(temp$Direction))
	temp<-acast(temp, Gene~comparisonName ,value.var="Direction")
	temp<-temp[do.call(order, data.frame(temp)),]
	maxNameChr<-max(nchar(row.names(temp)))
	if (maxNameChr>70) {
		row.names(temp)<-substr(row.names(temp),0,70)
		dataForFigure$Gene<-substr(dataForFigure$Gene,0,70)
		warning(paste0("The gene names were too long (",maxNameChr,"). Only first 70 letters were kept."))
	}
	dataForFigure$Gene<-factor(dataForFigure$Gene,levels=row.names(temp))
	
	width=max(2500, 60 * length(unique(dataForFigure$comparisonName)))
	height=max(2000, 40 * length(unique(dataForFigure$Gene)))
	png(paste0(taskName,"_significantHeatmap.png"),res=300,height=height,width=width)
	g<-ggplot(dataForFigure, aes(comparisonName, Gene))+
			geom_tile(aes(fill=Direction), color="white") +
			scale_fill_manual(values=c("light green", "red")) +
			theme(axis.text.x = element_text(angle=90, vjust=0.5, size=11, hjust=0.5, face="bold"),
					axis.text.y = element_text(size=11, face="bold")) +
			coord_equal()
	print(g)
	dev.off()
}


                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
#        list12 <- stocklistperiod[period, 2][[1]]
#        for (i in 1:max) {
#            print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
#        }
        for (i in 1:max) {
            id <- list11$id[i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
            }
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), rise, list11$id[[i]]))
        }
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, periodtext, maindate, olddate, days) {
    dev.new()
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (type == pricetype) {
        return (df$price)
    }
    if (type == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    normalize <- 0
    if (length(ids) > 0) {
        if (periodtext == "price") {
            normalize <- 1
        }
        if (periodtext == "index") {
            normalize <- 1
        }
    }
    
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, pricetype)
        perioddata[["text"]] <- pairs
        perioddatamap[["price"]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, indextype)
        perioddata[["text"]] <- pairs
        perioddatamap[["index"]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    ls <- list()
    names <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        if (normalize == 1) {
                            str("minmax")
                            str(l)
                            mymin <- abs(min(l))
                            mymax <- abs(max(l))
                            if (mymin > mymax) {
                                mymax <- mymin
                            }
                            for (j in 1:length(l)) {
                                l[j] <- l[j] * 100 / mymax;
                            }
                            str(l)
                        }
                        
                        dayset <- bigretl[[2]]
                        daynames <- names(dayset)
                        olddate <- min(daynames)
                        newdate <- max(daynames)
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        names[c] <- df$name
                    }
                }
            }
        }
    }
    displaychart(ls, names, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

#' Print a bp length nicely
#' 
#' \code{prettybp} returns a string representation of a base pair length with optional rounding
#' 
#' @param n base pairs
#' @param round.digits (optional) number of digits to round to. Default is 2. Set
#' to NULL to disable rounding. This value is ignored if signif.digits is not \code{NULL}.
#' @param signif.digits (optional) set this if rounding to significant digits
#' is preferred.
#' @param space Set to false to eliminate the space between the number and unit.
#' @seealso \code{\link{draw.chrom.axis}} for drawing a bp scaled x-axis 
#' @export
prettybp <- function (n, round.digits=2, signif.digits=NULL, space=TRUE) {
  if ( space ) {
    use.sep <- ' '
  } else {
    use.sep <- ''
  }
  if ( log10(mean(n)) >= 6 ) {
    if ( !is.null(signif.digits) ) {
      return ( paste(signif(n/1e6, signif.digits), 'Mb', sep=use.sep))
    } else if ( !is.null(round.digits) ) {
      return ( paste(round(n/1e6, round.digits), 'Mb', sep=use.sep))
    }
    return ( paste(n/1e6, 'Mb', sep=use.sep))
  } else if ( log10(n) >= 3) {
    if ( !is.null(signif.digits) ) {
      return ( paste(signif(n/1e3, signif.digits), 'kb', sep=use.sep))
    } else if ( !is.null(round.digits) ) {
      return ( paste(round(n/1e3, round.digits), 'kb', sep=use.sep))
    }
    return ( paste(n/1e3, 'kb', sep=use.sep))
  }
  if ( !is.null(signif.digits) ) {
    return ( paste(signif(n, signif.digits), 'bp', sep=use.sep))
  } else if ( !is.null(round.digits) ) {
    return ( paste(round(n, round.digits), 'bp', sep=use.sep))
  }
  return ( paste(n, 'bp', sep=use.sep) )
}

#' Draw a horizontal chromosome axis
#' 
#' \code{draw.chrom.axis} draws a chromosome axis with appropriate scale (Mb, kb, or bp).
#' 
#' @param start.pos Starting position on the chromosome (in bp)
#' @param end.pos Ending position on the chromosome (in bp)
#' @param ... (optional) addition options to pass to \code{text} for drawing
#' labels
#' @seealso \code{\link{draw.scale}} for drawing a color scale bar
#' @export
draw.chrom.axis <- function(start.pos, end.pos, chrom=NULL, label.chrom=TRUE,
                            label.scale=TRUE, tick.length=0.1, ...) {
  plot(0, type='n', ylim=c(-1, 1), xlim=c(start.pos, end.pos),
       axes=FALSE, bty='n', xlab='', ylab='', yaxs='i')
  
  abline(h=0, xpd=FALSE)
  
  ticks.at <- axTicks(1)
  plot.height <- par('pin')[2]
  sapply(ticks.at, function (x) { lines(c(x, x), c(-tick.length, tick.length)/plot.height)})
  text(ticks.at, rep(0, length(ticks.at)), ticks.at/1e6, pos=1, xpd=NA, ...)
  if ( label.scale ) {
    text(par('usr')[2], 0, 'Mb', pos=4, xpd=NA, ...)
  }
  if ( !is.null(chrom) && label.chrom ) {
    text(par('usr')[1], 0, chrom, pos=2, xpd=NA, ...)
  }
}


#' Assign colors to value according to a scale
#' 
#' \code{draw.scale} takes a vector of values, a color vector, and a range
#' vector and returns colors for plotting those values
#' 
#' 
#' @param x values to be plotted
#' @param scale.colors a vector of colors
#' @param scale.range range for scale (vector with 2 numeric elements)
#' @param all.inside If TRUE, out-of-range points are colored with the ends of
#' the color scale. If FALSE, they will be assigned no color (NA). 
#' @seealso \code{\link{draw.scale}} for drawing a color scale
#' @export
assign.scale.colors <- function(x, scale.colors, scale.range, all.inside=TRUE) {
  x.missing <- is.na(x)
  
  x[x.missing] <- mean(x, na.rm=TRUE)
  
  if ( missing(scale.range) ) scale.range <- range(x)
  xbins <- seq(min(scale.range), max(scale.range), length.out=length(scale.colors)+1)
  color.idx <- findInterval(x, xbins, rightmost.closed=TRUE, all.inside=all.inside)
  if ( scale.range[1] > scale.range[2] )
    color.idx <- 1+length(scale.colors)-color.idx
  
  
  x.colors <- scale.colors[color.idx]
  x.colors[x.missing | color.idx == 0 | color.idx > length(scale.colors)] <- NA
  return ( x.colors )
}




#' Draw a color scale bar
#' 
#' Adds a color scale legend to the current plot with specified colors and range.
#' 
#' 
#' @param scale.colors a vector of colors
#' @param scale.range range for scale (vector with 2 numeric elements, e.g. as returned by \code{range()})
#' @param num.labs (default 6) number of text labels to draw
#' @param pos (default topright)position for scale, either a keyword such as "top", "topleft" or a numeric vector length 2
#' @param adj controls the anchoring of the scale in respect to \code{pos}
#' @param horiz  TRUE for horizontal (default) or FALSE for vertical bar
#' @param outside TRUE to display legend within the plotting area (default) or FALSE to place it outside
#' @param size approximate length in inches
#' @param ratio ratio of scale bar width to height
#' @param tick.length number between 0 and 1, controls how long the ticks are vs the color boxes. 
#' @param scale.offset inset (outset) amount for legend that is inside (outside)
#' @param label.offset spacing between ticks and text labels
#' @param box this controls whether a black border is drawn around the colors or not.
#' @param x.shift (optional) adjust x position in units of scale width.
#' @param y.shift (optional) adjust y position in units of scale height.
#' 
#' @details This function draws a color scale bar in the current plot. Position argument
#' \code{pos} can be specified by keyword: \code{'center'}, \code{'middle'},
#' \code{'topleft'}, \code{'topright'}, \code{'top'}, \code{'bottomleft'},
#' \code{'bottomright'}, \code{'bottom'}, \code{'left'}, or \code{'right'}.
#' Alternately \code{pos} can be set by specifying a numeric vector of length 2,
#' describing the x and y locations of legend, where each is a number between 0
#' (left/bottom) and 1 (right/top). The \code{adj} argument controls the anchor
#' point for the legend itself relative to the plot. If unspecified, it will
#' match \code{pos}, if \code{outside} is \code{FALSE} (default) or \code{1-pos}
#' if \code{outside} is \code{TRUE}. This alignment is offset by \code{scale.offset}
#' so that the legend does not overlap the plot border.
#' 
#' The position can be further tweaked using the \code{x.shift} and \code{y.shift}
#' arguments. 1 will shift the legend right/up by 1 scale width/height.
#' 
#' The size and shape of the color legend are controlled by \code{size}, which
#' is the approximate length of the longer dimension in inches, and \code{ratio},
#' which is the ratio between width and height (or vice versa for vertical scale bars)
#' and should generally be > 1.
#' 
#' There are several arguments that control how the legend is drawn. The
#' \code{tick.length} (between 0 and 1) argument controls how much of the shorter
#' dimension of the legend is taken up by the color scale vs the ticks. \code{label.offset}
#' controls the spacing between the ticks and the text labels. Parameters to modify
#' text size should be set via \code{par()} prior to calling this function. Setting
#' \code{box = FALSE} will remove the black outline around the colors.
#' 
#' 
#' @seealso \code{\link{draw.chrom.axis}} for drawing x-axis 
#' @examples
#' plot(1:5, 1:5, col=gray(0:4/5), pch=15)
#' # Place a horizontal scale bar a the top, inside the plot.
#' draw.scale(gray(0:4/5), c(0, 1), pos='top')
#' # Place a vertical scale bar to the right, outside the plot.
#' draw.scale(gray(0:4/5), c(76.1, 76.92), pos='right', horiz=FALSE, outside=TRUE)
#' # Place a horizontal  scale bar at the top left, outside the plot, but
#' aligned with the left edge of the plot
#' draw.scale(gray(0:4/5), c(1, 10), pos='topleft', adj=c(0, 0), outside=TRUE)
#' @export
draw.scale <- function(scale.colors, scale.range, num.labs=min(length(scale.colors)+1, 6),
                       pos='topleft', adj=NULL, horiz=TRUE,
                       outside=FALSE, size=2, ratio=12, tick.length=0.25,
                       scale.offset=0.5, label.offset=0.1,
                       box=TRUE, x.shift=0, y.shift=0) {
  
  
  if ( outside ) {
    old.par <- par(xpd=NA)
  }
  
  # recognized keywords and corresponding positions
  pos.key <- list()
  pos.key$middle <- c(0.5, 0.5)
  pos.key$center <- c(0.5, 0.5)
  pos.key$topleft <- c(0, 1)
  pos.key$topright <- c(1, 1)
  pos.key$top <- c(0.5, 1)
  pos.key$bottomleft <- c(0, 0)
  pos.key$bottomright <- c(1, 0)
  pos.key$bottom <- c(0.5, 0)
  pos.key$left <- c(0, 0.5)
  pos.key$right <- c(1, 0.5)
  pos.key <- data.frame(pos.key, row.names=c('x', 'y'))
  
  if ( is.character(pos) ) pos <- tolower(pos)
  if ( is.character(pos) && length(pos)==1 && pos %in% names(pos.key) ) {
    pos <- pos.key[[pos]]
  }
  
  if ( !is.numeric(pos) || length(pos) != 2) {
    warning('Invalid pos Please specify a keyword or xy pair.')
    pos <- c(0, 1)
  }
  
  # If adj is not specified it is the same as pos for inside
  # opposite for outside
  if ( is.null(adj) ) {
    if ( outside )
      adj <- 1-pos
    else
      adj <- pos
  }
  
  par.usr <- par('usr')
  par.pin <- par('pin')
  
  plot.width <- par.usr[2]-par.usr[1]
  plot.height <- par.usr[4]-par.usr[3]
  
  # Calculate dimensions of scale legend
  if ( horiz ) {
    legend.width <- plot.width/par.pin[1]*size
    legend.height <- plot.height/par.pin[2]*size/ratio
  } else {
    legend.height <- plot.height/par.pin[2]*size
    legend.width <- plot.width/par.pin[1]*size/ratio
  }
  
  x1 <- par.usr[1]+pos[1]*plot.width-adj[1]*legend.width
  y1 <- par.usr[3]+pos[2]*plot.height-adj[2]*legend.height
  
  # Apply scale.offset
  if ( horiz ) {
    y1 <- y1-scale.offset*legend.height*2*(adj[2]-0.5)
    x1 <- x1-scale.offset*legend.height*plot.width/plot.height*2*(adj[1]-0.5)
  } else {
    x1 <- x1-scale.offset*legend.width*2*(adj[1]-0.5)
    y1 <- y1-scale.offset*legend.width*plot.height/plot.width*2*(adj[2]-0.5)
  }
  x2 <- x1+legend.width
  y2 <- y1+legend.height
  
  # Flip depending on orientation
  if ( horiz & adj[2] > 0.5 ) {
    tm <- y1
    y1 <- y2
    y2 <- tm
  } else if ( !horiz & adj[1] > 0.5 ) {
    tm <- x1
    x1 <- x2
    x2 <- tm
  }
  #     points(x1, y1, pch=8, col='red')
  #     rect(x1, y1, x2, y2, col='#ff6633')
  
  if ( !missing(x.shift) ) {
    x1 <- x1 + x.shift*legend.width
    x2 <- x2 + x.shift*legend.width
  }
  if ( !missing(y.shift) ) {
    y1 <- y1 + y.shift*legend.height
    y2 <- y2 + y.shift*legend.height
  }
  
  if ( horiz ) {
    x.points <- seq(x1, x2, length.out=length(scale.colors)+1)
    y.mid <- y1*tick.length+y2*(1-tick.length)
    y.text <- y2+label.offset*(y2-y1)
    # draw ticks
    x.ticks <- seq(x1, x2, length.out=num.labs)
    segments(x.ticks, rep(y1, num.labs), x.ticks, rep(y2, num.labs))
    # draw colored boxes
    sapply(1:length(scale.colors), function (i) {
      rect(x.points[i], y1, x.points[i+1], y.mid, border=scale.colors[i], col=scale.colors[i])
    })
    if ( box ) rect(x1, y1, x2, y.mid)
  } else {
    y.points <- seq(y1, y2, length.out=length(scale.colors)+1)
    x.mid <- x1*tick.length+x2*(1-tick.length)
    x.text <- x2+label.offset*(x2-x1)
    # draw ticks
    y.ticks <- seq(y1, y2, length.out=num.labs)
    segments(rep(x1, num.labs), y.ticks, rep(x2, num.labs), y.ticks)
    # draw colored boxes
    sapply(1:length(scale.colors), function (i) {
      rect(x1, y.points[i], x.mid, y.points[i+1], border=scale.colors[i], col=scale.colors[i])
    })
    if ( box ) rect(x1, y1, x.mid, y2, border='#000000')
  }
  
  
  tick.labels <- seq(scale.range[1], scale.range[2], length.out=num.labs)
  sigdig <- 0
  while ( length(unique(round(tick.labels, sigdig))) < length(tick.labels) ) sigdig <- sigdig + 1
  if ( horiz ) {
    text(x.ticks, rep(y.text, num.labs), format(round(tick.labels, sigdig)),
         adj=c(0.5, round(adj[2])))
  } else {
    text(rep(x.text, num.labs), y.ticks, format(round(tick.labels, sigdig)),
         adj=c(round(adj[1]), 0.5)) 
  }
  
  if ( outside ) {
    par(old.par)
  }
  
  invisible(c(x1, x2, y1, y2))
}



#' Draw a color scale bar (old version)
#' 
#' \code{draw.old.scale} adds a color scale to the corner of the current plot
#' with specified colors and range
#' 
#' 
#' Currently only a horizontal scale bar is supported. To adjust position in
#' plot coordinates use x.offset and y.offset. To adjust relative position use
#' x.shift and y.shift.
#' 
#' Keep in mind that if you shift the scale bar away from the plotting area
#' (i.e. into the margins), you may need to specify the additional parameter
#' xpd=NA which will be passed to the plotting commands and allows drawing
#' in the margins.
#' 
#' @param scale.colors a vector of colors
#' @param scale.range range for scale (vector with 2 numeric elements)
#' @param num.labs (optional) number of labels to draw
#' @param position (optional) either 'topleft' 'topright' 'bottomleft' or
#' 'bottomright'
#' @param size (optional) approximate length in inches
#' @param width.to.height (optional) ratio of scale bar width to height
#' @param x.offset (optional) adjust x position (uses \code{par('usr')} scale).
#' @param y.offset (optional) adjust y position (uses \code{par('usr')} scale).
#' @param x.shift (optional) adjust x position in units of scale width.
#' @param y.shift (optional) adjust y position in units of scale height.
#' @param ... (optional) addition options to pass to plotting commands for
#' drawing labels, lines and shapes
#' 
#' @seealso \code{\link{draw.chrom.axis}} for drawing x-axis 
#' @export
draw.old.scale <- function(scale.colors, scale.range, num.labs=6,
                           position='topleft', size=3, width.to.height=20,
                           x.offset, y.offset, x.shift, y.shift, ...) {
  par.usr <- par('usr')
  par.pin <- par('pin')
  
  if ( substr(position, 1, 3) == 'top' ) {
    y1 <- par.usr[4]
    y2 <- par.usr[4] - (par.usr[4]-par.usr[3])/(par.pin[2])*size/width.to.height
    top <- TRUE
  } else {
    y1 <- par.usr[3]
    y2 <- par.usr[3] + (par.usr[4]-par.usr[3])/(par.pin[2])*size/width.to.height
    top <- FALSE
  }
  
  if ( substr(position, 7-3*top, 11-3*top) == 'left' ) {
    x1 <- par.usr[1]
    x2 <- par.usr[1] + (par.usr[2]-par.usr[1])/(par.pin[1])*size
  } else {
    x2 <- par.usr[2]
    x1 <- par.usr[2] - (par.usr[2]-par.usr[1])/(par.pin[1])*size
  }
  
  if ( missing(x.offset) ) x.offset <- 0
  if ( missing(y.offset) ) y.offset <- 0
  
  if ( !missing(x.shift) ) {
    x.offset <- x.offset + x.shift*(x2-x1)
  }
  
  if ( !missing(y.shift) ) {
    y.offset <- y.offset + y.shift*(y2-y1)
  }
  
  y1 <- y1 + y.offset
  y2 <- y2 + y.offset
  x1 <- x1 + x.offset
  x2 <- x2 + x.offset
  
  x.points <- seq(x1+(x2-x1)*0.1, x1+(x2-x1)*0.9, length.out=length(scale.colors)+1)
  y.mid <- y1+(y2-y1)/2
  
  
  
  x.ticks <- seq(x1+(x2-x1)*0.1, x1+(x2-x1)*0.9, length.out=num.labs)
  arrows(x.ticks, rep(y1, num.labs), x.ticks, rep(y2, num.labs), length=0, ...)
  
  if ( substr(position, 1, 3) == 'top' ) {
    label.pos = 1
  } else {
    label.pos = 3
  }
  
  sapply(1:length(scale.colors), function (i) {
    x1 <- x.points[i]
    x2 <- x.points[i+1]
    polygon(c(x1, x1, x2, x2), c(y1, y.mid, y.mid, y1), border=scale.colors[i], col=scale.colors[i], ...)
  })
  
  
  tick.labels <- seq(scale.range[1], scale.range[2], length.out=num.labs)
  sigdig <- 1
  while ( length(unique(signif(tick.labels, sigdig))) < length(tick.labels) ) sigdig <- sigdig + 1
  
  text(x.ticks, rep(y2, num.labs), signif(tick.labels, sigdig),
       pos=label.pos, offset=0.25, ...)
  
}

#' @export
center.out.order <- function(n) {
  if ( n <= 2 )
    return (1:n)
  if ( n %% 2 == 1 ) {
    odd <- seq(1, n, 2)
    even <- seq((n-1), 2, -2)
  } else {
    odd <- seq(1, (n-1), 2)
    even <- seq(n, 2, -2)
  }
  return ( order(c(even, odd)) )
}

#' Calculate a range with margins (padding)
#' 
#' @export
mrange <- function(x, m=0.1) {
  if ( length(x) < 2 || length(unique(x)) < 2 ) {
    warning('expected x with at least 2 unique values.\n')
    return ( x )
  }
  if ( length(x) > 2 ) {
    x <- range(x)
  }
  
  dx <- diff(x)
  x[1] <- x[1] - m*dx
  x[2] <- x[2] + m*dx
  
  return ( x )
}


#' Calculate offsets for plotting y ~ x scatter plots where y is continuous and x is categorical
#' 
#' 
#' @examples
#' rx <- ceiling(runif(250, 0, 5))
#' ry <- rnorm(250, 0, 100)+runif(5, 0, 2000)[rx]
#' offset <- splitter(ry, rx)
#' plot(offset+as.numeric(rx), ry, pch=20, col=rainbow(5)[rx])
#' @export
#' @export
splitter <- function (y, x=NULL, rad=.025, scale=TRUE) {
  zx <- rep(0, length(y))
  if ( length(y) < 2 ) return (zx)
  
  if ( !is.null(x) ) {
    if ( length(unique(x)) > length(x)/2 ) warning('x does not appear to be categorical')
    
    
    if ( scale )
      z <- (y-min(y))/diff(range(y))
    
    subs <- tapply(z, x, splitter, rad=rad, scale=FALSE, simplify=FALSE)
    subidx <- tapply(1:length(y), x)
    
    for ( s in 1:length(subs) ) {
      zx[subidx==s] <- subs[[s]]*length(subs)/2
    }
    return (zx)
  }
  
  y.order <- order(y)
  z <- y[y.order]
  if ( scale )
    z <- (z-min(z))/diff(range(z))
  
  for  ( i in 2:length(z) ) {
    
    dz <- z[i]-z[1:(i-1)]
    if ( any(dz < rad) ) {
      nbs <- (1:(i-1))[dz < rad]
      nbd <- sqrt((z[nbs]-z[i])^2+(zx[nbs]-zx[i])^2)
      if ( any(nbd < rad) ) {
        dz <- z[i]-z[nbs]
        ax <- sin(acos(dz/rad))*rad*1.01
        if ( mean(zx[nbs]) < 0 )
          nbx <- zx[nbs]+ax
        else
          nbx <-  zx[nbs]-ax
        
        for ( j in order(abs(nbx)) ) {
          zx[i] <- nbx[j]
          nbd <- sqrt((z[nbs]-z[i])^2+(zx[nbs]-zx[i])^2)
          if ( all(nbd >= rad) ) {
            break
          }
        }
        
        if ( any(nbd < rad) )
          cat('!')
        
      }
      
      
      zx[1:i] <- zx[1:i]-mean(zx[1:i])
    }
  }
  zx[y.order] <- zx
  return (zx)
}















#' Integer data binning
#' 
#' Sometimes with integer data which is not uniformly distributed, a linear
#' color scale is not ideal. The function \code{bin.ints} converts an integer
#' vector into a factor vector where each level corresponds to a range of
#' integers and the elements of x are evenly distributed (as much as possible)
#' across the factor levels.
#' 
#' This is a convenience function that makesuse of \code{find.bins} and
#' \code{label.bins}.
#' 
#' @param x data to be binned
#' @param num.bins number of bins to aim for
#'   
#'   
#' @return
#' \code{bin.ints} returns an ordered factor vector with appropriately
#' labeled levels.
#' @examples
#' x <- rpois(100, 10)
#' x.bin <- bin.ints(x)
#' 
#' 
#' @seealso \code{\link{find.bins}} for determining bin breakpoints
#' @seealso \code{\link{label.bins}} for bin labels suitable for a legend
#' @export
bin.ints <- function(x, num.bins=10) {
  bps <- find.bins(x, num.bins)
  xbin <- findInterval(x, bps)
  binlab <- label.bins(x, xbin)
  factor(xbin, labels=binlab, ordered=TRUE)
}



#' Find breakpoints for binning numeric values
#' 
#' @param x data to be binned
#' @param num.bins number of bins to aim for
#'   
#' @examples
#' x <- rpois(100, 10)
#' bins <- find.bins(x)
#' x.bin <- findInterval(x, bins)
#' 
#' 
#' @seealso \code{\link{label.bins}} for bin labels suitable for a legend
#' @seealso \code{\link{bin.ints}} for generating a factor with labels
#' @export
find.bins <- function(x, num.bins=10) {
  bins <- NULL
  x.table <- table(x)
  names(x.table) <- NULL
  x.levels <- sort(unique(x))
  x.levels <- (x.levels + c(x.levels[-1], 1+max(x)))/2
  
  i <- 1
  while ( length(bins) < (num.bins-1)  & i <= length(x.table)) {
    if ( sum(x.table[1:i])/sum(x.table) > 1/(num.bins-length(bins)) ) {
      i <- max(1, i - 1)
      bins <- c(bins, x.levels[i])
      x.table <- x.table[-(1:i)]
      x.levels <- x.levels[-(1:i)]
      i <- 1
    } else {
      i <- i + 1
    }
  }
  bins <- c(bins, max(x)+1)
  return (bins)
}


#' Label bins generated by \code{find.bins()}
#' 
#' @param x data to be binned
#' @param bin binned data
#' @param greedy (default TRUE) whether to include in labels values of x which
#' may not appear in the data. e.g. instead of \code{0, 1, 2-3, 5-6} we return
#' \code{0, 1, 2-4, 5-6}
#' 
#' @examples
#' x <- rpois(100, 10)
#' bins <- find.bins(x)
#' x.bin <- findInterval(x, bins)
#' bin.labels <- label.bins(x, x.bin)
#' 
#' @seealso \code{\link{find.bins}} for determining bin breakpoints
#' @seealso \code{\link{bin.ints}} for generating a factor with labels
#' @export
label.bins <- function(x, bins, greedy=TRUE) {
  if ( missing(bins)  ) {
    x.bins <- find.bins(x)
    bins <- findInterval(x, x.bins)
  } else if ( length(bins) == 1 && is.numeric(bins) ) {
    x.bins <- find.bins(x, bins)
    bins <- findInterval(x, x.bins)
  } else if  ( length(bins) != length(x) ) {
    stop('x and bins must have same length.')
  }
  
  x.ranges <- simplify2array(tapply(x, bins, range))
  
  if ( greedy && min(diff(sort(unique(x)))) >= 1 )
    x.ranges[2, -ncol(x.ranges)] <- x.ranges[1, -1]-1
  
  apply(x.ranges, 2, function (r) 
    if (diff(r)) paste0(r[1], if (r[2]==max(x)) '+' else paste0('-', r[2])) else r[1]
  )
}





#' @export
gw.snp.pos <- function(chromosome, position, spacing=0.1) {
  chr.order <- gtools::mixedsort(unique(chromosome))
  snp.order <- order(match(chromosome, chr.order), position)
  
  co <- match(chromosome[snp.order], chr.order)
  po <- position[snp.order]
  
  chr.ranges <- do.call(rbind, tapply(po, co, range))
  rownames(chr.ranges) <- chr.order
  chr.sizes <- apply(chr.ranges, 1, diff)
  space <- mean(chr.sizes)*spacing
  chr.bounds <- unname(cumsum(c(0, chr.sizes+spacing)))
  
  chr.offsets <- chr.bounds[1:nrow(chr.ranges)] - chr.ranges[, 1]
  
  gwpos <- unname(chr.offsets[co] + po)
  gwpos[snp.order] <- gwpos
  
  attr(gwpos, 'chr.names') <- chr.order
  attr(gwpos, 'chr.bounds') <- chr.bounds
  
  class(gwpos) <- 'gwpos'
  
  return (gwpos)
}

#' @export
`[.gwpos` <- function(x, i, ...) {
  attrs <- attributes(x)
  out <- unclass(x)
  out <- out[i]
  attributes(out) <- attrs
  out
}

#' @export
gwaxis <- function(names, bounds, ax=1) {
  midpts <- (bounds[-1] + bounds[-length(bounds)])/2
  axis(ax, bounds, labels=FALSE)
  axis(ax, midpts, labels=names, lwd=0)
}

#' @export
plot.gwpos <- function (x, y=NULL, xlab=NULL, ylab=NULL, xaxt=NULL, ...) {
  
  if ( missing(xlab) ) xlab <- deparse(substitute(x))
  if ( missing(ylab) ) ylab <- deparse(substitute(y))
  
  plot.default(x, y, xlab=xlab, ylab=ylab, xaxt='n', ...)
  if ( missing(xaxt) || xaxt != 'n')
    gwaxis(attr(x, 'chr.names'), attr(x, 'chr.bounds'))
}
# This file is part of sb_pipe.
#
# sb_pipe is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# sb_pipe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with sb_pipe.  If not, see <http://www.gnu.org/licenses/>.
#
#
# Object: Plots and statistics for parameter estimation
#
# $Revision: 3.0 $
# $Author: Piero Dalle Pezze $
# $Date: 2016-07-01 14:14:32 $


library(ggplot2)
# library(scales)
source(file.path(SB_PIPE, 'sb_pipe','utils','R','sb_pipe_ggplot2_themes.r'))
source(file.path(SB_PIPE, 'sb_pipe','utils','R','plots.r'))





# m = number of model parameters
# n = number of data points
# p = significance level
compute_fratio_threshold <- function(m, n, p=0.05) {
  1 + (m/(n-m)) * qf(1.0-p, df1=m, df2=n-m)
}


# return the left value confidence interval
leftCI <- function(cut_dataset, full_dataset, chisquare_col_idx, param_col_idx, chisquare_conf_level) {
   # retrieve the minimum parameter value for cut_dataset
    min_ci <- min(cut_dataset[[param_col_idx]])    
    # retrieve the Chi^2 of the parameters with value smaller than the minimum value retrieved from the cut_dataset, within the full dataset. 
    # ...[min95, )  (we are retrieving those ...)
    lt_min_chisquares <- full_dataset[full_dataset[,param_col_idx] < min_ci, chisquare_col_idx] 
    if(min(lt_min_chisquares) < chisquare_conf_level) 
      min_ci <- "inf"
    min_ci
}


# return the right value confidence interval
rightCI <- function(cut_dataset, full_dataset, chisquare_col_idx, param_col_idx, chisquare_conf_level) {
   # retrieve the minimum parameter value for cut_dataset
    max_ci <- max(cut_dataset[[param_col_idx]])    
    # retrieve the Chi^2 of the parameters with value greater than the maximum value retrieved from the cut_dataset, within the full dataset. 
    # (, max95]...  (we are retrieving those ...)
    gt_max_chisquares <- full_dataset[full_dataset[,param_col_idx] > max_ci, chisquare_col_idx] 
    if(min(gt_max_chisquares) < chisquare_conf_level) 
      max_ci <- "inf"
    max_ci
}


plot_fits <- function(my_array) {
  iters <- c()
  j <- 0
  k <- 0
  for(i in 1:length(my_array)) {
    if(k < my_array[i]) {
      j <- 0
    }
    iters <- c(iters, j)
    j <- j+1    
    k <- my_array[i]   
  }
  df <- data.frame(Iter=iters, Chi2=my_array)
  scatterplot_log10(df, "Iter", "Chi2")
}


# rename columns
replace_colnames <- function(dfCols) {
  dfCols <- gsub("ObjectiveValue", "Chi2", dfCols)
  dfCols <- gsub("Values.", "", dfCols)
  dfCols <- gsub("..InitialValue.", "", dfCols)
}



plot_parameter_correlations <- function(df, dfCols, plots_dir, plot_filename_prefix, chi2_col_idx, logspace=TRUE) {
  fileout <- ""
  for (i in seq(chi2_col_idx+1,length(dfCols))) { 
    for (j in seq(i, length(dfCols))) {
      if(i==j) {
	fileout <- file.path(plots_dir, paste(plot_filename_prefix, dfCols[i], ".png", sep=""))
	g <- histogramplot(df[i])
	if(logspace) {
	  g <- g + xlab(paste("log10(",dfCols[i],")",sep=""))
	}
      } else {
	fileout <- file.path(plots_dir, paste(plot_filename_prefix, dfCols[i], "_", dfCols[j], ".png", sep=""))
	g <- scatterplot_w_colour(df, colnames(df)[i], colnames(df)[j], colnames(df)[chi2_col_idx]) +
        theme(legend.key.height = unit(0.5, "in"))
	if(logspace) {
	  g <- g + xlab(paste("log10(",dfCols[i],")",sep="")) + ylab(paste("log10(",dfCols[j],")",sep=""))
	}        
      }
      ggsave(fileout, dpi=300, width=8, height=6)
    }    
  }
}




all_fits_analysis <- function(model, filenamein, plots_dir, data_point_num, fileout_approx_ple_stats, fileout_conf_levels, plot_2d_66_95cl_corr=FALSE, logspace=TRUE) {
  
  data_point_num <- as.numeric(data_point_num)
  if(data_point_num <= 0.0) {
    error("data_point_num is non positive.")
    return
  }
  
  df = read.csv(filenamein, head=TRUE, dec=".", sep="\t")
  
  if(logspace) {
    # Transform the parameter space to a log10 parameter space. 
    # The column for the Chi^2 score is maintained instead. 
    df[,-1] <- log10(df[,-1])
  }
    
  dfCols <- replace_colnames(colnames(df))
  colnames(df) <- dfCols
  
  parameter_num = length(colnames(df)) - 1
  chisquare_at_conf_level_99 <- 0  
  chisquare_at_conf_level_95 <- 0    
  chisquare_at_conf_level_66 <- 0   
  if(length(dfCols) > 1) {
    chisquare_at_conf_level_99 <- min(df[,1]) * compute_fratio_threshold(parameter_num, data_point_num, .01) 
    chisquare_at_conf_level_95 <- min(df[,1]) * compute_fratio_threshold(parameter_num, data_point_num, .05) 
    chisquare_at_conf_level_66 <- min(df[,1]) * compute_fratio_threshold(parameter_num, data_point_num, .33)   
  }

  # select the rows with chi^2 smaller than our max threshold
  df99 <- df[df[,1] <= chisquare_at_conf_level_99, ]  
  df95 <- df[df[,1] <= chisquare_at_conf_level_95, ]
  df66 <- df95[df95[,1] <= chisquare_at_conf_level_66, ]  
  
  # Set my ggplot theme here
  theme_set(basic_theme(36))
 
  # save the chisquare vs iteration
  g <- plot_fits(df[,1])
  ggsave(file.path(plots_dir, paste(model, "_chi2_vs_iters.png", sep="")), dpi=300, width=8, height=6)
    
  min_chisquare <- min(df95[[1]])  
  fileoutPLE <- sink(fileout_conf_levels)
  cat(paste("Min_Chi2", "Param_Num", "Data_Points_Num", "Chi2_Conf_Level_95", "Fits_Num_95", "Chi2_Conf_Level_66", "Fits_Num_95\n", sep="\t"))
  cat(paste(min_chisquare, parameter_num, data_point_num, chisquare_at_conf_level_95, nrow(df95), chisquare_at_conf_level_66, nrow(df66), sep="\t"), append=TRUE)
  sink() 

  fileoutPLE <- sink(fileout_approx_ple_stats)
  cat(paste("Parameter", "Value", "CI_95_left", "CI_95_right", "CI_66_left", "CI_66_right\n", sep="\t"), append=TRUE)      
  for (i in seq(2,length(dfCols))) {
    # extract statistics  
    fileout <- file.path(plots_dir, paste(model, "_approx_ple_", dfCols[i], ".png", sep=""))
    g <- scatterplot_ple(df95, colnames(df95)[i], colnames(df95)[1], 
			 chisquare_at_conf_level_66, chisquare_at_conf_level_95) + 
         theme(legend.key.height = unit(0.5, "in"))
    if(logspace) {
      g <- g + xlab(paste("log10(",dfCols[i],")",sep=""))
    }         
         
    ggsave(fileout, dpi=300, width=8, height=6)
  
    # retrieve a parameter value associated to the minimum Chi^2
    par_value <- sample(df95[df95[,1] <= min_chisquare, i], 1)    
    # retrieve the confidence intervals
    min_ci_95 <- leftCI(df95, df99, 1, i, chisquare_at_conf_level_95)
    max_ci_95 <- rightCI(df95, df99, 1, i, chisquare_at_conf_level_95)    
    min_ci_66 <- leftCI(df66, df95, 1, i, chisquare_at_conf_level_66)
    max_ci_66 <- rightCI(df66, df95, 1, i, chisquare_at_conf_level_66)
    # save the result
    cat(paste(colnames(df95)[i], par_value, min_ci_95, max_ci_95, min_ci_66, max_ci_66, sep="\t"), append=TRUE)
    cat("\n", append=TRUE)    
  }
  sink()
  
  
  # plot parameter correlations using the 66% and 95% confidence level data sets
  if(plot_2d_66_95cl_corr) {
    plot_parameter_correlations(df66[order(-df66[,1]),], dfCols, plots_dir, paste(model, "_ci66_fits_", sep=""), 1, logspace)
    plot_parameter_correlations(df95[order(-df95[,1]),], dfCols, plots_dir, paste(model, "_ci95_fits_", sep=""), 1, logspace)
    #plot_parameter_correlations(df, dfCols, plots_dir, paste(model, "_all_fits_", sep=""), 1, logspace)
  }
  
}





final_fits_analysis <- function(model, filenamein, plots_dir, best_fits_percent, logspace=TRUE) {
  
  best_fits_percent <- as.numeric(best_fits_percent)
  if(best_fits_percent <= 0.0 || best_fits_percent > 100.0) {
    warning("best_fits_percent is not in (0, 100]. Now set to 100")
    best_fits_percent = 100
  }
  
  df = read.csv(filenamein, head=TRUE,sep="\t")
  
  if(logspace) {
    # Transform the parameter space to a log10 parameter space. 
    # The 2nd column containing the Chi^2 score is maintained 
    # as well as the 1st containing the parameter estimation name. 
    df[,c(-1,-2)] <- log10(df[,c(-1,-2)])
  }
    
  dfCols <- replace_colnames(colnames(df))
  colnames(df) <- dfCols
  
  # Calculate the number of rows to extract.
  selected_rows <- nrow(df)*best_fits_percent/100
  # sort by Chi^2 (descending) so that the low Chi^2 parameter tuples 
  # (which are the most important) are plotted in front. 
  # Then extract the tail from the data frame. 
  df <- df[order(-df[,2]),]
  df <- tail(df, selected_rows)
  
  # Set my ggplot theme here
  theme_set(basic_theme(36))
  
  plot_parameter_correlations(df, dfCols, plots_dir, paste(model, "_best_fits_", sep=""), 2, logspace)
  
}


                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]
    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
    }
    for (i in 1:max) {
        id <- list11$id[i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), list2[[id]], list11$id[[i]]))
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        dev.new()
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        dev.new()
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, periodtext, maindate, olddate, days) {
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (period == pricetype) {
        return (df$price)
    }
    if (period == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    ls <- list()
    names <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        dayset <- bigretl[[2]]
                        daynames <- names(dayset)
                        olddate <- min(daynames)
                        newdate <- max(daynames)
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        names[c] <- df$name
                    }
                }
            }
        }
    }
    displaychart(ls, names, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]
    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
    }
    for (i in 1:max) {
        id <- list11$id[i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), list2[[id]], list11$id[[i]]))
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        dev.new()
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        dev.new()
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, periodtext, maindate, olddate, days) {
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (period == pricetype) {
        return (df$price)
    }
    if (period == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    ls <- list()
    names <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        dayset <- bigretl[[2]]
                        daynames <- names(dayset)
                        olddate <- min(daynames)
                        newdate <- max(daynames)
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        names[c] <- df$name
                    }
                }
            }
        }
    }
    displaychart(ls, names, 5, periodtext, newdate, olddate)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

# not used

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

# not used

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

if (!exists("mymarketid")) {
    mymarketid <- "morncat"
}

if (!exists("mydate")) {
    mydate <- NULL
}

allstocks <- getstocks()
allmetas <- getmetas()
#mymeta <- getmarketmeta(allmetas, marketid)
#data_3 <- getstockmarket(allstocks, marketid)

#for (i in 1:nrow(data_3)) {
                                        #print(data_3[i,"date"])
                                        #return()
#}

                                        #for (i in data_3) {
                                        #print(i["date"])
                                        #return
                                        #}

#listid2 <- splitid(data_3)
#listdate2 <- splitdate(data_3)
#listdate <- split(data_3, data_3$date)
#listid <- split(data_3, data_3$id)

                                        #l <- listdate[[104]]
#if (!exists("days")) {
#    days <- 10
#}
#if (!exists("topbottom")) {
#    topbottom <- 5
#}
#count <- days
#if (!exists("mytableintervaldays")) {
#    mytableintervaldays <- 5
#}
                                        #date <- "2016-05-02"

#datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)

#if (!exists("period")) {
#    period <- 3
#}

                                        #alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
                                        #periodmaps <- alist[[1]]
                                        #stocklistperiod <- alist[[2]]
                                        #mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
                                        #mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)

                                        #gettopchart(days, topbottom, stocklistperiod, period)
                                        #getbottomchart(days, topbottom, stocklistperiod, period)
                                        #rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #risetopids <- head(names(rise[[1]]))

#getcontentgraph(date, ids, "1y")

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
similarity_cons_res <- tanimoto_analysis(min.tx = 45,
                                        K.values = 8,
                                        MW = 1,
                                        WT =  c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1),
                                        minimum_threshold = 0.3,
                                        filename = 'similarity_cons_res')

# Catalog vs predictions
load("./RData/interactions_source.RData")
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = similarity_cons_res, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = similarity_cons_res, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = similarity_cons_res)

#Figure
filename = 'Similarity_cons_res'
pdf(paste('./Article/',filename,'.pdf',sep=''),width=7,height=7)

# Plots
par(mfrow=c(2,2))
# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 1.09)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(similarity_cons_res[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000088","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
            axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
            # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
            points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
        } #i

        ## Add legend
        if(j == 12) {
            legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        }
} #j
dev.off()
tanimoto_analysis <- function(min.tx, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, blind = FALSE) {
    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon
                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog

                        if(similarity == 'both') { # For similarity matrices already evaluated
                            similarity.consumer <- similarity.consumers[[i]]
                            similarity.resource <- similarity.resources[[i]]
                        } else if(similarity == 'consumer') {
                            similarity.consumer <- similarity.consumers[[i]]
                        } else if (similarity == 'resource') {
                            similarity.resource <- similarity.resources[[i]]
                        }

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                              S0[S1[k], 'consumer'] <- ""
                              S0[S1[k], 'non-consumer'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                                consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                        resource = interactions[, 'resource'],
                                                                        inter_type = interactions[, 'inter'])


                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                  S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                  S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.consumer,
                                                                                taxa = 'consumer')

                            similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.resource,
                                                                                taxa = 'resource')

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.consumer = similarity.consumer,
                                                                                    similarity.resource = similarity.resource,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.consumer, similarity.resource)
                        iteration <- iteration + 1
                        setTxtProgressBar(pb, iteration)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values

        }#m
    }#n
    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
tanimoto_analysis <- function(min.tx, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, blind = FALSE) {
    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon
                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog

                        if(similarity == 'both') { # For similarity matrices already evaluated
                            similarity.consumer <- similarity.consumers[[i]]
                            similarity.resource <- similarity.resources[[i]]
                        } else if(similarity == 'consumer') {
                            similarity.consumer <- similarity.consumers[[i]]
                        } else if (similarity == 'resource') {
                            similarity.resource <- similarity.resources[[i]]
                        }

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                              S0[S1[k], 'consumer'] <- ""
                              S0[S1[k], 'non-consumer'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                                consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                        resource = interactions[, 'resource'],
                                                                        inter_type = interactions[, 'inter'])


                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                  S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                  S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.consumer,
                                                                                taxa = 'consumer')

                            similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.resource,
                                                                                taxa = 'resource')

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.consumer = similarity.consumer,
                                                                                    similarity.resource = similarity.resource,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.matrix)
                        iteration <- iteration + 1
                        setTxtProgressBar(pb, iteration)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values

        }#m
    }#n
    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------

similarity_cons_res <- tanimoto_analysis(min.tx = 45,
                                        K.values = 8,
                                        MW = 1,
                                        WT =  c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1),
                                        minimum_threshold = 0.3,
                                        filename = 'similarity_cons_res')

# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=7,height=7)

# Plots
par(mfrow=c(2,2))
# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 1.09)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000088","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
            axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
            # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
            points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
        } #i

        ## Add legend
        if(j == 12) {
            legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        }
} #j
dev.off()

save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))
                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, mytableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, mytableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]
    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
    }
    for (i in 1:max) {
        id <- list11$id[i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), list2[[id]], list11$id[[i]]))
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

gettopgraph <- function(market, mydate, days, topbottom, periodtext) {
    periodtexts <- getperiodtexts(market)
    period <- match(periodtext, periodtexts)
#    cat("perind ", period)
    stocks <- getstockmarket(allstocks, market)
    listdate <- split(stocks, stocks$date)
    datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
    alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
    periodmaps <- alist[[1]]
    stocklistperiod <- alist[[2]]
    mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
    gettopchart(market, days, topbottom, stocklistperiod, period)
}

getbottomgraph <- function(market, mydate, days, topbottom, periodtext) {
    periodtexts <- getperiodtexts(market)
    period <- match(periodtext, periodtexts)
#    cat("perind ", period)
    stocks <- getstockmarket(allstocks, market)
    listdate <- split(stocks, stocks$date)
    datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
    alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
    periodmaps <- alist[[1]]
    stocklistperiod <- alist[[2]]
    mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
    getbottomchart(market, days, topbottom, stocklistperiod, period)
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getrisinggraph <- function(market, mydate, days, topbottom, periodtext) {
    periodtexts <- getperiodtexts(market)
    period <- match(periodtext, periodtexts)
#    cat("perind ", period)
    stocks <- getstockmarket(allstocks, market)
    listdate <- split(stocks, stocks$date)
    datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
    alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
    periodmaps <- alist[[1]]
    stocklistperiod <- alist[[2]]
    rise <- getrising(days, periodmaps, stocklistperiod, period)
#    str("riserise")
#    str(names(rise[[1]]))
    risetopids <- head(names(rise[[1]]))
    maindate <- "new"
    olddate <- "old"
    getchart(market, days, stocklistperiod, period, risetopids)
    #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, periodtext, maindate, olddate) {
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (period == pricetype) {
        return (df$price)
    }
    if (period == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, mytableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:count) {
        index <- index - mytableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, ids, periodtext) {
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    ls <- list()
    names <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        dayset <- bigretl[[2]]
                        daynames <- names(dayset)
                        olddate <- min(daynames)
                        newdate <- max(daynames)
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        names[c] <- df$name
                    }
                }
            }
        }
    }
    displaychart(ls, names, 5, periodtext, newdate, olddate)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

# not used

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

# not used

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

if (!exists("mymarketid")) {
    mymarketid <- "morncat"
}

if (!exists("mydate")) {
    mydate <- NULL
}

allstocks <- getstocks()
allmetas <- getmetas()
#mymeta <- getmarketmeta(allmetas, marketid)
#data_3 <- getstockmarket(allstocks, marketid)

#for (i in 1:nrow(data_3)) {
                                        #print(data_3[i,"date"])
                                        #return()
#}

                                        #for (i in data_3) {
                                        #print(i["date"])
                                        #return
                                        #}

#listid2 <- splitid(data_3)
#listdate2 <- splitdate(data_3)
#listdate <- split(data_3, data_3$date)
#listid <- split(data_3, data_3$id)

                                        #l <- listdate[[104]]
if (!exists("days")) {
    days <- 10
}
if (!exists("topbottom")) {
    topbottom <- 5
}
count <- days
if (!exists("mytableintervaldays")) {
    mytableintervaldays <- 5
}
                                        #date <- "2016-05-02"

#datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)

if (!exists("period")) {
    period <- 3
}

                                        #alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
                                        #periodmaps <- alist[[1]]
                                        #stocklistperiod <- alist[[2]]
                                        #mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
                                        #mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)

                                        #gettopchart(days, topbottom, stocklistperiod, period)
                                        #getbottomchart(days, topbottom, stocklistperiod, period)
                                        #rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #risetopids <- head(names(rise[[1]]))

#getcontentgraph(date, ids, "1y")

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

tanimoto_analysis <- function(min.tx, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, blind = FALSE) {
    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon
                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog

                        if(similarity == 'both') { # For similarity matrices already evaluated
                            similarity.consumer <- similarity.consumers[[i]]
                            similarity.resource <- similarity.resources[[i]]
                        } else if(similarity == 'consumer') {
                            similarity.consumer <- similarity.consumers[[i]]
                        } else if (similarity == 'resource') {
                            similarity.resource <- similarity.resources[[i]]
                        }

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                              S0[S1[k], 'consumer'] <- ""
                              S0[S1[k], 'non-consumer'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                                consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                        resource = interactions[, 'resource'],
                                                                        inter_type = interactions[, 'inter'])


                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                  S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                  S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.consumer,
                                                                                taxa = 'consumer')

                            similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.resource,
                                                                                taxa = 'resource')

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.consumer = similarity.consumer,
                                                                                    similarity.resource = similarity.resource,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.matrix)
                        iteration <- iteration + 1
                        setTxtProgressBar(pb, iteration)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values

        }#m
    }#n
    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
# Run init.r before other scripts
rm(list=ls())
 # for use in R console.
 # set own relevant directory if working in R console, otherwise ignore if in terminal
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "./Script/0-1-Tanimoto_data.r
#           RData <- file = './RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "./Script/0-1-Interactions_sources.r
#           RData <- file = "./RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = './Script/1-Similarity_matrix.r'
#       RData <- file = './RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = './Script/2-1-Tanimoto_analysis.r'
#           RData <- file = './RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = './Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = './RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("./Script/tanimoto.r") # basic tanimoto similarity
source("./Script/tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("./Script/similarity_taxon.r") # similarity matrix for set of taxa
source("./Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("./Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("./Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/consumer_set_of_resource.R")
source("./Script/resource_set_of_consumer.R")
source("./Script/prediction_accuracy.r") #
source("./Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("./Script/serialNext.r") # function to avoid overwriting existing files in temporary analyses folder
source("./Script/eplot.r") # empty plot for figure generation
source("./Script/tanimoto_analysis.r")
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
#Similarity matrix as a single functions
similarity_taxon <- function(S0, wt, taxa) {
    # Note: the similarity on the diagonal has to be set to 1 since it's all the same species.
    # taxa is either resource or consumer

    similarity.matrix <- matrix(nrow = nrow(S0), ncol = nrow(S0), dimnames = list(S0[, 'taxon'], S0[, 'taxon']))

    taxonomy <- vector("list",nrow(S0))
    taxon <- vector("list",nrow(S0))
    for(i in 1:nrow(S0)) {
      taxonomy[[i]] <- unlist(strsplit(S0[i, 'taxonomy'], " \\|\\ "))
      if(length(which(taxonomy[[i]] == "NA")) > 0) {
          taxonomy[[i]] <- taxonomy[[i]][-which(taxonomy[[i]] == "NA")]
      }

      if(taxa == 'consumer') {
          taxon[[i]] <- unlist(strsplit(S0[i, 'resource'], " \\|\\ "))
      } else if(taxa == 'resource') {
          taxon[[i]] <- unlist(strsplit(S0[i, 'consumer'], " \\|\\ "))
      }
    }

    pb <- txtProgressBar(min = 0,max = nrow(S0), style = 3)

    for(i in 1:nrow(S0)){
      for(j in i:nrow(S0)){ #No need to evaluate both side of the matrix diagonal for the similarity matrix
          similarity.matrix[i,j] <- similarity.matrix[j,i] <- tanimoto_traits(resource_x = taxon[[i]],
                                                                              resource_y = taxon[[j]],
                                                                              trait_x = taxonomy[[i]],
                                                                              trait_y = taxonomy[[j]],
                                                                              trait_weight = wt
                                                                              )
      }#j
    setTxtProgressBar(pb, i)
    }#i
    close(pb)

    diag(similarity.matrix) <- 1

  return(similarity.matrix)
}#similarity_taxon function
#Similarity matrix as a single functions
similarity_taxon_predict <- function(S0, S1, wt, similarity.matrix, taxa) {

    # Parameters:
    #   S0                  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource'] (if blind = TRUE, it )
    #   S1                  The subset of S0 where we want to predict new preys, string vector
    #   wt                  Weight given to traits (including phylogeny) when computing similarities.
    #   similarity.matrix   Similarity.matrix for interaction catalogue (measured by function: similarity_taxon)
    #   taxa                Either resource or consumer

    #
    # Output
    #   A matrix of dimensions S x S with similarity measurements for all combinations of S[i,j]

    # Note: the similarity on the diagonal has to be set to 1 since it's all the same species.

    to.recalculate <- which(S0[, 'taxon'] %in% S1)
    similarity.matrix[, to.recalculate] <- similarity.matrix[to.recalculate, ] <- 0

    taxonomy <- vector("list",nrow(S0))
    taxon <- vector("list",nrow(S0))
    for(i in 1:nrow(S0)) {
      taxonomy[[i]] <- unlist(strsplit(S0[i, 'taxonomy'], " \\|\\ "))
      if(length(which(taxonomy[[i]] == "NA")) > 0) {
          taxonomy[[i]] <- taxonomy[[i]][-which(taxonomy[[i]] == "NA")]
      }

        if(taxa == 'consumer') {
            taxon[[i]] <- unlist(strsplit(S0[i, 'resource'], " \\|\\ "))
        } else if(taxa == 'resource') {
            taxon[[i]] <- unlist(strsplit(S0[i, 'consumer'], " \\|\\ "))
        }
    }

  # pb <- txtProgressBar(min = (nrow(similarity.matrix) - length(taxa.add)), max = ncol(similarity.matrix), style = 3)

  for(i in to.recalculate){
      for(j in 1:ncol(similarity.matrix)){ #No need to evaluate both side of the matrix diagonal for the similarity matrix
          similarity.matrix[i,j] <- similarity.matrix[j,i] <- tanimoto_traits(resource_x = taxon[[i]],
                                                                              resource_y = taxon[[j]],
                                                                              trait_x = taxonomy[[i]],
                                                                              trait_y = taxonomy[[j]],
                                                                              trait_weight = wt
                                                                              )
      }#j
  # setTxtProgressBar(pb, i)
  }#i
  # close(pb)
  diag(similarity.matrix) <- 1
  return(similarity.matrix)
}#similarity_taxon_predict function
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#    1. Evaluating similarity of consumers and resources
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
# // TODO: Evaluate similarity based on set of consumers for resources
# // TODO: Look into proximity graphs for better performance
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# LIBRARIES:
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/Tanimoto_data.RData")

# Measuring the similarity with multiple weights for all taxa in interaction catalogue
# Will be better once we code for proximity graphs

# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
# Format interaction catalogue to fit this table format
    S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
    S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']

    }

# Weight values for 2-way similarity measurements
    wt <- seq(0, 1, by = 0.1)

# 1st is for similarity measured from set of resources and taxonomy, for consumers
    similarity.consumers <- vector('list',11)
    names(similarity.consumers) <- wt
    for(i in 1:length(wt)) {
        similarity.consumers[[i]] <- similarity_taxon(S0 = S0_catalog, wt = wt[i], taxa = 'consumer')
        save(x = similarity.consumers, file = "./RData/Similarity_consumers.RData")
    }
    save(x = similarity.consumers, file = "./RData/Similarity_consumers.RData")

# 2nd is for similarity measured from set of consumers and taxonomy, for resources
    similarity.resources <- vector('list',11)
    names(similarity.resources) <- wt
    for(i in 1:length(wt)) {
        similarity.resources[[i]] <- similarity_taxon(S0 = S0_catalog, wt = wt[i], taxa = 'resource')
        save(x = similarity.resources, file = "./RData/Similarity_resources.RData")
    }
    save(x = similarity.resources, file = "./RData/Similarity_resources.RData")
two_way_tanimoto_predict <- function(Kc, Kr, S0, S1, MW, similarity.consumer, similarity.resource, minimum_threshold) {
    # Two-way Tanimoto Algorithm
    # ===========================

    # Parameters:
    #   Kc  Integer, how many neighbors to select for consumers
    #   Kr  Integer, how many neighbors to select for resources
    #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
    #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name
    #   MW  Mimimum weight to accept a candidate as a prey
    #

    # // TODO: I think MW should be a function of Kc & Kr and perhaps of the number of candidate resources. For example, a similar consumer could have multiple prey, which would artificially inflate the weight added to each prey in the candidate list. For exemple, Atlantic cod has over 600 prey species listed in the interaction catalogue... Hence, the longer the candidate list, the more likely a very small similarity will be turned into a predicted interaction
    # // REVIEW: Multiply similar.consumer[similarity] * similar.resource[similarity]? It's a similarity of a similarity in a sense...

    # // TODO: Different similarity measurement for resources and consumers

    # // REVIEW: Remove cannibalism from empirical data, or allow for it, or add parameter that allows or prevents cannibalism in the predictions


    # Output
    #   A vector of sets (the preys for each species)

    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # List of things to adjust - make it
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    # Process steps:
      # A prior process to this is to get the similarity matrix between all combinations of catalogue taxa and species in S1
      # For each species in S1:
      # 1. Identify resources already known in interaction catalogue (S0) for S1 species
        # 1.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
        # 1.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

      # 2. Identify Kc similar consumers to S1 in S0
        # 2.1 Extract set of candidate resources from each similar consumer, if any
        # 2.2 If candidate resource is in S1, add it to candidate list with weight 1
        # 2.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

      # 3. Make predictions:
        # 3.1 Remove taxa with weight < to minimum weight (MW) from prediction list
        # 3.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed


    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # !!! étendre predator et non predator pour resource... il faudrait aussi calculer la similarité des proies sur la base de leurs prédateurs partagés !!!
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    predictions <- matrix(nrow = length(S1), ncol = 3, data = "", dimnames = list(c(S1), c('consumer','resource_empirical','resource_predictions'))) # empty object for resource predictions
    predictions[, 'consumer'] <- S1

    # pb <- txtProgressBar(min = 0,max = length(S1), style = 3)
    for(i in 1:length(S1)) { # loop through each taxon in S1
        candidates <- matrix(nrow = 0, ncol = 2, dimnames = list(c(), c('resource', 'weight')), data = NA) # empty matrix for resource candidate list for S1[i], with taxon name and weight
        resources.S1 <- unlist(strsplit(S0[S1[i], 'resource'], " \\|\\ ")) # resources of S1[i]

        # Add resources that are already listed as resources for S1[i] in predictions[, 'resource_empirical'] or
        # Find similar resources to resources for S1[i] in S1
        if(length(resources.S1) > 0) {
            empirical <- character()
            for(j in 1:length(resources.S1)) { #loop through empirical resources for S1
                if(resources.S1[j] %in% S1) {
                    empirical <- c(empirical, resources.S1[j]) # observed resource found in S1 are automatically added to the column resource_empirical
                } else { # selecting Kr most similar resources in S1
                    # Let's assume for this part that we are not compiling a different similarity measure for predators and preys.
                    similar.resource <- matrix(nrow = length(S1)-1, ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources
                    similar.resource[, 'resource'] <- names(sort(similarity.resource[S1[-which(S1 == S1[i])], resources.S1[j]], decreasing = TRUE))
                    similar.resource[, 'similarity'] <- sort(similarity.resource[S1[-which(S1 == S1[i])], resources.S1[j]], decreasing = TRUE)

                    # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
                    if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {
                        same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])
                        similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]
                        similar.resource <- similar.resource[1:Kr, ]
                    } else {
                        similar.resource <- similar.resource[1:Kr, ]
                    }# if for random draw

                    for(l in 1:Kr) { # extracting resource candidates
                        if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break
                            break
                        } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                            NULL
                            # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed
                        } else if(similar.resource[l, 'similarity'] < minimum_threshold) {
                            NULL
                        } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add resource' with wt to its weight
                          candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])
                        } else {
                              candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it resource' with wt to its weight
                        }#if3
                    }#l
                }#if
            }#j
            predictions[S1[i], 'resource_empirical'] <- paste(empirical, collapse = ' | ')
        }#if1

        # Identify similar consumers to S1[i]
        similar.consumer <- matrix(nrow = nrow(similarity.consumer)-1, ncol = 2, dimnames = list(c(), c('consumer','similarity')), data = NA) # emporting K nearest neighbors for consumers
        similar.consumer[, 'consumer'] <- names(sort(similarity.consumer[-which(colnames(similarity.consumer) == S1[i]), S1[i]], decreasing = TRUE))
        similar.consumer[, 'similarity'] <- sort(similarity.consumer[-which(colnames(similarity.consumer) == S1[i]), S1[i]], decreasing = TRUE)

        # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
        if(similar.consumer[Kc+1, 'similarity'] == similar.consumer[Kc, 'similarity']) {
            same.similarity <- which(similar.consumer[, 'similarity'] == similar.consumer[Kc, 'similarity'])
            similar.consumer[same.similarity, ] <- similar.consumer[sample(same.similarity), ]
            similar.consumer <- similar.consumer[1:Kc, ]
        } else {
            similar.consumer <- similar.consumer[1:Kc, ]
        }# if for random draw


        # Est-ce que la valeur de similarité a de l'importance pour l'attribution des proies?
        # If yes, we could add an argument call wt_predator.
          # if(wt_predator == FALSE) {
          #   resources <- unique of all prey species of all similar predators
          # } else {}

        for(j in 1:Kc) { #loop through consumers

            if(all.equal(similar.consumer[, 'similarity'], rep('0',Kc)) == TRUE) { # if similarities all == 0, break
                break
            } else if(similar.consumer[j, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                NULL
            } else {

                # It's possible that consumers in the list have high taxonomic similarity, but no recorded resource
                candidate.resource <- unlist(strsplit(S0[similar.consumer[j, 'consumer'], 'resource'], " \\|\\ ")) # list of resources for consumer j
                # candidate.resource <- candidate.resource[(candidate.resource %in% resources.S1) == FALSE] # substracting candidate resources that are already listed as resources for S1[i] and hence considered in the preceding code segment

                for(k in 1:length(candidate.resource)) { # loop through resources of consumer j
                    if(length(candidate.resource) == 0) { # if candidate resource list is empty, break
                        break
                    } else if(candidate.resource[1] == "") { # if candidate list is an empty vector "", break
                        break
                    } else if(candidate.resource[k] == S1[i]) {
                    #   #// FIXME: if candidate resource is taxon for which predictions are being made, break (unless we want to allow CANIBALISM). Add argument for cannibalism allowed or not
                         NULL
                    } else if((candidate.resource[k] %in% S1) == TRUE) {
                        if((candidate.resource[k] %in% candidates[, 'resource']) == TRUE) {# if candidate is already in candidate list, add 1 to its weight
                            candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight']) + 1
                        } else {
                            candidates <- rbind(candidates, c(candidate.resource[k], 1)) # if candidate is not in the list, add it with 1 to its weight
                        }#if2

                    } else {
                        # Let's assume for this part that we are not compiling a different similarity measure for predators and preys.
                        similar.resource <- matrix(nrow = length(S1)-1, ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources
                        similar.resource[, 'resource'] <- names(sort(similarity.resource[S1[-which(S1 == S1[i])], candidate.resource[k]], decreasing = TRUE))
                        similar.resource[, 'similarity'] <- sort(similarity.resource[S1[-which(S1 == S1[i])], candidate.resource[k]], decreasing = TRUE)

                        # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
                        if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {
                            same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])
                            similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]
                            similar.resource <- similar.resource[1:Kr, ]
                        } else {
                            similar.resource <- similar.resource[1:Kr, ]
                        }# if for random draw

                        for(l in 1:Kr) { # extracting resource candidates
                            if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break
                                break
                            } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                                NULL
                                # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed
                            } else if(similar.resource[l, 'similarity'] < minimum_threshold) {
                                NULL
                            } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add 1 to its weight
                              candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])
                            } else {
                                  candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it with its weight = similarity
                            }#if3
                        }#l
                    } #if1
                }#k
            }#if
        }#j

        candidates <- candidates[which(candidates[, 'weight'] >= MW), ] # remove candidates with a weight below MW
        if(is.matrix(candidates) == TRUE) { #if it's a vector, there's only one predicted resource, no need to order
            candidates[order(candidates[, 'weight']), ] # sorts candidates according to their weight
            predictions[S1[i], 'resource_predictions'] <- paste(candidates[, 'resource'], collapse = ' | ')
        } else {
          predictions[S1[i], 'resource_predictions'] <- paste(candidates['resource'], collapse = ' | ')
        }#if
    # setTxtProgressBar(pb, i)
    }#i
    # close(pb)
    return(predictions)
}#two_way_tanimoto_predict function
# source("C:/GitHub/practice/datascience/datacamp/intro_to_r/lists.r")

my_vector <- 1:10

my_matrix <- matrix(1:9, ncol = 3)

my_list <- list(my_vector, my_matrix)

names(my_list) <- c("vec", "mat")

my_list2 <- list(vector = my_vector, matrix = my_matrix, first_list = my_list)

vector_from_list2 <- my_list2$first_list$vec

my_list2 <- c(my_list2, additional_value = 123)

str(my_list2)
                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, mytableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, mytableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]
    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
    }
    for (i in 1:max) {
        id <- list11$id[i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), list2[[id]], list11$id[[i]]))
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

gettopgraph <- function(market, mydate, days, topbottom, periodtext) {
    periodtexts <- getperiodtexts(market)
    period <- match(periodtext, periodtexts)
#    cat("perind ", period)
    stocks <- getstockmarket(allstocks, market)
    listdate <- split(stocks, stocks$date)
    datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
    alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
    periodmaps <- alist[[1]]
    stocklistperiod <- alist[[2]]
    mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
    gettopchart(days, topbottom, stocklistperiod, period)
}

getbottomgraph <- function(market, mydate, days, topbottom, periodtext) {
    periodtexts <- getperiodtexts(market)
    period <- match(periodtext, periodtexts)
#    cat("perind ", period)
    stocks <- getstockmarket(allstocks, market)
    listdate <- split(stocks, stocks$date)
    datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
    alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
    periodmaps <- alist[[1]]
    stocklistperiod <- alist[[2]]
    mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
    getbottomchart(days, topbottom, stocklistperiod, period)
}

gettopchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getbottomchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getrisinggraph <- function(market, mydate, days, topbottom, periodtext) {
    periodtexts <- getperiodtexts(market)
    period <- match(periodtext, periodtexts)
#    cat("perind ", period)
    stocks <- getstockmarket(allstocks, market)
    listdate <- split(stocks, stocks$date)
    datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
    alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
    periodmaps <- alist[[1]]
    stocklistperiod <- alist[[2]]
    rise <- getrising(days, periodmaps, stocklistperiod, period)
#    str("riserise")
#    str(names(rise[[1]]))
    risetopids <- head(names(rise[[1]]))
    maindate <- "new"
    olddate <- "old"
    getchart(days, stocklistperiod, period, risetopids)
    #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getchart <- function(days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, periodtext, maindate, olddate) {
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(period) {
    periodtext <- period
    if (period >= 0) {
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (period == pricetype) {
        return (df$price)
    }
    if (period == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, mytableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:count) {
        index <- index - mytableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, ids, periodtext) {
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    ls <- list()
    names <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        dayset <- bigretl[[2]]
                        daynames <- names(dayset)
                        olddate <- min(daynames)
                        newdate <- max(daynames)
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        names[c] <- df$name
                    }
                }
            }
        }
    }
    displaychart(ls, names, 5, periodtext, newdate, olddate)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

# not used

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

# not used

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

if (!exists("marketid")) {
    marketid <- "morncat"
}

if (!exists("mydate")) {
    mydate <- NULL
}

allstocks <- getstocks()
allmetas <- getmetas()
#mymeta <- getmarketmeta(allmetas, marketid)
#data_3 <- getstockmarket(allstocks, marketid)

#for (i in 1:nrow(data_3)) {
                                        #print(data_3[i,"date"])
                                        #return()
#}

                                        #for (i in data_3) {
                                        #print(i["date"])
                                        #return
                                        #}

#listid2 <- splitid(data_3)
#listdate2 <- splitdate(data_3)
#listdate <- split(data_3, data_3$date)
#listid <- split(data_3, data_3$id)

                                        #l <- listdate[[104]]
if (!exists("days")) {
    days <- 10
}
if (!exists("topbottom")) {
    topbottom <- 5
}
count <- days
if (!exists("mytableintervaldays")) {
    mytableintervaldays <- 5
}
                                        #date <- "2016-05-02"

#datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)

if (!exists("period")) {
    period <- 3
}

                                        #alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
                                        #periodmaps <- alist[[1]]
                                        #stocklistperiod <- alist[[2]]
                                        #mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
                                        #mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)

                                        #gettopchart(days, topbottom, stocklistperiod, period)
                                        #getbottomchart(days, topbottom, stocklistperiod, period)
                                        #rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #risetopids <- head(names(rise[[1]]))

#getcontentgraph(date, ids, "1y")

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

# Run init.r before other scripts
rm(list=ls())
 # for use in R console.
 # set own relevant directory if working in R console, otherwise ignore if in terminal
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "./Script/0-1-Tanimoto_data.r
#           RData <- file = './RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "./Script/0-1-Interactions_sources.r
#           RData <- file = "./RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = './Script/1-Similarity_matrix.r'
#       RData <- file = './RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = './Script/2-1-Tanimoto_analysis.r'
#           RData <- file = './RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = './Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = './RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("./Script/tanimoto.r") # basic tanimoto similarity
source("./Script/tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("./Script/similarity_taxon.r") # similarity matrix for set of taxa
source("./Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("./Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("./Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/consumer_set_of_resource.R")
source("./Script/resource_set_of_consumer.R")
source("./Script/prediction_accuracy.r") #
source("./Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("./Script/serialNext.r") # function to avoid overwriting existing files in temporary analyses folder
source("./Script/eplot.r") # empty plot for figure generation
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#    0.1   Formatting interaction catalog
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# LIBRARIES:
library(stringr)
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("../Interaction_catalog/RData/class_tx_tot.RData")
load("../Interaction_catalog/RData/GloBI_classification.RData")
load("../Interaction_catalog/RData/interactions.RData")
load("../Interaction_catalog/RData/GloBI_interactions.RData")
load("../Interaction_catalog/RData/sp_egsl.RData")
# ---------------------------------
# Unique binary interactions
# ---------------------------------

# Select binary interactions with species that have a fully resolved taxonomy
Biotic_inter <- vector('list',4)
names(Biotic_inter) <- c('Binary_interaction','Taxon_list','Inter_taxonomy','EGSL')

  # For Empirical Webs
    consumer <- numeric()
    resource <- numeric()
    pb <- txtProgressBar(min = 0,max = nrow(inter.tot), style = 3)
    for(i in 1:nrow(inter.tot)) {
      if(!is.na(class.tx.tot[inter.tot[i, 'Predator'], 1])) {
        consumer <- c(consumer, 1)
      } else {
        consumer <- c(consumer, 0)
      } #if

      if(!is.na(class.tx.tot[inter.tot[i, 'Prey'], 1])) {
        resource <- c(resource, 1)
      } else {
        resource <- c(resource, 0)
      } #if
      setTxtProgressBar(pb, i)
    } #i
    close(pb)

    # If all = 1, no need to adjust
    unique(consumer)
    unique(resource)

  # For GloBI interactions
    consumer <- numeric()
    resource <- numeric()
    pb <- txtProgressBar(min = 0,max = nrow(GloBI_interactions), style = 3)
    for(i in 1:nrow(GloBI_interactions)) {
      if(!is.na(GloBI_classification[GloBI_interactions[i, 'Predator'], 1])) {
        consumer <- c(consumer, 1)
      } else {
        consumer <- c(consumer, 0)
      } #if

      if(!is.na(GloBI_classification[GloBI_interactions[i, 'Prey'], 1])) {
        resource <- c(resource, 1)
      } else {
        resource <- c(resource, 0)
      } #if
      setTxtProgressBar(pb, i)
    } #i
    close(pb)

    # If all = 1, no need to adjust
    unique(consumer)
    unique(resource)

    cons_res <- cbind(resource,consumer)
    cons_res <- rowSums(cons_res)

    GloBI_interactions <- GloBI_interactions[-which(cons_res != 2), ]

    # Combining biotic interactions in complete dataset
    Biotic_inter[[1]] <- rbind(inter.tot[, 1:3], GloBI_interactions[, 1:3])
    colnames(Biotic_inter[[1]]) <- c('consumer','inter','resource')
    Biotic_inter[[1]] <- unique(Biotic_inter[[1]])

# ---------------------------------
# Unique taxon list
# ---------------------------------
  Biotic_inter[[2]] <- rbind(class.tx.tot, GloBI_classification)
  Biotic_inter[[2]] <- unique(Biotic_inter[[2]])
  rownames(Biotic_inter[[2]]) <- Biotic_inter[[2]][, 'taxon']

  # Adjust taxon names with taxonomy
  for(i in 1:nrow(Biotic_inter[[2]])) {
    Biotic_inter[[2]][i, 'taxon'] <- paste(Biotic_inter[[2]][i,paste(Biotic_inter[[2]][i, 'rank'])])
  }#i

  # Adjust taxon rank not kept
  Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'tribe'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'tribe'), 'family'])
  Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'superfamily'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'superfamily'), 'order'])
  Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'subfamily'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'subfamily'), 'family'])

  # First letter only as capital
  Names_change <- function(x){
    # Name resolve #1
    x <- str_trim(x, side="both") #remove spaces
    x <- tolower(x)
    x <- paste(toupper(substr(x,nchar(x)-(nchar(x)-1),nchar(x)-(nchar(x)-1))),substr(x,nchar(x)-(nchar(x)-2),nchar(x)),sep="")
    return(x)
  }

  Biotic_inter[[2]][, -13] <- apply(Biotic_inter[[2]][, -13], 2, Names_change)
  Biotic_inter[[1]][, -2] <- apply(Biotic_inter[[1]][, -2], 2, Names_change)
  Biotic_inter[[2]] <- apply(Biotic_inter[[2]], 2, gsub, pattern = 'NANA', replacement = 'NA')

  # Also adjust in interactions list
  for(i in 1:nrow(Biotic_inter[[1]])) {
    Biotic_inter[[1]][i, 'consumer'] <- Biotic_inter[[2]][paste(Biotic_inter[[1]][i, 'consumer']), 'taxon']
    Biotic_inter[[1]][i, 'resource'] <- Biotic_inter[[2]][paste(Biotic_inter[[1]][i, 'resource']), 'taxon']
  }

# Also adjust egsl species list
 Biotic_inter[[4]] <- matrix(nrow = nrow(sp.egsl), ncol = ncol(Biotic_inter[[2]]), data = NA, dimnames = list(c(), colnames(Biotic_inter[[2]])))
 rownames(Biotic_inter[[4]]) <- sp.egsl[,1]
 for(i in 1:nrow(sp.egsl)) {
    Biotic_inter[[4]][i, ] <- Biotic_inter[[2]][sp.egsl[i,1], ]
 }

# Also adjust for Empirical Webs interactions
for(i in 1:nrow(inter.tot)) {
  inter.tot[i, 'Predator'] <- Biotic_inter[[2]][paste(inter.tot[i, 'Predator']), 'taxon']
  inter.tot[i, 'Prey'] <- Biotic_inter[[2]][paste(inter.tot[i, 'Prey']), 'taxon']
}

# Also adjust GloBI_interactions
for(i in 1:nrow(GloBI_interactions)) {
  GloBI_interactions[i, 'Predator'] <- Biotic_inter[[2]][paste(GloBI_interactions[i, 'Predator']), 'taxon']
  GloBI_interactions[i, 'Prey'] <- Biotic_inter[[2]][paste(GloBI_interactions[i, 'Prey']), 'taxon']
}

Biotic_inter[[1]] <- Biotic_inter[[1]][-which(Biotic_inter[[1]][,'resource'] == "Copepod"), ]


  # Unique values and adjusting rownames
  Biotic_inter[[1]] <- unique(Biotic_inter[[1]])
  Biotic_inter[[2]] <- unique(Biotic_inter[[2]])
  rownames(Biotic_inter[[2]]) <- Biotic_inter[[2]][, 'taxon']
  rownames(Biotic_inter[[4]]) <- Biotic_inter[[4]][, 'taxon']
  Biotic_inter[[4]] <- Biotic_inter[[4]][,-c(7,9,10,13)]
  GloBI_interactions <- unique(GloBI_interactions[, 1:3])
  inter.tot <- unique(inter.tot[, 1:3])

# --------------------------------------------
# First dataset: taxon with taxonomy as vector
# --------------------------------------------

colnames(GloBI_interactions) <- c('consumer','inter','resource')
taxon.list <- unique(c(unique(Biotic_inter[[1]][, 'consumer']), unique(Biotic_inter[[1]][, 'resource'])))

taxon <- matrix(nrow = length(taxon.list), ncol = 2, data = NA, dimnames = list(c(), c("taxon", "kingdom | phylum | class | order | family | genus | species")))
taxon[, 1] <- taxon.list

# Extracting taxonomy for each binary interaction
rank <- c("kingdom","phylum","class","order","family","genus","species")
taxonomy <- matrix(nrow = nrow(taxon), ncol = length(rank), dimnames = list(c(), rank))

pb <- txtProgressBar(min = 0,max = nrow(taxon), style = 3)
for(i in 1:nrow(taxon)) {
  taxonomy[i, ] <- Biotic_inter[[2]][taxon[i, 'taxon'], rank]
  setTxtProgressBar(pb, i)
} #i
close(pb)

# Combining taxonomy into single element
# Ranks are  "kingdom | phylum | class | order | family | genus | species"
taxon[, 2] <- apply(taxonomy, 1, paste, collapse = ' | ')

# write.table(taxon, "Phil_data/0-taxon_list.txt", sep="\t")

# ---------------------------------------------------------------------------
# Second dataset: Predators with sets of prey and non-prey for Empirical Webs
# ---------------------------------------------------------------------------
rownames(inter.tot) <- seq(1,nrow(inter.tot))
emp.web.inter <- consumer_set_of_resource(consumer = inter.tot[, 'Predator'],
                                          resource = inter.tot[, 'Prey'],
                                          inter_type = inter.tot[, 'FeedInter']
                                          )

# write.table(emp.web.inter, "Phil_data/1-emp_webs_interactions.txt", sep="\t")

emp.web.resource <- resource_set_of_consumer(consumer = inter.tot[, 'Predator'],
                                            resource = inter.tot[, 'Prey'],
                                            inter_type = inter.tot[, 'FeedInter']
                                            )


# ----------------------------------------------------------------------------------
# Third dataset: Predators with sets of prey and non-prey for Empirical Webs + GloBI
# ----------------------------------------------------------------------------------
rownames(Biotic_inter[[1]]) <- seq(1,nrow(Biotic_inter[[1]]))
total.inter <- consumer_set_of_resource(consumer = Biotic_inter[[1]][, 'consumer'],
                                        resource = Biotic_inter[[1]][, 'resource'],
                                        inter_type = Biotic_inter[[1]][, 'inter']
                                        )

# write.table(total.inter, "Phil_data/2-total_interactions.txt", sep="\t")

total.resource <- resource_set_of_consumer(consumer = Biotic_inter[[1]][, 'consumer'],
                                            resource = Biotic_inter[[1]][, 'resource'],
                                            inter_type = Biotic_inter[[1]][, 'inter']
                                            )

# ----------------------------
# Fourth dataset: EGSL species
# ----------------------------
egsl <- matrix(nrow = nrow(Biotic_inter[[4]]), ncol = 2, data = NA, dimnames = list(c(Biotic_inter[[4]][, 'taxon']), c("taxon", "kingdom | phylum | class | order | family | genus | species")))
egsl[, 'taxon'] <- Biotic_inter[[4]][, 'taxon']
egsl[, 2] <- apply(Biotic_inter[[4]][,3:9], 1, paste, collapse = ' | ')
egsl <- unique(egsl)

# remove duplicated taxon
which(duplicated(egsl[,'taxon']))
egsl <- egsl[-1209, ]

# write.table(egsl, "Phil_data/3-EGSL_species.txt", sep="\t", row.names = FALSE, col.names = c('EGSL_species'))

# ----------------------------
# RData
# ----------------------------
Tanimoto_data <- vector("list", 6)
Tanimoto_data[[1]] <- taxon
Tanimoto_data[[2]] <- emp.web.inter
Tanimoto_data[[3]] <- total.inter
Tanimoto_data[[4]] <- egsl
Tanimoto_data[[5]] <- emp.web.resource
Tanimoto_data[[6]] <- total.resource

save(x = Tanimoto_data, file = "./RData/Tanimoto_data.RData")
# source("C:/GitHub/practice/datascience/datacamp/intro_to_r/data_frames.r")

mtcars <- read.csv("C:/GitHub/practice/datascience/datacamp/intro_to_r/data/mtcars.csv")

#head(mtcars)
#str(mtcars)

terrestrial <- "Terrestrial planet"
gas_giant <- "Gas giant"

name <- c("Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune")
type <- c(terrestrial, terrestrial, terrestrial,
          terrestrial, gas_giant, gas_giant, gas_giant, gas_giant)
diameter <- c(0.382, 0.949, 1, 0.532, 11.209, 9.449, 4.007, 3.883)
rotation <- c(58.64, -243.02, 1, 1.03, 0.41, 0.43, -0.72, 0.67)
rings <- c(FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE)

planets_df <- data.frame(name, type, diameter, rotation, rings)

str(planets_df)

mercury_diameter <- planets_df[1,3]
mars_data <- planets_df[4,]

first_five_diameters <- planets_df[1:5,"diameter"]

rings_vector <- planets_df$rings

planet_data_with_rings <- planets_df[rings_vector,]
splitLog <- function(dt, burninP = .2){ ## get indicators and coefficients while discarding burn-in
  ## 'Product' is whether coefficients should be delta*beta (default) or just beta
  res <- vector(2, mode = "list")
  names(res) <- c("Indicators", "Coefficients")
  init <- round(.2 * nrow(dt))
  dt.b <- dt[init:nrow(dt), ]
  res[[1]] <- dt.b[, grep("coefIndicator", names(dt.b))]
  res[[2]] <- dt.b[, grep("GLM.glmCoefficients", names(dt.b))]
  return(res)
}
getSummary <- function(x, alpha = .95){
  return(
    data.frame(lwr = as.numeric(quantile(x, probs = (1 - alpha)/2 )),
               mean = mean(x),
               upr = as.numeric(quantile(x, probs = (1 + alpha)/2)),
               row.names = "")
  )
}
#
list2df <- function(ll){ ## could be skipped with a little of extra work... TODO
  N <- length(ll)
  dt <- data.frame(matrix(NA, nrow = N, ncol = 4 ))
  names(dt) <- c("parameter", "lwr", "mean", "upr")
  dt$parameter <- names(ll)
  for(i in 1:N) dt[i, 2:4] <- ll[[i]]
  return(dt)
}
#
getSummary <- function(x, alpha = .95){
  return(data.frame(lwr = quantile(x, probs = (1 - alpha)/2) ,
                    mean = mean(x),
                    upr = quantile(x, probs = (1 + alpha)/2)
  ))
}
#
conditional_betas_BEAST <- function(betas, inds){
  if(ncol(betas) != ncol(inds)) stop("Coefficients and indicators are not the same dimension")
  K <- ncol(betas)
  result <- data.frame(matrix(NA, ncol = 3 , nrow = K))
  names(result) <- c("lwr", "mean", "upr")
  for(k in 1:K){
    result[k, ] <- getSummary(betas[, k][inds[, k] == 1])
  }
  return(result)
}
#
plotSimpleGLM <- function(Names, Log, probZero = .5, BF = 3, intercept = FALSE, Burnin = .2,
                          export = TRUE, fileName = "GLM_plot", title = ""){
  require(ggplot2)
  require(repr)
  require(scales)
  require(grid)
  ## 'Names' is a vector with the predictor names
  ## 'Log' is the .log file [already loaded as a data.frame] to be analysed
  ## 'probZero' is the probability that no predictors are included
  ## 'BF' is the Bayes factor threshold (default 3)
  ## 'intercept' is a boolean specifying whether an intercept was included in the model
  ## 'Burnin' is the percent of the chain to be discarded as burn-in
  ## 'betaind' is a boolean specifying whether to report delta*beta
  Pars <- splitLog(Log, burninP = Burnin)
  if(intercept){
    if(!ncol(Pars$Indicators)== (length(Names)+ 1)) stop("Model probably doesn't have intercept")
    Pars <- lapply(Pars, function(x) x[, -ncol(x)])
  }
  Summaries <- lapply(Pars, function(d) apply(d, 2, getSummary))
  SumDf <- lapply(Summaries, list2df)
  npred <- length(Names)
  inclusion.probabilities <- data.frame(
    p.mean = SumDf$Indicators$mean,
    p.lwr =  SumDf$Indicators$lwr,
    p.upr =  SumDf$Indicators$upr,
    predictor = Names
  )
  #
  regression.coefficients <- data.frame(predictor = Names,
                                        b = conditional_betas_BEAST(betas = Pars$Coefficients,
                                                                    inds = Pars$Indicators))
  #
  q <- 1-((probZero)^(1/npred))
  bf <- BF
  cutoff <- (q*bf)/(q*(bf-1) + 1)
  #
  p0 <- ggplot(regression.coefficients, aes(x = predictor , y = b.mean))+
    geom_pointrange(aes(ymin = b.lwr, ymax = b.upr), position = position_dodge(0.5)) +
    coord_flip() +
    scale_y_continuous("Coefficient", expand = c(0, 0)) +
    scale_x_discrete("Predictor") +
    geom_hline(yintercept = 0, linetype = "solid", color = "black", size = 0.5) +
    theme_bw()

  p0 <- p0 +  theme(legend.position = "none")
  p1 <- ggplot(inclusion.probabilities, aes(x = predictor, y = p.mean))+
    geom_bar(stat = "identity") +
    coord_flip() +
    scale_y_continuous("Inclusion probability", expand = c(0, 0)) +
    scale_x_discrete("Predictor") +
    geom_hline(yintercept = cutoff, linetype = "dashed", colour = "black", size = 0.7) +
    geom_hline(yintercept = q, linetype = "solid", colour = "green", size = 0.2) +
    ggtitle(title) +
    theme_bw()
  p1 <- p1 + guides(fill = guide_legend(reverse = TRUE)) +
    theme(axis.text.y = element_blank(),
          axis.ticks.y = element_blank(),
          axis.title.y = element_blank()
    )
  if(export){
    pdf(paste(fileName, ".pdf", sep = ""))
  }
  options(repr.plot.width = 10, repr.plot.height = 5)
  grid.draw(cbind(ggplotGrob(p0), ggplotGrob(p1), size = "first"))
  if(export){
    dev.off()
  }
}
splitLog <- function(dt, burninP = .2){ ## get indicators and coefficients while discarding burn-in
  ## 'Product' is whether coefficients should be delta*beta (default) or just beta
  res <- vector(2, mode = "list")
  names(res) <- c("Indicators", "Coefficients")
  init <- round(.2 * nrow(dt))
  dt.b <- dt[init:nrow(dt), ]
  res[[1]] <- dt.b[, grep("coefIndicator", names(dt.b))]
  res[[2]] <- dt.b[, grep("GLM.glmCoefficients", names(dt.b))]
  return(res)
}
getSummary <- function(x, alpha = .95){
  return(
    data.frame(lwr = as.numeric(quantile(x, probs = (1 - alpha)/2 )),
         mean = mean(x), upr = as.numeric(quantile(x, probs = (1 + alpha)/2)), row.names = "")
  )
}
#
list2df <- function(ll){ ## could be skipped with a little of extra work... TODO
  N <- length(ll)
  dt <- data.frame(matrix(NA, nrow = N, ncol = 4 ))
  names(dt) <- c("parameter", "lwr", "mean", "upr")
  dt$parameter <- names(ll)
  for(i in 1:N) dt[i, 2:4] <- ll[[i]]
  return(dt)
}
#
getSummary <- function(x, alpha = .95){
  return(data.frame(lwr = quantile(x, probs = (1 - alpha)/2) ,
                    mean = mean(x),
                    upr = quantile(x, probs = (1 + alpha)/2)
  ))
}
#
conditional_betas_BEAST <- function(betas, inds){
  if(ncol(betas) != ncol(inds)) stop("Coefficients and indicators are not the same dimension")
  K <- ncol(betas)
  result <- data.frame(matrix(NA, ncol = 3 , nrow = K))
  names(result) <- c("lwr", "mean", "upr")
  for(k in 1:K){
    result[k, ] <- getSummary(betas[, k][inds[, k] == 1])
  }
  return(result)
}
#
plotSimpleGLM <- function(Names, Log, probZero = .5, BF = 3, intercept = FALSE, Burnin = .2,
                          export = TRUE, fileName = "GLM_plot", title = ""){
  require(ggplot2)
  require(repr)
  require(scales)
  require(grid)
  ## 'Names' is a vector with the predictor names
  ## 'Log' is the .log file [already loaded as a data.frame] to be analysed
  ## 'probZero' is the probability that no predictors are included
  ## 'BF' is the Bayes factor threshold (default 3)
  ## 'intercept' is a boolean specifying whether an intercept was included in the model
  ## 'Burnin' is the percent of the chain to be discarded as burn-in
  ## 'betaind' is a boolean specifying whether to report delta*beta
  Pars <- splitLog(Log, burninP = Burnin)
  if(intercept){
    if(!ncol(Pars$Indicators)== (length(Names)+ 1)) stop("Model probably doesn't have intercept")
    Pars <- lapply(Pars, function(x) x[, -ncol(x)])
  }
  Summaries <- lapply(Pars, function(d) apply(d, 2, getSummary))
  SumDf <- lapply(Summaries, list2df)
  npred <- length(Names)
  inclusion.probabilities <- data.frame(
    p.mean = SumDf$Indicators$mean,
    p.lwr =  SumDf$Indicators$lwr,
    p.upr =  SumDf$Indicators$upr,
    predictor = Names
  )
  #
  regression.coefficients <- data.frame(predictor = Names,
                                        b = conditional_betas_BEAST(betas = Pars$Coefficients,
                                                                    inds = Pars$Indicators))
  #
  q <- 1-((probZero)^(1/npred))
  bf <- BF
  cutoff <- (q*bf)/(q*(bf-1) + 1)
  #
  p0 <- ggplot(regression.coefficients, aes(x = predictor , y = b.mean))+
    geom_pointrange(aes(ymin = b.lwr, ymax = b.upr), position = position_dodge(0.5)) +
    coord_flip() +
    scale_y_continuous("Coefficient", expand = c(0, 0)) +
    scale_x_discrete("Predictor") +
    geom_hline(yintercept = 0, linetype = "solid", color = "black", size = 0.5) +
    theme_bw()

  p0 <- p0 +  theme(legend.position = "none")
  p1 <- ggplot(inclusion.probabilities, aes(x = predictor, y = p.mean))+
    geom_bar(stat = "identity") +
    coord_flip() +
    scale_y_continuous("Inclusion probability", expand = c(0, 0)) +
    scale_x_discrete("Predictor") +
    geom_hline(yintercept = cutoff, linetype = "dashed", colour = "black", size = 0.7) +
    geom_hline(yintercept = q, linetype = "solid", colour = "green", size = 0.2) +
    ggtitle(title) +
    theme_bw()
  p1 <- p1 + guides(fill = guide_legend(reverse = TRUE)) +
    theme(axis.text.y = element_blank(),
          axis.ticks.y = element_blank(),
          axis.title.y = element_blank()
    )
  if(export){
    pdf(paste(fileName, ".pdf", sep = ""))
  }
  options(repr.plot.width = 10, repr.plot.height = 5)
  grid.draw(cbind(ggplotGrob(p0), ggplotGrob(p1), size = "first"))
  if(export){
    dev.off()
  }
}
# Run init.r before other scripts
rm(list=ls())
 # for use in R console.
 # set own relevant directory if working in R console, otherwise ignore if in terminal
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "./Script/0-1-Tanimoto_data.r
#           RData <- file = './RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "./Script/0-1-Interactions_sources.r
#           RData <- file = "./RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = './Script/1-Similarity_matrix.r'
#       RData <- file = './RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = './Script/2-1-Tanimoto_analysis.r'
#           RData <- file = './RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = './Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = './RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("./Script/tanimoto.r") # basic tanimoto similarity
source("./Script/tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("./Script/similarity_taxon.r") # similarity matrix for set of taxa
source("./Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("./Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("./Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/consumer_set_of_resource.R")
source("./Script/prediction_accuracy.r") #
source("./Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("./Script/serialNext.r") # function to avoid overwriting existing files in temporary analyses folder
source("./Script/eplot.r") # empty plot for figure generation
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# Generating serial number for files in case file already exists
# http://stackoverflow.com/questions/25429557/how-to-create-a-new-output-file-in-r-if-a-file-with-that-name-already-exists
serialNext = function(prefix){
    if(!file.exists(prefix)){
        return(prefix)
    }
        i=1
    repeat {
        f = paste(unlist(strsplit(prefix, '[.]R'))[1],i,'.R',unlist(strsplit(prefix, '[.]R'))[2],sep="")
        if(!file.exists(f)){return(f)}
        i=i+1
     }
  }
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:
    filename <- 'Multiple_parameters'
    min.tx = 45
    K.values = c(2,4,6,8)
    MW = c(1,3,5)
    WT = c(0,0.3,0.6,1)
    blind = FALSE
    minimum_threshold = 0.3
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/Tanimoto_data.RData")
load("./RData/interactions_source.RData")
suppressMessages(load("./RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
# Format interaction catalogue to fit this table format
    S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
    S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
    }

# setting up the analyses for multiple communities
# Data for communities on which to test the algorithm
    Cm <- unique(interactions_sources[, 'source'])
    communities <- vector("list", length(Cm))
    names(communities) <- Cm

    # Taxa list per community to predict
        for(i in 1:length(communities)) {
            Ci <- which(interactions_sources[, 'source'] == Cm[i])
            S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

            if(length(which(!S1 %in% S0_catalog)) > 0) {
                print('Taxa in C[i] are not all included in taxa list S0')
                break
            }

            communities[[i]] <- S1
        }

# Substracting GloBI interactions for this portion
    Cm.lg <- numeric()
    for(i in 1:length(communities)) {
        Cm.lg <- c(Cm.lg,length(communities[[i]]))
    }

    to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

    Cm <- Cm[-to.delete]
    for(i in rev(to.delete)) {
        communities[[i]] <- NULL
    }
    names(communities) <- Cm

# Setting up lists to store the results
    wt.init <- wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
    wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
    for(i in rev(wt.remove)) {
        similarity.matrices[[i]] <- NULL
    }

    sim.wt <- names(similarity.matrices)
    Tanimoto_analysis <- vector("list",length(sim.wt))
    names(Tanimoto_analysis) <- sim.wt
    for(i in 1:length(sim.wt)) {
        Tanimoto_analysis[[i]] <- vector("list", length(Cm))
        names(Tanimoto_analysis[[i]]) <- Cm
    }

# List to store results of multiple K values
K <- vector("list", length(K.values))
for(i in 1:length(K.values)) {
    K[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- K
names(Tanimoto_analysis) <- K.values
remove(K)

min.wt <- vector("list", length(MW))
for(i in 1:length(MW)) {
    min.wt[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- min.wt
names(Tanimoto_analysis) <- MW
remove(min.wt)

file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
save(x = Tanimoto_analysis, file = file.to.save)

init.time <- Sys.time()
for(n in 1:length(MW)) {
    mw <- MW[n]
    for(m in 1:length(K.values)) {

        # Tanimoto analysis with different weights for different communities
            # Parameters:
                Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
            #   wt  Weight of traits in similarity measurement
            #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
            #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

            # Output:
            #   A vector of sets of resources for each taxon

            for(i in 1:length(WT)){ #1st loop for all types of wt values
                wt <- WT[i]
                pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                for(j in 1:length(Cm)) { #2nd loop for all C[i]
                    S1 <- communities[[j]]
                    S0 <- S0_catalog
                    similarity.matrix <- similarity.matrices[[i]]

                    # Two choices here:
                    #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                    #   2. The analysis takes into account preexisting information already contained in the catalogue

                    # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                    if(blind == TRUE) {
                        for(k in 1:length(S1)) {
                          S0[S1[k], 'resource'] <- ""
                          S0[S1[k], 'non-resource'] <- ""
                        }

                    # 2. Preexisting information kept to inform algorithm
                    } else { # blind == FALSE

                        interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                        # Only modifying those that are loosing data from the catalogue, less time
                            to.change <- numeric()
                            for(k in 1:length(S1)) {
                                to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                            }
                            to.change <- unique(to.change)

                        # Modifying sets of resources and non-resources for taxa in S1
                            interactions <- interactions[to.change, ]
                            rownames(interactions) <- seq(1,nrow(interactions))
                            resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                      resource = interactions[, 'resource'],
                                                                      inter_type = interactions[, 'inter'])

                        # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                            for(k in 1:nrow(resource_set)) {
                              S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                              S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                            }
                        remove(interactions, resource_set, to.change)
                    } #if blind or not blind

                    # Recalculate similarity
                        similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                            S1 = S1,
                                                                            wt = wt,
                                                                            similarity.matrix = similarity.matrix)

                    # Predicting interactions
                        Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                Kr = Kr,
                                                                                S0 = S0,
                                                                                S1 = S1,
                                                                                MW = mw,
                                                                                similarity.matrix = similarity.matrix,
                                                                                minimum_threshold = minimum_threshold)

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(S0, S1, similarity.matrix)
                    setTxtProgressBar(pb, j)
                }#2nd loop for all C[i]

                save(x = Tanimoto_analysis, file = file.to.save)
                remove(wt)

            }#1st loop for all types of wt values
            close(pb)
    }#m
}#n
print(Sys.time() - init.time)

# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf("./Article/Catalog_vs_predictions.pdf",width=7,height=7)
# Plots
par(mfrow=c(2,2))
# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 1.09)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000088","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
            axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
            # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
            points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
        } #i

        ## Add legend
        if(j == 12) {
            legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        }
} #j
dev.off()

save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))
# Run readme.r before other scripts
rm(list=ls())
 # for use in R console.
 # set own relevant directory if working in R console, otherwise ignore if in terminal
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "./Script/0-1-Tanimoto_data.r
#           RData <- file = './RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "./Script/0-1-Interactions_sources.r
#           RData <- file = "./RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = './Script/1-Similarity_matrix.r'
#       RData <- file = './RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = './Script/2-1-Tanimoto_analysis.r'
#           RData <- file = './RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = './Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = './RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("./Script/tanimoto.r") # basic tanimoto similarity
source("./Script/tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("./Script/similarity_taxon.r") # similarity matrix for set of taxa
source("./Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("./Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("./Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/consumer_set_of_resource.R")
source("./Script/prediction_accuracy.r") #
source("./Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("./Script/serialNext.r") # function to avoid overwriting existing files in temporary analyses folder
source("./Script/eplot.r") # empty plot for figure generation
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#    0.2   Extracting which taxa is found in which community from empirical data
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# LIBRARIES:
library(stringr)
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------

#Loading all datasets with interactions
load("../Interaction_catalog/RData/barnes2008.RData")
load("../Interaction_catalog/RData/Kortsch2015.RData")
load("../Interaction_catalog/RData/GlobalWeb.RData")
load("../Interaction_catalog/RData/brose2005.RData")
load("../Interaction_catalog/RData/class_tx_tot.RData")
load("../Interaction_catalog/RData/GloBI_classification.RData")
load("../Interaction_catalog/RData/GloBI_interactions.RData")

# load("RData/EwE.RData") # Not yet finished
# load("RData/GloBI.RData") # Not yet finished

# List of webs
InterDataTot <- c(Barnes2008, Brose2005, GlobalWeb, Kortsch2015) # EwE to add

# Complete taxon list and interaction list from all webs
tx.list <- matrix(nrow=0, ncol=2, data=NA, dimnames = list(c(), c("taxon","rank")))
inter.list <- matrix(nrow=0, ncol=4, data=NA, dimnames = list(c(), c("Predator","FeedInter","Prey","Source")))


for(i in 1:length(InterDataTot)) {
  tx.list <- rbind(tx.list, as.matrix(InterDataTot[[i]][[5]]))
  inter.list <- rbind(inter.list, cbind(as.matrix(InterDataTot[[i]][[4]]), rep(names(InterDataTot[i]), nrow(InterDataTot[[i]][[4]]))))
}

tx.list <- unique(tx.list)
inter.list <- unique(inter.list)

# Taxonomic resolutions and those selected to move further in the analysis
# Decision is to use all taxonomic resolutions greater or equal to families
taxo.resol <- unique(inter.list[, 2])
taxo.resolution.accepted <- c("species", "genus", "family", "tribe", "subfamily", "superfamily")

# Extracting interactions for analysis
time_init <- Sys.time()
inter.tot <- inter_taxo_resolution(tx.list, inter.list, taxo.resolution.accepted)
Sys.time() - time_init

# Changing to binary interactions
for(i in 1:nrow(inter.tot)) {
  if(inter.tot[i, 2] != "0" & inter.tot[i, 2] != "1") {inter.tot[i, 2] <- "1"}
}

# Extracting taxon list for analysis
row.tx.accepted <- numeric()
for(i in 1:length(taxo.resolution.accepted)) {
  row.tx.accepted <- c(row.tx.accepted,which(tx.list[,2] == taxo.resolution.accepted[i]))
}

tx.list.tot <- tx.list[row.tx.accepted, ]

#inter.tot
#tx.list.tot

# ---------------- INTERACTIONS ---------------
GloBI_interactions <- cbind(GloBI_interactions[, c('Predator','FeedInter','Prey')], rep('GloBI', nrow(GloBI_interactions)), GloBI_interactions[, 'inter.resolution'])

Biotic_inter <- vector('list',4)
names(Biotic_inter) <- c('Binary_interaction','Taxon_list','Inter_taxonomy','EGSL')

# Combining biotic interactions in complete dataset
Biotic_inter[[1]] <- rbind(inter.tot[, 1:4], GloBI_interactions[, 1:4])
colnames(Biotic_inter[[1]]) <- c('consumer','inter','resource','source')
Biotic_inter[[1]] <- unique(Biotic_inter[[1]])

# ---------------------------------
# Unique taxon list
# ---------------------------------
Biotic_inter[[2]] <- rbind(class.tx.tot, GloBI_classification)
Biotic_inter[[2]] <- unique(Biotic_inter[[2]])
rownames(Biotic_inter[[2]]) <- Biotic_inter[[2]][, 'taxon']

# Adjust taxon names with taxonomy
for(i in 1:nrow(Biotic_inter[[2]])) {
Biotic_inter[[2]][i, 'taxon'] <- paste(Biotic_inter[[2]][i,paste(Biotic_inter[[2]][i, 'rank'])])
}#i

# Adjust taxon rank not kept
Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'tribe'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'tribe'), 'family'])
Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'superfamily'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'superfamily'), 'order'])
Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'subfamily'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'subfamily'), 'family'])

# First letter only as capital
Names_change <- function(x){
# Name resolve #1
x <- str_trim(x, side="both") #remove spaces
x <- tolower(x)
x <- paste(toupper(substr(x,nchar(x)-(nchar(x)-1),nchar(x)-(nchar(x)-1))),substr(x,nchar(x)-(nchar(x)-2),nchar(x)),sep="")
return(x)
}

Biotic_inter[[2]][, -13] <- apply(Biotic_inter[[2]][, -13], 2, Names_change)
Biotic_inter[[1]][, -2] <- apply(Biotic_inter[[1]][, -2], 2, Names_change)
Biotic_inter[[2]] <- apply(Biotic_inter[[2]], 2, gsub, pattern = 'NANA', replacement = 'NA')
Biotic_inter[[1]]<- Biotic_inter[[1]][-which(Biotic_inter[[1]][, 'resource'] == 'Unidentified'), ] # Removing unidentified

no.result.to.delete <- c( "Baraeoptera roria",
                          "Cydorus latus",
                          "Hemiuris communis",
                          "Hyponigrus obsidianus",
                          "Sarortherdon macrochir",
                          "Scaphaloberis mucronata",
                          "Secernentia nematodes",
                          "Zealolessica cheira",
                          "Haploparaksis crassirostris",
                          'Spermophilus armatus',
                          "Spermophilus brunneus",
                          "Spermophilus franklinii",
                          "Spermophilus richardsonii",
                          "Spermophilus tridecemlineatus",
                          "Spermophilus washingtoni",
                          'Glossoma',
                          "Paracentropristes pomospilus",
                          "Delphacinae",
                          "Staphylininae",
                          "Ursinae",
                          "Zelandoperlinae",
                          "Euclymeninae",
                          "Pilumninae")

to.delete <- numeric() # À utiliser à la fin après avoir combiner les jeux de données
for(i in 1:length(no.result.to.delete)){
to.delete <- c(to.delete,which(Biotic_inter[[1]][, 'resource'] == no.result.to.delete[i]), which(Biotic_inter[[1]][, 'consumer'] == no.result.to.delete[i]))
}
to.delete <- unique(to.delete)
Biotic_inter[[1]] <- Biotic_inter[[1]][-to.delete, ]

# Also adjust in interactions list
for(i in 1:nrow(Biotic_inter[[1]])) {
Biotic_inter[[1]][i, 'consumer'] <- Biotic_inter[[2]][paste(Biotic_inter[[1]][i, 'consumer']), 'taxon']
Biotic_inter[[1]][i, 'resource'] <- Biotic_inter[[2]][paste(Biotic_inter[[1]][i, 'resource']), 'taxon']
}

# Unique values and adjusting rownames
Biotic_inter[[1]] <- unique(Biotic_inter[[1]])
Biotic_inter[[2]] <- unique(Biotic_inter[[2]])
rownames(Biotic_inter[[2]]) <- Biotic_inter[[2]][, 'taxon']

# Les informations de GloBI peuvent être une duplication des informations déjà relevées des food webs empiriques. Il faudrait songer à les retirer.
for(i in 1:nrow(Biotic_inter[[1]])) {
    if(Biotic_inter[[1]][i, 'source'] == "Globi") {
        Biotic_inter[[1]][i, 'source'] <- ""
    }
}
interactions_sources <- Biotic_inter[[1]]
interactions_sources <- interactions_sources[-which(interactions_sources[,'resource'] == "Copepod"), ]
rownames(interactions_sources) <- seq(1,nrow(interactions_sources))
save(x = interactions_sources, file = "./RData/interactions_source.RData")
#
# # Interactions unique avec sources
# multi_inter <- which(duplicated(Biotic_inter[[1]][,1:3]))
# # to.remove <- numeric() # If I wish to remove duplicated interactions at this stage
# for(i in 1:length(multi_inter)) {
#     duplicata <- which(Biotic_inter[[1]][, 1] == Biotic_inter[[1]][multi_inter[i], 1] & Biotic_inter[[1]][, 2] == Biotic_inter[[1]][multi_inter[i], 2] & Biotic_inter[[1]][, 3] == Biotic_inter[[1]][multi_inter[i], 3])
#
#     for(j in 2:length(duplicata)) {
#         if(Biotic_inter[[1]][duplicata[j], 'source'] == "") {
#             NULL
#         } else {
#             Biotic_inter[[1]][duplicata[1], 'source'] <- paste(c(Biotic_inter[[1]][duplicata[1], 'source'], Biotic_inter[[1]][duplicata[j], 'source']), collapse = " | ")
#         }
#         # to.remove <- c(to.remove, duplicata[j])
#     }#j
# }#i
# # Biotic_inter[[1]] <- Biotic_inter[[1]][-to.remove, ]
#
# # Set of sources
# #   Pour les analyses, tout sera retiré pour chaque S1, même si des informations alternatives sont disponibles. On sera donc nécessairement à blind = TRUE
# load("RData/Tanimoto_data.RData")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#    1. Evaluating similarity of consumers and resources
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
# // TODO: Evaluate similarity based on set of consumers for resources
# // TODO: Look into proximity graphs for better performance
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# LIBRARIES:
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------

# Measuring the similarity with multiple weights for all taxa in interaction catalogue
# Will be better once we code for proximity graphs
    wt <- seq(0, 1, by = 0.1)
    similarity.matrices <- vector('list',11)
    names(similarity.matrices) <- seq(0, 1, by = 0.1)
    for(i in 1:length(wt)) {
        similarity.matrices[[i]] <- similarity_taxon(S0 = S0_catalog, wt = wt[i])
        save(x = similarity.matrices, file = "./RData/Similarity.matrices.RData")
    }
    save(x = similarity.matrices, file = "./RData/Similarity.matrices.RData")
    # -----------------------------------------------------------------------------
    # PROJECT:
    #    Evaluating the structure of the communities of the estuary
    #    and gulf of St.Lawrence
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # STEP:
    #   2. Tanimoto analysis for multiple parameter values
    # -----------------------------------------------------------------------------

    # Evaluating the contribution of the catalog vs the predictions to the algorithm

    # -----------------------------------------------------------------------------
    # FILES:
    #   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
    #   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # PARAMETERS:
        filename <- 'Catalog_vs_predictions'
        min.tx = 45
        K.values = 8
        MW = 1
        WT = seq(0,1,by=0.1)
        blind = FALSE
        minimum_threshold = 0.3
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # SCRIPT
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    suppressMessages(load("./RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- seq(0,1,by=0.1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            similarity.matrices[[i]] <- NULL
        }

        sim.wt <- names(similarity.matrices)
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

    # List to store results of multiple K values
    K <- vector("list", length(K.values))
    for(i in 1:length(K.values)) {
        K[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- K
    names(Tanimoto_analysis) <- K.values
    remove(K)

    min.wt <- vector("list", length(MW))
    for(i in 1:length(MW)) {
        min.wt[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- min.wt
    names(Tanimoto_analysis) <- MW
    remove(min.wt)

    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    init.time <- Sys.time()
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon

                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog
                        similarity.matrix <- similarity.matrices[[i]]

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.matrix)

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.matrix = similarity.matrix,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.matrix)
                        setTxtProgressBar(pb, j)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values
                close(pb)
        }#m
    }#n
    print(Sys.time() - init.time)

# Catalog vs predictions
    accuracy  <- vector('list', 3)
    names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
    accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
    accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
    accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
    pdf("./Article/Catalog_vs_predictions.pdf",width=7,height=7)
    # Plots
    par(mfrow=c(2,2))
    # Graph
    for(j in 9:12) {
            eplot(xmin = -0.09, xmax = 1.09)
            par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
            foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
            names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
            col <- c("#FF8822","#449955","#2288FF")
            # col <- c("#FF000088","#00FF0088","#0000FF88")
            # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
            # col <- sample(colours(), length(foodwebs))

            # Axes
                # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
                axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
                axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
                axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
                axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
                # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
                # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

                mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
                mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

            for(i in 1:length(accuracy)) {
                accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                # hack: we draw arrows but with very special "arrowheads" for error bars
                arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
                points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
            } #i

            ## Add legend
            if(j == 12) {
                legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
            }
    } #j
    dev.off()

save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#    0.1   Formatting interaction catalog
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# LIBRARIES:
library(stringr)
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("../Interaction_catalog/RData/class_tx_tot.RData")
load("../Interaction_catalog/RData/GloBI_classification.RData")
load("../Interaction_catalog/RData/interactions.RData")
load("../Interaction_catalog/RData/GloBI_interactions.RData")
load("../Interaction_catalog/RData/sp_egsl.RData")
# ---------------------------------
# Unique binary interactions
# ---------------------------------

# Select binary interactions with species that have a fully resolved taxonomy
Biotic_inter <- vector('list',4)
names(Biotic_inter) <- c('Binary_interaction','Taxon_list','Inter_taxonomy','EGSL')

  # For Empirical Webs
    consumer <- numeric()
    resource <- numeric()
    pb <- txtProgressBar(min = 0,max = nrow(inter.tot), style = 3)
    for(i in 1:nrow(inter.tot)) {
      if(!is.na(class.tx.tot[inter.tot[i, 'Predator'], 1])) {
        consumer <- c(consumer, 1)
      } else {
        consumer <- c(consumer, 0)
      } #if

      if(!is.na(class.tx.tot[inter.tot[i, 'Prey'], 1])) {
        resource <- c(resource, 1)
      } else {
        resource <- c(resource, 0)
      } #if
      setTxtProgressBar(pb, i)
    } #i
    close(pb)

    # If all = 1, no need to adjust
    unique(consumer)
    unique(resource)

  # For GloBI interactions
    consumer <- numeric()
    resource <- numeric()
    pb <- txtProgressBar(min = 0,max = nrow(GloBI_interactions), style = 3)
    for(i in 1:nrow(GloBI_interactions)) {
      if(!is.na(GloBI_classification[GloBI_interactions[i, 'Predator'], 1])) {
        consumer <- c(consumer, 1)
      } else {
        consumer <- c(consumer, 0)
      } #if

      if(!is.na(GloBI_classification[GloBI_interactions[i, 'Prey'], 1])) {
        resource <- c(resource, 1)
      } else {
        resource <- c(resource, 0)
      } #if
      setTxtProgressBar(pb, i)
    } #i
    close(pb)

    # If all = 1, no need to adjust
    unique(consumer)
    unique(resource)

    cons_res <- cbind(resource,consumer)
    cons_res <- rowSums(cons_res)

    GloBI_interactions <- GloBI_interactions[-which(cons_res != 2), ]

    # Combining biotic interactions in complete dataset
    Biotic_inter[[1]] <- rbind(inter.tot[, 1:3], GloBI_interactions[, 1:3])
    colnames(Biotic_inter[[1]]) <- c('consumer','inter','resource')
    Biotic_inter[[1]] <- unique(Biotic_inter[[1]])

# ---------------------------------
# Unique taxon list
# ---------------------------------
  Biotic_inter[[2]] <- rbind(class.tx.tot, GloBI_classification)
  Biotic_inter[[2]] <- unique(Biotic_inter[[2]])
  rownames(Biotic_inter[[2]]) <- Biotic_inter[[2]][, 'taxon']

  # Adjust taxon names with taxonomy
  for(i in 1:nrow(Biotic_inter[[2]])) {
    Biotic_inter[[2]][i, 'taxon'] <- paste(Biotic_inter[[2]][i,paste(Biotic_inter[[2]][i, 'rank'])])
  }#i

  # Adjust taxon rank not kept
  Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'tribe'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'tribe'), 'family'])
  Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'superfamily'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'superfamily'), 'order'])
  Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'subfamily'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'subfamily'), 'family'])

  # First letter only as capital
  Names_change <- function(x){
    # Name resolve #1
    x <- str_trim(x, side="both") #remove spaces
    x <- tolower(x)
    x <- paste(toupper(substr(x,nchar(x)-(nchar(x)-1),nchar(x)-(nchar(x)-1))),substr(x,nchar(x)-(nchar(x)-2),nchar(x)),sep="")
    return(x)
  }

  Biotic_inter[[2]][, -13] <- apply(Biotic_inter[[2]][, -13], 2, Names_change)
  Biotic_inter[[1]][, -2] <- apply(Biotic_inter[[1]][, -2], 2, Names_change)
  Biotic_inter[[2]] <- apply(Biotic_inter[[2]], 2, gsub, pattern = 'NANA', replacement = 'NA')

  # Also adjust in interactions list
  for(i in 1:nrow(Biotic_inter[[1]])) {
    Biotic_inter[[1]][i, 'consumer'] <- Biotic_inter[[2]][paste(Biotic_inter[[1]][i, 'consumer']), 'taxon']
    Biotic_inter[[1]][i, 'resource'] <- Biotic_inter[[2]][paste(Biotic_inter[[1]][i, 'resource']), 'taxon']
  }

# Also adjust egsl species list
 Biotic_inter[[4]] <- matrix(nrow = nrow(sp.egsl), ncol = ncol(Biotic_inter[[2]]), data = NA, dimnames = list(c(), colnames(Biotic_inter[[2]])))
 rownames(Biotic_inter[[4]]) <- sp.egsl[,1]
 for(i in 1:nrow(sp.egsl)) {
    Biotic_inter[[4]][i, ] <- Biotic_inter[[2]][sp.egsl[i,1], ]
 }

# Also adjust for Empirical Webs interactions
for(i in 1:nrow(inter.tot)) {
  inter.tot[i, 'Predator'] <- Biotic_inter[[2]][paste(inter.tot[i, 'Predator']), 'taxon']
  inter.tot[i, 'Prey'] <- Biotic_inter[[2]][paste(inter.tot[i, 'Prey']), 'taxon']
}

# Also adjust GloBI_interactions
for(i in 1:nrow(GloBI_interactions)) {
  GloBI_interactions[i, 'Predator'] <- Biotic_inter[[2]][paste(GloBI_interactions[i, 'Predator']), 'taxon']
  GloBI_interactions[i, 'Prey'] <- Biotic_inter[[2]][paste(GloBI_interactions[i, 'Prey']), 'taxon']
}

Biotic_inter[[1]] <- Biotic_inter[[1]][-which(Biotic_inter[[1]][,'resource'] == "Copepod"), ]


  # Unique values and adjusting rownames
  Biotic_inter[[1]] <- unique(Biotic_inter[[1]])
  Biotic_inter[[2]] <- unique(Biotic_inter[[2]])
  rownames(Biotic_inter[[2]]) <- Biotic_inter[[2]][, 'taxon']
  rownames(Biotic_inter[[4]]) <- Biotic_inter[[4]][, 'taxon']
  Biotic_inter[[4]] <- Biotic_inter[[4]][,-c(7,9,10,13)]
  GloBI_interactions <- unique(GloBI_interactions[, 1:3])
  inter.tot <- unique(inter.tot[, 1:3])

# --------------------------------------------
# First dataset: taxon with taxonomy as vector
# --------------------------------------------

colnames(GloBI_interactions) <- c('consumer','inter','resource')
taxon.list <- unique(c(unique(Biotic_inter[[1]][, 'consumer']), unique(Biotic_inter[[1]][, 'resource'])))

taxon <- matrix(nrow = length(taxon.list), ncol = 2, data = NA, dimnames = list(c(), c("taxon", "kingdom | phylum | class | order | family | genus | species")))
taxon[, 1] <- taxon.list

# Extracting taxonomy for each binary interaction
rank <- c("kingdom","phylum","class","order","family","genus","species")
taxonomy <- matrix(nrow = nrow(taxon), ncol = length(rank), dimnames = list(c(), rank))

pb <- txtProgressBar(min = 0,max = nrow(taxon), style = 3)
for(i in 1:nrow(taxon)) {
  taxonomy[i, ] <- Biotic_inter[[2]][taxon[i, 'taxon'], rank]
  setTxtProgressBar(pb, i)
} #i
close(pb)

# Combining taxonomy into single element
# Ranks are  "kingdom | phylum | class | order | family | genus | species"
taxon[, 2] <- apply(taxonomy, 1, paste, collapse = ' | ')

# write.table(taxon, "Phil_data/0-taxon_list.txt", sep="\t")

# ---------------------------------------------------------------------------
# Second dataset: Predators with sets of prey and non-prey for Empirical Webs
# ---------------------------------------------------------------------------
rownames(inter.tot) <- seq(1,nrow(inter.tot))
emp.web.inter <- consumer_set_of_resource(consumer = inter.tot[, 'Predator'],
                                          resource = inter.tot[, 'Prey'],
                                          inter_type = inter.tot[, 'FeedInter']
                                          )

# write.table(emp.web.inter, "Phil_data/1-emp_webs_interactions.txt", sep="\t")

# ----------------------------------------------------------------------------------
# Third dataset: Predators with sets of prey and non-prey for Empirical Webs + GloBI
# ----------------------------------------------------------------------------------
rownames(Biotic_inter[[1]]) <- seq(1,nrow(Biotic_inter[[1]]))
total.inter <- consumer_set_of_resource(consumer = Biotic_inter[[1]][, 'consumer'],
                                        resource = Biotic_inter[[1]][, 'resource'],
                                        inter_type = Biotic_inter[[1]][, 'inter']
                                        )

# write.table(total.inter, "Phil_data/2-total_interactions.txt", sep="\t")

# ----------------------------
# Fourth dataset: EGSL species
# ----------------------------
egsl <- matrix(nrow = nrow(Biotic_inter[[4]]), ncol = 2, data = NA, dimnames = list(c(Biotic_inter[[4]][, 'taxon']), c("taxon", "kingdom | phylum | class | order | family | genus | species")))
egsl[, 'taxon'] <- Biotic_inter[[4]][, 'taxon']
egsl[, 2] <- apply(Biotic_inter[[4]][,3:9], 1, paste, collapse = ' | ')
egsl <- unique(egsl)

# remove duplicated taxon
which(duplicated(egsl[,'taxon']))
egsl <- egsl[-1209, ]

# write.table(egsl, "Phil_data/3-EGSL_species.txt", sep="\t", row.names = FALSE, col.names = c('EGSL_species'))

# ----------------------------
# RData
# ----------------------------
Tanimoto_data <- vector("list", 4)
Tanimoto_data[[1]] <- taxon
Tanimoto_data[[2]] <- emp.web.inter
Tanimoto_data[[3]] <- total.inter
Tanimoto_data[[4]] <- egsl

save(x = Tanimoto_data, file = "./RData/Tanimoto_data.RData")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:
    filename <- 'Multiple_parameters'
    min.tx = 45
    K.values = c(2,4,6,8)
    MW = c(1,3,5)
    WT = c(0,0.3,0.6,1)
    blind = FALSE
    minimum_threshold = 0.3
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/Tanimoto_data.RData")
load("./RData/interactions_source.RData")
suppressMessages(load("./RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
# Format interaction catalogue to fit this table format
    S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
    S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
    }

# setting up the analyses for multiple communities
# Data for communities on which to test the algorithm
    Cm <- unique(interactions_sources[, 'source'])
    communities <- vector("list", length(Cm))
    names(communities) <- Cm

    # Taxa list per community to predict
        for(i in 1:length(communities)) {
            Ci <- which(interactions_sources[, 'source'] == Cm[i])
            S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

            if(length(which(!S1 %in% S0_catalog)) > 0) {
                print('Taxa in C[i] are not all included in taxa list S0')
                break
            }

            communities[[i]] <- S1
        }

# Substracting GloBI interactions for this portion
    Cm.lg <- numeric()
    for(i in 1:length(communities)) {
        Cm.lg <- c(Cm.lg,length(communities[[i]]))
    }

    to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

    Cm <- Cm[-to.delete]
    for(i in rev(to.delete)) {
        communities[[i]] <- NULL
    }
    names(communities) <- Cm

# Setting up lists to store the results
    wt.init <- seq(0,1,by=0.1)
    wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
    for(i in rev(wt.remove)) {
        similarity.matrices[[i]] <- NULL
    }

    sim.wt <- names(similarity.matrices)
    Tanimoto_analysis <- vector("list",length(sim.wt))
    names(Tanimoto_analysis) <- sim.wt
    for(i in 1:length(sim.wt)) {
        Tanimoto_analysis[[i]] <- vector("list", length(Cm))
        names(Tanimoto_analysis[[i]]) <- Cm
    }

# List to store results of multiple K values
K <- vector("list", length(K.values))
for(i in 1:length(K.values)) {
    K[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- K
names(Tanimoto_analysis) <- K.values
remove(K)

min.wt <- vector("list", length(MW))
for(i in 1:length(MW)) {
    min.wt[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- min.wt
names(Tanimoto_analysis) <- MW
remove(min.wt)

file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
save(x = Tanimoto_analysis, file = file.to.save)

init.time <- Sys.time()
for(n in 1:length(MW)) {
    mw <- MW[n]
    for(m in 1:length(K.values)) {

        # Tanimoto analysis with different weights for different communities
            # Parameters:
                Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
            #   wt  Weight of traits in similarity measurement
            #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
            #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

            # Output:
            #   A vector of sets of resources for each taxon

            for(i in 1:length(WT)){ #1st loop for all types of wt values
                wt <- WT[i]
                pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                for(j in 1:length(Cm)) { #2nd loop for all C[i]
                    S1 <- communities[[j]]
                    S0 <- S0_catalog
                    similarity.matrix <- similarity.matrices[[i]]

                    # Two choices here:
                    #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                    #   2. The analysis takes into account preexisting information already contained in the catalogue

                    # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                    if(blind == TRUE) {
                        for(k in 1:length(S1)) {
                          S0[S1[k], 'resource'] <- ""
                          S0[S1[k], 'non-resource'] <- ""
                        }

                    # 2. Preexisting information kept to inform algorithm
                    } else { # blind == FALSE

                        interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                        # Only modifying those that are loosing data from the catalogue, less time
                            to.change <- numeric()
                            for(k in 1:length(S1)) {
                                to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                            }
                            to.change <- unique(to.change)

                        # Modifying sets of resources and non-resources for taxa in S1
                            interactions <- interactions[to.change, ]
                            rownames(interactions) <- seq(1,nrow(interactions))
                            resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                      resource = interactions[, 'resource'],
                                                                      inter_type = interactions[, 'inter'])

                        # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                            for(k in 1:nrow(resource_set)) {
                              S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                              S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                            }
                        remove(interactions, resource_set, to.change)
                    } #if blind or not blind

                    # Recalculate similarity
                        similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                            S1 = S1,
                                                                            wt = wt,
                                                                            similarity.matrix = similarity.matrix)

                    # Predicting interactions
                        Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                Kr = Kr,
                                                                                S0 = S0,
                                                                                S1 = S1,
                                                                                MW = mw,
                                                                                similarity.matrix = similarity.matrix,
                                                                                minimum_threshold = minimum_threshold)

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(S0, S1, similarity.matrix)
                    setTxtProgressBar(pb, j)
                }#2nd loop for all C[i]

                save(x = Tanimoto_analysis, file = file.to.save)
                remove(wt)

            }#1st loop for all types of wt values
            close(pb)
    }#m
}#n
print(Sys.time() - init.time)

# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf("./Article/Catalog_vs_predictions.pdf",width=7,height=7)
# Plots
par(mfrow=c(2,2))
# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 1.09)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000088","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
            axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
            # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
            points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
        } #i

        ## Add legend
        if(j == 12) {
            legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        }
} #j
dev.off()

save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))
# ---------------------------------------------------------------------------
# Two-way Tanimoto algorithm: prediction accuracy for 2-Tanimoto_analysis.r
# ---------------------------------------------------------------------------

tanimoto_accuracy <- function(Tanimoto_analysis, predict.only = FALSE, empirical.only = FALSE) {
    load("./RData/interactions_source.RData")
    source("./Script/prediction_matrix.r")
    source("./Script/empirical_matrix.r")
    source("./Script/prediction_accuracy.r")


    accuracy <- matrix(ncol = 12, nrow = length(Tanimoto_analysis) * length(Tanimoto_analysis[[1]]) * length(Tanimoto_analysis[[1]][[1]]) * length(Tanimoto_analysis[[1]][[1]][[1]]), data = 0, dimnames = list(c(), c('MW','K','wt','Cm','a','b','c','d','TSS','ScoreY1','ScoreY0','FSS')))
    iteration <- 1
    for(n in 1: length(Tanimoto_analysis)) { #loop through MW values
        for(m in 1: length(Tanimoto_analysis[[1]])) { # loop through K values
            for(i in 1:length(Tanimoto_analysis[[1]][[1]])){ #1st loop for all types of wt values
                for(j in 1:length(Tanimoto_analysis[[1]][[1]][[1]])) { #2nd loop for all C[i]
                    # Arguments:
                    S1 <- Tanimoto_analysis[[n]][[m]][[i]][[j]][, 'consumer']
                    predictions <- Tanimoto_analysis[[n]][[m]][[i]][[j]]
                    interactions_source <- interactions_sources
                    source <- names(Tanimoto_analysis[[n]][[m]][[i]])[j]

                    accuracy[iteration, 'MW'] <- names(Tanimoto_analysis)[n]
                    accuracy[iteration, 'K'] <- names(Tanimoto_analysis[[n]])[m]
                    accuracy[iteration, 'wt'] <- names(Tanimoto_analysis[[n]][[m]])[i]
                    accuracy[iteration, 'Cm'] <- names(Tanimoto_analysis[[n]][[m]][[i]])[j]
                    accuracy[iteration, 5:12] <- prediction_accuracy(predicted = prediction_matrix(S1 = S1, predictions = predictions, predict.only = predict.only, empirical.only = empirical.only),
                                                        empirical = empirical_matrix(S1 = S1, interactions_source = interactions_source, source = source))

                    iteration <- iteration + 1
                    remove(S1, predictions, interactions_source, source)
                }#j
            }#i
        }#m
    }#n

    return(accuracy)

}#Tanimoto_accuracy function
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Evaluation of analysis accuracy + tables and figures
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FILES:
#           Script <- file = 'Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = 'RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

load("./RData/Tanimoto_analysis.RData")

Tanimoto_accuracy <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

# Creating an empty plot
eplot <- function(x, y) {
  plot(x = x, y = y, bty = "n",ann = FALSE,xaxt = "n",yaxt = "n",type = "n",bg = "grey", ylim = c(-0.09,1.09), xlim = c(-0.09,1.09))
}

pdf("./Article/results4.pdf",width=7,height=7)
# Plots
par(mfrow=c(2,2))
# Graph
for(j in 8:11) {
    eplot(x = accuracy[, 'wt'], y = accuracy[, j])
    par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
    # foodwebs <- to.verify
    # col <- c('blue','green','black','red','yellow','darkgrey','orange','brown','grey','green','darkgreen','darkblue')
    col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL)
    names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
    # sample(colours(), length(foodwebs))
    # cols <- c("#FF000088","#00FF0088","#0000FF88")
    # cols2 <- c("#FF0000","#00FF00","#0000FF")

    # Axes
    # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
    axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 0)
    axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.09)
    axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1)
    axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.09)
    # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
    # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

    #
    mtext(text = names[j-7], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
    mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

    for(i in 1:12) {
        x <- as.numeric(names(Tanimoto_analysis[[1]]))
        y <- numeric()
        for(k in 1:6) {
            y <- c(y,mean(as.numeric(accuracy[which(accuracy[, 'K'] == i & accuracy[, 'wt'] == names(Tanimoto_analysis[[1]])[k]), j][-5])))
            # mean(as.numeric(accuracy[which(accuracy[, 'K'] == i & accuracy[, 'wt'] == names(Tanimoto_analysis[[1]])[k]), j][-5]))
        }

        points(x = x, y = y, bg = col[i], cex = 1.25, pch = 18, col = col[i])
        lines(x = x, y = y, col = col[i], lwd = 0.5)

        # points(x = accuracy[which(accuracy[, 'K'] == i), 'wt'], y = accuracy[which(accuracy[, 'K'] == i), j], bg = col[i], cex = 1.25, pch = 18, col = col[i])
        # lines(x = accuracy[which(accuracy[, 'K'] == i), 'wt'], y = accuracy[which(accuracy[, 'K'] == i), j], col = col[i], lwd = 0.5)
    }

    # boxplot(formula = as.numeric(accuracy[, j]) ~ accuracy[, 'wt'],
    #         data = accuracy,
    #         boxwex = 0.075,
    #         axes = FALSE,
    #         add = TRUE,
    #         at = seq(0, 1, by = 0.1))
}
dev.off()
    # -----------------------------------------------------------------------------
    # PROJECT:
    #    Evaluating the structure of the communities of the estuary
    #    and gulf of St.Lawrence
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # STEP:
    #   2. Tanimoto analysis for multiple parameter values
    # -----------------------------------------------------------------------------

    # Evaluating the contribution of the catalog vs the predictions to the algorithm

    # -----------------------------------------------------------------------------
    # FILES:
    #   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
    #   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # PARAMETERS:
        filename <- 'Catalog_vs_predictions'
        min.tx = 45
        K.values = 8
        MW = 1
        WT = seq(0,1,by=0.1)
        blind = FALSE
        minimum_threshold = 0.3
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # SCRIPT
    # -----------------------------------------------------------------------------
    load("RData/Tanimoto_data.RData")
    load("RData/interactions_source.RData")
    suppressMessages(load("RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- seq(0,1,by=0.1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            similarity.matrices[[i]] <- NULL
        }

        sim.wt <- names(similarity.matrices)
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

    # List to store results of multiple K values
    K <- vector("list", length(K.values))
    for(i in 1:length(K.values)) {
        K[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- K
    names(Tanimoto_analysis) <- K.values
    remove(K)

    min.wt <- vector("list", length(MW))
    for(i in 1:length(MW)) {
        min.wt[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- min.wt
    names(Tanimoto_analysis) <- MW
    remove(min.wt)

    file.to.save <- serialNext("Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    init.time <- Sys.time()
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon

                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog
                        similarity.matrix <- similarity.matrices[[i]]

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.matrix)

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.matrix = similarity.matrix,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.matrix)
                        setTxtProgressBar(pb, j)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values
                close(pb)
        }#m
    }#n
    print(Sys.time() - init.time)

# Catalog vs predictions
    accuracy  <- vector('list', 3)
    names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
    accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
    accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
    accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
    pdf("Article/Catalog_vs_predictions.pdf",width=7,height=7)
    # Plots
    par(mfrow=c(2,2))
    # Graph
    for(j in 9:12) {
            eplot(xmin = -0.09, xmax = 1.09)
            par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
            foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
            names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
            col <- c("#FF8822","#449955","#2288FF")
            # col <- c("#FF000088","#00FF0088","#0000FF88")
            # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
            # col <- sample(colours(), length(foodwebs))

            # Axes
                # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
                axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
                axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
                axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
                axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
                # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
                # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

                mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
                mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

            for(i in 1:length(accuracy)) {
                accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                # hack: we draw arrows but with very special "arrowheads" for error bars
                arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
                points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
            } #i

            ## Add legend
            if(j == 12) {
                legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
            }
    } #j
    dev.off()

save(x = Tanimoto_analysis, file = paste('Analyses/',filename,'.RData',sep=''))
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:
    filename <- 'Multiple_parameters'
    min.tx = 45
    K.values = c(2,4,6,8)
    MW = c(1,3,5)
    WT = c(0,0.3,0.6,1)
    blind = FALSE
    minimum_threshold = 0.3
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("RData/Tanimoto_data.RData")
load("RData/interactions_source.RData")
suppressMessages(load("RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
# Format interaction catalogue to fit this table format
    S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
    S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
    }

# setting up the analyses for multiple communities
# Data for communities on which to test the algorithm
    Cm <- unique(interactions_sources[, 'source'])
    communities <- vector("list", length(Cm))
    names(communities) <- Cm

    # Taxa list per community to predict
        for(i in 1:length(communities)) {
            Ci <- which(interactions_sources[, 'source'] == Cm[i])
            S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

            if(length(which(!S1 %in% S0_catalog)) > 0) {
                print('Taxa in C[i] are not all included in taxa list S0')
                break
            }

            communities[[i]] <- S1
        }

# Substracting GloBI interactions for this portion
    Cm.lg <- numeric()
    for(i in 1:length(communities)) {
        Cm.lg <- c(Cm.lg,length(communities[[i]]))
    }

    to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

    Cm <- Cm[-to.delete]
    for(i in rev(to.delete)) {
        communities[[i]] <- NULL
    }
    names(communities) <- Cm

# Setting up lists to store the results
    wt.init <- seq(0,1,by=0.1)
    wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
    for(i in rev(wt.remove)) {
        similarity.matrices[[i]] <- NULL
    }

    sim.wt <- names(similarity.matrices)
    Tanimoto_analysis <- vector("list",length(sim.wt))
    names(Tanimoto_analysis) <- sim.wt
    for(i in 1:length(sim.wt)) {
        Tanimoto_analysis[[i]] <- vector("list", length(Cm))
        names(Tanimoto_analysis[[i]]) <- Cm
    }

# List to store results of multiple K values
K <- vector("list", length(K.values))
for(i in 1:length(K.values)) {
    K[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- K
names(Tanimoto_analysis) <- K.values
remove(K)

min.wt <- vector("list", length(MW))
for(i in 1:length(MW)) {
    min.wt[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- min.wt
names(Tanimoto_analysis) <- MW
remove(min.wt)

file.to.save <- serialNext("Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
save(x = Tanimoto_analysis, file = file.to.save)

init.time <- Sys.time()
for(n in 1:length(MW)) {
    mw <- MW[n]
    for(m in 1:length(K.values)) {

        # Tanimoto analysis with different weights for different communities
            # Parameters:
                Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
            #   wt  Weight of traits in similarity measurement
            #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
            #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

            # Output:
            #   A vector of sets of resources for each taxon

            for(i in 1:length(WT)){ #1st loop for all types of wt values
                wt <- WT[i]
                pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                for(j in 1:length(Cm)) { #2nd loop for all C[i]
                    S1 <- communities[[j]]
                    S0 <- S0_catalog
                    similarity.matrix <- similarity.matrices[[i]]

                    # Two choices here:
                    #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                    #   2. The analysis takes into account preexisting information already contained in the catalogue

                    # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                    if(blind == TRUE) {
                        for(k in 1:length(S1)) {
                          S0[S1[k], 'resource'] <- ""
                          S0[S1[k], 'non-resource'] <- ""
                        }

                    # 2. Preexisting information kept to inform algorithm
                    } else { # blind == FALSE

                        interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                        # Only modifying those that are loosing data from the catalogue, less time
                            to.change <- numeric()
                            for(k in 1:length(S1)) {
                                to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                            }
                            to.change <- unique(to.change)

                        # Modifying sets of resources and non-resources for taxa in S1
                            interactions <- interactions[to.change, ]
                            rownames(interactions) <- seq(1,nrow(interactions))
                            resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                      resource = interactions[, 'resource'],
                                                                      inter_type = interactions[, 'inter'])

                        # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                            for(k in 1:nrow(resource_set)) {
                              S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                              S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                            }
                        remove(interactions, resource_set, to.change)
                    } #if blind or not blind

                    # Recalculate similarity
                        similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                            S1 = S1,
                                                                            wt = wt,
                                                                            similarity.matrix = similarity.matrix)

                    # Predicting interactions
                        Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                Kr = Kr,
                                                                                S0 = S0,
                                                                                S1 = S1,
                                                                                MW = mw,
                                                                                similarity.matrix = similarity.matrix,
                                                                                minimum_threshold = minimum_threshold)

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(S0, S1, similarity.matrix)
                    setTxtProgressBar(pb, j)
                }#2nd loop for all C[i]

                save(x = Tanimoto_analysis, file = file.to.save)
                remove(wt)

            }#1st loop for all types of wt values
            close(pb)
    }#m
}#n
print(Sys.time() - init.time)

# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf("Article/Catalog_vs_predictions.pdf",width=7,height=7)
# Plots
par(mfrow=c(2,2))
# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 1.09)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000088","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
            axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
            # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
            points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
        } #i

        ## Add legend
        if(j == 12) {
            legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        }
} #j
dev.off()

save(x = Tanimoto_analysis, file = paste('Analyses/',filename,'.RData',sep=''))
# Run readme.r before other scripts
rm(list=ls())
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "Script/0-1-Tanimoto_data.r
#           RData <- file = 'RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "Script/0-1-Interactions_sources.r
#           RData <- file = "RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = 'Script/1-Similarity_matrix.r'
#       RData <- file = 'RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = 'Script/2-1-Tanimoto_analysis.r'
#           RData <- file = 'RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = 'Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = 'RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("Script/Tanimoto.r") # basic tanimoto similarity
source("Script/Tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("Script/similarity_taxon.r") # similarity matrix for set of taxa
source("Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/consumer_set_of_resource.R")
source("Script/prediction_accuracy.r") #
source("Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("Script/serialNext.r") # function to avoid overwriting existing files in temporary analyses folder
source("Script/eplot.r") # empty plot for figure generation
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
    # -----------------------------------------------------------------------------
    # PROJECT:
    #    Evaluating the structure of the communities of the estuary
    #    and gulf of St.Lawrence
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # STEP:
    #   2. Tanimoto analysis for multiple parameter values
    # -----------------------------------------------------------------------------

    # Evaluating the contribution of the catalog vs the predictions to the algorithm

    # -----------------------------------------------------------------------------
    # FILES:
    #   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
    #   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # PARAMETERS:
        min.tx = 45
        K.values = 8
        MW = 1
        WT = c(0, 0.2, 0.5, 0.8, 1)
        blind = FALSE
        minimum_threshold = 0.3
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # SCRIPT
    # -----------------------------------------------------------------------------
    load("RData/Tanimoto_data.RData")
    load("RData/interactions_source.RData")
    suppressMessages(load("RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- seq(0,1,by=0.1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            similarity.matrices[[i]] <- NULL
        }

        sim.wt <- names(similarity.matrices)
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

    # List to store results of multiple K values
    K <- vector("list", length(K.values))
    for(i in 1:length(K.values)) {
        K[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- K
    names(Tanimoto_analysis) <- K.values
    remove(K)

    min.wt <- vector("list", length(MW))
    for(i in 1:length(MW)) {
        min.wt[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- min.wt
    names(Tanimoto_analysis) <- MW
    remove(min.wt)

    file.to.save <- serialNext("RData/tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    save(x = Tanimoto_analysis, file = paste(serialNext("RData/tanimoto_temp/Tanimoto_analysis.RData"),)

    init.time <- Sys.time()
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon

                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog
                        similarity.matrix <- similarity.matrices[[i]]

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.matrix)

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.matrix = similarity.matrix,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.matrix)
                        setTxtProgressBar(pb, j)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values
                close(pb)
        }#m
    }#n
    print(Sys.time() - init.time)


# Catalog vs predictions
    accuracy  <- vector('list', 3)
    names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
    accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
    accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
    accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
    pdf("Article/Catalog_vs_predictions.pdf",width=7,height=7)
    # Plots
    par(mfrow=c(2,2))
    # Graph
    for(j in 9:12) {
            eplot(xmin = -0.09, xmax = 1.09)
            par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
            foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
            names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
            col <- c("#FF8822","#99FF55","#2288FF")
            # col <- c("#FF000088","#00FF0088","#0000FF88")
            # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
            # col <- sample(colours(), length(foodwebs))

            # Axes
                # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
                axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
                axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
                axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
                axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
                # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
                # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

                mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
                mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

            for(i in 1:length(accuracy)) {
                accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                # hack: we draw arrows but with very special "arrowheads" for error bars
                arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
                points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
            } #i

            ## Add legend
            if(j == 12) {
                legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
            }
    } #j
    dev.off()
# Run readme.r before other scripts
rm(list=ls())
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "Script/0-1-Tanimoto_data.r
#           RData <- file = 'RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "Script/0-1-Interactions_sources.r
#           RData <- file = "RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = 'Script/1-Similarity_matrix.r'
#       RData <- file = 'RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = 'Script/2-1-Tanimoto_analysis.r'
#           RData <- file = 'RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = 'Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = 'RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("Script/Tanimoto.r") # basic tanimoto similarity
source("Script/Tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("Script/similarity_taxon.r") # similarity matrix for set of taxa
source("Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/consumer_set_of_resource.R")
source("Script/prediction_accuracy.r") #
source("Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("Script/serialNext.r")
source("Script/eplot.r") # empty plot for figure generation
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Two-way Tanimoto algorithm: prediction accuracy for 2-Tanimoto_analysis.r
# ---------------------------------------------------------------------------

tanimoto_accuracy <- function(Tanimoto_analysis, predict.only = FALSE, empirical.only = FALSE) {
    load("RData/interactions_source.RData")
    source("Script/prediction_matrix.r")
    source("Script/empirical_matrix.r")
    source("Script/prediction_accuracy.r")


    accuracy <- matrix(ncol = 12, nrow = length(Tanimoto_analysis) * length(Tanimoto_analysis[[1]]) * length(Tanimoto_analysis[[1]][[1]]) * length(Tanimoto_analysis[[1]][[1]][[1]]), data = 0, dimnames = list(c(), c('MW','K','wt','Cm','a','b','c','d','TSS','ScoreY1','ScoreY0','FSS')))
    iteration <- 1
    for(n in 1: length(Tanimoto_analysis)) { #loop through MW values
        for(m in 1: length(Tanimoto_analysis[[1]])) { # loop through K values
            for(i in 1:length(Tanimoto_analysis[[1]][[1]])){ #1st loop for all types of wt values
                for(j in 1:length(Tanimoto_analysis[[1]][[1]][[1]])) { #2nd loop for all C[i]
                    # Arguments:
                    S1 <- Tanimoto_analysis[[n]][[m]][[i]][[j]][, 'consumer']
                    predictions <- Tanimoto_analysis[[n]][[m]][[i]][[j]]
                    interactions_source <- interactions_sources
                    source <- names(Tanimoto_analysis[[n]][[m]][[i]])[j]

                    accuracy[iteration, 'MW'] <- names(Tanimoto_analysis)[n]
                    accuracy[iteration, 'K'] <- names(Tanimoto_analysis[[n]])[m]
                    accuracy[iteration, 'wt'] <- names(Tanimoto_analysis[[n]][[m]])[i]
                    accuracy[iteration, 'Cm'] <- names(Tanimoto_analysis[[n]][[m]][[i]])[j]
                    accuracy[iteration, 5:12] <- prediction_accuracy(predicted = prediction_matrix(S1 = S1, predictions = predictions, predict.only = predict.only, empirical.only = empirical.only),
                                                        empirical = empirical_matrix(S1 = S1, interactions_source = interactions_source, source = source))

                    iteration <- iteration + 1
                    remove(S1, predictions, interactions_source, source)
                }#j
            }#i
        }#m
    }#n

    return(accuracy)

}#Tanimoto_accuracy function
    # -----------------------------------------------------------------------------
    # PROJECT:
    #    Evaluating the structure of the communities of the estuary
    #    and gulf of St.Lawrence
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # STEP:
    #   2. Tanimoto analysis for multiple parameter values
    # -----------------------------------------------------------------------------

    # Evaluating the contribution of the catalog vs the predictions to the algorithm

    # -----------------------------------------------------------------------------
    # FILES:
    #   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
    #   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # PARAMETERS:
        min.tx = 45
        K.values = 5
        MW = 1
        WT = c(0,0.5,1)
        blind = FALSE
        minimum_threshold = 0.3
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # SCRIPT
    # -----------------------------------------------------------------------------
    load("RData/Tanimoto_data.RData")
    load("RData/interactions_source.RData")
    suppressMessages(load("RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- seq(0,1,by=0.1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            similarity.matrices[[i]] <- NULL
        }

        sim.wt <- names(similarity.matrices)
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

    # List to store results of multiple K values
    K <- vector("list", length(K.values))
    for(i in 1:length(K.values)) {
        K[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- K
    names(Tanimoto_analysis) <- K.values
    remove(K)

    min.wt <- vector("list", length(MW))
    for(i in 1:length(MW)) {
        min.wt[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- min.wt
    names(Tanimoto_analysis) <- MW
    remove(min.wt)

    file.to.save <- serialNext("RData/tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    save(x = Tanimoto_analysis, file = paste(serialNext("RData/tanimoto_temp/Tanimoto_analysis.RData"),)

    init.time <- Sys.time()
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon

                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog
                        similarity.matrix <- similarity.matrices[[i]]

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.matrix)

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.matrix = similarity.matrix,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.matrix)
                        setTxtProgressBar(pb, j)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values
                close(pb)
        }#m
    }#n
    print(Sys.time() - init.time)


# Catalog vs predictions
    Catalog <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
    Predict <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis predict.only = TRUE)
    Algo <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)
# Run readme.r before other scripts
rm(list=ls())
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "Script/0-1-Tanimoto_data.r
#           RData <- file = 'RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "Script/0-1-Interactions_sources.r
#           RData <- file = "RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = 'Script/1-Similarity_matrix.r'
#       RData <- file = 'RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = 'Script/2-1-Tanimoto_analysis.r'
#           RData <- file = 'RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = 'Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = 'RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("Script/Tanimoto.r") # basic tanimoto similarity
source("Script/Tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("Script/similarity_taxon.r") # similarity matrix for set of taxa
source("Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/consumer_set_of_resource.R")
source("Script/prediction_accuracy.r") #
source("Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
Source("Script/serialNext.r"))
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# Run readme.r before other scripts
rm(list=ls())
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "Script/0-1-Tanimoto_data.r
#           RData <- file = 'RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "Script/0-1-Interactions_sources.r
#           RData <- file = "RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = 'Script/1-Similarity_matrix.r'
#       RData <- file = 'RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = 'Script/2-1-Tanimoto_analysis.r'
#           RData <- file = 'RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = 'Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = 'RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("Script/Tanimoto.r") # basic tanimoto similarity
source("Script/Tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("Script/similarity_taxon.r") # similarity matrix for set of taxa
source("Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/consumer_set_of_resource.R")
source("Script/prediction_accuracy.r") #
source("Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Two-way Tanimoto algorithm: prediction accuracy for 2-Tanimoto_analysis.r
# ---------------------------------------------------------------------------

tanimoto_accuracy <- function(Tanimoto_analysis, predict.only = FALSE, empirical.only = FALSE) {
    load("RData/interactions_source.RData")
    source("Script/prediction_matrix.r")
    source("Script/empirical_matrix.r")
    source("Script/tanimoto_efficiency.r")


    accuracy <- matrix(ncol = 12, nrow = length(Tanimoto_analysis) * length(Tanimoto_analysis[[1]]) * length(Tanimoto_analysis[[1]][[1]]) * length(Tanimoto_analysis[[1]][[1]][[1]]), data = 0, dimnames = list(c(), c('MW','K','wt','Cm','a','b','c','d','TSS','ScoreY1','ScoreY0','FSS')))
    iteration <- 1
    for(n in 1: length(Tanimoto_analysis)) { #loop through MW values
        for(m in 1: length(Tanimoto_analysis[[1]])) { # loop through K values
            for(i in 1:length(Tanimoto_analysis[[1]][[1]])){ #1st loop for all types of wt values
                for(j in 1:length(Tanimoto_analysis[[1]][[1]][[1]])) { #2nd loop for all C[i]
                    # Arguments:
                    S1 <- Tanimoto_analysis[[n]][[m]][[i]][[j]][, 'consumer']
                    predictions <- Tanimoto_analysis[[n]][[m]][[i]][[j]]
                    interactions_source <- interactions_sources
                    source <- names(Tanimoto_analysis[[n]][[m]][[i]])[j]

                    accuracy[iteration, 'MW'] <- names(Tanimoto_analysis)[n]
                    accuracy[iteration, 'K'] <- names(Tanimoto_analysis[[n]])[m]
                    accuracy[iteration, 'wt'] <- names(Tanimoto_analysis[[n]][[m]])[i]
                    accuracy[iteration, 'Cm'] <- names(Tanimoto_analysis[[n]][[m]][[i]])[j]
                    accuracy[iteration, 5:12] <- prediction_accuracy(predicted = prediction_matrix(S1 = S1, predictions = predictions, predict.only = predict.only, empirical.only = empirical.only),
                                                        empirical = empirical_matrix(S1 = S1, interactions_source = interactions_source, source = source))

                    iteration <- iteration + 1
                    remove(S1, predictions, interactions_source, source)
                }#j
            }#i
        }#m
    }#n

    return(accuracy)

}#Tanimoto_accuracy function
# Extracting as interaction matrix
prediction_matrix <- function(S1, predictions, predict.only = FALSE, empirical.only = FALSE) {
    # predict.only: only predictions will be used to recreate the prediction matrix
    # empirical.only: only empirical data will be used to recreate the prediction matrix, corresponding to the contribution of the interaction catalog
    # rownames need to be taxa names
    predict.matrix <- matrix(nrow = length(S1), ncol = length(S1), data = 0, dimnames = list(S1,S1))

    for(i in 1:length(S1)) {
        predict <- unlist(strsplit(predictions[i, 'resource_predictions'], " \\|\\ ")) # list of resource predicted for consumer i
        empirical <- unlist(strsplit(predictions[i, 'resource_empirical'], " \\|\\ ")) # list of resource observed for consumer i

        if(length(predict) == 0) {
          NULL
        } else {
            for(j in 1:length(predict)) {
                if(empirical.only == TRUE) {
                    break
                } else { # empirical.only == FALSE
                    predict.matrix[predict[j],i] <- 1
                } #if
            }#j
        }#if

        if(length(empirical) == 0) {
          NULL
        } else {
            for(j in 1:length(empirical)) {
                if(predict.only == TRUE) {
                    break
                } else { # predict.only == FALSE
                    predict.matrix[empirical[j],i] <- 1
                } #if
            }#j
        }#if
    }#i
    return(predict.matrix)
}#prediction_matrix function end
# Run readme.r before other scripts
rm(list=ls())
setwd("/Users/davidbeauchesne/Dropbox/Structure_Comm_EGSL/Tanimoto_algorithm")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "Script/0-1-Tanimoto_data.r
#           RData <- file = 'RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "Script/0-1-Interactions_sources.r
#           RData <- file = "RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = 'Script/1-Similarity_matrix.r'
#       RData <- file = 'RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = 'Script/2-1-Tanimoto_analysis.r'
#           RData <- file = 'RData/Tanimoto_analysis.RData'
# 
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = 'Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = 'RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("Script/Tanimoto.r") # basic tanimoto similarity
source("Script/Tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("Script/similarity_taxon.r") # similarity matrix for set of taxa
source("Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/consumer_set_of_resource.R")
source("Script/tanimoto_efficiency.r") # predictions formatted to food web matrix format (S x S)
source("Script/prediction_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# The functions require rchart-helper.R preloaded

# getQ2TimelapsePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getQ2TimelapsePlot = function(data, names, colors, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    dateFactors = list()
    for (i in 1:length(data)) {
        dateFactors[[i]] = as.factor(data[[i]]$date)
        boxplot = boxplot(data[[i]]$x ~ dateFactors[[i]],
                          data=data.frame(dateFactors[[i]], data[[i]]$x), plot=FALSE)
        stats = setNames(as.data.frame(boxplot$stats), nm=NULL)

        # Timpstamp in miliseconds
        unixTimestamps =
            1000 * as.numeric(as.POSIXct(sort(unique(data[[i]]$date)),
                                         origin="1970-01-01"))
        statsMedian = rbind(setNames(unixTimestamps, nm=NULL), stats[3,])
        statsQ2 = rbind(setNames(unixTimestamps, nm=NULL), stats[c(2, 4),])

        series[[2 * (i - 1) + 1]] =
            list(name=names[i], data=statsMedian, zIndex=1, color=colors[i],
                 marker=list(fillColor="white", lineWidth=2, lineColor=colors[i]))
        series[[2 * i]] = list(name="50th quartile", data=statsQ2, zIndex=0,
                 type="arearange", color=colors[i], lineWidth=0, linkedTo=":previous", fillOpacity=0.3)
    }

    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=list(text=yLabel), min=0)
    chart$set(series=series)
    return(chart)
}

# Helper for creating histogram
getBinItemList = function(data, businesses, interval=100) {
    binItemList = c()
    currentBin = interval
    maxBin = max(data$count) + interval
    while (currentBin < maxBin) {
        items = filter(data, currentBin - interval <= count & count < currentBin)
        binItemList = c(binItemList,
                        paste("< ", currentBin, "<br>",
                              paste(items$name, collapse="<br>, ")))
        currentBin = currentBin + interval
    }
    return(binItemList)
}

# getStackedHistogram
# data[[]]$x
getStackedHistogram = function(data, names, xLabel, interval=100, logScale=FALSE, logBase=exp(1), normalize=FALSE, colors = c("#7cb5ec", "#000000")) {
    series = list()
    plotLines = list()
    for (i in 1:length(data)){
        x = data[[i]]$x

        plotLines[[i * 2 - 1]] =
            list(color=colors[i],
                 value=mean(x),
                 width=2,
                 label=list(text="mean", style=list(color=colors[i]), verticalAlign="middle"))
        plotLines[[i * 2]] =
            list(color=colors[i],
                 value=median(x),
                 dashStyle="dash",
                 width=2,
                 label=list(text="median", style=list(color=colors[i]), verticalAlign="middle"))

        maxBin = max(data[[i]]$x)
        actualInterval = interval

        if (logScale) {
            x = log(x + 1, base=logBase)
            maxBin = log(maxBin + 1, base=logBase)
            actualInterval = log(interval, base=logBase)
        }
        histogram = hist(x, breaks=seq(0, maxBin + actualInterval, actualInterval), plot=FALSE)
        histNames = getBinItemList(data[[i]], interval=actualInterval)

        nBins = min(length(histogram$breaks), length(histogram$counts))
        counts = histogram$counts[1:nBins]
        if (normalize) {
            counts = counts / nrow(data[[i]])
        }
        bins = getValues(
            histogram$breaks[1:nBins],
            counts,
            name=histNames)
        series[[i]] = list(name=names[i], data=bins)
    }
   
    chart <- Highcharts$new()
    chart$chart(type="column")
    chart$plotOptions(
        column="{ grouping: false, pointPadding: 0, borderWidth: 0, groupPadding: 0, shadow: false}")
    chart$xAxis(title=paste("{text: '", xLabel, "'}", sep=""),
                plotLines=plotLines)
    yLabel = "frequency"
    if (normalize) {
        yLabel = paste(yLabel, "(normalized)")
    }
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""))
    chart$set(series=series)
    return(chart)
}

# getTimelapseLinePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getTimelapseLinePlot = function(data, names, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    for (i in 1:length(data)){
        timelapseValues = getTimelapseValues(
            as.POSIXlt(strptime(as.character(data[[i]]$date), "%Y-%m-%d", tz=timezone)),
            data[[i]]$x)
        series[[i]] = list(name=names[i], data=timelapseValues)
    }


    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""), gridLineColor="#FFFFFF")
    chart$set(series=series)
    return(chart)
}
# The functions require rchart-helper.R preloaded

# getQ2TimelapsePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getQ2TimelapsePlot = function(data, names, colors, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    dateFactors = list()
    for (i in 1:length(data)) {
        dateFactors[[i]] = as.factor(data[[i]]$date)
        boxplot = boxplot(data[[i]]$x ~ dateFactors[[i]],
                          data=data.frame(dateFactors[[i]], data[[i]]$x), plot=FALSE)
        stats = setNames(as.data.frame(boxplot$stats), nm=NULL)

        # Timpstamp in miliseconds
        unixTimestamps = 1000 * as.numeric(as.POSIXct( sort(unique(data[[i]]$date))))
        statsMedian = rbind(setNames(unixTimestamps, nm=NULL), stats[3,])
        statsQ2 = rbind(setNames(unixTimestamps, nm=NULL), stats[c(2, 4),])

        series[[2 * (i - 1) + 1]] =
            list(name=names[i], data=statsMedian, zIndex=1, color=colors[i],
                 marker=list(fillColor="white", lineWidth=2, lineColor=colors[i]))
        series[[2 * i]] = list(name="50th quartile", data=statsQ2, zIndex=0,
                 type="arearange", color=colors[i], lineWidth=0, linkedTo=":previous", fillOpacity=0.3)
    }

    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=list(text=yLabel), min=0)
    chart$set(series=series)
    return(chart)
}

# Helper for creating histogram
getBinItemList = function(data, businesses, interval=100) {
    binItemList = c()
    currentBin = interval
    maxBin = max(data$count) + interval
    while (currentBin < maxBin) {
        items = filter(data, currentBin - interval <= count & count < currentBin)
        binItemList = c(binItemList,
                        paste("< ", currentBin, "<br>",
                              paste(items$name, collapse="<br>, ")))
        currentBin = currentBin + interval
    }
    return(binItemList)
}

# getStackedHistogram
# data[[]]$x
getStackedHistogram = function(data, names, xLabel, interval=100, logScale=FALSE, logBase=exp(1), normalize=FALSE, colors = c("#7cb5ec", "#000000")) {
    series = list()
    plotLines = list()
    for (i in 1:length(data)){
        x = data[[i]]$x

        plotLines[[i * 2 - 1]] =
            list(color=colors[i],
                 value=mean(x),
                 width=2,
                 label=list(text="mean", style=list(color=colors[i]), verticalAlign="middle"))
        plotLines[[i * 2]] =
            list(color=colors[i],
                 value=median(x),
                 dashStyle="dash",
                 width=2,
                 label=list(text="median", style=list(color=colors[i]), verticalAlign="middle"))

        maxBin = max(data[[i]]$x)
        actualInterval = interval

        if (logScale) {
            x = log(x + 1, base=logBase)
            maxBin = log(maxBin + 1, base=logBase)
            actualInterval = log(interval, base=logBase)
        }
        histogram = hist(x, breaks=seq(0, maxBin + actualInterval, actualInterval), plot=FALSE)
        histNames = getBinItemList(data[[i]], interval=actualInterval)

        nBins = min(length(histogram$breaks), length(histogram$counts))
        counts = histogram$counts[1:nBins]
        if (normalize) {
            counts = counts / nrow(data[[i]])
        }
        bins = getValues(
            histogram$breaks[1:nBins],
            counts,
            name=histNames)
        series[[i]] = list(name=names[i], data=bins)
    }
   
    chart <- Highcharts$new()
    chart$chart(type="column")
    chart$plotOptions(
        column="{ grouping: false, pointPadding: 0, borderWidth: 0, groupPadding: 0, shadow: false}")
    chart$xAxis(title=paste("{text: '", xLabel, "'}", sep=""),
                plotLines=plotLines)
    yLabel = "frequency"
    if (normalize) {
        yLabel = paste(yLabel, "(normalized)")
    }
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""))
    chart$set(series=series)
    return(chart)
}

# getTimelapseLinePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getTimelapseLinePlot = function(data, names, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    for (i in 1:length(data)){
        timelapseValues = getTimelapseValues(
            as.POSIXlt(strptime(as.character(data[[i]]$date), "%Y-%m-%d", tz=timezone)),
            data[[i]]$x)
        series[[i]] = list(name=names[i], data=timelapseValues)
    }


    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""), gridLineColor="#FFFFFF")
    chart$set(series=series)
    return(chart)
}
# The functions require rchart-helper.R preloaded

# getQ2TimelapsePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getQ2TimelapsePlot = function(data, names, colors, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    dateFactors = list()
    for (i in 1:length(data)) {
        dateFactors[[i]] = as.factor(data[[i]]$date)
        boxplot = boxplot(data[[i]]$x ~ dateFactors[[i]],
                          data=data.frame(dateFactors[[i]], data[[i]]$x), plot=FALSE)
        stats = setNames(as.data.frame(boxplot$stats), nm=NULL)

        # Timpstamp in miliseconds
        unixTimestamps = 1000 * as.numeric(as.POSIXct( sort(unique(data[[i]]$date))))
        statsMedian = rbind(setNames(unixTimestamps, nm=NULL), stats[3,])
        statsQ2 = rbind(setNames(unixTimestamps, nm=NULL), stats[c(2, 4),])

        series[[2 * (i - 1) + 1]] =
            list(name=names[i], data=statsMedian, zIndex=1, color=colors[i],
                 marker=list(fillColor="white", lineWidth=2, lineColor=colors[i]))
        series[[2 * i]] = list(name="50th quartile", data=statsQ2, zIndex=0,
                 type="arearange", color=colors[i], lineWidth=0, linkedTo=":previous", fillOpacity=0.3)
    }

    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=list(text=yLabel), min=0)
    chart$set(series=series)
    return(chart)
}

# Helper for creating histogram
getBinItemList = function(data, businesses, interval=100) {
    binItemList = c()
    currentBin = interval
    maxBin = max(data$count) + interval
    while (currentBin < maxBin) {
        items = filter(data, currentBin - interval <= count & count < currentBin)
        binItemList = c(binItemList,
                        paste("< ", currentBin, "<br>",
                              paste(items$name, collapse="<br>, ")))
        currentBin = currentBin + interval
    }
    return(binItemList)
}

# getStackedHistogram
# data[[]]$x
getStackedHistogram = function(data, names, xLabel, interval=100, logScale=FALSE, logBase=exp(1), normalize=FALSE) {
    series = list()
    for (i in 1:length(data)){
        x = data[[i]]$x
        maxBin = max(data[[i]]$x)
        actualInterval = interval

        if (logScale) {
            x = log(x + 1, base=logBase)
            maxBin = log(maxBin + 1, base=logBase)
            actualInterval = log(interval, base=logBase)
        }
        histogram = hist(x, breaks=seq(0, maxBin + actualInterval, actualInterval), plot=FALSE)
        histNames = getBinItemList(data[[i]], interval=actualInterval)

        nBins = min(length(histogram$breaks), length(histogram$counts))
        counts = histogram$counts[1:nBins]
        if (normalize) {
            counts = counts / nrow(data[[i]])
        }
        bins = getValues(
            histogram$breaks[1:nBins],
            counts,
            name=histNames)
        series[[i]] = list(name=names[i], data=bins)
    }
   
    chart <- Highcharts$new()
    chart$chart(type="column")
    chart$plotOptions(
        column="{ grouping: false, pointPadding: 0, borderWidth: 0, groupPadding: 0, shadow: false}")
    chart$xAxis(title=paste("{text: '", xLabel, "'}", sep=""))
    yLabel = "frequency"
    if (normalize) {
        yLabel = paste(yLabel, "(normalized)")
    }
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""))
    chart$set(series=series)
    return(chart)
}

# getTimelapseLinePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getTimelapseLinePlot = function(data, names, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    for (i in 1:length(data)){
        timelapseValues = getTimelapseValues(
            as.POSIXlt(strptime(as.character(data[[i]]$date), "%Y-%m-%d", tz=timezone)),
            data[[i]]$x)
        series[[i]] = list(name=names[i], data=timelapseValues)
    }


    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""), gridLineColor="#FFFFFF")
    chart$set(series=series)
    return(chart)
}
                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, mytableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, date) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (date == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, mytableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]
    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
    }
    for (i in 1:max) {
        id <- list11$id[i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), list2[[id]], list11$id[[i]]))
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

gettopchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getbottomchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getchart <- function(days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, periodtext, maindate, olddate) {
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(period) {
    periodtext <- period
    if (period >= 0) {
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (period == pricetype) {
        return (df$price)
    }
    if (period == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, date, mytableintervaldays) {
    datedstocklists <- list()
    if (is.null(date)) {
        dateindex <- match(date, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    str(dateindex)
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:count) {
        index <- index - mytableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(con, date, ids, periodtext) {
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getmarket(con, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    ls <- list()
    names <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        dayset <- bigretl[[2]]
                        daynames <- names(dayset)
                        olddate <- min(daynames)
                        newdate <- max(daynames)
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        names[c] <- df$name
                    }
                }
            }
        }
    }
    displaychart(ls, names, 5, periodtext, newdate, olddate)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- subset(meta, marketid == market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmarket <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

if (!exists("marketid")) {
    marketid <- "morncat"
}

data <- dbGetQuery(con, "select * from stock")
meta <- dbGetQuery(con, "select * from meta")
mymeta <- subset(meta, marketid == mymarketid)
data_3 <- getmarket(con, marketid)
names(data_3)
s <- subset(data_3, "id" == "EUCA000749")

for (i in 1:nrow(data_3)) {
                                        #print(data_3[i,"date"])
                                        #return()
}

                                        #for (i in data_3) {
                                        #print(i["date"])
                                        #return
                                        #}

listid2 <- splitid(data_3)
listdate2 <- splitdate(data_3)
listdate <- split(data_3, data_3$date)
listid <- split(data_3, data_3$id)

                                        #l <- listdate[[104]]
if (!exists("days")) {
    days <- 10
}
if (!exists("topbottom")) {
    topbottom <- 5
}
count <- days
if (!exists("mytableintervaldays")) {
    mytableintervaldays <- 5
}
                                        #date <- "2016-05-02"

datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)

if (!exists("period")) {
    period <- 3
}

                                        #alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
                                        #periodmaps <- alist[[1]]
                                        #stocklistperiod <- alist[[2]]
                                        #mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
                                        #mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)

                                        #gettopchart(days, topbottom, stocklistperiod, period)
                                        #getbottomchart(days, topbottom, stocklistperiod, period)
                                        #rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #risetopids <- head(names(rise[[1]]))

getcontentgraph(con, date, ids, "1y")

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

context('adapter reference class')

test_that('it can initialize an adapter correctly', {
  a <- adapter(identity, identity)
})

test_that('it can read using a simple example adapter correctly', {
  tmp <- new.env()
  read_function <- function(opts) tmp$x <- opts$resource
  a <- adapter(read_function, identity)
  expect_identical(a$read("test"), "test")
  expect_identical(tmp$x, "test")
})

test_that('it can write using a simple example adapter correctly', {
  tmp <- new.env()
  read_function <- function(opts) tmp[[opts$resource]]
  write_function <- function(val, opts) { force(opts); tmp$x <- val }
  a <- adapter(read_function, write_function)
  a$write("test")
  expect_identical(tmp$x, "test")
  expect_identical(a$read('x'), "test")
})

describe("RDS2 functionality", {
  library(RDS2)

  test_that("it can read an RDS2 object correctly", {
    file_adapter <- construct_file_adapter()
    rds2_object <- structure("foo", RDS2.serialize = list(
      read  = function(obj) paste0(obj, "bar"),
      write = identity
    ))
    file <- tempfile(fileext = ".rds")
    RDS2::saveRDS(rds2_object, file)
    with_mock(`syberiaStages:::has_RDS2` = function() TRUE, {
      object <- file_adapter$read(file)
      expect_false("RDS2.serialize" %in% names(attributes(object)))
    })
    with_mock(`syberiaStages:::has_RDS2` = function() FALSE, {
      object <- file_adapter$read(file)
      expect_true("RDS2.serialize" %in% names(attributes(object)))
    })
  })
})

test_that('it formats options according to a formatting function', {
  formatter <- function(opts) list(file = opts$resource)
  a <- adapter(identity, identity, formatter)
  expect_identical(a$read("test")$file, "test")
})

test_that('it merges in default options if set', {
  a <- adapter(identity, identity, identity, list(blah = 'foo'))
  expect_identical(a$read("test")$blah, "foo")
})

test_that('it does not overwrite set values with defaults', {
  a <- adapter(identity, identity, identity, list(blah = 'foo'))
  expect_identical(a$read(list(blah = 'bar'))$blah, "bar")
})

context('fetch_adapter')

test_that('it fetches the s3 adapter', {
  expect_identical(fetch_adapter('s3')$.keyword, 's3')
})

test_that('it fetches the default adapter', {
  expect_identical(fetch_adapter('file')$.keyword, 'file')
})

test_that('it fetches the R adapter', {
  expect_identical(fetch_adapter('R')$.keyword, 'R')
})

#' @export
SummaryFromFiles <- function(file){
  infoTable <- as.matrix(read.csv(file, header=TRUE))
  assign("infoTable",infoTable,globalenv())
  BEG1 <- as.numeric(infoTable[1,2])
  END1 <- as.numeric(infoTable[2,2])
  str1 <- toString(infoTable[4,2])
  assign("str1", str1, globalenv())
  dir.create(paste(c(str1, "/PloidyRFiles"), collapse= ""), showWarnings = FALSE)
  str1.1 <- "/I"
  str2 <- "/I"
  str3 <- "_allelesFromPost_4_diffs.txt"
  infoFile <- toString(infoTable[6,2])
  info <- read.csv(infoFile)
  Notes <- table(info$PrePloidy)
  LocusRef <- scan(infoTable[11,2])
  testLoci <- sort(LocusRef)
  numLoci <- length(testLoci)
  refCheck <- as.numeric(infoTable[7,2])
  alleleMat <- matrix(ncol=8)
  if(refCheck == 1){
    allMat <- as.matrix(read.csv(infoTable[8,2], header = FALSE) )
    allDistancesMat <- as.matrix(read.csv(infoTable[9,2], header = FALSE))
    prevInfo <- read.csv(infoTable[10,2], header = TRUE)
    info <- rbind(info, prevInfo)
  } else{
    allMat <- matrix(ncol=5)
    allDistancesMat <- matrix(data=c("Locus",testLoci),nrow=numLoci+1,ncol=1)
  }
  assign("info",info,globalenv())
  ########## This part summarizes all allele data into allMat ################
  for (i in BEG1:END1){
    filePath <- paste(c(str1,str1.1,i,str2,i,str3), collapse = "")
    iNum <- paste(c("I",i), collapse = "")
    if (file.exists(filePath) == TRUE){
      dat <- read.table(filePath)	
      matLen <- length(dat[,7])/6
      valuesMat <- matrix(ncol=5)
      rowRef <- which(grepl(paste(c("^",iNum,"$"), collapse = ""), info$Individual))
      alleleCounter <- 1
      for (j in 1:matLen){
        if(dat[(alleleCounter),1] <= testLoci[length(testLoci)] & dat[(alleleCounter),1] %in% testLoci){
          alleles <- sort(c((dat[(alleleCounter),7]/dat[alleleCounter,8]), (dat[(alleleCounter+1),7]/dat[alleleCounter,8]), 					(dat[(alleleCounter+2),7]/dat[alleleCounter,8]), (dat[(alleleCounter+3),7]/dat[alleleCounter,8]), (dat[(alleleCounter+4),				7]/dat[alleleCounter,8]), (dat[(alleleCounter+5),7]/dat[alleleCounter,8])))
          allAlleleDists <- alleles		
          sameAlleles <- alleles[3:6]
          alleles <- alleles[1:2]
          
          valuesMat <- rbind(valuesMat, c(dat[alleleCounter,1],i,info$PrePloidy[rowRef], mean(alleles), sd(sameAlleles)))
          alleleMat <- rbind(alleleMat,c(i,dat[alleleCounter,1],allAlleleDists[1],allAlleleDists[2], 										allAlleleDists[3],allAlleleDists[4], allAlleleDists[5], allAlleleDists[6]))
        }
        else{}
        alleleCounter <- alleleCounter+6
        
      }
      valuesMat <- valuesMat[2:length(valuesMat[,1]),]
      allMat <- rbind(allMat, valuesMat)
      ## tempVal <- mean(filtMat)
      indDist <- matrix(nrow=numLoci+1, ncol = 1)
      indDist[1,] = iNum
      for (k in 1:numLoci){
        M <- valuesMat[valuesMat[,1] == testLoci[k], 4]
        indDist[k+1,] <-mean(M)
      }	
      allDistancesMat <- cbind(allDistancesMat,indDist)
      print(paste(c(iNum, " COMPLETED"), collapse = ""), quote = FALSE)
    }
    
    else {
      print(paste(c(iNum," FILE NOT FOUND"), collapse = ""), quote = FALSE)
    }
  }
  
  
  
  
  
  
  write.table(allDistancesMat, file = paste(c(str1,"/PloidyRFiles/allDistancesMat.csv"), collapse=""), row.names=FALSE, col.names=FALSE, sep=",")
  cat(c("Writing:" ,paste(c(str1,"/PloidyRFiles/allDistancesMat.csv"), collapse = "") ,"\n"))
  
  allMat <- allMat[2:length(allMat[,1]),]  ####Important!
  
  write.table(allMat, file = paste(c(str1,"/PloidyRFiles/allMat.csv"), collapse=""), row.names=FALSE, col.names=FALSE, sep=",")
  cat(c("Writing:" , paste(c(str1,"/PloidyRFiles/allMat.csv"), collapse = ""), "\n"))
  alleleMat <- alleleMat[2:length(alleleMat[,1]),] 
  write.table(alleleMat, file = paste(c(str1,"/PloidyRFiles/alleleMat.csv"), collapse=""), row.names=FALSE, col.names=FALSE, sep=",")
  cat(c("Writing:" , paste(c(str1,"/PloidyRFiles/alleleMat.csv"), collapse = ""), "\n"))
  assign("allMat",allMat,globalenv())
  assign("alleleMat", alleleMat, globalenv())
  assign("testLoci",testLoci,globalenv())
  assign("numLoci", numLoci, globalenv())
  avgDist <- matrix(nrow=numLoci, ncol = 1)
  devDist <- matrix(nrow=numLoci, ncol = 1)
  for (k in 1:numLoci){
    M <- allMat[allMat[,1] == testLoci[k], 3]
    avgDist[k,] <- mean(M)
    devDist[k,] <- sd(M)
  }
}
######################################################################
######################################################################
## ROUTINE ZUM EINLESEN VON ERA-DATEN (ZONAL-WIND) IM NCDF-FORMAT
## UND AUFFINDEN DES JETSTREAMS AUF NORDHEMISPHÄRE
## source('~/Master_Thesis/r-code-git/locate_jetstream_polynomial_2d.r')
######################################################################
######################################################################


######################################################################
## AUFRUF WICHTIGER BIBLIOTHEKEN UND PAKETE
######################################################################
##

library(ncdf4)
library(parallel)
library(chron)

# eigenes package für least squares fit mit chebyshev polynomen
# install.packages("pckg.cheb_0.2.tar.gz", repos = NULL, type = "source")
library(pckg.cheb)

setwd("~/Master_Thesis/r-code-git/")
path <- "data/"
# path <- "/home/skiefer/era/raw/"
file <- "era-t63-1957-2016.nh-trop-inv.nc"  # Nordhemisphäre + Tropen


######################################################################
## KLEINE HILFSFUNKTIONEN
######################################################################
##

fun.fill <- function(x, n) {
  while (length(x) < n) {
    x <- c(x, NA)
  }
  return(x)
}


######################################################################
## EINLESEN DER DATEN
## ERA40 / ERA-INTERIM
## T63 - GRID - GAUSSIAN
## NORDHEMISPHÄRE & TROPEN
## 192 (lat) * 64 (lon)
######################################################################
##

nc <- nc_open(paste(path, file, sep = ""))
# print(nc)
u.monmean <- ncvar_get(nc, "var131") # U-Wind-Komponente
v.monmean <- ncvar_get(nc, "var132") # V-Wind-Komponente
# w.monmean <- ncvar_get(nc, "var135") # W-Wind-Komponente
# z.monmean <- ncvar_get(nc, "var129") # Geopotenzial
# t.monmean <- ncvar_get(nc, "var130") # Temperatur
# d.monmean <- ncvar_get(nc, "var155") # Divergenz

lon <- ncvar_get(nc, "lon") # Längengrad
lat <- ncvar_get(nc, "lat") # Breitengrad
lev <- ncvar_get(nc, "lev") # Drucklevel
date.help <- ncvar_get(nc, "time")

nc_close(nc)
rm(nc)

uv.monmean <- sqrt( u.monmean ** 2 + v.monmean **2 )

######################################################################
## VARIABLEN UND PARAMETER
######################################################################
##

n.cpu <- 5 #5 # Anzahl der CPUs für parApply
n.order.lat <- 23 # Ordnung des Least-Square-Verfahrens für Fit über Breitengrad
n.order.lon <- 8 # Ordnung des Least-Square-Verfahrens für Fit über Längengrad
n.order.lat.seq <- 3 # Ordnung des Least-Square-Verfahrens für sequentiellen Fit über Breitengrad
len.seq <- 8 # Länge der ersten Sequenz der 

## Räumliche Auflösung
n.lat <- length(lat)
n.lon <- length(lon)

## Zeitliche Auflösung
dts = chron(dates. = date.help/24, origin. = c(month = 9,day = 1,year = 1957), format = "day mon year")
dts.month <- months(dts, abbreviate = TRUE)
dts.year <- years(dts)

## Zeitlich gemittelter Zonalwind
u.mean <- apply(u.monmean,c(1,2),mean)
u.std <- apply(u.monmean,c(1,2),sd)

## Meridional und zeitlich gemittelter Zonalwind
# u.mon.mer.mean <- apply(u.monmean, 2, mean)
# u.mon.mer.sd <- apply(u.mean, 2, sd)

## Meridional gemittelter Zonalwind
# u.monmean.mermean <- apply(u.monmean, c(2,3), mean)
# u.monmean.mersd <- apply(u.monmean, c(2,3), sd)



######################################################################
## LEAST SQUARES FIT 
## CHEBYSHEV POLYNOME 23-TER ORDNUNG
## AN ZONAL WIND IN MERIDIONALER RICHTUNG
######################################################################
##

# list.model.lat <- apply(u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
list.model.lat <- parApply(cl, u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
stopCluster(cl)
dim.list <- dim(list.model.lat)

## Chebyshev-Koeffizienten
cheb.coeff <- sapply(list.model.lat, "[[", 1)
cheb.coeff <- apply(array(data = cheb.coeff, dim = c((n.order.lat + 1), dim.list[1], dim.list[2])) , c(1,3), t)

## Gefiltertes Modell für Zonal-Wind
model.u <- sapply(list.model.lat, "[[", 2)
model.u <- apply(array(data = model.u, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)

## Erste Ableitung des gefilterten Modells für Zonalwind
model.u.deriv.1st <- sapply(list.model.lat, "[[", 3)
model.u.deriv.1st <- apply(array(data = model.u.deriv.1st, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)

## Extrema des Modells (Positionen und Werte)
model.extr.lat <- sapply(list.model.lat, "[[", 4)
model.extr.u <- sapply(list.model.lat, "[[", 5)
model.extr.lat <- sapply(model.extr.lat, fun.fill, n = 24)
model.extr.lat <- apply(array(model.extr.lat, c(24, dim.list[1], dim.list[2])), c(1,3), t)
model.extr.u <- sapply(model.extr.u, fun.fill, n = 24)
model.extr.u <- apply(array(model.extr.u, c(24, dim.list[1], dim.list[2])), c(1,3), t)

## Maxima des Modells (Positionen und Werte)
model.max.u <- apply(model.extr.u, c(1,3), max, na.rm = TRUE)
model.max.lat <- array(rep(0, 192*664), c(dim.list))
for (i in 1:dim.list[2]) {
  for (j in 1:dim.list[1]) {
    model.max.lat[j,i] <- model.extr.lat[j, which(model.extr.u[j,,i] == model.max.u[j,i]), i]
  }
}
rm(list.model.lat, dim.list)
rm(dim.list)


######################################################################
## LEAST SQUARES FIT 
## CHEBYSHEV POLYNOME 8-TER ORDNUNG
## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
######################################################################
##

#list.model.lon <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
cl <- makeCluster(getOption("cl.cores", n.cpu))
list.model.lon <- parApply(cl, model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
stopCluster(cl)

## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
model.max.lon <- list.model.lon, "[[", 2)
rm(list.model.lon)


######################################################################
## FEHLERGRÖẞEN
## MSE
## RMSE
######################################################################
##

residuals.cheb <- u.monmean - model.u
residuals.cheb.seq <- u.monmean - model.u.seq
mse <- sum(residuals.cheb ** 2) / length(residuals.cheb)
mse.seq <- sum(residuals.cheb.seq **2) / length(residuals.cheb.seq)
rmse <- sqrt(sum(residuals.cheb ** 2) / length(residuals.cheb))
rmse.seq <- sqrt(sum(residuals.cheb.seq **2) / length(residuals.cheb.seq))

## rmse.seq = 0.4079846  ## mse.seq = 0.1664514
## rmse     = 0.2911683  ## mse     = 0.08477901


######################################################################
######################################################################
save.image()



######################################################################
## Berechnung von Mean und Sd
## über fünf Jahre & saisonal
######################################################################
dts.year.mn <- seq(1960, 2010, 5)

ind.mam <- which(dts.month == "Mar" | dts.month == "Apr" | dts.month == "May")
ind.jja <- which(dts.month == "Jun" | dts.month == "Jul" | dts.month == "Aug")
ind.son <- which(dts.month == "Sep" | dts.month == "Oct" | dts.month == "Nov")
ind.djf <- which(dts.month == "Dec" | dts.month == "Jan" | dts.month == "Feb")

## Mittelwerte global
u.seas.mam.mean <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.mam.sd <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.jja.mean <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.jja.sd <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.son.mean <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.son.sd <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.djf.mean <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.djf.sd <- array( NA , dim = c(n.lon, n.lat, 11))

## Mittelwerte meridional *???*
u.mer.seas.mam.mean <- array( NA , dim = c(n.lat, 11))
u.mer.seas.mam.sd <- array( NA , dim = c(n.lat, 11))
u.mer.seas.jja.mean <- array( NA , dim = c(n.lat, 11))
u.mer.seas.jja.sd <- array( NA , dim = c(n.lat, 11))
u.mer.seas.son.mean <- array( NA , dim = c(n.lat, 11))
u.mer.seas.son.sd <- array( NA , dim = c(n.lat, 11))
u.mer.seas.djf.mean <- array( NA , dim = c(n.lat, 11))
u.mer.seas.djf.sd <- array( NA , dim = c(n.lat, 11))

for (i in seq(1, 11)) {
  print(i)
  yr.i <- dts.year.mn[i]
  ind.yr <- which(dts.year ==  yr.i | dts.year == (yr.i + 1) | dts.year == (yr.i + 2) | dts.year == (yr.i + 3) | dts.year == (yr.i + 4) )
  ## Mar Apr May
  ind.mam.yr <- intersect(ind.yr, ind.mam)
  u.seas.mam.mean[,,i] <- apply(u.monmean[,, ind.mam.yr], c(1,2), mean)
  u.seas.mam.sd[,,i] <- apply(u.monmean[,, ind.mam.yr], c(1,2), sd)
  u.mer.seas.mam.mean[,i] <- apply(u.monmean[,, ind.mam.yr], 2, mean)
  u.mer.seas.mam.sd[,i] <- apply(u.monmean[,, ind.mam.yr], 2, sd)
  ## Jun Jul Aug
  ind.jja.yr <- intersect(ind.yr, ind.jja)
  u.seas.jja.mean[,,i] <- apply(u.monmean[,, ind.jja.yr], c(1,2), mean)
  u.seas.jja.sd[,,i] <- apply(u.monmean[,, ind.jja.yr], c(1,2), sd)
  u.mer.seas.jja.mean[,i] <- apply(u.monmean[,, ind.jja.yr], 2, mean)
  u.mer.seas.jja.sd[,i] <- apply(u.monmean[,, ind.jja.yr], 2, sd)
  ## Sep Oct Nov
  ind.son.yr <- intersect(ind.yr, ind.son)
  u.seas.son.mean[,,i] <- apply(u.monmean[,, ind.son.yr], c(1,2), mean)
  u.seas.son.sd[,,i] <- apply(u.monmean[,, ind.son.yr], c(1,2), sd)
  u.mer.seas.son.mean[,i] <- apply(u.monmean[,, ind.son.yr], 2, mean)
  u.mer.seas.son.sd[,i] <- apply(u.monmean[,, ind.son.yr], 2, sd)
  ## Dec Jan Feb
  ind.djf.yr <- intersect(ind.yr, ind.djf)
  u.seas.djf.mean[,,i] <- apply(u.monmean[,, ind.djf.yr], c(1,2), mean)
  u.seas.djf.sd[,,i] <- apply(u.monmean[,, ind.djf.yr], c(1,2), sd)
  u.mer.seas.djf.mean[,i] <- apply(u.monmean[,, ind.djf.yr], 2, mean)
  u.mer.seas.djf.sd[,i] <- apply(u.monmean[,, ind.djf.yr], 2, sd)
  ## Löschen von Übergangsvariablen
  rm(yr.i, ind.yr, ind.mam.yr, ind.jja.yr, ind.son.yr, ind.djf.yr, i)
}

max(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
min(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
range(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)

max(u.seas.mam.mean)
min(u.seas.mam.mean)
range(u.seas.mam.mean)

max(u.seas.jja.mean)
min(u.seas.jja.mean)
range(u.seas.jja.mean)

max(u.seas.son.mean)
min(u.seas.son.mean)
range(u.seas.son.mean)

max(u.seas.djf.mean)
min(u.seas.djf.mean)
range(u.seas.djf.mean)


image.plot(lon, lat, u.mean+u.std)
contour(lon, lat, u.std[,,1], add=TRUE)
addland(col= "grey50", lwd = 1)

cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
list.lat.m.sd <- parApply(cl, (u.mean[,] - u.std[,]), 1, pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
list.lat.mn <- parApply(cl, u.mean[,], 1, pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
list.lat.p.sd <- parApply(cl, (u.mean[,] + u.std[,]), 1, pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
stopCluster(cl)

model.extr.lat.m.sd <- sapply(list.lat.m.sd, "[[", 4)
model.extr.lat.mn <- sapply(list.lat.mn, "[[", 4)
model.extr.lat.p.sd <- sapply(list.lat.m.sd, "[[", 4)

model.extr.u.m.sd <- sapply(list.lat.m.sd, "[[", 5)
model.extr.u.mn <- sapply(list.lat.mn, "[[", 5)
model.extr.u.p.sd <- sapply(list.lat.p.sd, "[[", 5)

model.extr.lat.m.sd <- sapply(model.extr.lat.m.sd, fun.fill, n = 16)
model.extr.lat.mn <- sapply(model.extr.lat.mn, fun.fill, n = 16)
model.extr.lat.p.sd <- sapply(model.extr.lat.p.sd, fun.fill, n = 16)

model.extr.u.m.sd <- sapply(model.extr.u.m.sd, fun.fill, n = 16)
model.extr.u.mn <- sapply(model.extr.u.mn, fun.fill, n = 16)
model.extr.u.p.sd <- sapply(model.extr.u.p.sd, fun.fill, n = 16)

model.max.u.m.sd <- apply(model.extr.u.m.sd, 2, max, na.rm = TRUE)
model.max.u.mn <- apply(model.extr.u.mn, 2, max, na.rm = TRUE)
model.max.u.p.sd <- apply(model.extr.u.p.sd, 2, max, na.rm = TRUE)

model.max.lat.m.sd <- array(rep(0, 192))
model.max.lat.mn <- array(rep(0, 192))
model.max.lat.p.sd <- array(rep(0, 192))

for (i in 1:192) {
  model.max.lat.m.sd[i] <- model.extr.lat.m.sd[which(model.extr.u.m.sd[,i] == model.max.u.m.sd[i]), i]
  model.max.lat.mn[i] <- model.extr.lat.mn[which(model.extr.u.mn[,i] == model.max.u.mn[i]), i]
  model.max.lat.p.sd[i] <- model.extr.lat.p.sd[which(model.extr.u.p.sd[,i] == model.max.u.p.sd[i]), i]
}

list.lon.m.sd <- pckg.cheb:::cheb.fit(d = model.max.lat.m.sd, x.axis = lon, n = 11)
list.lon.mn <- pckg.cheb:::cheb.fit(d = model.max.lat.mn, x.axis = lon, n = 11)
list.lon.p.sd <- pckg.cheb:::cheb.fit(d = model.max.lat.p.sd, x.axis = lon, n = 11)

model.max.lon.m.sd <- list.lon.m.sd[[2]]
model.max.lon.mn <- list.lon.mn[[2]]
model.max.lon.p.sd <- list.lon.p.sd[[2]]


lines(lon, model.max.lon.m.sd)
lines(lon, model.max.lon.mn)
lines(lon, model.max.lon.p.sd)




####################################################################################################
########## ableitung des drehimpulses ##############################################################
########## aus zonal wind ##########################################################################
####################################################################################################
### ref: m = 
### formel noch inkorrekt
### keine schleife benutzen
##
# m <- matrix(NA,n.lon,n.lat)
# for (i in 1:n.lon){
#   for (j in 1:n.lat){
#     m[i,j] <- u.era.t63.monmean[i,j,1]*cos(lat.era.t63[j]) + 1/86400*u.era.t63.monmean[i,j,1]**2*cos(lat.era.t63[j])**2
#   }
# }
# #m <- u.era.t63.monmean*cos(lat.era.t63)
# 




# ######################################################################
# ## LEAST SQUARES FIT ÜBER **SEQUENZEN** (l=8)
# ## CHEBYSHEV POLYNOME 3-TER ORDNUNG
# ## AN ZONAL-WIND IN MERIDIONALER RICHTUNG
# ######################################################################
# ##
# 
# # list.model.lat.seq <- apply(u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
# list.model.lat.seq <- parApply(cl, u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# stopCluster(cl)
# dim.list <- dim(list.model.lat.seq)
# 
# ## Gefiltertes Modell für Zonal-Wind
# model.u.seq <- sapply(list.model.lat.seq, "[[", 1)
# model.u.seq <- apply(array(data = model.u.seq, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Erste Ableitung des gefilterten Modells für Zonalwind
# model.u.deriv.1st.seq <- sapply(list.model.lat.seq, "[[", 2)
# model.u.deriv.1st.seq <- apply(array(data = model.u.deriv.1st.seq, dim = c(n.lon, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Extrema des Modells (Positionen und Werte)
# model.extr.lat.seq <- sapply(list.model.lat.seq, "[[", 3)
# model.extr.lat.seq <- sapply(model.extr.lat.seq, fun.fill, n = 24)
# model.extr.lat.seq <- apply(array(model.extr.lat.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# model.extr.u.seq <- sapply(list.model.lat.seq, "[[", 4)
# model.extr.u.seq <- sapply(model.extr.u.seq, fun.fill, n = 24)
# model.extr.u.seq <- apply(array(model.extr.u.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# 
# ## Maxima des Modells (Positionen und Werte)
# model.max.u.seq <- apply(model.extr.u.seq, c(1,3), max, na.rm = TRUE)
# model.max.lat.seq <- array(rep(0, dim.list[1]*dim.list[2]), c(dim.list))
# for (i in 1:dim.list[2]) {
#   for (j in 1:dim.list[1]) {
#     model.max.lat.seq[j,i] <- model.extr.lat.seq[j, which(model.extr.u.seq[j,,i] == model.max.u.seq[j,i]), i]
#   }
# }
# rm(list.model.lat.seq, dim.list)
# 
# 
# ######################################################################
# ## LEAST SQUARES FIT 
# ## CHEBYSHEV POLYNOME 8-TER ORDNUNG
# ## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
# ## ANGEWANDT AUF SEQUENZIERTES MODELL
# ######################################################################
# ##
# 
# #list.model.lon.seq <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = 8)
# cl <- makeCluster(getOption("cl.cores", n.cpu))
# list.model.lon.seq <- parApply(cl, model.max.lat.seq, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
# stopCluster(cl)
# 
# ## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
# model.max.lon.seq <- sapply(list.model.lon.seq, "[[", 2)
# rm(list.model.lon.seq)

sourceResult <- tryCatch({ source("~/.ripconfig") },
	error = function(e){}, warning = function(e){})

if (!exists("RIPCONFIG_CRAN_PATH"))
{
	RIPCONFIG_CRAN_PATH = "http://cran.r-project.org/"
}

if (!exists("RIPCONFIG_LIB_PATH"))
{
	RIPCONFIG_LIB_PATH = .libPaths()[1]
}

repoConfig <- getOption("repos")
repoConfig["CRAN"] = RIPCONFIG_CRAN_PATH
options(repos = repoConfig)

manifestName <- '.rip'
args <- commandArgs(trailingOnly = T)

info <- function(...)
{
	cat(paste0(...), "\n")
}

assertPwd <- function(isRipProject)
{
	if (isRipProject != file.exists(manifestName))
	{
		stop("Current directory ", if (isRipProject) "is not" else "is already" , " a rip project")
	}
}

loadPackages <- function()
{
	fh <- file(manifestName, open = "r")
	packages <- c()
	while (length(line <- readLines(fh, n = 1)) > 0)
	{
		packages <- c(packages, line);
	}
	close(fh)
	return(packages)
}

savePackages <- function(packages)
{
	fh <- file(manifestName, open = "w")
	writeLines(sort(packages), fh)
	close(fh)
}

quietInstall <- function(packages)
{
	install.packages(packages, verbose = F, quiet = T, lib = RIPCONFIG_LIB_PATH)
}

restore <- function()
{
	assertPwd(T)
	packages <- loadPackages()
	packageCount <- length(packages)

	if (!packageCount)
	{
		stop("No packages in manifest to restore")
	}

	info("Restoring ", packageCount, " package(s)")
	quietInstall(packages)
}

install <- function()
{
	assertPwd(T)
	packagesToInstall <- args[0:-1]

	if (!length(packagesToInstall))
	{
		stop("Please specify at least one package")
	}

	packages <- loadPackages()

	for (package in packagesToInstall)
	{
		if (!(package %in% available.packages()[,"Package"]))
		{
			stop("Package is not available in the repository: ", package)
		}
	}

	quietInstall(packagesToInstall)
	savePackages(union(packages, packagesToInstall))
}

init <- function()
{
	assertPwd(F)
	file.create(manifestName)
}

listVersions <- function()
{
	assertPwd(T)
	packages <- loadPackages()

	for (package in packages)
	{
		version <- packageVersion(package)
		info(package, ": ", version)
	}
}

help <- function(commandName = NA)
{
	if (!is.na(commandName))
	{
		info("Invalid command: ", commandName, "\n")
	}

	commands <- list(
		init = "initialises an empty manifest",
		install = "installs one or more packages and records them in your manifest",
		restore = "installs all packages referenced in your manifest",
		list = "displays a list of currently installed packages with their versions")

	output = paste0("rip ", names(commands), "\n  ", commands, "\n")

	info("Usage:\n")
	for (command in output)
	{
		info(command)
	}
}

main <- function()
{
	commandName <- args[1]
	command <- switch(commandName,
		init = init,
		install = install,
		restore = restore,
		list = listVersions,
		"-h" = , "--help" = , help = help,
		function() { help(commandName) })

	command()
}

dummy <- main()                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, mytableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, date) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (date == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, mytableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]
    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
    }
    for (i in 1:max) {
        id <- list11$id[i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), list2[[id]], list11$id[[i]]))
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

gettopchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    displaychart(ls, names, topbottom, period, maindate, olddate)
}

getbottomchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    displaychart(ls, names, topbottom, period, maindate, olddate)
}

getchart <- function(days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    displaychart(ls, names, topbottom, period, maindate, olddate)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        print("here1")
        t.test(c1,c2,paired=TRUE)
        print("here2")
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, period, maindate, olddate) {
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }
        periodtext <- period

        if (period >= 0) {
            newtext <- getperiodtext(mymeta, period)
            if (!is.na(newtext)) {
                periodtext <- newtext
            }
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (period == pricetype) {
        return (df$price)
    }
    if (period == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
#                                            str("her")
#                                            str(id)
#                                            str(days)
#                                            str(period)
#                                            str(datedstocklist)
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, date, mytableintervaldays) {
    datedstocklists <- list()
    if (is.null(date)) {
        dateindex <- match(date, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    str(dateindex)
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:count) {
        index <- index - mytableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(con, date, ids, periodtext) {
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getmarket(con, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    ls <- list()
    names <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        l <- getelem3(id, days, datedstocklists, period, topbottom)
                        ls[c] <- list(l)
                        names[c] <- id
                    }
                }
            }
        }
    }
    maindate <- "1"
    olddate <- "2"
    displaychart(ls, names, 5, period, maindate, olddate)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- subset(meta, marketid == market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmarket <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

if (!exists("marketid")) {
    marketid <- "morncat"
}

data <- dbGetQuery(con, "select * from stock")
meta <- dbGetQuery(con, "select * from meta")
mymeta <- subset(meta, marketid == mymarketid)
data_3 <- getmarket(con, marketid)
names(data_3)
s <- subset(data_3, "id" == "EUCA000749")

for (i in 1:nrow(data_3)) {
                                        #print(data_3[i,"date"])
                                        #return()
}

                                        #for (i in data_3) {
                                        #print(i["date"])
                                        #return
                                        #}

listid2 <- splitid(data_3)
listdate2 <- splitdate(data_3)
listdate <- split(data_3, data_3$date)
listid <- split(data_3, data_3$id)

                                        #l <- listdate[[104]]
if (!exists("days")) {
    days <- 10
}
if (!exists("topbottom")) {
    topbottom <- 5
}
count <- days
if (!exists("mytableintervaldays")) {
    mytableintervaldays <- 5
}
                                        #date <- "2016-05-02"

datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)

if (!exists("period")) {
    period <- 3
}

                                        #alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
                                        #periodmaps <- alist[[1]]
                                        #stocklistperiod <- alist[[2]]
                                        #mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
                                        #mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)

                                        #gettopchart(days, topbottom, stocklistperiod, period)
                                        #getbottomchart(days, topbottom, stocklistperiod, period)
                                        #rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #risetopids <- head(names(rise[[1]]))

getcontentgraph(con, date, ids, "1y")

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, mytableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, date) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (date == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, mytableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]
    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
    }
    for (i in 1:max) {
        id <- list11$id[i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), list2[[id]], list11$id[[i]]))
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

gettopchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    displaychart(ls, names, topbottom, period, maindate, olddate)
}

getbottomchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    displaychart(ls, names, topbottom, period, maindate, olddate)
}

getchart <- function(days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    displaychart(ls, names, topbottom, period, maindate, olddate)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        print("here1")
        t.test(c1,c2,paired=TRUE)
        print("here2")
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, period, maindate, olddate) {
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }
        periodtext <- period

        if (period >= 0) {
            newtext <- getperiodtext(mymeta, period)
            if (!is.na(newtext)) {
                periodtext <- newtext
            }
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (period == pricetype) {
        return (df$price)
    }
    if (period == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
                                        #    str("her")
                                        #    str(id)
                                        #    str(days)
                                        #    str(period)
                                        #    str(datedstocklist)
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, date, mytableintervaldays) {
    datedstocklists <- list()
    if (is.null(date)) {
        dateindex <- match(date, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    str(dateindex)
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:count) {
        index <- index - mytableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(con, date, ids, periodtext) {
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getmarket(con, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pair <- pairs[[pairkey]]
            market <- pair[[1]]
            period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
            marketdata <- marketdatamap[market]
            datedstocklists <- marketdata[[1]][3]
            ls <- list()
            names <- list()
            c <- 0
            for (i in 1:length(ids)) {
                idpair <- ids[[i]]
                idmarket <- idpair[1]
                id <- idpair[2]
                                        #           str("for")
                cat(market, idmarket, id)
                if (market == idmarket) {
                    cat("per", text, " ", id, " ", period, " ")
                    c <- c + 1
                    l <- getelem3(id, days, datedstocklists, period, topbottom)
                    ls[c] <- list(l)
                    names[c] <- "test"
                                        #                str(l)
                }
            }
        }
    }
    maindate <- "1"
    olddate <- "2"
    displaychart(ls, names, 5, period, maindate, olddate)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- subset(meta, marketid == market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmarket <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

if (!exists("marketid")) {
    marketid <- "morncat"
}

data <- dbGetQuery(con, "select * from stock")
meta <- dbGetQuery(con, "select * from meta")
mymeta <- subset(meta, marketid == mymarketid)
data_3 <- getmarket(con, marketid)
names(data_3)
s <- subset(data_3, "id" == "EUCA000749")

for (i in 1:nrow(data_3)) {
                                        #print(data_3[i,"date"])
                                        #return()
}

                                        #for (i in data_3) {
                                        #print(i["date"])
                                        #return
                                        #}

listid2 <- splitid(data_3)
listdate2 <- splitdate(data_3)
listdate <- split(data_3, data_3$date)
listid <- split(data_3, data_3$id)

                                        #l <- listdate[[104]]
if (!exists("days")) {
    days <- 10
}
if (!exists("topbottom")) {
    topbottom <- 5
}
count <- days
if (!exists("mytableintervaldays")) {
    mytableintervaldays <- 5
}
                                        #date <- "2016-05-02"

datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)

if (!exists("period")) {
    period <- 3
}

                                        #alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
                                        #periodmaps <- alist[[1]]
                                        #stocklistperiod <- alist[[2]]
                                        #mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
                                        #mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)

                                        #gettopchart(days, topbottom, stocklistperiod, period)
                                        #getbottomchart(days, topbottom, stocklistperiod, period)
                                        #rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #risetopids <- head(names(rise[[1]]))

getcontentgraph(con, date, ids, "1y")

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

## Preliminary analysis of water inflow data

# Import the water inflow sample data
samples <- read.csv("./water_inflow_data.csv",  stringsAsFactors = FALSE)
# I did edit a couple of the dates because R seems to struggle with dates (but then don't we all)

# Rename all the measurements for easier reading
rn <- function(old.name, new.name){
  names(samples)[names(samples) == old.name] <<- new.name
}

rn("Flow.rate..litres.sec.", "Flow")

rn("BOD.5.Day.ATU..mg.l.", "BOD")
rn("Nitrogen...Total.as.N..mg.l.", "Nitrogen.Total")
rn("Phosphorus...Total.as.P..mg.l.", "Phosphorus")
rn("Alkalinity.to.pH.4.5.as.CaCO3..mg.l.", "Alkalinity")
rn("Ammoniacal.Nitrogen.as.N..mg.l.", "Nitrogen.Ammoniacal")
rn("Chloride..mg.l.", "Chloride")
rn("Nitrite.as.N..mg.l.", "Nitrite")
rn("Nitrogen...Total.Oxidised.as.N..mg.l.", "Nitrogen.Oxidised")
rn("Orthophosphate..reactive.as.P..mg.l.", "Orthophosphate")
rn("Silicate..reactive.as.SiO2..mg.l.", "Silicate")
rn("Phosphate...Total.as.P..mg.l.", "Phosphate")
rn("Conductivity.at.20C..uS.cm.", "Conductivity")
rn("Turbidity..NTU.", "Turbidity")
rn("Solids..Suspended.at.105.C..mg.l.", "Solids")
rn("Calcium..mg.l.", "Calcium")
rn("Magnesium..mg.l.", "Magnesium")
rn("Potassium..mg.l.", "Potassium")
rn("Sodium..mg.l.", "Sodium")

# Also remane the comment because it actually contains the site name
rn("Comment", "Name")

# Remove the spaces from the grid references
samples$Grid.reference <- gsub(" ", "", samples$Grid.reference, fixed = TRUE)

# How many site names are there?
length(unique(samples$Name))

# How many grid references are there?
length(unique(samples$Grid.reference))

# How many pairs of comments and grid references?
sites <- data.frame(OSGrid = samples$Grid.reference, Name = samples$Name)
sites <- unique(sites)
nrow(sites)

# Give each of the sites a unique id (might come in handy)
sites$Id <- seq.int(nrow(sites))

# Export the sites list so WGS84 can be added to it
write.table(sites, "sites.csv", row.names = FALSE, col.names = TRUE, sep = ",")

## Go to http://gridreferencefinder.com/batchConvert/batchConvert.php to do the geocoding

# Import the geocoded sites
sites <- read.csv("./sites_with_locations.csv", header = TRUE, stringsAsFactors = FALSE)

# Cluster using k-means
km <- kmeans(cbind(sites$X, sites$Y), centers = 3)
# Plot without a background to look at the clusters
plot(sites$X, sites$Y, col = km$cluster, pch = 20)
plot(sites$Lng, sites$Lat, col = km$cluster, pch = 20)

# Get a map of the area and plot sites
library(ggmap)
map_centre <- c(lon = -2.85, lat = 52.80) # chosen by inspection
map <- qmap(map_centre) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)

# Zoom in in the Marton cluster of 10
map_centre <- c(lon = -3.045, lat = 52.623) # chosen by inspection
map <- qmap(map_centre, zoom = 15) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)


# Let's check out the distribution of measurments
# A function to standardised the graphs
graf <- function(column.name){
  scratch <- samples[,c(column.name)]
  scratch <- gsub("[^.0-9]+", "", scratch) # just the numbers and nothing else
  scratch <- as.numeric(scratch)
  title <- paste("Histogram of", column.name, sep = " ")
  hist(main = title, scratch, xlab = column.name, breaks = 20)
}
# Complete graph-arama
graf("BOD")
graf("Nitrogen.Total")             
graf("Phosphorus")           
graf("Alkalinity")          
graf("Nitrogen.Ammoniacal")
graf("Chloride")
graf("Nitrite") 
graf("Nitrogen.Oxidised") 
graf("Orthophosphate")       
graf("Silicate")
graf("Phosphate")             
graf("Conductivity")
graf("Turbidity")
graf("Solids")
graf("Calcium")              
graf("Magnesium")
graf("Potassium")
graf("Sodium")

"
The graphs for calcium, conductivity, silicate, alkalinity look like they might have been censored.
There appears to be a spike at one end of the distribution, like the data might have contained
a bunch of < or > but inspection reveals that silicate contains only one reading with < (<0.200).
"

# Let's find the bad boys
baduns <- function(column.name){
  # The column.name is passed as a string so the column has to be accessed using [] notation
  # rather than directly.
  scratch <- samples[,c("Name", column.name)]
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)]) # then convert to numeric
  scratch <- aggregate(scratch[,column.name], by = list(scratch$Name), max)
  scratch <- scratch[order(-scratch$x),] # Bad boys at the top
  names(scratch)[names(scratch) == "Group.1"] <- "Name"
  scratch <- head(scratch, n=8) # Calcium etc... have only been recorded for 8 sites.
  print(scratch)
  scratch <- scratch[order(scratch$x),] # reverse the order
  bp <- barplot(scratch$x, xlab=column.name, horiz=TRUE)
  text(0, bp, scratch$Name, cex=1, pos=4)
}

baduns("BOD")
baduns("Nitrogen.Total")             
baduns("Phosphorus")           
baduns("Alkalinity")          
baduns("Nitrogen.Ammoniacal")
baduns("Chloride")
baduns("Nitrite") 
baduns("Nitrogen.Oxidised") 
baduns("Orthophosphate")       
baduns("Silicate")
baduns("Phosphate")             
baduns("Conductivity")
baduns("Turbidity")
baduns("Solids")
baduns("Calcium")              
baduns("Magnesium")
baduns("Potassium")
baduns("Sodium")

# Sites with 9 or more samples.
scratch <- as.data.frame(table(samples$Name))
colnames(scratch) <- c("Name", "Freq")
sites <- merge(sites, scratch, by="Name")
scratch <- sites[sites$Freq >= 8,]
scratch <- merge(scratch, samples, by = "Name")

# The dates are ambiguous so stick in the century using a regex
scratch$Sample.taken <- gsub("(\\d{2}-[A-Z]{3}-)", "\\120", scratch$Sample.taken, perl = TRUE)
scratch$Sample.taken <- strptime(scratch$Sample.taken, "%d-%b-%Y %H:%M")
scratch$Sample.taken <- as.Date(scratch$Sample.taken)
scratch$Sample.taken <- as.POSIXct(scratch$Sample.taken, "%d-%b-%Y")

# The flows include some comments to the effect that there is no flow so these are made into zeros
scratch$Flow <- as.numeric(scratch$Flow)
scratch$Flow[is.na(scratch$Flow)] <- 0

library(ggplot2)
library(scales)

# Let's graph the ones with reasonable amounts of data
timegraph <- function(column.name){
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)])
  scratch$total <- scratch[,c(column.name)] * scratch$Flow
  ggplot(scratch, aes(x = Sample.taken, y = scratch$total, colour=Name, group=Name)) +
    geom_line() +
    scale_x_datetime(date_breaks = "1 month", date_labels = "%b") +
    xlab("2015-2016") + 
    ylab(paste0(column.name, " * Flow"))
}

timegraph("BOD")
timegraph("Nitrogen.Total")             
timegraph("Phosphorus")           
timegraph("Alkalinity")          
timegraph("Nitrogen.Ammoniacal")
timegraph("Chloride")
timegraph("Nitrite") 
timegraph("Nitrogen.Oxidised") 
timegraph("Orthophosphate")       
timegraph("Silicate")
timegraph("Phosphate")             
timegraph("Conductivity")
timegraph("Turbidity")
timegraph("Solids")
timegraph("Calcium")              
timegraph("Magnesium")
timegraph("Potassium")
timegraph("Sodium")
## Preliminary analysis of water inflow data

# Import the water inflow sample data
samples <- read.csv("./water_inflow_data.csv",  stringsAsFactors = FALSE)
# I did edit a couple of the dates because R seems to struggle with dates (but then don't we all)

# Rename all the measurements for easier reading
rn <- function(old.name, new.name){
  names(samples)[names(samples) == old.name] <<- new.name
}

rn("Flow.rate..litres.sec.", "Flow")

rn("BOD.5.Day.ATU..mg.l.", "BOD")
rn("Nitrogen...Total.as.N..mg.l.", "Nitrogen.Total")
rn("Phosphorus...Total.as.P..mg.l.", "Phosphorus")
rn("Alkalinity.to.pH.4.5.as.CaCO3..mg.l.", "Alkalinity")
rn("Ammoniacal.Nitrogen.as.N..mg.l.", "Nitrogen.Ammoniacal")
rn("Chloride..mg.l.", "Chloride")
rn("Nitrite.as.N..mg.l.", "Nitrite")
rn("Nitrogen...Total.Oxidised.as.N..mg.l.", "Nitrogen.Oxidised")
rn("Orthophosphate..reactive.as.P..mg.l.", "Orthophosphate")
rn("Silicate..reactive.as.SiO2..mg.l.", "Silicate")
rn("Phosphate...Total.as.P..mg.l.", "Phosphate")
rn("Conductivity.at.20C..uS.cm.", "Conductivity")
rn("Turbidity..NTU.", "Turbidity")
rn("Solids..Suspended.at.105.C..mg.l.", "Solids")
rn("Calcium..mg.l.", "Calcium")
rn("Magnesium..mg.l.", "Magnesium")
rn("Potassium..mg.l.", "Potassium")
rn("Sodium..mg.l.", "Sodium")

# Also remane the comment because it actually contains the site name
rn("Comment", "Name")

# Remove the spaces from the grid references
samples$Grid.reference <- gsub(" ", "", samples$Grid.reference, fixed = TRUE)

# How many site names are there?
length(unique(samples$Name))

# How many grid references are there?
length(unique(samples$Grid.reference))

# How many pairs of comments and grid references?
sites <- data.frame(OSGrid = samples$Grid.reference, Name = samples$Name)
sites <- unique(sites)
nrow(sites)

# Give each of the sites a unique id (might come in handy)
sites$Id <- seq.int(nrow(sites))

# Export the sites list so WGS84 can be added to it
write.table(sites, "sites.csv", row.names = FALSE, col.names = TRUE, sep = ",")

## Go to http://gridreferencefinder.com/batchConvert/batchConvert.php to do the geocoding

# Import the geocoded sites
sites <- read.csv("./sites_with_locations.csv", header = TRUE, stringsAsFactors = FALSE)

# Cluster using k-means
km <- kmeans(cbind(sites$X, sites$Y), centers = 3)
# Plot without a background to look at the clusters
plot(sites$X, sites$Y, col = km$cluster, pch = 20)
plot(sites$Lng, sites$Lat, col = km$cluster, pch = 20)

# Get a map of the area and plot sites
library(ggmap)
map_centre <- c(lon = -2.85, lat = 52.80) # chosen by inspection
map <- qmap(map_centre) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)

# Zoom in in the Marton cluster of 10
map_centre <- c(lon = -3.045, lat = 52.623) # chosen by inspection
map <- qmap(map_centre, zoom = 15) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)


# Let's check out the distribution of measurments
# A function to standardised the graphs
graf <- function(column.name){
  scratch <- samples[,c(column.name)]
  scratch <- gsub("[^.0-9]+", "", scratch) # just the numbers and nothing else
  scratch <- as.numeric(scratch)
  title <- paste("Histogram of", column.name, sep = " ")
  hist(main = title, scratch, xlab = column.name, breaks = 20)
}
# Complete graph-arama
graf("BOD")
graf("Nitrogen.Total")             
graf("Phosphorus")           
graf("Alkalinity")          
graf("Nitrogen.Ammoniacal")
graf("Chloride")
graf("Nitrite") 
graf("Nitrogen.Oxidised") 
graf("Orthophosphate")       
graf("Silicate")
graf("Phosphate")             
graf("Conductivity")
graf("Turbidity")
graf("Solids")
graf("Calcium")              
graf("Magnesium")
graf("Potassium")
graf("Sodium")

"
The graphs for calcium, conductivity, silicate, alkalinity look like they might have been censored.
There appears to be a spike at one end of the distribution, like the data might have contained
a bunch of < or > but inspection reveals that silicate contains only one reading with < (<0.200).
"

# Let's find the bad boys
baduns <- function(column.name){
  # The column.name is passed as a string so the column has to be accessed using [] notation
  # rather than directly.
  scratch <- samples[,c("Name", column.name)]
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)]) # then convert to numeric
  scratch <- aggregate(scratch[,column.name], by = list(scratch$Name), max)
  scratch <- scratch[order(-scratch$x),] # Bad boys at the top
  names(scratch)[names(scratch) == "Group.1"] <- "Name"
  scratch <- head(scratch, n=8) # Calcium etc... have only been recorded for 8 sites.
  print(scratch)
  scratch <- scratch[order(scratch$x),] # reverse the order
  bp <- barplot(scratch$x, xlab=column.name, horiz=TRUE)
  text(0, bp, scratch$Name, cex=1, pos=4)
}

baduns("BOD")
baduns("Nitrogen.Total")             
baduns("Phosphorus")           
baduns("Alkalinity")          
baduns("Nitrogen.Ammoniacal")
baduns("Chloride")
baduns("Nitrite") 
baduns("Nitrogen.Oxidised") 
baduns("Orthophosphate")       
baduns("Silicate")
baduns("Phosphate")             
baduns("Conductivity")
baduns("Turbidity")
baduns("Solids")
baduns("Calcium")              
baduns("Magnesium")
baduns("Potassium")
baduns("Sodium")

# Sites with 9 or more samples.
scratch <- as.data.frame(table(samples$Name))
colnames(scratch) <- c("Name", "Freq")
sites <- merge(sites, scratch, by="Name")
scratch <- sites[sites$Freq >= 8,]
scratch <- merge(scratch, samples, by = "Name")

# The dates are ambiguous so stick in the century using a regex
scratch$Sample.taken <- gsub("(\\d{2}-[A-Z]{3}-)", "\\120", scratch$Sample.taken, perl = TRUE)
scratch$Sample.taken <- strptime(scratch$Sample.taken, "%d-%b-%Y %H:%M")
scratch$Sample.taken <- as.Date(scratch$Sample.taken)
scratch$Sample.taken <- as.POSIXct(scratch$Sample.taken, "%d-%b-%Y")

# The flows include some comments to the effect that there is no flow so these are made into zeros
scratch$Flow <- as.numeric(scratch$Flow)
scratch$Flow[is.na(scratch$Flow)] <- 0

library(ggplot2)
library(scales)

# Let's graph the ones with reasonable amounts of data
timegraph <- function(column.name){
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)])
  scratch$total <- scratch[,c(column.name)] * scratch$Flow
  ggplot(scratch, aes(x = Sample.taken, y = scratch$total, colour=Name, group=Name)) +
    geom_line() +
    scale_x_datetime(date_breaks = "1 month", date_labels = "%b") +
    xlab("2015-2016") + 
    ylab(paste0(column.name, " * Flow"))
}

timegraph("BOD")
timegraph("Nitrogen.Total")             
timegraph("Phosphorus")           
timegraph("Alkalinity")          
timegraph("Nitrogen.Ammoniacal")
timegraph("Chloride")
timegraph("Nitrite") 
timegraph("Nitrogen.Oxidised") 
timegraph("Orthophosphate")       
timegraph("Silicate")
timegraph("Phosphate")             
timegraph("Conductivity")
timegraph("Turbidity")
timegraph("Solids")
timegraph("Calcium")              
timegraph("Magnesium")
timegraph("Potassium")
timegraph("Sodium")


## Preliminary analysis of water inflow data

# Import the water inflow sample data
samples <- read.csv("./water_inflow_data.csv",  stringsAsFactors = FALSE)
# I did edit a couple of the dates because R seems to struggle with dates (but then don't we all)

# Rename all the measurements for easier reading
rn <- function(old.name, new.name){
  names(samples)[names(samples) == old.name] <<- new.name
}

rn("Flow.rate..litres.sec.", "Flow")

rn("BOD.5.Day.ATU..mg.l.", "BOD")
rn("Nitrogen...Total.as.N..mg.l.", "Nitrogen.Total")
rn("Phosphorus...Total.as.P..mg.l.", "Phosphorus")
rn("Alkalinity.to.pH.4.5.as.CaCO3..mg.l.", "Alkalinity")
rn("Ammoniacal.Nitrogen.as.N..mg.l.", "Nitrogen.Ammoniacal")
rn("Chloride..mg.l.", "Chloride")
rn("Nitrite.as.N..mg.l.", "Nitrite")
rn("Nitrogen...Total.Oxidised.as.N..mg.l.", "Nitrogen.Oxidised")
rn("Orthophosphate..reactive.as.P..mg.l.", "Orthophosphate")
rn("Silicate..reactive.as.SiO2..mg.l.", "Silicate")
rn("Phosphate...Total.as.P..mg.l.", "Phosphate")
rn("Conductivity.at.20C..uS.cm.", "Conductivity")
rn("Turbidity..NTU.", "Turbidity")
rn("Solids..Suspended.at.105.C..mg.l.", "Solids")
rn("Calcium..mg.l.", "Calcium")
rn("Magnesium..mg.l.", "Magnesium")
rn("Potassium..mg.l.", "Potassium")
rn("Sodium..mg.l.", "Sodium")

# Also remane the comment because it actually contains the site name
rn("Comment", "Name")

# Remove the spaces from the grid references
samples$Grid.reference <- gsub(" ", "", samples$Grid.reference, fixed = TRUE)

# How many site names are there?
length(unique(samples$Name))

# How many grid references are there?
length(unique(samples$Grid.reference))

# How many pairs of comments and grid references?
sites <- data.frame(OSGrid = samples$Grid.reference, Name = samples$Name)
sites <- unique(sites)
nrow(sites)

# Give each of the sites a unique id (might come in handy)
sites$Id <- seq.int(nrow(sites))

# Export the sites list so WGS84 can be added to it
write.table(sites, "sites.csv", row.names = FALSE, col.names = TRUE, sep = ",")

## Go to http://gridreferencefinder.com/batchConvert/batchConvert.php to do the geocoding

# Import the geocoded sites
sites <- read.csv("./sites_with_locations.csv", header = TRUE, stringsAsFactors = FALSE)

# Cluster using k-means
km <- kmeans(cbind(sites$X, sites$Y), centers = 3)
# Plot without a background to look at the clusters
plot(sites$X, sites$Y, col = km$cluster, pch = 20)
plot(sites$Lng, sites$Lat, col = km$cluster, pch = 20)

# Get a map of the area and plot sites
library(ggmap)
map_centre <- c(lon = -2.85, lat = 52.80) # chosen by inspection
map <- qmap(map_centre) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)

# Zoom in in the Marton cluster of 10
map_centre <- c(lon = -3.045, lat = 52.623) # chosen by inspection
map <- qmap(map_centre, zoom = 15) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)


# Let's check out the distribution of measurments
# A function to standardised the graphs
graf <- function(column.name){
  scratch <- samples[,c(column.name)]
  scratch <- gsub("[^.0-9]+", "", scratch) # just the numbers and nothing else
  scratch <- as.numeric(scratch)
  title <- paste("Histogram of", column.name, sep = " ")
  hist(main = title, scratch, xlab = column.name, breaks = 20)
}
# Complete graph-arama
graf("BOD")
graf("Nitrogen.Total")             
graf("Phosphorus")           
graf("Alkalinity")          
graf("Nitrogen.Ammoniacal")
graf("Chloride")
graf("Nitrite") 
graf("Nitrogen.Oxidised") 
graf("Orthophosphate")       
graf("Silicate")
graf("Phosphate")             
graf("Conductivity")
graf("Turbidity")
graf("Solids")
graf("Calcium")              
graf("Magnesium")
graf("Potassium")
graf("Sodium")

"
The graphs for calcium, conductivity, silicate, alkalinity look like they might have been censored.
There appears to be a spike at one end of the distribution, like the data might have contained
a bunch of < or > but inspection reveals that silicate contains only one reading with < (<0.200).
"

# Let's find the bad boys
baduns <- function(column.name){
  # The column.name is passed as a string so the column has to be accessed using [] notation
  # rather than directly.
  scratch <- samples[,c("Name", column.name)]
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)]) # then convert to numeric
  scratch <- aggregate(scratch[,column.name], by = list(scratch$Name), max)
  scratch <- scratch[order(-scratch$x),] # Bad boys at the top
  names(scratch)[names(scratch) == "Group.1"] <- "Name"
  scratch <- head(scratch, n=8) # Calcium etc... have only been recorded for 8 sites.
  print(scratch)
  scratch <- scratch[order(scratch$x),] # reverse the order
  bp <- barplot(scratch$x, xlab=column.name, horiz=TRUE)
  text(0, bp, scratch$Name, cex=1, pos=4)
}

baduns("BOD")
baduns("Nitrogen.Total")             
baduns("Phosphorus")           
baduns("Alkalinity")          
baduns("Nitrogen.Ammoniacal")
baduns("Chloride")
baduns("Nitrite") 
baduns("Nitrogen.Oxidised") 
baduns("Orthophosphate")       
baduns("Silicate")
baduns("Phosphate")             
baduns("Conductivity")
baduns("Turbidity")
baduns("Solids")
baduns("Calcium")              
baduns("Magnesium")
baduns("Potassium")
baduns("Sodium")

# Sites with 9 or more samples.
scratch <- as.data.frame(table(samples$Name))
colnames(scratch) <- c("Name", "Freq")
sites <- merge(sites, scratch, by="Name")
scratch <- sites[sites$Freq >= 8,]
scratch <- merge(scratch, samples, by = "Name")

# The dates are ambiguous so stick in the century using a regex
scratch$Sample.taken <- gsub("(\\d{2}-[A-Z]{3}-)", "\\120", scratch$Sample.taken, perl = TRUE)
scratch$Sample.taken <- strptime(scratch$Sample.taken, "%d-%b-%Y %H:%M")
scratch$Sample.taken <- as.Date(scratch$Sample.taken)
scratch$Sample.taken <- as.POSIXct(scratch$Sample.taken, "%d-%b-%Y")

# The flows include some comments to the effect that there is no flow so these are made into zeros
scratch$Flow <- as.numeric(scratch$Flow)
scratch$Flow[is.na(scratch$Flow)] <- 0

library(ggplot2)
library(scales)

# Let's graph the ones with reasonable amounts of data
timegraph <- function(column.name){
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)])
  scratch$total <- scratch[,c(column.name)] * scratch$Flow
  ggplot(scratch, aes(x = Sample.taken, y = scratch$total, colour=Name, group=Name)) +
    geom_line() +
    scale_x_datetime(date_breaks = "1 month", date_labels = "%b") +
    xlab("2015-2016") + 
    ylab(paste0(column.name, " * Flow"))
}

timegraph("BOD")
timegraph("Nitrogen.Total")             
timegraph("Phosphorus")           
timegraph("Alkalinity")          
timegraph("Nitrogen.Ammoniacal")
timegraph("Chloride")
timegraph("Nitrite") 
timegraph("Nitrogen.Oxidised") 
timegraph("Orthophosphate")       
timegraph("Silicate")
timegraph("Phosphate")             
timegraph("Conductivity")
timegraph("Turbidity")
timegraph("Solids")
timegraph("Calcium")              
timegraph("Magnesium")
timegraph("Potassium")
timegraph("Sodium")
## Preliminary analysis of water inflow data

# Import the water inflow sample data
samples <- read.csv("./water_inflow_data.csv",  stringsAsFactors = FALSE)
# I did edit a couple of the dates because R seems to struggle with dates (but then don't we all)

# Rename all the measurements for easier reading
rn <- function(old.name, new.name){
  names(samples)[names(samples) == old.name] <<- new.name
}

rn("Flow.rate..litres.sec.", "Flow")

rn("BOD.5.Day.ATU..mg.l.", "BOD")
rn("Nitrogen...Total.as.N..mg.l.", "Nitrogen.Total")
rn("Phosphorus...Total.as.P..mg.l.", "Phosphorus")
rn("Alkalinity.to.pH.4.5.as.CaCO3..mg.l.", "Alkalinity")
rn("Ammoniacal.Nitrogen.as.N..mg.l.", "Nitrogen.Ammoniacal")
rn("Chloride..mg.l.", "Chloride")
rn("Nitrite.as.N..mg.l.", "Nitrite")
rn("Nitrogen...Total.Oxidised.as.N..mg.l.", "Nitrogen.Oxidised")
rn("Orthophosphate..reactive.as.P..mg.l.", "Orthophosphate")
rn("Silicate..reactive.as.SiO2..mg.l.", "Silicate")
rn("Phosphate...Total.as.P..mg.l.", "Phosphate")
rn("Conductivity.at.20C..uS.cm.", "Conductivity")
rn("Turbidity..NTU.", "Turbidity")
rn("Solids..Suspended.at.105.C..mg.l.", "Solids")
rn("Calcium..mg.l.", "Calcium")
rn("Magnesium..mg.l.", "Magnesium")
rn("Potassium..mg.l.", "Potassium")
rn("Sodium..mg.l.", "Sodium")

# Also remane the comment because it actually contains the site name
rn("Comment", "Name")

# Remove the spaces from the grid references
samples$Grid.reference <- gsub(" ", "", samples$Grid.reference, fixed = TRUE)

# How many site names are there?
length(unique(samples$Name))

# How many grid references are there?
length(unique(samples$Grid.reference))

# How many pairs of comments and grid references?
sites <- data.frame(OSGrid = samples$Grid.reference, Name = samples$Name)
sites <- unique(sites)
nrow(sites)

# Give each of the sites a unique id (might come in handy)
sites$Id <- seq.int(nrow(sites))

# Export the sites list so WGS84 can be added to it
write.table(sites, "sites.csv", row.names = FALSE, col.names = TRUE, sep = ",")

## Go to http://gridreferencefinder.com/batchConvert/batchConvert.php to do the geocoding

# Import the geocoded sites
sites <- read.csv("./sites_with_locations.csv", header = TRUE, stringsAsFactors = FALSE)

# Cluster using k-means
km <- kmeans(cbind(sites$X, sites$Y), centers = 3)
# Plot without a background to look at the clusters
plot(sites$X, sites$Y, col = km$cluster, pch = 20)
plot(sites$Lng, sites$Lat, col = km$cluster, pch = 20)

# Get a map of the area and plot sites
library(ggmap)
map_centre <- c(lon = -2.85, lat = 52.80) # chosen by inspection
map <- qmap(map_centre) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)

# Zoom in in the Marton cluster of 10
map_centre <- c(lon = -3.045, lat = 52.623) # chosen by inspection
map <- qmap(map_centre, zoom = 15) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)


# Let's check out the distribution of measurments
# A function to standardised the graphs
graf <- function(column.name){
  scratch <- samples[,c(column.name)]
  scratch <- gsub("[^.0-9]+", "", scratch) # just the numbers and nothing else
  scratch <- as.numeric(scratch)
  title <- paste("Histogram of", column.name, sep = " ")
  hist(main = title, scratch, xlab = column.name, breaks = 20)
}
# Complete graph-arama
graf("BOD")
graf("Nitrogen.Total")             
graf("Phosphorus")           
graf("Alkalinity")          
graf("Nitrogen.Ammoniacal")
graf("Chloride")
graf("Nitrite") 
graf("Nitrogen.Oxidised") 
graf("Orthophosphate")       
graf("Silicate")
graf("Phosphate")             
graf("Conductivity")
graf("Turbidity")
graf("Solids")
graf("Calcium")              
graf("Magnesium")
graf("Potassium")
graf("Sodium")

"
The graphs for calcium, conductivity, silicate, alkalinity look like they might have been censored.
There appears to be a spike at one end of the distribution, like the data might have contained
a bunch of < or > but inspection reveals that silicate contains only one reading with < (<0.200).
"

# Let's find the bad boys
baduns <- function(column.name){
  # The column.name is passed as a string so the column has to be accessed using [] notation
  # rather than directly.
  scratch <- samples[,c("Name", column.name)]
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)]) # then convert to numeric
  scratch <- aggregate(scratch[,column.name], by = list(scratch$Name), max)
  scratch <- scratch[order(-scratch$x),] # Bad boys at the top
  names(scratch)[names(scratch) == "Group.1"] <- "Name"
  scratch <- head(scratch, n=8) # Calcium etc... have only been recorded for 8 sites.
  print(scratch)
  scratch <- scratch[order(scratch$x),] # reverse the order
  bp <- barplot(scratch$x, xlab=column.name, horiz=TRUE)
  text(0, bp, scratch$Name, cex=1, pos=4)
}

baduns("BOD")
baduns("Nitrogen.Total")             
baduns("Phosphorus")           
baduns("Alkalinity")          
baduns("Nitrogen.Ammoniacal")
baduns("Chloride")
baduns("Nitrite") 
baduns("Nitrogen.Oxidised") 
baduns("Orthophosphate")       
baduns("Silicate")
baduns("Phosphate")             
baduns("Conductivity")
baduns("Turbidity")
baduns("Solids")
baduns("Calcium")              
baduns("Magnesium")
baduns("Potassium")
baduns("Sodium")

# Sites with 9 or more samples.
scratch <- as.data.frame(table(samples$Name))
colnames(scratch) <- c("Name", "Freq")
sites <- merge(sites, scratch, by="Name")
scratch <- sites[sites$Freq >= 8,]
scratch <- merge(scratch, samples, by = "Name")

# The dates are ambiguous so stick in the century using a regex
scratch$Sample.taken <- gsub("(\\d{2}-[A-Z]{3}-)", "\\120", scratch$Sample.taken, perl = TRUE)
scratch$Sample.taken <- strptime(scratch$Sample.taken, "%d-%b-%Y %H:%M")
scratch$Sample.taken <- as.Date(scratch$Sample.taken)
scratch$Sample.taken <- as.POSIXct(scratch$Sample.taken, "%d-%b-%Y")

# The flows include some comments to the effect that there is no flow so these are made into zeros
scratch$Flow <- as.numeric(scratch$Flow)
scratch$Flow[is.na(scratch$Flow)] <- 0

library(ggplot2)
library(scales)

# Let's graph the ones with reasonable amounts of data
timegraph <- function(column.name){
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)])
  scratch$total <- scratch[,c(column.name)] * scratch$Flow
  ggplot(scratch, aes(x = Sample.taken, y = scratch$total, colour=Name, group=Name)) +
    geom_line() +
    scale_x_datetime(date_breaks = "1 month", date_labels = "%b") +
    xlab("2015-2016") + 
    ylab(paste0(column.name, " * Flow"))
}

timegraph("BOD")
timegraph("Nitrogen.Total")             
timegraph("Phosphorus")           
timegraph("Alkalinity")          
timegraph("Nitrogen.Ammoniacal")
timegraph("Chloride")
timegraph("Nitrite") 
timegraph("Nitrogen.Oxidised") 
timegraph("Orthophosphate")       
timegraph("Silicate")
timegraph("Phosphate")             
timegraph("Conductivity")
timegraph("Turbidity")
timegraph("Solids")
timegraph("Calcium")              
timegraph("Magnesium")
timegraph("Potassium")
timegraph("Sodium")
## Preliminary analysis of water inflow data

# Import the water inflow sample data
samples <- read.csv("./water_inflow_data.csv",  stringsAsFactors = FALSE)

# Rename all the measurements for easier reading
rn <- function(old.name, new.name){
  names(samples)[names(samples) == old.name] <<- new.name
}

rn("BOD.5.Day.ATU..mg.l.", "BOD")
rn("Nitrogen...Total.as.N..mg.l.", "Nitrogen.Total")
rn("Phosphorus...Total.as.P..mg.l.", "Phosphorus")
rn("Alkalinity.to.pH.4.5.as.CaCO3..mg.l.", "Alkalinity")
rn("Ammoniacal.Nitrogen.as.N..mg.l.", "Nitrogen.Ammoniacal")
rn("Chloride..mg.l.", "Chloride")
rn("Nitrite.as.N..mg.l.", "Nitrite")
rn("Nitrogen...Total.Oxidised.as.N..mg.l.", "Nitrogen.Oxidised")
rn("Orthophosphate..reactive.as.P..mg.l.", "Orthophosphate")
rn("Silicate..reactive.as.SiO2..mg.l.", "Silicate")
rn("Phosphate...Total.as.P..mg.l.", "Phosphate")
rn("Conductivity.at.20C..uS.cm.", "Conductivity")
rn("Turbidity..NTU.", "Turbidity")
rn("Solids..Suspended.at.105.C..mg.l.", "Solids")
rn("Calcium..mg.l.", "Calcium")
rn("Magnesium..mg.l.", "Magnesium")
rn("Potassium..mg.l.", "Potassium")
rn("Sodium..mg.l.", "Sodium")

# Also remane the comment because it actually contains the site name
rn("Comment", "Name")

# Remove the spaces from the grid references
samples$Grid.reference <- gsub(" ", "", samples$Grid.reference, fixed = TRUE)

# How many site names are there?
length(unique(samples$Name))

# How many grid references are there?
length(unique(samples$Grid.reference))

# How many pairs of comments and grid references?
sites <- data.frame(OSGrid = samples$Grid.reference, Name = samples$Name)
sites <- unique(sites)
nrow(sites)

# Give each of the sites a unique id (might come in handy)
sites$Id <- seq.int(nrow(sites))

# Export the sites list so WGS84 can be added to it
write.table(sites, "sites.csv", row.names = FALSE, col.names = TRUE, sep = ",")

## Go to http://gridreferencefinder.com/batchConvert/batchConvert.php to do the geocoding

# Import the geocoded sites
sites <- read.csv("./sites_with_locations.csv", header = TRUE, stringsAsFactors = FALSE)

# Cluster using k-means
km <- kmeans(cbind(sites$X, sites$Y), centers = 3)
# Plot without a background to look at the clusters
plot(sites$X, sites$Y, col = km$cluster, pch = 20)
plot(sites$Lng, sites$Lat, col = km$cluster, pch = 20)

# Get a map of the area and plot sites
library(ggmap)
map_centre <- c(lon = -2.85, lat = 52.80) # chosen by inspection
map <- qmap(map_centre) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)

# Zoom in in the Marton cluster of 10
map_centre <- c(lon = -3.045, lat = 52.623) # chosen by inspection
map <- qmap(map_centre, zoom = 15) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)


# Let's check out the distribution of measurments
# A function to standardised the graphs
graf <- function(column.name){
  scratch <- samples[,c(column.name)]
  scratch <- gsub("[^.0-9]+", "", scratch) # just the numbers and nothing else
  scratch <- as.numeric(scratch)
  title <- paste("Histogram of", column.name, sep = " ")
  hist(main = title, scratch, xlab = column.name, breaks = 20)
}
# Complete graph-arama
graf("BOD")
graf("Nitrogen.Total")             
graf("Phosphorus")           
graf("Alkalinity")          
graf("Nitrogen.Ammoniacal")
graf("Chloride")
graf("Nitrite") 
graf("Nitrogen.Oxidised") 
graf("Orthophosphate")       
graf("Silicate")
graf("Phosphate")             
graf("Conductivity")
graf("Turbidity")
graf("Solids")
graf("Calcium")              
graf("Magnesium")
graf("Potassium")
graf("Sodium")

"
The graphs for calcium, conductivity, silicate, alkalinity look like they might have been censored.
There appears to be a spike at one end of the distribution, like the data might have contained
a bunch of < or > but inspection reveals that silicate contains only one reading with < (<0.200).
"

# Let's find the bad boys
baduns <- function(column.name){
  # The column.name is passed as a string so the column has to be accessed using [] notation
  # rather than directly.
  scratch <- samples[,c("Name", column.name)]
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)]) # then convert to numeric
  scratch <- aggregate(scratch[,column.name], by = list(scratch$Name), max)
  scratch <- scratch[order(-scratch$x),] # Bad boys at the top
  names(scratch)[names(scratch) == "Group.1"] <- "Name"
  scratch <- head(scratch, n=8) # Calcium etc... have only been recorded for 8 sites.
  print(scratch)
  scratch <- scratch[order(scratch$x),] # reverse the order
  bp <- barplot(scratch$x, xlab=column.name, horiz=TRUE)
  text(0, bp, scratch$Name, cex=1, pos=4)
}

baduns("Nitrogen.Total")
baduns("BOD")
baduns("Nitrogen.Total")             
baduns("Phosphorus")           
baduns("Alkalinity")          
baduns("Nitrogen.Ammoniacal")
baduns("Chloride")
baduns("Nitrite") 
baduns("Nitrogen.Oxidised") 
baduns("Orthophosphate")       
baduns("Silicate")
baduns("Phosphate")             
baduns("Conductivity")
baduns("Turbidity")
baduns("Solids")
baduns("Calcium")              
baduns("Magnesium")
baduns("Potassium")
baduns("Sodium")

# Sites with 9 or more samples.
scratch <- as.data.frame(table(samples$Name))
colnames(scratch) <- c("Name", "Freq")
sites <- merge(sites, scratch, by="Name")
scratch <- sites[sites$Freq >= 9,]


#' Calibrate oli images to TM images
#'
#' Calibrate oli images to TM images using linear regression
#' @param oliwrs2dir character. oli WRS-2 scene directory path
#' @param tmwrs2dir character. TM WRS-2 scene directory path
#' @import raster
#' @import ggplot2
#' @import gridExtra
#' @export


olical_single = function(oli_file, tm_file, overwrite=F){
  
  get_intersection = function(files){
    int = intersect(extent(raster(files[1])),extent(raster(files[2])))
    if(length(files) >= 3){for(i in 3:length(files))int = intersect(extent(raster(files[i])), int)}
    return(int)
  }
  
  predict_oli_index = function(tbl, outsampfile){  
    
    #create a multivariable linear model
    model = rlm(refsamp ~ b2samp + b3samp + b4samp + b5samp + b6samp + b7samp, data=tbl) #
    
    tbl$singlepred = round(predict(model))
    write.csv(tbl, outsampfile, row.names=F)
    
    #plot the regression
    r = cor(tbl$refsamp, tbl$singlepred)
    coef = rlm(tbl$refsamp ~ tbl$singlepred)
    
    pngout = sub("samp.csv", "plot.png",outsampfile)
    png(pngout,width=700, height=700)
    title = paste(tbl$index[1],"linear regression: slope =",paste(signif(coef$coefficients[2], digits=3),",",sep=""),
                  "y Intercept =",paste(round(coef$coefficients[1], digits=3),",",sep=""),
                  "r =",signif(r, digits=3))
    plot(x=tbl$singlepred,y=tbl$refsamp,
         main=title,
         xlab=paste(tbl$oli_img[1],tbl$index[1]),
         ylab=paste(tbl$ref_img[1],tbl$index[1]))
    abline(coef = coef$coefficients, col="red")  
    dev.off()
    
    #return the information
    coef_tbl = data.frame(rbind(model$coefficients))
    cnames = c("yint","b2c","b3c","b4c","b5c","b6c","b7c")
    colnames(coef_tbl) = cnames
    tbls = list(coef_tbl,tbl)
    return(tbls)
  }

#   sample_it = function(img, bins, n){
#     
#     mi = min(img, na.rm=T)
#     ma = max(img, na.rm=T)
#     
#     step = (ma - mi)/bins
#     breaks = seq(mi,ma,step)
#     
#     min_samp = array(n, bins)
#     for(i in 1:(length(breaks)-1)){
#       these = which(img > breaks[i] & img <= breaks[i+1])
#       if(i == 1){samp = sample(these, size=min(min_samp[i],length(these)))} else {
#         samp = c(samp, sample(these, size=min(min_samp[i],length(these))))
#       } 
#     }
#     return(samp)
#   }
  
  #define the filenames
  oli_sr_file = oli_file
  oli_mask_file = sub("l8sr.tif", "cloudmask.tif", oli_sr_file)
  ref_tc_file = tm_file
  ref_tca_file = sub("tc", "tca", ref_tc_file)
  ref_mask_file = sub("tc", "cloudmask", ref_tc_file)
  
  #make new directory
  dname = dirname(oli_sr_file)
  oliimgid = substr(basename(oli_sr_file),1,16)
  outdir = file.path(substr(dname,1,nchar(dname)-12),"calibration", oliimgid)  #-5
  dir.create(outdir, showWarnings = F, recursive=T)
  
  #check to see if single cal has already been run
  files = list.files(outdir)
  thesefiles = c("tca_cal_plot.png","tcb_cal_plot.png","tcg_cal_plot.png","tcw_cal_plot.png",
                 "tca_cal_samp.csv","tcb_cal_samp.csv","tcg_cal_samp.csv","tcw_cal_samp.csv")
  results = rep(NA,length(thesefiles))
  for(i in 1:length(results)){
    test = grep(thesefiles[i], files)
    results[i] = length(test) > 0
  }
  if(all(results) == T & overwrite == F){return(0)}
  
  
  #load files as raster
  oli_sr_img = brick(oli_sr_file)
  oli_mask_img = raster(oli_mask_file)
  ref_tc_img = brick(ref_tc_file)
  ref_tca_img  = raster(ref_tca_file)
  ref_mask_img = raster(ref_mask_file)
  
  #align the extents
  extent(oli_sr_img)  = alignExtent(oli_sr_img, ref_tc_img, snap="near")
  extent(oli_mask_img) = alignExtent(oli_mask_img, ref_tc_img, snap="near")
  extent(ref_tc_img)   = alignExtent(ref_tc_img, ref_tc_img, snap="near")
  extent(ref_tca_img)  = alignExtent(ref_tca_img, ref_tc_img, snap="near")
  extent(ref_mask_img) = alignExtent(ref_mask_img, ref_tc_img, snap="near")
  
  #crop the images to their intersection
  int = get_intersection(c(oli_mask_file,ref_mask_file))
  oli_b5_img = crop(subset(oli_sr_img,5),int)
  ref_tca_img = crop(ref_tca_img,int)
  oli_mask_img = crop(oli_mask_img,int)
  ref_mask_img = crop(ref_mask_img,int)
  
  #make a composite mask

  oli_mask_v = as.vector(oli_mask_img)
  ref_mask_v = as.vector(ref_mask_img)

  mask = oli_mask_v*ref_mask_v #make composite mask
  oli_mask_v = ref_mask_v = 0 # save memory
  
  #load oli and etm+ bands
  oli_b5_v = as.vector(oli_b5_img)
  ref_tca_v = as.vector(ref_tca_img)
  
  dif = oli_b5_v - ref_tca_v #find the difference
  oli_b5_v = ref_tca_v = 0 #save memory
  nas = which(mask == 0) #find the bads in the mask
  dif[nas] = NA #set the bads in the dif to NA so they are not included in the calc of mean and stdev
  stdv = sd(dif, na.rm=T) #get stdev of difference
  center = mean(dif, na.rm=T) #get the mean difference
  dif = dif < (center+stdv*2) & dif > (center-stdv*2) #find the pixels that are not that different
    
  
  goods = which(dif == 1)
  if(length(goods) < 20000){return(0)}
  
  #stratified sample
  #refpix = as.matrix(ref_tca_img)[goods]
  #samp = sample_it(refpix, bins=20, n=1000)
  
  #random sample
  samp = sample(1:length(goods), 20000)
  samp = goods[samp]
  sampxy = xyFromCell(oli_mask_img, samp)
  
  #save memory
  mask = 0
  
  #extract the sample pixels from the bands
  olisamp = extract(subset(oli_sr_img, 2:7), sampxy)
  tcsamp = extract(ref_tc_img, sampxy)
  tcasamp = extract(ref_tca_img, sampxy)
  
  #make sure the values are good for running regression on (diversity)
  unib2samp = length(unique(olisamp[,1]))
  unib3samp = length(unique(olisamp[,2]))
  unib4samp = length(unique(olisamp[,3]))
  unib5samp = length(unique(olisamp[,4]))
  unib6samp = length(unique(olisamp[,5]))
  unib7samp = length(unique(olisamp[,6]))
  
  unitcbsamp = length(unique(tcsamp[,1]))
  unitcgsamp = length(unique(tcsamp[,2]))
  unitcwsamp = length(unique(tcsamp[,3]))
  unitcasamp = length(unique(tcasamp))
  
  
  if(unib2samp < 15 | unib3samp < 15 | unib4samp < 15 | unib5samp < 15 | unib6samp < 15 | 
     unib7samp < 15 | unitcbsamp < 15 | unitcgsamp < 15 | unitcwsamp < 15 | unitcasamp < 15){return()}
  
  olibname = basename(oli_sr_file)
  refbname = basename(ref_tc_file)
  refabname = basename(ref_tca_file)
  
  tcb_tbl = data.frame(olibname,refbname,"tcb",sampxy,tcsamp[,1],olisamp)
  tcg_tbl = data.frame(olibname,refbname,"tcg",sampxy,tcsamp[,2],olisamp)
  tcw_tbl = data.frame(olibname,refbname,"tcw",sampxy,tcsamp[,3],olisamp)
  tca_tbl = data.frame(olibname,refabname,"tca",sampxy,tcasamp,olisamp)
  
  
  tcb_tbl = tcb_tbl[complete.cases(tcb_tbl),]
  tcg_tbl = tcg_tbl[complete.cases(tcg_tbl),]
  tcw_tbl = tcw_tbl[complete.cases(tcw_tbl),]
  tca_tbl = tca_tbl[complete.cases(tca_tbl),]
  
  ##############take this out################
  #print(all.equal(nrow(tcb_tbl),nrow(tcg_tbl),nrow(tcw_tbl)))
  ###########################################
  
  cnames = c("oli_img","ref_img","index","x","y","refsamp","b2samp","b3samp","b4samp","b5samp","b6samp","b7samp") 
  colnames(tcb_tbl) = cnames
  colnames(tcg_tbl) = cnames
  colnames(tcw_tbl) = cnames
  colnames(tca_tbl) = cnames
  
  #predict the indices
  #TCB
  outsampfile = file.path(outdir,paste(oliimgid,"_tcb_cal_samp.csv",sep=""))
  model = predict_oli_index(tcb_tbl, outsampfile)
  bcoef = model[[1]]
  bsamp = model[[2]]
  br = cor(bsamp$refsamp, bsamp$singlepred)
  
  #TCG
  outsampfile = file.path(outdir,paste(oliimgid,"_tcg_cal_samp.csv",sep=""))
  model = predict_oli_index(tcg_tbl, outsampfile)
  gcoef = model[[1]]
  gsamp = model[[2]]
  gr = cor(gsamp$refsamp, gsamp$singlepred)
  
  #TCW
  outsampfile = file.path(outdir,paste(oliimgid,"_tcw_cal_samp.csv",sep=""))
  model = predict_oli_index(tcw_tbl, outsampfile)
  wcoef = model[[1]]
  wsamp = model[[2]]
  wr = cor(wsamp$refsamp, wsamp$singlepred)
  
  #TCA
  outsampfile = file.path(outdir,paste(oliimgid,"_tca_cal_samp.csv",sep=""))
  model = predict_oli_index(tca_tbl, outsampfile)
  acoef = model[[1]]
  asamp = model[[2]]
  ar = cor(asamp$refsamp, asamp$singlepred)
  
  #TCA
  #singlepred = atan(gsamp$singlepred/bsamp$singlepred) * (180/pi) * 100
  #refsamp = atan(gsamp$refsamp/bsamp$refsamp) * (180/pi) * 100
  #tbl = data.frame(oli_img = olibname,
  #                 ref_img = refbname,
  #                 index = "tca",
  #                 x = tcb_tbl$x,
  #                 y = tcb_tbl$y,
  #                 refsamp,singlepred)
  #final = tbl[complete.cases(tbl),]
  #outsampfile = file.path(outdir,paste(oliimgid,"_tca_cal_samp.csv",sep=""))
  #write.csv(final, outsampfile, row.names=F)
  
  #plot it
  #r = cor(final$refsamp, final$singlepred)
  #coef = rlm(final$refsamp ~ final$singlepred)

  #pngout = sub("samp.csv", "plot.png",outsampfile)
  #png(pngout,width=700, height=700)
  #title = paste("tca linear regression: slope =",paste(signif(coef$coefficients[2], digits=3),",",sep=""),
  #              "y Intercept =",paste(round(coef$coefficients[1], digits=3),",",sep=""),
  #              "r =",signif(r, digits=3))
  #plot(x=final$singlepred,y=final$refsamp,
  #     main=title,
  #     xlab=paste(olibname,"tca"),
  #     ylab=paste(refbname,"tca"))
  #abline(coef = coef$coefficients, col="red")  
  #dev.off()
  
  #info = data.frame(oli_file = olibname, ref_file = refbname,
  #                  index = "tca", yint = as.numeric(coef$coefficients[1]),
  #                  b1c = as.numeric(coef$coefficients[2]), r=r)
  
  #coefoutfile = file.path(outdir,paste(oliimgid,"_tca_cal_coef.csv",sep=""))
  #write.csv(info, coefoutfile, row.names=F)
  
  
  #write out the coef files
  tcbinfo = data.frame(oli_file=olibname, ref_file=refbname, index="tcb", bcoef, r=br)
  tcginfo = data.frame(oli_file=olibname, ref_file=refbname, index="tcg", gcoef, r=gr)
  tcwinfo = data.frame(oli_file=olibname, ref_file=refbname, index="tcw", wcoef, r=wr)
  tcainfo = data.frame(oli_file=olibname, ref_file=refabname, index="tca", acoef, r=ar)
  
  tcbcoefoutfile = file.path(outdir,paste(oliimgid,"_tcb_cal_coef.csv",sep=""))
  tcgcoefoutfile = file.path(outdir,paste(oliimgid,"_tcg_cal_coef.csv",sep=""))
  tcwcoefoutfile = file.path(outdir,paste(oliimgid,"_tcw_cal_coef.csv",sep=""))
  tcacoefoutfile = file.path(outdir,paste(oliimgid,"_tca_cal_coef.csv",sep=""))
  
  write.csv(tcbinfo, tcbcoefoutfile, row.names=F)
  write.csv(tcginfo, tcgcoefoutfile, row.names=F)
  write.csv(tcwinfo, tcwcoefoutfile, row.names=F)
  write.csv(tcainfo, tcacoefoutfile, row.names=F)
  
  
  #outfile = file.path(outdir,paste(oliimgid,"_tc_cal_planes.png",sep=""))
  #make_tc_planes_comparison(bsamp, gsamp, wsamp, outfile)
  
}
#' Calibrate MSS images to TM images
#'
#' Calibrate MSS images to TM images using linear regression
#' @param msswrs2dir character. MSS WRS-2 scene directory path
#' @param tmwrs2dir character. TM WRS-2 scene directory path
#' @import raster
#' @import ggplot2
#' @import gridExtra
#' @export


msscal_single = function(mss_file, tm_file){
  
  #mss_file = "K:/test/mss/wrs2/038029/images/1986/LM50380291986214_dos_sr_30m.tif"
  #tm_file = "K:/test/tm/wrs2/038029/images/1986/LT50380291986214_tc.tif"
  
  get_intersection = function(files){
    int = intersect(extent(raster(files[1])),extent(raster(files[2])))
    if(length(files) >= 3){for(i in 3:length(files))int = intersect(extent(raster(files[i])), int)}
    return(int)
  }
  
  predict_mss_index = function(tbl, outsampfile){  
    #create a multivariable linear model
    model = rlm(refsamp ~ b1samp + b2samp + b3samp + b4samp, data=tbl) #tbl replaced final 1/22/2016
    
    tbl$singlepred = round(predict(model))
    write.csv(tbl, outsampfile, row.names=F)
    
    #plot the regression
    r = cor(tbl$refsamp, tbl$singlepred)
    coef = rlm(tbl$refsamp ~ tbl$singlepred)
    
    pngout = sub("samp.csv", "plot.png",outsampfile)
    png(pngout,width=700, height=700)
    title = paste(tbl$index[1],"linear regression: slope =",paste(signif(coef$coefficients[2], digits=3),",",sep=""),
                  "y Intercept =",paste(round(coef$coefficients[1], digits=3),",",sep=""),
                  "r =",signif(r, digits=3))
    plot(x=tbl$singlepred,y=tbl$refsamp, #tbl replaced final 1/22/2016
         main=title,
         xlab=paste(tbl$mss_img[1],tbl$index[1]),
         ylab=paste(tbl$ref_img[1],tbl$index[1]))   
    abline(coef = coef$coefficients, col="red")  
    dev.off()
    
    coef_tbl = data.frame(rbind(model$coefficients))
    cnames = c("yint","b1c","b2c","b3c","b4c")
    colnames(coef_tbl) = cnames
    tbls = list(coef_tbl,tbl)
    return(tbls)
  }
  
  #write_coef = function(mss_file, ref_file, index, coef,r){
  #  info = data.frame(mss_file = basename(mss_file),
  #                    ref_file = basename(ref_file),
  #                    index = index,
  #                    yint = as.numeric(coef[1]),
  #                    b1c = as.numeric(coef[2]),
  #                    b2c = as.numeric(coef[3]),
  #                    b3c = as.numeric(coef[4]),
  #                    b4c = as.numeric(coef[5]),
  #                    r=r)
  #  
  #  coefoutfile = file.path(outdir,paste(mssimgid,"_",index,"_cal_coef.csv",sep=""))
  #  write.csv(info, coefoutfile, row.names=F)
  #}
  
  #sample_it = function(img, bins, n){
  #  
  #  mi = min(img, na.rm=T)
  #  ma = max(img, na.rm=T)
  #  
  #  step = (ma - mi)/bins
  #  breaks = seq(mi,ma,step)
  #  
  #  min_samp = array(n, bins)
  #  for(i in 1:(length(breaks)-1)){
  #    these = which(img > breaks[i] & img <= breaks[i+1])
  #    if(i == 1){samp = sample(these, size=min(min_samp[i],length(these)))} else {
  #      samp = c(samp, sample(these, size=min(min_samp[i],length(these))))
  #    } 
  #  }
  #  return(samp)
  #}
  

  #define the filenames
  mss_sr_file = mss_file
  mss_mask_file = sub("dos_sr_30m.tif", "cloudmask_30m.tif", mss_sr_file)
  ref_tc_file = tm_file
  ref_tca_file = sub("tc", "tca", ref_tc_file)
  ref_mask_file = sub("tc", "cloudmask", ref_tc_file)
  
  #make new directory
  dname = dirname(mss_sr_file)
  mssimgid = substr(basename(mss_sr_file),1,16)
  outdir = file.path(substr(dname,1,nchar(dname)-12),"calibration", mssimgid)  #-5
  dir.create(outdir, showWarnings = F, recursive=T)
  
  #load files as raster
  mss_sr_img = brick(mss_sr_file)
  mss_mask_img = raster(mss_mask_file)
  ref_tc_img = brick(ref_tc_file)
  ref_tca_img  = raster(ref_tca_file)
  ref_mask_img = raster(ref_mask_file)
  
  #align the extents
  extent(mss_sr_img)  = alignExtent(mss_sr_img, ref_tc_img, snap="near")
  extent(mss_mask_img) = alignExtent(mss_mask_img, ref_tc_img, snap="near")
  extent(ref_tc_img)   = alignExtent(ref_tc_img, ref_tc_img, snap="near")
  extent(ref_tca_img)  = alignExtent(ref_tca_img, ref_tc_img, snap="near")
  extent(ref_mask_img) = alignExtent(ref_mask_img, ref_tc_img, snap="near")
  
  #crop the images to their intersection
  int = get_intersection(c(mss_sr_file,mss_mask_file,ref_tc_file,ref_tca_file,ref_mask_file))
  mss_sr_img = crop(mss_sr_img,int)
  mss_mask_img = crop(mss_mask_img,int)
  ref_tc_img = crop(ref_tc_img,int)
  ref_tca_img = crop(ref_tca_img,int)
  ref_mask_img = crop(ref_mask_img,int)
  
  #make a composite mask
  #mss_mask_img = as.matrix(mss_mask_img)
  #ref_mask_img = as.matrix(ref_mask_img)
  mss_mask_v = as.vector(mss_mask_img)
  ref_mask_v = as.vector(ref_mask_img)
  #mask = mss_mask_img*ref_mask_img
  mask = mss_mask_v*ref_mask_v
  mss_mask_v = ref_mask_v = 0 # save memory
  
  goods = which(mask == 1)
  if(length(goods) < 20000){return()}
  
  #stratified sample
  #refpix = as.matrix(ref_tca_img)[goods]
  #samp = sample_it(refpix, bins=20, n=1000)
  
  #random sample
  samp = sample(1:length(goods), 20000)
  samp = goods[samp]
  sampxy = xyFromCell(mss_mask_img, samp) #added on 1/22/2016
  
  #save memory
  mask = 0
  
  #extract the sample pixels from the bands
  #b1samp = as.matrix(subset(mss_sr_img, 1))[samp]
  #b2samp = as.matrix(subset(mss_sr_img, 2))[samp]
  #b3samp = as.matrix(subset(mss_sr_img, 3))[samp]
  #b4samp = as.matrix(subset(mss_sr_img, 4))[samp]
  
  
  msssamp = extract(mss_sr_img, sampxy)
  tcsamp = extract(ref_tc_img, sampxy)
  tcasamp = extract(ref_tca_img, sampxy)
  
  #make sure the values are good for running regression on (diversity)
  unib1samp = length(unique(msssamp[,1]))
  unib2samp = length(unique(msssamp[,2]))
  unib3samp = length(unique(msssamp[,3]))
  unib4samp = length(unique(msssamp[,4]))
  
  unitcbsamp = length(unique(tcsamp[,1]))
  unitcgsamp = length(unique(tcsamp[,2]))
  unitcwsamp = length(unique(tcsamp[,3]))
  unitcasamp = length(unique(tcasamp))
  
  
  #if(unib1samp < 15 | unib2samp < 15 | unib3samp < 15 | unib4samp < 15 ){return()}
  if(unib1samp < 15 | unib2samp < 15 | unib3samp < 15 | unib4samp < 15 |
     unitcbsamp < 15 | unitcgsamp < 15 | unitcwsamp < 15 | unitcasamp < 15){return()}
  
  #samplen = length(samp)
  
  mssbname = basename(mss_sr_file)
  refbname = basename(ref_tc_file)
  refabname = basename(ref_tca_file)
  
  tcb_tbl = data.frame(mssbname,refbname,"tcb",sampxy,tcsamp[,1],msssamp)
  tcg_tbl = data.frame(mssbname,refbname,"tcg",sampxy,tcsamp[,2],msssamp)
  tcw_tbl = data.frame(mssbname,refbname,"tcw",sampxy,tcsamp[,3],msssamp)
  tca_tbl = data.frame(mssbname,refabname,"tca",sampxy,tcasamp,msssamp)
  
  
  tcb_tbl = tcb_tbl[complete.cases(tcb_tbl),]
  tcg_tbl = tcg_tbl[complete.cases(tcg_tbl),]
  tcw_tbl = tcw_tbl[complete.cases(tcw_tbl),]
  tca_tbl = tca_tbl[complete.cases(tca_tbl),]
  
  cnames = c("mss_img","ref_img","index","x","y","refsamp","b1samp","b2samp","b3samp","b4samp") 
  colnames(tcb_tbl) = cnames
  colnames(tcg_tbl) = cnames
  colnames(tcw_tbl) = cnames
  colnames(tca_tbl) = cnames
  
  #predict the indices
  #TCB
  #refsamp = as.matrix(subset(ref_tc_img, 1))[samp]
  #unirefsamp = length(unique(refsamp))
  #if(unirefsamp < 15){return()}
  #sampoutfile = file.path(outdir,paste(mssimgid,"_tcb_cal_samp.csv",sep=""))
  #model = predict_mss_index(refsamp, b1samp, b2samp, b3samp, b4samp, mss_sr_file, ref_tc_file, "tcb", sampoutfile, samplen)
  #bcoef = model[[1]]
  #bsamp = model[[2]]
  #br = cor(bsamp$refsamp, bsamp$singlepred)
  
  outsampfile = file.path(outdir,paste(mssimgid,"_tcb_cal_samp.csv",sep=""))
  model = predict_mss_index(tcb_tbl, outsampfile)
  bcoef = model[[1]]
  bsamp = model[[2]]
  br = cor(bsamp$refsamp, bsamp$singlepred)
  
  
  #TCG
  #refsamp = as.matrix(subset(ref_tc_img, 2))[samp]
  #unirefsamp = length(unique(refsamp))
  #if(unirefsamp < 15){return()}
  #sampoutfile = file.path(outdir,paste(mssimgid,"_tcg_cal_samp.csv",sep=""))
  #model = predict_mss_index(refsamp, b1samp, b2samp, b3samp, b4samp, mss_sr_file, ref_tc_file, "tcg", sampoutfile, samplen)
  #gcoef = model[[1]]
  #gsamp = model[[2]]
  #gr = cor(gsamp$refsamp, gsamp$singlepred)
  
  outsampfile = file.path(outdir,paste(mssimgid,"_tcg_cal_samp.csv",sep=""))
  model = predict_mss_index(tcg_tbl, outsampfile)
  gcoef = model[[1]]
  gsamp = model[[2]]
  gr = cor(gsamp$refsamp, gsamp$singlepred)
  
  #TCW
  #refsamp = as.matrix(subset(ref_tc_img, 3))[samp]
  #unirefsamp = length(unique(refsamp))
  #if(unirefsamp < 15){return()}
  #sampoutfile = file.path(outdir,paste(mssimgid,"_tcw_cal_samp.csv",sep=""))
  #model = predict_mss_index(refsamp, b1samp, b2samp, b3samp, b4samp, mss_sr_file, ref_tc_file, "tcw", sampoutfile, samplen)
  #wcoef = model[[1]]
  #wsamp = model[[2]]
  #wr = cor(wsamp$refsamp, wsamp$singlepred)
  
  outsampfile = file.path(outdir,paste(mssimgid,"_tcw_cal_samp.csv",sep=""))
  model = predict_mss_index(tcw_tbl, outsampfile)
  wcoef = model[[1]]
  wsamp = model[[2]]
  wr = cor(wsamp$refsamp, wsamp$singlepred)
  
  
  #TCA
  outsampfile = file.path(outdir,paste(mssimgid,"_tca_cal_samp.csv",sep=""))
  model = predict_mss_index(tca_tbl, outsampfile)
  acoef = model[[1]]
  asamp = model[[2]]
  ar = cor(asamp$refsamp, asamp$singlepred)
  
  
  #singlepred = atan(gsamp$singlepred/bsamp$singlepred) * (180/pi) * 100
  #refsamp = atan(gsamp$refsamp/bsamp$refsamp) * (180/pi) * 100
  #tbl = data.frame(mss_img = rep(basename(mss_sr_file),length(singlepred)),
  #                 ref_img = rep(basename(ref_tc_file),length(singlepred)),
  #                 index = rep("tca",length(singlepred)),
  #                 refsamp,singlepred)
  #final = tbl[complete.cases(tbl),]
  #sampoutfile = file.path(outdir,paste(mssimgid,"_tca_cal_samp.csv",sep=""))
  #write.csv(final, sampoutfile, row.names=F)
  
  
  #r = cor(final$refsamp, final$singlepred)
  #coef = rlm(final$refsamp ~ final$singlepred)
  
  #pngout = sub("samp.csv", "plot.png",sampoutfile)
  #png(pngout,width=700, height=700)
  #title = paste("tca linear regression: slope =",paste(signif(coef$coefficients[2], digits=3),",",sep=""),
  #                                 "y Intercept =",paste(round(coef$coefficients[1], digits=3),",",sep=""),
  #                                 "r =",signif(r, digits=3))
  #plot(x=final$singlepred,y=final$refsamp,
  #     main=title,
  #     xlab=paste(basename(mss_sr_file),"tca"),
  #     ylab=paste(basename(ref_tc_file),"tca"))
  #abline(coef = coef$coefficients, col="red")  
  #dev.off()
  
  #info = data.frame(mss_file = basename(mss_sr_file), ref_file = basename(ref_tc_file),
  #                  index = "tca", yint = as.numeric(coef$coefficients[1]),
  #                  b1c = as.numeric(coef$coefficients[2]), r=r)
  
  #coefoutfile = file.path(outdir,paste(mssimgid,"_tca_cal_coef.csv",sep=""))
  #write.csv(info, coefoutfile, row.names=F)
  
  #write out the coef files
  #write_coef(mss_sr_file, ref_tc_file, "tcb", bcoef, br)
  #write_coef(mss_sr_file, ref_tc_file, "tcg", gcoef, gr)
  #write_coef(mss_sr_file, ref_tc_file, "tcw", wcoef, wr)

  
  tcbinfo = data.frame(mss_file=mssbname, ref_file=refbname, index="tcb", bcoef, r=br)
  tcginfo = data.frame(mss_file=mssbname, ref_file=refbname, index="tcg", gcoef, r=gr)
  tcwinfo = data.frame(mss_file=mssbname, ref_file=refbname, index="tcw", wcoef, r=wr)
  tcainfo = data.frame(mss_file=mssbname, ref_file=refabname, index="tca", acoef, r=ar)
  
  tcbcoefoutfile = file.path(outdir,paste(mssimgid,"_tcb_cal_coef.csv",sep=""))
  tcgcoefoutfile = file.path(outdir,paste(mssimgid,"_tcg_cal_coef.csv",sep=""))
  tcwcoefoutfile = file.path(outdir,paste(mssimgid,"_tcw_cal_coef.csv",sep=""))
  tcacoefoutfile = file.path(outdir,paste(mssimgid,"_tca_cal_coef.csv",sep=""))
  
  write.csv(tcbinfo, tcbcoefoutfile, row.names=F)
  write.csv(tcginfo, tcgcoefoutfile, row.names=F)
  write.csv(tcwinfo, tcwcoefoutfile, row.names=F)
  write.csv(tcainfo, tcacoefoutfile, row.names=F)
  
  
  #outfile = file.path(outdir,paste(mssimgid,"_tc_cal_planes.png",sep=""))
  #make_tc_planes_comparison(bsamp, gsamp, wsamp, outfile)
  
}
######################################################################
######################################################################
## ROUTINE ZUM EINLESEN VON ERA-DATEN (ZONAL-WIND) IM NCDF-FORMAT
## UND AUFFINDEN DES JETSTREAMS AUF NORDHEMISPHÄRE
## source('~/Master_Thesis/r-code-git/locate_jetstream_polynomial_2d.r')
######################################################################
######################################################################


######################################################################
## AUFRUF WICHTIGER BIBLIOTHEKEN UND PAKETE
######################################################################
##

library(ncdf4)
library(parallel)
library(chron)

# eigenes package für least squares fit mit chebyshev polynomen
# install.packages("pckg.cheb_0.2.tar.gz", repos = NULL, type = "source")
library(pckg.cheb)

setwd("~/Master_Thesis/r-code-git/")
path <- "data/"
# path <- "/home/skiefer/era/raw/"
file <- "era-t63-1957-2016.nh-trop-inv.nc"  # Nordhemisphäre + Tropen


######################################################################
## KLEINE HILFSFUNKTIONEN
######################################################################
##

fun.fill <- function(x, n) {
  while (length(x) < n) {
    x <- c(x, NA)
  }
  return(x)
}


######################################################################
## EINLESEN DER DATEN
## ERA40 / ERA-INTERIM
## T63 - GRID - GAUSSIAN
## NORDHEMISPHÄRE & TROPEN
## 192 (lat) * 64 (lon)
######################################################################
##

nc <- nc_open(paste(path, file, sep = ""))
# print(nc)
u.monmean <- ncvar_get(nc, "var131") # U-Wind-Komponente
# v.monmean <- ncvar_get(nc, "var132") # V-Wind-Komponente
# w.monmean <- ncvar_get(nc, "var135") # W-Wind-Komponente
# z.monmean <- ncvar_get(nc, "var129") # Geopotenzial
# t.monmean <- ncvar_get(nc, "var130") # Temperatur
# d.monmean <- ncvar_get(nc, "var155") # Divergenz

lon <- ncvar_get(nc, "lon") # Längengrad
lat <- ncvar_get(nc, "lat") # Breitengrad
lev <- ncvar_get(nc, "lev") # Drucklevel
date.help <- ncvar_get(nc, "time")

nc_close(nc)
rm(nc)


######################################################################
## VARIABLEN UND PARAMETER
######################################################################
##

n.cpu <- 5 #5 # Anzahl der CPUs für parApply
n.order.lat <- 23 # Ordnung des Least-Square-Verfahrens für Fit über Breitengrad
n.order.lon <- 8 # Ordnung des Least-Square-Verfahrens für Fit über Längengrad
n.order.lat.seq <- 3 # Ordnung des Least-Square-Verfahrens für sequentiellen Fit über Breitengrad
len.seq <- 8 # Länge der ersten Sequenz der 

## Räumliche Auflösung
n.lat <- length(lat)
n.lon <- length(lon)

## Zeitliche Auflösung
dts = chron(dates. = date.help/24, origin. = c(month = 9,day = 1,year = 1957), format = "day mon year")
dts.month <- months(dts, abbreviate = TRUE)
dts.year <- years(dts)

## Zeitlich gemittelter Zonalwind
u.mean <- apply(u.monmean,c(1,2),mean)
u.std <- apply(u.monmean,c(1,2),sd)

## Meridional und zeitlich gemittelter Zonalwind
u.mon.mer.mean <- apply(u.monmean, 2, mean)
u.mon.mer.sd <- apply(u.mean, 2, sd)

## Meridional gemittelter Zonalwind
# u.monmean.mermean <- apply(u.monmean, c(2,3), mean)
# u.monmean.mersd <- apply(u.monmean, c(2,3), sd)


######################################################################
## LEAST SQUARES FIT 
## CHEBYSHEV POLYNOME 23-TER ORDNUNG
## AN ZONAL WIND IN MERIDIONALER RICHTUNG
######################################################################
##

# list.model.lat <- apply(u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
list.model.lat <- parApply(cl, u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
stopCluster(cl)
dim.list <- dim(list.model.lat)

## Chebyshev-Koeffizienten
cheb.coeff <- sapply(list.model.lat, "[[", 1)
cheb.coeff <- apply(array(data = cheb.coeff, dim = c((n.order.lat + 1), dim.list[1], dim.list[2])) , c(1,3), t)

## Gefiltertes Modell für Zonal-Wind
model.u <- sapply(list.model.lat, "[[", 2)
model.u <- apply(array(data = model.u, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)

## Erste Ableitung des gefilterten Modells für Zonalwind
model.u.deriv.1st <- sapply(list.model.lat, "[[", 3)
model.u.deriv.1st <- apply(array(data = model.u.deriv.1st, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)

## Extrema des Modells (Positionen und Werte)
model.extr.lat <- sapply(list.model.lat, "[[", 4)
model.extr.u <- sapply(list.model.lat, "[[", 5)
model.extr.lat <- sapply(model.extr.lat, fun.fill, n = 24)
model.extr.lat <- apply(array(model.extr.lat, c(24, dim.list[1], dim.list[2])), c(1,3), t)
model.extr.u <- sapply(model.extr.u, fun.fill, n = 24)
model.extr.u <- apply(array(model.extr.u, c(24, dim.list[1], dim.list[2])), c(1,3), t)

## Maxima des Modells (Positionen und Werte)
model.max.u <- apply(model.extr.u, c(1,3), max, na.rm = TRUE)
model.max.lat <- array(rep(0, 192*664), c(dim.list))
for (i in 1:dim.list[2]) {
  for (j in 1:dim.list[1]) {
    model.max.lat[j,i] <- model.extr.lat[j, which(model.extr.u[j,,i] == model.max.u[j,i]), i]
  }
}
rm(list.model.lat, dim.list)
rm(dim.list)


######################################################################
## LEAST SQUARES FIT 
## CHEBYSHEV POLYNOME 8-TER ORDNUNG
## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
######################################################################
##

#list.model.lon <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
cl <- makeCluster(getOption("cl.cores", n.cpu))
list.model.lon <- parApply(cl, model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
stopCluster(cl)

## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
model.max.lon <- sapply(list.model.lon, "[[", 2)
rm(list.model.lon)




######################################################################
## FEHLERGRÖẞEN
## MSE
## RMSE
######################################################################
##

residuals.cheb <- u.monmean - model.u
residuals.cheb.seq <- u.monmean - model.u.seq
mse <- sum(residuals.cheb ** 2) / length(residuals.cheb)
mse.seq <- sum(residuals.cheb.seq **2) / length(residuals.cheb.seq)
rmse <- sqrt(sum(residuals.cheb ** 2) / length(residuals.cheb))
rmse.seq <- sqrt(sum(residuals.cheb.seq **2) / length(residuals.cheb.seq))

## rmse.seq = 0.4079846  ## mse.seq = 0.1664514
## rmse     = 0.2911683  ## mse     = 0.08477901


######################################################################
######################################################################
save.image()


######################################################################
## Berechnung von Mean und Sd
## über fünf Jahre & saisonal
######################################################################
dts.year.mn <- seq(1960, 2010, 5)

ind.mam <- which(dts.month == "Mar" | dts.month == "Apr" | dts.month == "May")
ind.jja <- which(dts.month == "Jun" | dts.month == "Jul" | dts.month == "Aug")
ind.son <- which(dts.month == "Sep" | dts.month == "Oct" | dts.month == "Nov")
ind.djf <- which(dts.month == "Dec" | dts.month == "Jan" | dts.month == "Feb")

## Mittelwerte global
u.seas.mam.mean <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.mam.sd <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.jja.mean <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.jja.sd <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.son.mean <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.son.sd <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.djf.mean <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.djf.sd <- array( NA , dim = c(n.lon, n.lat, 11))

## Mittelwerte meridional *???*
u.mer.seas.mam.mean <- array( NA , dim = c(n.lat, 11))
u.mer.seas.mam.sd <- array( NA , dim = c(n.lat, 11))
u.mer.seas.jja.mean <- array( NA , dim = c(n.lat, 11))
u.mer.seas.jja.sd <- array( NA , dim = c(n.lat, 11))
u.mer.seas.son.mean <- array( NA , dim = c(n.lat, 11))
u.mer.seas.son.sd <- array( NA , dim = c(n.lat, 11))
u.mer.seas.djf.mean <- array( NA , dim = c(n.lat, 11))
u.mer.seas.djf.sd <- array( NA , dim = c(n.lat, 11))

for (i in seq(1, 11)) {
  print(i)
  yr.i <- dts.year.mn[i]
  ind.yr <- which(dts.year ==  yr.i | dts.year == (yr.i + 1) | dts.year == (yr.i + 2) | dts.year == (yr.i + 3) | dts.year == (yr.i + 4) )
  ## Mar Apr May
  ind.mam.yr <- intersect(ind.yr, ind.mam)
  u.seas.mam.mean[,,i] <- apply(u.monmean[,, ind.mam.yr], c(1,2), mean)
  u.seas.mam.sd[,,i] <- apply(u.monmean[,, ind.mam.yr], c(1,2), sd)
  u.mer.seas.mam.mean[,i] <- apply(u.monmean[,, ind.mam.yr], 2, mean)
  u.mer.seas.mam.sd[,i] <- apply(u.monmean[,, ind.mam.yr], 2, sd)
  ## Jun Jul Aug
  ind.jja.yr <- intersect(ind.yr, ind.jja)
  u.seas.jja.mean[,,i] <- apply(u.monmean[,, ind.jja.yr], c(1,2), mean)
  u.seas.jja.sd[,,i] <- apply(u.monmean[,, ind.jja.yr], c(1,2), sd)
  u.mer.seas.jja.mean[,i] <- apply(u.monmean[,, ind.jja.yr], 2, mean)
  u.mer.seas.jja.sd[,i] <- apply(u.monmean[,, ind.jja.yr], 2, sd)
  ## Sep Oct Nov
  ind.son.yr <- intersect(ind.yr, ind.son)
  u.seas.son.mean[,,i] <- apply(u.monmean[,, ind.son.yr], c(1,2), mean)
  u.seas.son.sd[,,i] <- apply(u.monmean[,, ind.son.yr], c(1,2), sd)
  u.mer.seas.son.mean[,i] <- apply(u.monmean[,, ind.son.yr], 2, mean)
  u.mer.seas.son.sd[,i] <- apply(u.monmean[,, ind.son.yr], 2, sd)
  ## Dec Jan Feb
  ind.djf.yr <- intersect(ind.yr, ind.djf)
  u.seas.djf.mean[,,i] <- apply(u.monmean[,, ind.djf.yr], c(1,2), mean)
  u.seas.djf.sd[,,i] <- apply(u.monmean[,, ind.djf.yr], c(1,2), sd)
  u.mer.seas.djf.mean[,i] <- apply(u.monmean[,, ind.djf.yr], 2, mean)
  u.mer.seas.djf.sd[,i] <- apply(u.monmean[,, ind.djf.yr], 2, sd)
  ## Löschen von Übergangsvariablen
  rm(yr.i, ind.yr, ind.mam.yr, ind.jja.yr, ind.son.yr, ind.djf.yr, i)
}

max(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
min(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
range(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)

max(u.seas.mam.mean)
min(u.seas.mam.mean)
range(u.seas.mam.mean)

max(u.seas.jja.mean)
min(u.seas.jja.mean)
range(u.seas.jja.mean)

max(u.seas.son.mean)
min(u.seas.son.mean)
range(u.seas.son.mean)

max(u.seas.djf.mean)
min(u.seas.djf.mean)
range(u.seas.djf.mean)


image.plot(lon, lat, u.seas.mam.mean[,,1])
contour(lon, lat, u.seas.mam.sd[,,1], add=TRUE)


####################################################################################################
########## ableitung des drehimpulses ##############################################################
########## aus zonal wind ##########################################################################
####################################################################################################
### ref: m = 
### formel noch inkorrekt
### keine schleife benutzen
##
# m <- matrix(NA,n.lon,n.lat)
# for (i in 1:n.lon){
#   for (j in 1:n.lat){
#     m[i,j] <- u.era.t63.monmean[i,j,1]*cos(lat.era.t63[j]) + 1/86400*u.era.t63.monmean[i,j,1]**2*cos(lat.era.t63[j])**2
#   }
# }
# #m <- u.era.t63.monmean*cos(lat.era.t63)
# 




# ######################################################################
# ## LEAST SQUARES FIT ÜBER **SEQUENZEN** (l=8)
# ## CHEBYSHEV POLYNOME 3-TER ORDNUNG
# ## AN ZONAL-WIND IN MERIDIONALER RICHTUNG
# ######################################################################
# ##
# 
# # list.model.lat.seq <- apply(u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
# list.model.lat.seq <- parApply(cl, u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# stopCluster(cl)
# dim.list <- dim(list.model.lat.seq)
# 
# ## Gefiltertes Modell für Zonal-Wind
# model.u.seq <- sapply(list.model.lat.seq, "[[", 1)
# model.u.seq <- apply(array(data = model.u.seq, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Erste Ableitung des gefilterten Modells für Zonalwind
# model.u.deriv.1st.seq <- sapply(list.model.lat.seq, "[[", 2)
# model.u.deriv.1st.seq <- apply(array(data = model.u.deriv.1st.seq, dim = c(n.lon, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Extrema des Modells (Positionen und Werte)
# model.extr.lat.seq <- sapply(list.model.lat.seq, "[[", 3)
# model.extr.lat.seq <- sapply(model.extr.lat.seq, fun.fill, n = 24)
# model.extr.lat.seq <- apply(array(model.extr.lat.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# model.extr.u.seq <- sapply(list.model.lat.seq, "[[", 4)
# model.extr.u.seq <- sapply(model.extr.u.seq, fun.fill, n = 24)
# model.extr.u.seq <- apply(array(model.extr.u.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# 
# ## Maxima des Modells (Positionen und Werte)
# model.max.u.seq <- apply(model.extr.u.seq, c(1,3), max, na.rm = TRUE)
# model.max.lat.seq <- array(rep(0, dim.list[1]*dim.list[2]), c(dim.list))
# for (i in 1:dim.list[2]) {
#   for (j in 1:dim.list[1]) {
#     model.max.lat.seq[j,i] <- model.extr.lat.seq[j, which(model.extr.u.seq[j,,i] == model.max.u.seq[j,i]), i]
#   }
# }
# rm(list.model.lat.seq, dim.list)
# 
# 
# ######################################################################
# ## LEAST SQUARES FIT 
# ## CHEBYSHEV POLYNOME 8-TER ORDNUNG
# ## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
# ## ANGEWANDT AUF SEQUENZIERTES MODELL
# ######################################################################
# ##
# 
# #list.model.lon.seq <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = 8)
# cl <- makeCluster(getOption("cl.cores", n.cpu))
# list.model.lon.seq <- parApply(cl, model.max.lat.seq, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
# stopCluster(cl)
# 
# ## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
# model.max.lon.seq <- sapply(list.model.lon.seq, "[[", 2)
# rm(list.model.lon.seq)

## Preliminary analysis of water inflow data

# Import the water inflow sample data
samples <- read.csv("./water_inflow_data.csv",  stringsAsFactors=FALSE)

# Rename all the measurements for easier reading
rn <- function(old.name, new.name){
  names(samples)[names(samples) == old.name] <<- new.name
}

rn("BOD.5.Day.ATU..mg.l.", "BOD")
rn("Nitrogen...Total.as.N..mg.l.", "Nitrogen")
rn("Phosphorus...Total.as.P..mg.l.", "Phosphorus")
rn("Alkalinity.to.pH.4.5.as.CaCO3..mg.l.", "Alkalinity")
rn("Ammoniacal.Nitrogen.as.N..mg.l.", "Nitrogen.Ammoniacal")
rn("Chloride..mg.l.", "Chloride")
rn("Nitrite.as.N..mg.l.", "Nitrite")
rn("Nitrogen...Total.Oxidised.as.N..mg.l.", "Nitrogen.Oxidised")
rn("Orthophosphate..reactive.as.P..mg.l.", "Orthophosphate")
rn("Silicate..reactive.as.SiO2..mg.l.", "Silicate")
rn("Phosphate...Total.as.P..mg.l.", "Phosphate")
rn("Conductivity.at.20C..uS.cm.", "Conductivity")
rn("Turbidity..NTU.", "Turbidity")
rn("Solids..Suspended.at.105.C..mg.l.", "Solids")
rn("Calcium..mg.l.", "Calcium")
rn("Magnesium..mg.l.", "Magnesium")
rn("Potassium..mg.l.", "Potassium")
rn("Sodium..mg.l.", "Sodium")

# Remove the spaces from the grid references
samples$Grid.reference <- gsub(" ", "", samples$Grid.reference, fixed = TRUE)

# How many site names are there?
length(unique(samples$Comment))

# How many grid references are there?
length(unique(samples$Grid.reference))

# How many pairs of comments and grid references?
sites <- data.frame(OSGrid = samples$Grid.reference, Name = samples$Comment)
sites <- unique(sites)
nrow(sites)

# Give each of the sites a unique id (might come in handy)
sites$Id <- seq.int(nrow(sites))

# Export the sites list so WGS84 can be added to it
write.table(sites, "sites.csv", row.names = FALSE, col.names = TRUE, sep = ",")

## Go to http://gridreferencefinder.com/batchConvert/batchConvert.php to do the geocoding

# Import the geocoded sites
sites <- read.csv("./sites_with_locations.csv", header = TRUE, stringsAsFactors = FALSE)

# Cluster using k-means
km <- kmeans(cbind(sites$X, sites$Y), centers = 3)
# Plot without a background to look at the clusters
plot(sites$X, sites$Y, col = km$cluster, pch = 20)
plot(sites$Lng, sites$Lat, col = km$cluster, pch = 20)

# Get a map of the area and plot sites
library(ggmap)
map_centre <- c(lon = -2.85, lat = 52.80) # chosen by inspection
map <- qmap(map_centre) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)

# Zoom in in the Marton cluster of 10
map_centre <- c(lon = -3.045, lat = 52.623) # chosen by inspection
map <- qmap(map_centre, zoom = 15) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)


# Let's check out the distribution of measurments
# A function to standardised the graphs
graf <- function(column.name){
  scratch <- samples[,c(column.name)]
  scratch <- gsub("[^\\d]", "", scratch, fixed = TRUE)
  scratch <- as.numeric(scratch)
  title <- paste("Histogram of", column.name, sep = " ")
  hist(main = title, scratch, xlab = column.name, breaks = 20)
}
# Complete graph-arama
graf("BOD")
graf("Nitrogen")             
graf("Phosphorus")           
graf("Alkalinity")          
graf("Nitrogen.Ammoniacal")
graf("Chloride")
graf("Nitrite") 
graf("Nitrogen.Oxidised") 
graf("Orthophosphate")       
graf("Silicate")
graf("Phosphate")             
graf("Conductivity")
graf("Turbidity")
graf("Solids")
graf("Calcium")              
graf("Magnesium")
graf("Potassium")
graf("Sodium")

"
The graphs for calcium, conductivity, silicate, alkalinity look like they might have been censored.
There appears to be a spike at one end of the distribution, like the data might have contained
a bunch of < or > but inspection reveals that silicate contains only one reading with < (<0.200).
"




       s    :  O]    D   9 d   = . W    i $ >K ` g  ٗ N y     p    A  Cg  Ϲ   '   8/ ? `d I y     @	 :*	 8	 oI	 ^	 *f	 j	 +u	 :	 ^	 Z	 W	 	 s	 y	 _
 
 6n
 }~
 ˎ
 
 e
 J
 V
 G
  J R a  X =  5  I '   G* 8 m   P; `A x ٣ O    ' E 1  q  p! 6 ^  G 5  Y  + B ge  ߈ Z   s  ǚ   a   C    F  )  j1 h e  w     ! = /a c 	    #< \B [o   I  + "4 T: o^ c    C    J 1 +8 L *a g 7o ]} 1  v        - H 9# -- 6 ~? i J  0   A N W [  % }, 2 8 > tD N _Y ^ ` e r g  V Ȭ h     n% 5 5 L c gp |  ϻ  3 ~    -  * o= #P b e %w ` G +     E' . 5 6= zD K R Y oe ql  x |  O  /   k   Y  G o   x ' e6 D dQ Y a b  ?  ( ğ   T5   + @   65 T u^ h # 3  FH  ZI    J!! ! ! " 0v" " J" '# 	\# l# |# Q$ 4#$ )$ 2$ N9$ p$ p$ $ I$ % %  % 2% G% I% Rz% % % % % #& C& %M& :[& #& & &  & ' ' xB' V' k' t' x' ' ' _' +'  '( O0( +A( w( ( w( %) /B) ^^) z) ) ) H) ) ** 5*     
pkgs <- c(
	"alabama",
	"base64enc",
	"caret",
	"cubature",
	"data.table",
	"DEoptim",
	"devtools",
	"doParallel",
	"doSNOW",
	"dplyr",
	"dyn",
	"dynlm",
	"extrafont",
	"feather",
	"fAsianOptions",
	"fAssets",
	"fBasics",
	"fBonds",
	"fCopulae",
	"fExoticOptions",
	"fExtremes",
	"fGarch",
	"fImport",
	"fMultivar",
	"fNonlinear",
	"fOptions",
	"fPortfolio",
	"fRegression",
	"fTrading",
	"fUnitRoots",
	"foreach",
	"forecast",
	"glmnet",
	"gmailr",
	"ggfortify",
	"ggplot2",
	"ggthemes",
	"gmp",
	"Hmisc",
	"knitr",
	"leaps",
	"linprog",
	"lubridate",
	"lpSolve",
	"lpSolveAPI",
	"mail",
	"mapproj",
	"maptools",
	"microbenchmark",
	"mongolite",
	"NMOF",
	"openxlsx",
	"parcor",
	"party",
	"pbivnorm",
	"plm",
	"plotly",
	"PythonInR",
	"quantmod",
	"R.cache",
	"randomForest",
	"Rcpp",
	"RCurl",
	"rJava",
	"readr",
	"reshape",
	"rmarkdown",
	"Rmpfr",
	"rjson",
	"roxygen2",
	"RQuantLib",
	"RSelenium",
	"RSQLite",
	"rvest",
	"scales",
	"sqldf",
	"stringr",
	"Synth",
	"plyr",
	"TSA",
	"tikzDevice",
	"x12",
	"xlsx",
	"XML",
	"xml2",
	"xts",
	"zoo"
	)

install.packages(pkgs)

# rjulia
devtools::install_github("armgong/rjulia", ref="julia0.5")

# http://bioconductor.org/packages/release/bioc/html/rhdf5.html
source("https://bioconductor.org/biocLite.R")
biocLite("rhdf5", ask=F) # HDF5 interface to R

# ------------------------------------------------------------------------------------ #
# -- Initial Developer: FranciscoME ----------------------------------------------- -- #
# -- Code: MachineTradeR Machine Trading R -- Publisher --------------------------- -- #
# -- License: MIT ----------------------------------------------------------------- -- #
# ------------------------------------------------------------------------------------ #

# -- Pelham Jenkins 
# -- Muro de instrumento
# -- Muro de usuario
# -- Twitter

# -- Benito Derman
# -- Muro de instrumento
# -- Muro de usuario
# -- Twitter

# -- Sonni Romano
# -- Muro de instrumento
# -- Muro de usuario
# -- Twitter

# -- Robert Bay
# -- Muro de instrumento
# -- Muro de usuario

RB_M1 <- c("It is far better to foresee even without certainty than not
           to foresee at all. - Henri Poincare", "It is through science that we prove,
           but through intuition that we discover. - Henri Poincare")

"A computer once beat me at chess, but it was no match for me at kick boxing. - Emo Philips"

"The good news about computers is that they do what you tell them to do.
The bad news is that they do what you tell them to do. - Ted Nelson"

"To err is human - and to blame it on a computer is even more so. - Robert Orben"

"It's hardware that makes a machine fast. It's software that makes a fast machine slow. Craig Bruce"

"I am thankful the most important key in history was invented. It's not the key
to your house, your car, your boat, your safety deposit box, your bike lock or your private community. It's the key to order, sanity, and peace of mind. The key is 'Delete.' Elayne Boosler"

"Computers are like Old Testament gods; lots of rules and no mercy. - Joseph Campbell"

"Computer science is no more about computers than astronomy is about telescopes. Edsger Dijkstra"

"Imagine if every Thursday your shoes exploded if you tied them the usual way. This happens to us all the time with computers, and nobody thinks of complaining. Jef Raskin"

"Home computers are being called upon to perform many new functions, including the consumption of homework formerly eaten by the dog. Doug Larson"

"Computers are useless. They can only give you answers. Pablo Picasso"

"Part of the inhumanity of the computer is that, once it is competently programmed and working smoothly, it is completely honest. Isaac Asimov"

"The question of whether a computer can think is no more interesting than the question of whether a submarine can swim. Edsger Dijkstra"

"We're entering a new world in which data may be more important than software. Tim O'Reilly"

"In computing, turning the obvious into the useful is a living definition of the word 'frustration'. Alan Perlis"

#tp_algotrading
#Esta cuenta es un algoritmo de inteligencia artificial. #tp_algotrading , #algotrading , #machinelearning , #machineintelligence


# -- Twitter

library(dplyr)
library(readr)
library(RODBC)

DIMA <- "filepath and filename to DIMA"

## This reduces it to forbs only in the process
haf.list <- read_csv("HAF_preferred_species_by_code.csv") %>% subset(GROWTH.HABIT == "FORB")

channel <- odbcConnectAccess(DIMA) ## Assumes 32-bit R and 32-bit Access. Use odbcConnectAccess2007() if both are 64-bit
species.lists <- sqlQuery("SELECT joinSitePlotLine.SiteID, joinSitePlotLine.PlotKey, joinSitePlotLine.PlotID, tblSpecRichDetail.SpeciesList FROM joinSitePlotLine INNER JOIN (tblSpecRichHeader LEFT JOIN tblSpecRichDetail ON tblSpecRichHeader.RecKey = tblSpecRichDetail.RecKey) ON joinSitePlotLine.LineKey = tblSpecRichHeader.LineKey;")
odbcCloseAll()


## Counting the number of preferred species in the data
# The semicolons are the way that DIMA delimits the species in its own tables
for (n in 1:nrow(species.lists)){
  ## Take the HAF preferred species list, reduce it to a subset where they are also found in the
  # vector species list extracted from the plot, and count the number of rows in that subset. No loop required.
  species.lists$HAF.preferred.count[n] <- subset(haf.list,
                                                 haf.list$CODE %in%
                                                   unlist(strsplit(as.character(species.lists[n,4]),";"))
                                                 ) %>% nrow()
}# This file is part of sb_pipe.
#
# sb_pipe is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# sb_pipe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with sb_pipe.  If not, see <http://www.gnu.org/licenses/>.
#
#
# Object: Plotting of the confidence intervals
#
# $Revision: 3.0 $
# $Author: Piero Dalle Pezze $
# $Date: 2016-07-7 11:14:32 $


library(ggplot2)


# Retrieve the environment variable SB_PIPE
SB_PIPE <- Sys.getenv(c("SB_PIPE"))
source(file.path(SB_PIPE,'sb_pipe','utils','R','sb_pipe_ggplot2_themes.r'))



# For each time point compute the most relevant descriptive statistics: mean, sd, var, skew, kurt, ci95, coeffvar, 
# min, 1st quantile, median, 3rd quantile, and max.
#
# :param timepoint.values: array of time points
# :param 
compute_descriptive_statistics <- function(timepoint.values, timepoint, variable, nfiles) {
    # compute mean, standard deviation, error, error.left, error.right
    timepoint$mean <- mean(timepoint.values, na.rm = TRUE)
    timepoint$sd <- sd(timepoint.values, na.rm = TRUE)
    timepoint$var <- var(timepoint.values, na.rm = TRUE)
    #y <- timepoint.values - timepoint.mean
    timepoint$skew <- mean(timepoint.values^3, na.rm = TRUE)/mean(timepoint.values^2, na.rm = TRUE)^1.5
    timepoint$kurt <- mean(timepoint.values^4, na.rm = TRUE)/mean(timepoint.values^2, na.rm = TRUE)^2 -3
    # 0.95 confidence level 
    #timepoint$ci95 <- qt(0.975, df=nfiles-1)*timepoint$sd/sqrt(nfiles)  # quantile t-distribution (few sample, stddev unknown exactly)
    timepoint$ci95 <- qnorm(0.975)*timepoint$sd/sqrt(nfiles) # quantile normal distribution (lot of samples)
    timepoint$coeffvar <- timepoint$sd / timepoint$mean
    timepoint$min <- min(timepoint.values, na.rm = TRUE)
    timepoint$stquantile <- quantile(timepoint.values, na.rm = TRUE)[2]  # Q1
    timepoint$median <- median(timepoint.values, na.rm = TRUE)  # Q2 or quantile(timepoint.values)[3]
    timepoint$rdquantile <- quantile(timepoint.values, na.rm = TRUE)[4]  # Q3
    timepoint$max <- max(timepoint.values, na.rm = TRUE)

    # put data in lists
    variable$mean <- c ( variable$mean, timepoint$mean )
    variable$sd <- c ( variable$sd, timepoint$sd )
    variable$var <- c ( variable$var, timepoint$var )
    variable$skew <- c ( variable$skew, timepoint$skew )
    variable$kurt <- c ( variable$kurt, timepoint$kurt )
    variable$ci95 <- c ( variable$ci95, timepoint$ci95 )
    variable$coeffvar <- c ( variable$coeffvar, timepoint$coeffvar )
    variable$min <- c ( variable$min, timepoint$min )
    variable$stquantile <- c ( variable$stquantile, timepoint$stquantile )
    variable$median <- c ( variable$median, timepoint$median )
    variable$rdquantile <- c ( variable$rdquantile, timepoint$rdquantile )
    variable$max <- c ( variable$max, timepoint$max )
 
    #print(nfiles)
    #for debug
    #print(column[j])
    #print(timepoints[k])
    #print(variable.mean)
    #prints(variable.sd)
    return (variable)
}


get_column_names_statistics <- function(column.names, name) {    
    column.names <- c (column.names,
                       paste(name, "_Mean", sep=""),
                       paste(name, "_StdDev", sep=""),
                       paste(name, "_Variance", sep=""),
                       paste(name, "_Skewness", sep=""),
                       paste(name, "_Kurtosis", sep=""),                       
                       paste(name, "_t-dist_CI95%", sep=""),
                       paste(name, "_StdErr", sep=""),
                       paste(name, "_CoeffVar", sep=""),
                       paste(name, "_Minimum", sep=""),
                       paste(name, "_1stQuantile", sep=""),
                       paste(name, "_Median", sep=""),
                       paste(name, "_3rdQuantile", sep=""),
                       paste(name, "_Maximum", sep=""))
    #print(name)
    return (column.names)
}

get_statistics_table <- function(statistics, variable, s=2) {    
    #print(variable$mean) 
    statistics[,s]   <- variable$mean
    statistics[,s+1] <- variable$sd
    statistics[,s+2] <- variable$var
    statistics[,s+3] <- variable$skew
    statistics[,s+4] <- variable$kurt
    statistics[,s+5] <- variable$ci95
    statistics[,s+6] <- variable$coeffvar
    statistics[,s+7] <- variable$min
    statistics[,s+8] <- variable$stquantile
    statistics[,s+9] <- variable$median
    statistics[,s+10] <- variable$rdquantile
    statistics[,s+11] <- variable$max
    return (statistics)
}


plot_error_bars <- function(outputdir, version, name, variable, timepoints, simulate__xaxis_label, bar_type="sd") {
    filename = ""

    if(bar_type == "none") {
      # standard error configuration
      filename = file.path(outputdir, paste(version, "_none_", name, ".png", sep=""))
      # Let's plot this special case now as it does not require error bars
      df <- data.frame(a=timepoints, b=variable$mean)      
      g <- ggplot() + geom_line(data=df, aes(x=a, y=b), color="black", size=1.0)
      g <- g + xlab(simulate__xaxis_label) + ylab(paste(name, " level [a.u.]", sep=""))
      ggsave(filename, dpi=300,  width=8, height=6) #, bg = "transparent")      

    } else { 

      df <- data.frame(a=timepoints, b=variable$mean, c=variable$sd, d=variable$ci95)
      #print(df)
      g <- ggplot(df, aes(x=a, y=b))

      # plot the error bars
      g <- g + geom_errorbar(aes(ymin=b-c, ymax=b+c), colour="blue",  size=1.0, width=0.1)    
        
      if(bar_type == "sd") {
	# standard deviation configuration
	filename = file.path(outputdir, paste(version, "_sd_", name, ".png", sep=""))
      } else {
	# standard deviation + confidence interval configuration
	filename = file.path(outputdir, paste(version, "_sd_n_ci95_", name, ".png", sep=""))
        # plot the C.I.	
	g <- g + geom_errorbar(aes(ymin=b-d, ymax=b+d), colour="lightblue", size=1.0, width=0.1)	
      }

      # plot the line
      g <- g + geom_line(aes(x=a, y=b), color="black", size=1.0)    

      # decorate
      g <- g + xlab(simulate__xaxis_label) + ylab(paste(name, " level [a.u.]", sep="")) + theme(legend.position = "none")
      ggsave(filename, dpi=300,  width=8, height=6)#, bg = "transparent")
   }
}



plot_error_bars_plus_statistics <- function(inputdir, outputdir, version, files, outputfile, simulate__xaxis_label) {
    
    theme_set(tc_theme(28))  

    # Read variable
    timecourses <- read.table( file.path(inputdir, files[1]), header=TRUE, na.strings="NA", dec=".", sep="\t" )
    column <- names (timecourses)

    column.names <- c ("Time")
    
    simulate__start <- timecourses$Time[1]
    simulate__end <- timecourses$Time[length(timecourses$Time)] 
    timepoints <- seq(from=simulate__start, to=simulate__end, by=(simulate__end-simulate__start)/(length(timecourses$Time)-1))
      
    time_length <- length(timepoints)
  

    # statistical table (to export)
    statistics <- matrix( nrow=time_length, ncol=(((length(column)-1)*13)+1) )
    statistics[,1] <- timepoints
    s <- 2
    linewidth=14
    
    # an empty colum that we need for creating a data.frame of length(timecourses$Time) rows
    na <- c(rep(NA, length(timecourses$Time)))

    for(j in 1:length(column)) {
      if(column[j] != "Time") {
	print(column[j])

	# Extract column[j] for each file.
	dataset <- data.frame(na)
	for(i in 1:length(files)) {
	    dataset <- data.frame(dataset, read.table(file.path(inputdir,files[i]),header=TRUE,na.strings="NA",dec=".",sep="\t")[,j])
	}
	# remove the first column (na)
	dataset <- subset(dataset, select=-c(na))
	
	#print(dataset)
	# structures
	timepoint <- list("mean"=0,"sd"=0,"var"=0,"skew"=0,"kurt"=0,"ci95"=0,
			  "coeffvar"=0,"min"=0,"stquantile"=0,"median"=0,"rdquantile"=0,"max"=0)	
	variable <-list("mean"=c(),"sd"=c(),"var"=c(),"skew"=c(),"kurt"=c(),"ci95"=c(),
		      "coeffvar"=c(),"min"=c(),"stquantile"=c(),"median"=c(),"rdquantile"=c(),"max"=c())
	k <- 1
	# for each computed timepoint
 	for( l in 1:length ( timecourses$Time ) ) {

	  timepoint.values <- c ( )

  	  if ( k <= length( timepoints ) && as.character(timepoints[k]) == as.character(timecourses$Time[l]) ) {
	      #print(timepoints[k])
 	      # for each Sample
 	      for(m in 1:length(files)) {
		  timepoint.values <- c(timepoint.values, dataset[l,m])  
 	      }
  	      variable <- compute_descriptive_statistics(timepoint.values, timepoint, variable, length(files))   
 	      #print(variable)
  	      k <- k + 1
  	  }
 	}
  	column.names <- get_column_names_statistics(column.names, column[j])
  	statistics <- get_statistics_table(statistics, variable, s)
 	s <- s+13
  	plot_error_bars(outputdir, version, column[j], variable, timepoints, simulate__xaxis_label, "none")
  	plot_error_bars(outputdir, version, column[j], variable, timepoints, simulate__xaxis_label, "sd")  
  	plot_error_bars(outputdir, version, column[j], variable, timepoints, simulate__xaxis_label, "sd_n_ci95")  	
      }
    }
    #print (statistics)
    write.table(statistics, outputfile, sep="\t", col.names = column.names, row.names = FALSE) 
}


#' Import data from Wildlife Computers ".tab" text files
#' 
#' @param x filename to be imported or a TDR dataset to be formated.
#' @param dt if TRUE function will return a data.table object, else, a data.frame.
#' @param ... Arguments to be passed to \code{\link{file}} such as \code{encoding}.
#' @details Wildlife Computers > Instrument helper > Save instrument readings > R format
#' @export
#' @keywords raw_processing
#' @import sqldf data.table
read.wcih <- function(x, dt = TRUE, ...) {
  stopifnot(require("data.table"))
  stopifnot(require("sqldf"))
  if (is.character(x)) {
    f <- file(x, ...)
    nms <- unlist(read.table(x, skip = 3, as.is = TRUE, nrows = 1))
    fmt <- list(skip = 4, header = FALSE, row.names = FALSE, sep = " ")
    x <- sqldf("select * from f", dbname = tempfile(), file.format = fmt)[ , -1]
  } else {
    nms <- names(x)
  }
  
  new_nms <- c(
    "Time" = "time", "Depth" = "depth", 
    "External Temperature" = "temp", "Light Level" = "light", 
    "int aX" = "ax", "int aY" = "ay", "int aZ" = "az", 
    "int mX" = "mx", "int mY" = "my", "int mZ" = "mz", 
    "Velocity" = "spd", "Internal Temperature" = "itemp"
  )
  
  x <- setnames(as.data.table(x), new_nms[nms])
  x <- x[ , lapply(.SD, as.numeric)]
  x <- x[ , time := as.POSIXct(floor(time), origin = "1970-01-01", tz = 'UTC')]
  
  x <- if (dt) 
    data.table(x, key = "time")
  else 
    as.data.frame(x)
}

#' Identify Prey Catch attempts
#' 
#' @param x 3 axes acceleration table with time in the first column and acceleration 
#' axes in the following columns. Variables must be entitled "time" for time, 
#' "ax", "ay", and "az" for x, y and z accelerometer axes.
#' @param fs sampling frequency of the input data (Hz).
#' @param fc Cut-off frequency for the butterworth high pass filter (Hz)
#' @return returns a logical vector of prey catch attempts at 1 Hz frequency. 
#' Value is TRUE if the record belong to prey catch attempt FALSE otherwise.
#' @import data.table signal RcppRoll
#' @export
#' @keywords raw_processing
prey_catch_attempts <- function(x, fs = 16, fc = 2.64) {
  stopifnot(require("data.table"))
  stopifnot(require("signal"))
  stopifnot(require("RcppRoll"))
  # Generate Butterworth filter 
  # Critical frequencies of the filter: f_cutoff / (f_sampling/2)
  bf_pca  <- butter(3, W = fc / (0.5*fs), type = 'high')
  
  # Apply filter
  if (!is.data.table(x)) x <- data.table(x, key = "time")
  .f <- function(x) as.numeric(filtfilt(bf_pca, x))
  x <- x[ , 2:4 := lapply(.SD, .f), .SDcols = 2:4]
  gc()
  
  # 1 s fixed window standard deviation + aggregate data to 1 Hz
  x <- x[ , lapply(.SD, sd, na.rm = TRUE), by = time]
  # In case of NAs set ACC to zero
  nas <- lapply(x[ , 2:4, with = FALSE], is.na)
  nas_vector <- Reduce("|", nas)
  if (any(nas_vector)) {
    warning("NAs found and replaced by 0. NA proportion:", mean(nas_vector))
    x$ax[nas$ax] <- 0
    x$ay[nas$ay] <- 0
    x$az[nas$az] <- 0
  }
  gc()
  
  # 5 s moving window standard deviation
  .f <- function(x) c(0,0,roll_sd(x, 5),0,0)
  x <- x[ , 2:4 := lapply(.SD, .f), .SDcols = 2:4]
  gc()
  
  # kmean clutering: "high" = TRUE vs "low" = FALSE
  .f <- function(x) { 
    km_mod <- kmeans(x, 2)
    high_state <- which.max(km_mod$centers)
    as.logical(km_mod$cluster == high_state)
  }
  x <- x[ , 2:4 := lapply(.SD, .f), .SDcols = 2:4]
  
  # Aggregate and return to data.frame
  # records classified as PCA if the three axis are simultaneously in high state
  Reduce("&", x[ , time := NULL])
}

#' Compute swimming effort
#' 
#' @param fc Cut-off frequencies for the butterworth band pass filter (Hz)
#' @inheritParams prey_catch_attempts
#' @param rms Should the root mean square be used (instead of mean of absolute values) 
#' when averaging the acceleration to 1 Hz ?
#' @return returns a vector of swimming effort values at 1 Hz.
#' @details Only Y accelerometer axe is used to compute swimming effort.
#' @import data.table signal
#' @export
#' @keywords raw_processing
swimming_effort <- function(x, fs = 16, fc = c(0.4416, 1.0176), rms = FALSE) {
  stopifnot(require("data.table"))
  stopifnot(require("signal"))
  # Generate a Butterworth filter 
  # Critical frequencies of the filter: f_filter / (f_sampling/2)
  bf_swm  <-  butter(3, W = fc / (0.5*fs), type = 'pass')
  
  # Apply filter
  if (!is.data.table(x)) x <- data.table(x, key = "time")
  x <- x[ , ay := abs(as.numeric(filtfilt(bf_swm, ay)))]
  x <- x[ , c(2, 4) := NULL, with = FALSE] # remove unused "ax" & "az" columns
  
  # 1 s fixed window average + aggregate data to 1 Hz
  if (!rms) {
    x <- x[ , lapply(.SD, function(x) mean(abs(x), na.rm = TRUE)), by = time]
  } else {
    x <- x[ , lapply(.SD, function(x) sqrt(mean(x^2, na.rm = TRUE))), by = time]
  }
  x <- x$ay
}
globalVariables("ay")

#' Static acceleration
#' 
#' The raw acceleration is first filtered using a low pass butterworth filter. 
#' Then , the extracted signal can be scaled so that the norm of the the vector 
#' G is 1 at each second.
#' 
#' @param fc Cut-off frequency for the butterworth low pass filter (Hz)
#' @param Gscale Should the values be scaled by the norm of the static 
#' acceleration vector ?
#' @param agg_1hz Should the input be aggregated to 1 Hz ?
#' @inheritParams prey_catch_attempts
#' @return returns a data.frame with time, and X, Y and Z static accelearyion at 1 Hz.
#' @details This filtered acceleration can be used to compute pitch and roll angles
#' @import data.table signal
#' @keywords raw_processing
#' @export
static_acc <- function(x, fs = 16, fc = 0.20, Gscale = TRUE, agg_1hz = TRUE) {
  stopifnot(require("data.table"))
  stopifnot(require("signal"))
  # Generate a Butterworth filter 
  # Critical frequencies of the filter: f_filter / (f_sampling/2)
  bf_grav  <-  butter(3, W = fc / (0.5*fs), type = 'low')
  
  # Apply filter
  if (!is.data.table(x)) x <- data.table(x, key = "time")
  x <- x[ , 2:4 := lapply(.SD, function(x) as.numeric(filtfilt(bf_grav, x))), 
          .SDcols = 2:4]
  
  # 1 s fixed window average + aggregate data to 1 Hz
  if (agg_1hz) {
    x <- x[ , lapply(.SD, mean, na.rm = TRUE), by = time]
  }
  x <- setnames(x, c('time', 'axG', 'ayG', 'azG'))
  
  # Scale axis
  if (Gscale) {
    Gnorm <- sqrt(x$axG^2 + x$ayG^2 + x$azG^2)
    x <- x[ , 2:4 := lapply(.SD, function(x) x / Gnorm), .SDcols = 2:4]
  }
  
  as.data.frame(x)
}

#' Dynamic (Body) acceleration DBA
#' 
#' DBA is calculated by smoothing data for each axis to calculate the static 
#' acceleration (\code{\link{static_acc}}), and then subtracting it from 
#' the raw acceleration.
#' 
#' @param ... Parameters to be passed to \code{\link{static_acc}} (e.g \code{fc}).
#' @inheritParams static_acc
#' @return returns a data.frame with time, and X, Y and Z static accelearyion at 1 Hz.
#' @details This filtered acceleration can be used to compute ODBA and VeDBA.
#' @import data.table signal
#' @export
#' @keywords raw_processing
dynamic_acc <- function(x, fs = 16, agg_1hz = TRUE, ...) {
  static <- static_acc(copy(x), fs = fs, Gscale = FALSE, agg_1hz = FALSE, ...)
  x <- x[ , `:=`(2:4, Map("-", x[ , 2:4, with = FALSE], static[ , 2:4])), with = FALSE]
  rm(list = "static") ; gc()
  if (agg_1hz) {
    x <- x[ , lapply(.SD, mean, na.rm = TRUE), by = time]
  }
  as.data.frame(setnames(x, c("time", "axD", "ayD", "azD")))
}

#' Attitude angles from static accelation
#' 
#' @param object A data frame or TDR table including static acceleration variables 
#' entitled "axG", "ayG", and "azG" for X, Y, and Z axes of the accelerometer.
#' @export
#' @keywords raw_processing
pitch <- function(object) {
  -atan(object$axG/sqrt(object$ayG^2 + object$azG^2))
}

#' @rdname pitch
#' @export
#' @details For roll angle, the x axe is not necessary.
#' @return A vector of pitch/roll of the same length as \code{object}.
#' @keywords raw_processing
roll <- function(object) {
  atan2(object$ayG^2, object$azG)
}

#' Overall Dynamic Body Acceleration (ODBA)
#' 
#' @param object A data frame or TDR table including dynamic acceleration variables 
#' entitled "axD", "ayD", and "azD" for X, Y, and Z axes of the accelerometer.
#' @export
#' @return A vector of ODBA of the same length as \code{object}.
#' @keywords raw_processing
overall_DBA <- function(object) {
  object <- as.data.table(object)
  object <- object[ , tot := abs(axD) + abs(ayD) + abs(azD)]
  object$tot
}

#' Vectorial Dynamic Body Acceleration (VeDBA)
#' 
#' @param object A data frame or TDR table including dynamic acceleration variables 
#' entitled "axD", "ayD", and "azD" for X, Y, and Z axes of the accelerometer.
#' @export
#' @return A vector of VeDBA of the same length as \code{object}.
#' @keywords raw_processing
vectorial_DBA <- function(object) {
  object <- as.data.table(object)
  object <- object[ , tot := sqrt(axD^2 + ayD^2 + azD^2)]
  object$tot
}
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        cancel = function(job_ids, user = private$user, host = private$host) {
            job_ids <- paste(job_ids, collapse = ",")

            stain_ssh(user, host, paste("scancel", job_ids))
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host,
                          submit_dir = "~/stain", dependency_list = "") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")

                # Add any dependencies to sbatch command.
                history <- self$submission_history()$job_id
                dependencies <- sbatch_dependency_list(dependency_list, history)

                if (nchar(dependencies) > 0) {
                    dependencies <- sbatch_opt("dependency")(dependencies)
                }

                submit_cmd <- paste("sbatch",
                                    dependencies,
                                    "submit.slurm")
                submit_cmd <- paste("cd", job_dir, "&&", submit_cmd)
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir = "~/stain") {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        submission_history = function() {
            # `stain_sub_history` will warn if submission history is empty.
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                return(history)
            }
        },
        fetch_job_states = function(user = private$user, host = private$host) {
            submission_history <- stain_sub_history(self$dir)
            job_ids <- submission_history$job_id

            verify_state_table <- function(state_table) {
                if (nrow(status_table) > 0) {
                    return(state_table)
                } else {
                    job_ids <- paste(job_ids, collapse = ", ")
                    message(paste("No statuses found for job ids:", job_ids))
                }
            }

            fetch_squeue_table <- function() {
                tryCatch({
                    squeue_table <- stain_ssh_squeue(user, host, job_ids)
                    squeue_table <- squeue_table[, c("JOBID", "STATE")]
                    colnames(squeue_table) <- c("job_id", "state")
                    # Will throw error if data frame has no rows.
                    squeue_table$exit_code <- NA
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    squeue_table <- data.frame()
                }, finally = return(squeue_table))
            }

            fetch_sacct_table <- function() {
                tryCatch({
                    sacct_table <- stain_ssh_sacct(user, host, job_ids)
                    colnames(sacct_table) <- c("job_id", "state", "exit_code")
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    sacct_table <- data.frame()
                }, finally = return(sacct_table))
            }

            squeue_table <- fetch_squeue_table()
            sacct_table <- fetch_sacct_table()
            states <- rbind(squeue_table, sacct_table)
            states <- aggregate(states, list(states$job_id), function(x) {
                na.omit(x)[1]
            })[,-1]

            return(merge(states, submission_history))
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
######################################################################
######################################################################
## ROUTINE ZUM EINLESEN VON ERA-DATEN (ZONAL-WIND) IM NCDF-FORMAT
## UND AUFFINDEN DES JETSTREAMS AUF NORDHEMISPHÄRE
## source('~/Master_Thesis/02-r-code-git/locate_jetstream_polynomial_2d.r')
######################################################################
######################################################################


######################################################################
## AUFRUF WICHTIGER BIBLIOTHEKEN UND PAKETE
######################################################################
##

library(ncdf4)
library(parallel)
library(chron)

# eigenes package für least squares fit mit chebyshev polynomen
# install.packages("pckg.cheb_0.9.tar.gz", repos = NULL, type = "source")
library(pckg.cheb)

setwd("~/Master_Thesis/02-r-code-git/")
path <- "data/"
# path <- "/home/skiefer/era/raw/"
file <- "era-t63-1957-2016.nh-trop-inv.nc"  # Nordhemisphäre + Tropen


######################################################################
## KLEINE HILFSFUNKTIONEN
######################################################################
##

fun.fill <- function(x, n) {
  while (length(x) < n) {
    x <- c(x, NA)
  }
  return(x)
}


######################################################################
## EINLESEN DER DATEN
## ERA40 / ERA-INTERIM
## T63 - GRID - GAUSSIAN
## NORDHEMISPHÄRE & TROPEN
## 192 (lat) * 64 (lon)
######################################################################
##

nc <- nc_open(paste(path, file, sep = ""))
# print(nc)
u.monmean <- ncvar_get(nc, "var131") # U-Wind-Komponente
v.monmean <- ncvar_get(nc, "var132") # V-Wind-Komponente
# w.monmean <- ncvar_get(nc, "var135") # W-Wind-Komponente
# z.monmean <- ncvar_get(nc, "var129") # Geopotenzial
# t.monmean <- ncvar_get(nc, "var130") # Temperatur
# d.monmean <- ncvar_get(nc, "var155") # Divergenz

lon <- ncvar_get(nc, "lon") # Längengrad
lat <- ncvar_get(nc, "lat") # Breitengrad
lev <- ncvar_get(nc, "lev") # Drucklevel
date.help <- ncvar_get(nc, "time")

nc_close(nc)
rm(nc)

uv.monmean <- sqrt( u.monmean ** 2 + v.monmean **2 )

######################################################################
## VARIABLEN UND PARAMETER
######################################################################
##

n.cpu <- 24 # Anzahl der CPUs für parApply
n.order.lat <- 31 # Ordnung des Least-Square-Verfahrens für Fit über Breitengrad
n.order.lon <- 8 # Ordnung des Least-Square-Verfahrens für Fit über Längengrad

## Räumliche Auflösung
n.lat <- length(lat)
n.lon <- length(lon)

## Zeitliche Auflösung
dts = chron(dates. = date.help/24, origin. = c(month = 9,day = 1,year = 1957), format = "day mon year")
dts.month <- months(dts, abbreviate = TRUE)
dts.year <- years(dts)

## Zeitlich gemittelter Zonalwind
# u.mean <- apply(u.monmean,c(1,2),mean)
# u.std <- apply(u.monmean,c(1,2),sd)

## Meridional und zeitlich gemittelter Zonalwind
# u.mon.mer.mean <- apply(u.monmean, 2, mean)
# u.mon.mer.sd <- apply(u.mean, 2, sd)

## Meridional gemittelter Zonalwind
# u.monmean.mermean <- apply(u.monmean, c(2,3), mean)
# u.monmean.mersd <- apply(u.monmean, c(2,3), sd)



######################################################################
## LEAST SQUARES FIT 
## CHEBYSHEV POLYNOME 23-TER ORDNUNG
## AN ZONAL WIND IN MERIDIONALER RICHTUNG
######################################################################
##

# list.model.lat <- apply(u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
list.model.lat <- parApply(cl, u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.roots, x.axis = lat, n = n.order.lat, bc.harmonic = FALSE, roots.bound.l = 20, roots.bound.u = 80)
stopCluster(cl)
dim.list <- dim(list.model.lat)

## Chebyshev-Koeffizienten
cheb.coeff <- sapply(list.model.lat, "[[", 1)
cheb.coeff <- apply(array(data = cheb.coeff, dim = c((n.order.lat + 1), dim.list[1], dim.list[2])) , c(1,3), t)

## Gefiltertes Modell für Zonal-Wind
model.u <- sapply(list.model.lat, "[[", 2)
model.u <- apply(array(data = model.u, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)

## Erste Ableitung des gefilterten Modells für Zonalwind
model.u.deriv.1st <- sapply(list.model.lat, "[[", 3)
model.u.deriv.1st <- apply(array(data = model.u.deriv.1st, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)

## Extrema des Modells (Positionen und Werte)
model.extr.lat <- sapply(list.model.lat, "[[", 4)
model.extr.u <- sapply(list.model.lat, "[[", 5)
model.extr.lat <- sapply(model.extr.lat, fun.fill, n = 24)
model.extr.lat <- apply(array(model.extr.lat, c(24, dim.list[1], dim.list[2])), c(1,3), t)
model.extr.u <- sapply(model.extr.u, fun.fill, n = 24)
model.extr.u <- apply(array(model.extr.u, c(24, dim.list[1], dim.list[2])), c(1,3), t)

## Maxima des Modells (Positionen und Werte)
model.max.u <- apply(model.extr.u, c(1,3), max, na.rm = TRUE)
model.max.lat <- array(rep(0, 192*664), c(dim.list))
for (i in 1:dim.list[2]) {
  for (j in 1:dim.list[1]) {
    model.max.lat[j,i] <- model.extr.lat[j, which(model.extr.u[j,,i] == model.max.u[j,i]), i]
  }
}
rm(list.model.lat, dim.list)


######################################################################
## LEAST SQUARES FIT 
## CHEBYSHEV POLYNOME 8-TER ORDNUNG
## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
######################################################################
##

#list.model.lon <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
cl <- makeCluster(getOption("cl.cores", n.cpu))
list.model.lon <- parApply(cl, model.max.lat, 2, pckg.cheb:::cheb.fit.roots, x.axis = lon, n = n.order.lon, bc.harmonic = TRUE)
stopCluster(cl)

## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
#model.max.lon <- list.model.lon, "[[", 2)
#rm(list.model.lon)


######################################################################
## FEHLERGRÖẞEN
## MSE
## RMSE
######################################################################
##

residuals.cheb <- u.monmean - model.u
#residuals.cheb.seq <- u.monmean - model.u.seq
mse <- sum(residuals.cheb ** 2) / length(residuals.cheb)
#mse.seq <- sum(residuals.cheb.seq **2) / length(residuals.cheb.seq)
rmse <- sqrt(sum(residuals.cheb ** 2) / length(residuals.cheb))
#rmse.seq <- sqrt(sum(residuals.cheb.seq **2) / length(residuals.cheb.seq))

## rmse.seq = 0.4079846  ## mse.seq = 0.1664514
## rmse     = 0.2911683  ## mse     = 0.08477901


######################################################################
######################################################################
save.image()



######################################################################
## Berechnung von Mean und Sd
## über fünf Jahre & saisonal
######################################################################
# dts.year.mn <- seq(1960, 2010, 5)
# 
# ind.mam <- which(dts.month == "Mar" | dts.month == "Apr" | dts.month == "May")
# ind.jja <- which(dts.month == "Jun" | dts.month == "Jul" | dts.month == "Aug")
# ind.son <- which(dts.month == "Sep" | dts.month == "Oct" | dts.month == "Nov")
# ind.djf <- which(dts.month == "Dec" | dts.month == "Jan" | dts.month == "Feb")
# 
# ## Mittelwerte global
# u.seas.mam.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.mam.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.jja.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.jja.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.son.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.son.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.djf.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.djf.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# 
# ## Mittelwerte meridional *???*
# u.mer.seas.mam.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.mam.sd <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.jja.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.jja.sd <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.son.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.son.sd <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.djf.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.djf.sd <- array( NA , dim = c(n.lat, 11))
# 
# for (i in seq(1, 11)) {
#   print(i)
#   yr.i <- dts.year.mn[i]
#   ind.yr <- which(dts.year ==  yr.i | dts.year == (yr.i + 1) | dts.year == (yr.i + 2) | dts.year == (yr.i + 3) | dts.year == (yr.i + 4) )
#   ## Mar Apr May
#   ind.mam.yr <- intersect(ind.yr, ind.mam)
#   u.seas.mam.mean[,,i] <- apply(u.monmean[,, ind.mam.yr], c(1,2), mean)
#   u.seas.mam.sd[,,i] <- apply(u.monmean[,, ind.mam.yr], c(1,2), sd)
#   u.mer.seas.mam.mean[,i] <- apply(u.monmean[,, ind.mam.yr], 2, mean)
#   u.mer.seas.mam.sd[,i] <- apply(u.monmean[,, ind.mam.yr], 2, sd)
#   ## Jun Jul Aug
#   ind.jja.yr <- intersect(ind.yr, ind.jja)
#   u.seas.jja.mean[,,i] <- apply(u.monmean[,, ind.jja.yr], c(1,2), mean)
#   u.seas.jja.sd[,,i] <- apply(u.monmean[,, ind.jja.yr], c(1,2), sd)
#   u.mer.seas.jja.mean[,i] <- apply(u.monmean[,, ind.jja.yr], 2, mean)
#   u.mer.seas.jja.sd[,i] <- apply(u.monmean[,, ind.jja.yr], 2, sd)
#   ## Sep Oct Nov
#   ind.son.yr <- intersect(ind.yr, ind.son)
#   u.seas.son.mean[,,i] <- apply(u.monmean[,, ind.son.yr], c(1,2), mean)
#   u.seas.son.sd[,,i] <- apply(u.monmean[,, ind.son.yr], c(1,2), sd)
#   u.mer.seas.son.mean[,i] <- apply(u.monmean[,, ind.son.yr], 2, mean)
#   u.mer.seas.son.sd[,i] <- apply(u.monmean[,, ind.son.yr], 2, sd)
#   ## Dec Jan Feb
#   ind.djf.yr <- intersect(ind.yr, ind.djf)
#   u.seas.djf.mean[,,i] <- apply(u.monmean[,, ind.djf.yr], c(1,2), mean)
#   u.seas.djf.sd[,,i] <- apply(u.monmean[,, ind.djf.yr], c(1,2), sd)
#   u.mer.seas.djf.mean[,i] <- apply(u.monmean[,, ind.djf.yr], 2, mean)
#   u.mer.seas.djf.sd[,i] <- apply(u.monmean[,, ind.djf.yr], 2, sd)
#   ## Löschen von Übergangsvariablen
#   rm(yr.i, ind.yr, ind.mam.yr, ind.jja.yr, ind.son.yr, ind.djf.yr, i)
# }
# 
# max(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
# min(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
# range(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
# 
# max(u.seas.mam.mean)
# min(u.seas.mam.mean)
# range(u.seas.mam.mean)
# 
# max(u.seas.jja.mean)
# min(u.seas.jja.mean)
# range(u.seas.jja.mean)
# 
# max(u.seas.son.mean)
# min(u.seas.son.mean)
# range(u.seas.son.mean)
# 
# max(u.seas.djf.mean)
# min(u.seas.djf.mean)
# range(u.seas.djf.mean)
# 
# 
# image.plot(lon, lat, u.mean+u.std)
# contour(lon, lat, u.std[,,1], add=TRUE)
# addland(col= "grey50", lwd = 1)
# 
# cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
# list.lat.m.sd <- parApply(cl, (u.mean[,] - u.std[,]), 1, pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
# list.lat.mn <- parApply(cl, u.mean[,], 1, pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
# list.lat.p.sd <- parApply(cl, (u.mean[,] + u.std[,]), 1, pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
# stopCluster(cl)
# 
# model.extr.lat.m.sd <- sapply(list.lat.m.sd, "[[", 4)
# model.extr.lat.mn <- sapply(list.lat.mn, "[[", 4)
# model.extr.lat.p.sd <- sapply(list.lat.m.sd, "[[", 4)
# 
# model.extr.u.m.sd <- sapply(list.lat.m.sd, "[[", 5)
# model.extr.u.mn <- sapply(list.lat.mn, "[[", 5)
# model.extr.u.p.sd <- sapply(list.lat.p.sd, "[[", 5)
# 
# model.extr.lat.m.sd <- sapply(model.extr.lat.m.sd, fun.fill, n = 16)
# model.extr.lat.mn <- sapply(model.extr.lat.mn, fun.fill, n = 16)
# model.extr.lat.p.sd <- sapply(model.extr.lat.p.sd, fun.fill, n = 16)
# 
# model.extr.u.m.sd <- sapply(model.extr.u.m.sd, fun.fill, n = 16)
# model.extr.u.mn <- sapply(model.extr.u.mn, fun.fill, n = 16)
# model.extr.u.p.sd <- sapply(model.extr.u.p.sd, fun.fill, n = 16)
# 
# model.max.u.m.sd <- apply(model.extr.u.m.sd, 2, max, na.rm = TRUE)
# model.max.u.mn <- apply(model.extr.u.mn, 2, max, na.rm = TRUE)
# model.max.u.p.sd <- apply(model.extr.u.p.sd, 2, max, na.rm = TRUE)
# 
# model.max.lat.m.sd <- array(rep(0, 192))
# model.max.lat.mn <- array(rep(0, 192))
# model.max.lat.p.sd <- array(rep(0, 192))
# 
# for (i in 1:192) {
#   model.max.lat.m.sd[i] <- model.extr.lat.m.sd[which(model.extr.u.m.sd[,i] == model.max.u.m.sd[i]), i]
#   model.max.lat.mn[i] <- model.extr.lat.mn[which(model.extr.u.mn[,i] == model.max.u.mn[i]), i]
#   model.max.lat.p.sd[i] <- model.extr.lat.p.sd[which(model.extr.u.p.sd[,i] == model.max.u.p.sd[i]), i]
# }
# 
# list.lon.m.sd <- pckg.cheb:::cheb.fit(d = model.max.lat.m.sd, x.axis = lon, n = 11)
# list.lon.mn <- pckg.cheb:::cheb.fit(d = model.max.lat.mn, x.axis = lon, n = 11)
# list.lon.p.sd <- pckg.cheb:::cheb.fit(d = model.max.lat.p.sd, x.axis = lon, n = 11)
# 
# model.max.lon.m.sd <- list.lon.m.sd[[2]]
# model.max.lon.mn <- list.lon.mn[[2]]
# model.max.lon.p.sd <- list.lon.p.sd[[2]]
# 
# 
# lines(lon, model.max.lon.m.sd)
# lines(lon, model.max.lon.mn)
# lines(lon, model.max.lon.p.sd)




####################################################################################################
########## ableitung des drehimpulses ##############################################################
########## aus zonal wind ##########################################################################
####################################################################################################
### ref: m = 
### formel noch inkorrekt
### keine schleife benutzen
##
# m <- matrix(NA,n.lon,n.lat)
# for (i in 1:n.lon){
#   for (j in 1:n.lat){
#     m[i,j] <- u.era.t63.monmean[i,j,1]*cos(lat.era.t63[j]) + 1/86400*u.era.t63.monmean[i,j,1]**2*cos(lat.era.t63[j])**2
#   }
# }
# #m <- u.era.t63.monmean*cos(lat.era.t63)
# 




# ######################################################################
# ## LEAST SQUARES FIT ÜBER **SEQUENZEN** (l=8)
# ## CHEBYSHEV POLYNOME 3-TER ORDNUNG
# ## AN ZONAL-WIND IN MERIDIONALER RICHTUNG
# ######################################################################
# ##
# 
# # list.model.lat.seq <- apply(u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
# list.model.lat.seq <- parApply(cl, u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# stopCluster(cl)
# dim.list <- dim(list.model.lat.seq)
# 
# ## Gefiltertes Modell für Zonal-Wind
# model.u.seq <- sapply(list.model.lat.seq, "[[", 1)
# model.u.seq <- apply(array(data = model.u.seq, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Erste Ableitung des gefilterten Modells für Zonalwind
# model.u.deriv.1st.seq <- sapply(list.model.lat.seq, "[[", 2)
# model.u.deriv.1st.seq <- apply(array(data = model.u.deriv.1st.seq, dim = c(n.lon, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Extrema des Modells (Positionen und Werte)
# model.extr.lat.seq <- sapply(list.model.lat.seq, "[[", 3)
# model.extr.lat.seq <- sapply(model.extr.lat.seq, fun.fill, n = 24)
# model.extr.lat.seq <- apply(array(model.extr.lat.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# model.extr.u.seq <- sapply(list.model.lat.seq, "[[", 4)
# model.extr.u.seq <- sapply(model.extr.u.seq, fun.fill, n = 24)
# model.extr.u.seq <- apply(array(model.extr.u.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# 
# ## Maxima des Modells (Positionen und Werte)
# model.max.u.seq <- apply(model.extr.u.seq, c(1,3), max, na.rm = TRUE)
# model.max.lat.seq <- array(rep(0, dim.list[1]*dim.list[2]), c(dim.list))
# for (i in 1:dim.list[2]) {
#   for (j in 1:dim.list[1]) {
#     model.max.lat.seq[j,i] <- model.extr.lat.seq[j, which(model.extr.u.seq[j,,i] == model.max.u.seq[j,i]), i]
#   }
# }
# rm(list.model.lat.seq, dim.list)
# 
# 
# ######################################################################
# ## LEAST SQUARES FIT 
# ## CHEBYSHEV POLYNOME 8-TER ORDNUNG
# ## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
# ## ANGEWANDT AUF SEQUENZIERTES MODELL
# ######################################################################
# ##
# 
# #list.model.lon.seq <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = 8)
# cl <- makeCluster(getOption("cl.cores", n.cpu))
# list.model.lon.seq <- parApply(cl, model.max.lat.seq, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
# stopCluster(cl)
# 
# ## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
# model.max.lon.seq <- sapply(list.model.lon.seq, "[[", 2)
# rm(list.model.lon.seq)

######################################################################
######################################################################
## ROUTINE ZUM EINLESEN VON ERA-DATEN (ZONAL-WIND) IM NCDF-FORMAT
## UND AUFFINDEN DES JETSTREAMS AUF NORDHEMISPHÄRE
## source('~/Master_Thesis/02-r-code-git/locate_jetstream_polynomial_2d.r')
######################################################################
######################################################################


######################################################################
## AUFRUF WICHTIGER BIBLIOTHEKEN UND PAKETE
######################################################################
##

library(ncdf4)
library(parallel)
library(chron)

# eigenes package für least squares fit mit chebyshev polynomen
# install.packages("pckg.cheb_0.2.tar.gz", repos = NULL, type = "source")
library(pckg.cheb)

setwd("~/Master_Thesis/02-r-code-git/")
path <- "data/"
# path <- "/home/skiefer/era/raw/"
file <- "era-t63-1957-2016.nh-trop-inv.nc"  # Nordhemisphäre + Tropen


######################################################################
## KLEINE HILFSFUNKTIONEN
######################################################################
##

fun.fill <- function(x, n) {
  while (length(x) < n) {
    x <- c(x, NA)
  }
  return(x)
}


######################################################################
## EINLESEN DER DATEN
## ERA40 / ERA-INTERIM
## T63 - GRID - GAUSSIAN
## NORDHEMISPHÄRE & TROPEN
## 192 (lat) * 64 (lon)
######################################################################
##

nc <- nc_open(paste(path, file, sep = ""))
# print(nc)
u.monmean <- ncvar_get(nc, "var131") # U-Wind-Komponente
v.monmean <- ncvar_get(nc, "var132") # V-Wind-Komponente
# w.monmean <- ncvar_get(nc, "var135") # W-Wind-Komponente
# z.monmean <- ncvar_get(nc, "var129") # Geopotenzial
# t.monmean <- ncvar_get(nc, "var130") # Temperatur
# d.monmean <- ncvar_get(nc, "var155") # Divergenz

lon <- ncvar_get(nc, "lon") # Längengrad
lat <- ncvar_get(nc, "lat") # Breitengrad
lev <- ncvar_get(nc, "lev") # Drucklevel
date.help <- ncvar_get(nc, "time")

nc_close(nc)
rm(nc)

uv.monmean <- sqrt( u.monmean ** 2 + v.monmean **2 )

######################################################################
## VARIABLEN UND PARAMETER
######################################################################
##

n.cpu <- 24 # Anzahl der CPUs für parApply
n.order.lat <- 31 # Ordnung des Least-Square-Verfahrens für Fit über Breitengrad
n.order.lon <- 8 # Ordnung des Least-Square-Verfahrens für Fit über Längengrad
# n.order.lat.seq <- 3 # Ordnung des Least-Square-Verfahrens für sequentiellen Fit über Breitengrad
# len.seq <- 8 # Länge der ersten Sequenz des seq. Least-Squares

## Räumliche Auflösung
n.lat <- length(lat)
n.lon <- length(lon)

## Zeitliche Auflösung
dts = chron(dates. = date.help/24, origin. = c(month = 9,day = 1,year = 1957), format = "day mon year")
dts.month <- months(dts, abbreviate = TRUE)
dts.year <- years(dts)

## Zeitlich gemittelter Zonalwind
# u.mean <- apply(u.monmean,c(1,2),mean)
# u.std <- apply(u.monmean,c(1,2),sd)

## Meridional und zeitlich gemittelter Zonalwind
# u.mon.mer.mean <- apply(u.monmean, 2, mean)
# u.mon.mer.sd <- apply(u.mean, 2, sd)

## Meridional gemittelter Zonalwind
# u.monmean.mermean <- apply(u.monmean, c(2,3), mean)
# u.monmean.mersd <- apply(u.monmean, c(2,3), sd)



######################################################################
## LEAST SQUARES FIT 
## CHEBYSHEV POLYNOME 23-TER ORDNUNG
## AN ZONAL WIND IN MERIDIONALER RICHTUNG
######################################################################
##

# list.model.lat <- apply(u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
list.model.lat <- parApply(cl, u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
stopCluster(cl)
dim.list <- dim(list.model.lat)

## Chebyshev-Koeffizienten
cheb.coeff <- sapply(list.model.lat, "[[", 1)
cheb.coeff <- apply(array(data = cheb.coeff, dim = c((n.order.lat + 1), dim.list[1], dim.list[2])) , c(1,3), t)

## Gefiltertes Modell für Zonal-Wind
model.u <- sapply(list.model.lat, "[[", 2)
model.u <- apply(array(data = model.u, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)

## Erste Ableitung des gefilterten Modells für Zonalwind
model.u.deriv.1st <- sapply(list.model.lat, "[[", 3)
model.u.deriv.1st <- apply(array(data = model.u.deriv.1st, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)

## Extrema des Modells (Positionen und Werte)
model.extr.lat <- sapply(list.model.lat, "[[", 4)
model.extr.u <- sapply(list.model.lat, "[[", 5)
model.extr.lat <- sapply(model.extr.lat, fun.fill, n = 24)
model.extr.lat <- apply(array(model.extr.lat, c(24, dim.list[1], dim.list[2])), c(1,3), t)
model.extr.u <- sapply(model.extr.u, fun.fill, n = 24)
model.extr.u <- apply(array(model.extr.u, c(24, dim.list[1], dim.list[2])), c(1,3), t)

## Maxima des Modells (Positionen und Werte)
model.max.u <- apply(model.extr.u, c(1,3), max, na.rm = TRUE)
model.max.lat <- array(rep(0, 192*664), c(dim.list))
for (i in 1:dim.list[2]) {
  for (j in 1:dim.list[1]) {
    model.max.lat[j,i] <- model.extr.lat[j, which(model.extr.u[j,,i] == model.max.u[j,i]), i]
  }
}
rm(list.model.lat, dim.list)


######################################################################
## LEAST SQUARES FIT 
## CHEBYSHEV POLYNOME 8-TER ORDNUNG
## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
######################################################################
##

#list.model.lon <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
cl <- makeCluster(getOption("cl.cores", n.cpu))
list.model.lon <- parApply(cl, model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
stopCluster(cl)

## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
#model.max.lon <- list.model.lon, "[[", 2)
#rm(list.model.lon)


######################################################################
## FEHLERGRÖẞEN
## MSE
## RMSE
######################################################################
##

residuals.cheb <- u.monmean - model.u
#residuals.cheb.seq <- u.monmean - model.u.seq
mse <- sum(residuals.cheb ** 2) / length(residuals.cheb)
#mse.seq <- sum(residuals.cheb.seq **2) / length(residuals.cheb.seq)
rmse <- sqrt(sum(residuals.cheb ** 2) / length(residuals.cheb))
#rmse.seq <- sqrt(sum(residuals.cheb.seq **2) / length(residuals.cheb.seq))

## rmse.seq = 0.4079846  ## mse.seq = 0.1664514
## rmse     = 0.2911683  ## mse     = 0.08477901


######################################################################
######################################################################
save.image()



######################################################################
## Berechnung von Mean und Sd
## über fünf Jahre & saisonal
######################################################################
# dts.year.mn <- seq(1960, 2010, 5)
# 
# ind.mam <- which(dts.month == "Mar" | dts.month == "Apr" | dts.month == "May")
# ind.jja <- which(dts.month == "Jun" | dts.month == "Jul" | dts.month == "Aug")
# ind.son <- which(dts.month == "Sep" | dts.month == "Oct" | dts.month == "Nov")
# ind.djf <- which(dts.month == "Dec" | dts.month == "Jan" | dts.month == "Feb")
# 
# ## Mittelwerte global
# u.seas.mam.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.mam.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.jja.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.jja.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.son.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.son.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.djf.mean <- array( NA , dim = c(n.lon, n.lat, 11))
# u.seas.djf.sd <- array( NA , dim = c(n.lon, n.lat, 11))
# 
# ## Mittelwerte meridional *???*
# u.mer.seas.mam.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.mam.sd <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.jja.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.jja.sd <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.son.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.son.sd <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.djf.mean <- array( NA , dim = c(n.lat, 11))
# u.mer.seas.djf.sd <- array( NA , dim = c(n.lat, 11))
# 
# for (i in seq(1, 11)) {
#   print(i)
#   yr.i <- dts.year.mn[i]
#   ind.yr <- which(dts.year ==  yr.i | dts.year == (yr.i + 1) | dts.year == (yr.i + 2) | dts.year == (yr.i + 3) | dts.year == (yr.i + 4) )
#   ## Mar Apr May
#   ind.mam.yr <- intersect(ind.yr, ind.mam)
#   u.seas.mam.mean[,,i] <- apply(u.monmean[,, ind.mam.yr], c(1,2), mean)
#   u.seas.mam.sd[,,i] <- apply(u.monmean[,, ind.mam.yr], c(1,2), sd)
#   u.mer.seas.mam.mean[,i] <- apply(u.monmean[,, ind.mam.yr], 2, mean)
#   u.mer.seas.mam.sd[,i] <- apply(u.monmean[,, ind.mam.yr], 2, sd)
#   ## Jun Jul Aug
#   ind.jja.yr <- intersect(ind.yr, ind.jja)
#   u.seas.jja.mean[,,i] <- apply(u.monmean[,, ind.jja.yr], c(1,2), mean)
#   u.seas.jja.sd[,,i] <- apply(u.monmean[,, ind.jja.yr], c(1,2), sd)
#   u.mer.seas.jja.mean[,i] <- apply(u.monmean[,, ind.jja.yr], 2, mean)
#   u.mer.seas.jja.sd[,i] <- apply(u.monmean[,, ind.jja.yr], 2, sd)
#   ## Sep Oct Nov
#   ind.son.yr <- intersect(ind.yr, ind.son)
#   u.seas.son.mean[,,i] <- apply(u.monmean[,, ind.son.yr], c(1,2), mean)
#   u.seas.son.sd[,,i] <- apply(u.monmean[,, ind.son.yr], c(1,2), sd)
#   u.mer.seas.son.mean[,i] <- apply(u.monmean[,, ind.son.yr], 2, mean)
#   u.mer.seas.son.sd[,i] <- apply(u.monmean[,, ind.son.yr], 2, sd)
#   ## Dec Jan Feb
#   ind.djf.yr <- intersect(ind.yr, ind.djf)
#   u.seas.djf.mean[,,i] <- apply(u.monmean[,, ind.djf.yr], c(1,2), mean)
#   u.seas.djf.sd[,,i] <- apply(u.monmean[,, ind.djf.yr], c(1,2), sd)
#   u.mer.seas.djf.mean[,i] <- apply(u.monmean[,, ind.djf.yr], 2, mean)
#   u.mer.seas.djf.sd[,i] <- apply(u.monmean[,, ind.djf.yr], 2, sd)
#   ## Löschen von Übergangsvariablen
#   rm(yr.i, ind.yr, ind.mam.yr, ind.jja.yr, ind.son.yr, ind.djf.yr, i)
# }
# 
# max(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
# min(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
# range(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
# 
# max(u.seas.mam.mean)
# min(u.seas.mam.mean)
# range(u.seas.mam.mean)
# 
# max(u.seas.jja.mean)
# min(u.seas.jja.mean)
# range(u.seas.jja.mean)
# 
# max(u.seas.son.mean)
# min(u.seas.son.mean)
# range(u.seas.son.mean)
# 
# max(u.seas.djf.mean)
# min(u.seas.djf.mean)
# range(u.seas.djf.mean)
# 
# 
# image.plot(lon, lat, u.mean+u.std)
# contour(lon, lat, u.std[,,1], add=TRUE)
# addland(col= "grey50", lwd = 1)
# 
# cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
# list.lat.m.sd <- parApply(cl, (u.mean[,] - u.std[,]), 1, pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
# list.lat.mn <- parApply(cl, u.mean[,], 1, pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
# list.lat.p.sd <- parApply(cl, (u.mean[,] + u.std[,]), 1, pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
# stopCluster(cl)
# 
# model.extr.lat.m.sd <- sapply(list.lat.m.sd, "[[", 4)
# model.extr.lat.mn <- sapply(list.lat.mn, "[[", 4)
# model.extr.lat.p.sd <- sapply(list.lat.m.sd, "[[", 4)
# 
# model.extr.u.m.sd <- sapply(list.lat.m.sd, "[[", 5)
# model.extr.u.mn <- sapply(list.lat.mn, "[[", 5)
# model.extr.u.p.sd <- sapply(list.lat.p.sd, "[[", 5)
# 
# model.extr.lat.m.sd <- sapply(model.extr.lat.m.sd, fun.fill, n = 16)
# model.extr.lat.mn <- sapply(model.extr.lat.mn, fun.fill, n = 16)
# model.extr.lat.p.sd <- sapply(model.extr.lat.p.sd, fun.fill, n = 16)
# 
# model.extr.u.m.sd <- sapply(model.extr.u.m.sd, fun.fill, n = 16)
# model.extr.u.mn <- sapply(model.extr.u.mn, fun.fill, n = 16)
# model.extr.u.p.sd <- sapply(model.extr.u.p.sd, fun.fill, n = 16)
# 
# model.max.u.m.sd <- apply(model.extr.u.m.sd, 2, max, na.rm = TRUE)
# model.max.u.mn <- apply(model.extr.u.mn, 2, max, na.rm = TRUE)
# model.max.u.p.sd <- apply(model.extr.u.p.sd, 2, max, na.rm = TRUE)
# 
# model.max.lat.m.sd <- array(rep(0, 192))
# model.max.lat.mn <- array(rep(0, 192))
# model.max.lat.p.sd <- array(rep(0, 192))
# 
# for (i in 1:192) {
#   model.max.lat.m.sd[i] <- model.extr.lat.m.sd[which(model.extr.u.m.sd[,i] == model.max.u.m.sd[i]), i]
#   model.max.lat.mn[i] <- model.extr.lat.mn[which(model.extr.u.mn[,i] == model.max.u.mn[i]), i]
#   model.max.lat.p.sd[i] <- model.extr.lat.p.sd[which(model.extr.u.p.sd[,i] == model.max.u.p.sd[i]), i]
# }
# 
# list.lon.m.sd <- pckg.cheb:::cheb.fit(d = model.max.lat.m.sd, x.axis = lon, n = 11)
# list.lon.mn <- pckg.cheb:::cheb.fit(d = model.max.lat.mn, x.axis = lon, n = 11)
# list.lon.p.sd <- pckg.cheb:::cheb.fit(d = model.max.lat.p.sd, x.axis = lon, n = 11)
# 
# model.max.lon.m.sd <- list.lon.m.sd[[2]]
# model.max.lon.mn <- list.lon.mn[[2]]
# model.max.lon.p.sd <- list.lon.p.sd[[2]]
# 
# 
# lines(lon, model.max.lon.m.sd)
# lines(lon, model.max.lon.mn)
# lines(lon, model.max.lon.p.sd)




####################################################################################################
########## ableitung des drehimpulses ##############################################################
########## aus zonal wind ##########################################################################
####################################################################################################
### ref: m = 
### formel noch inkorrekt
### keine schleife benutzen
##
# m <- matrix(NA,n.lon,n.lat)
# for (i in 1:n.lon){
#   for (j in 1:n.lat){
#     m[i,j] <- u.era.t63.monmean[i,j,1]*cos(lat.era.t63[j]) + 1/86400*u.era.t63.monmean[i,j,1]**2*cos(lat.era.t63[j])**2
#   }
# }
# #m <- u.era.t63.monmean*cos(lat.era.t63)
# 




# ######################################################################
# ## LEAST SQUARES FIT ÜBER **SEQUENZEN** (l=8)
# ## CHEBYSHEV POLYNOME 3-TER ORDNUNG
# ## AN ZONAL-WIND IN MERIDIONALER RICHTUNG
# ######################################################################
# ##
# 
# # list.model.lat.seq <- apply(u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
# list.model.lat.seq <- parApply(cl, u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# stopCluster(cl)
# dim.list <- dim(list.model.lat.seq)
# 
# ## Gefiltertes Modell für Zonal-Wind
# model.u.seq <- sapply(list.model.lat.seq, "[[", 1)
# model.u.seq <- apply(array(data = model.u.seq, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Erste Ableitung des gefilterten Modells für Zonalwind
# model.u.deriv.1st.seq <- sapply(list.model.lat.seq, "[[", 2)
# model.u.deriv.1st.seq <- apply(array(data = model.u.deriv.1st.seq, dim = c(n.lon, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Extrema des Modells (Positionen und Werte)
# model.extr.lat.seq <- sapply(list.model.lat.seq, "[[", 3)
# model.extr.lat.seq <- sapply(model.extr.lat.seq, fun.fill, n = 24)
# model.extr.lat.seq <- apply(array(model.extr.lat.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# model.extr.u.seq <- sapply(list.model.lat.seq, "[[", 4)
# model.extr.u.seq <- sapply(model.extr.u.seq, fun.fill, n = 24)
# model.extr.u.seq <- apply(array(model.extr.u.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# 
# ## Maxima des Modells (Positionen und Werte)
# model.max.u.seq <- apply(model.extr.u.seq, c(1,3), max, na.rm = TRUE)
# model.max.lat.seq <- array(rep(0, dim.list[1]*dim.list[2]), c(dim.list))
# for (i in 1:dim.list[2]) {
#   for (j in 1:dim.list[1]) {
#     model.max.lat.seq[j,i] <- model.extr.lat.seq[j, which(model.extr.u.seq[j,,i] == model.max.u.seq[j,i]), i]
#   }
# }
# rm(list.model.lat.seq, dim.list)
# 
# 
# ######################################################################
# ## LEAST SQUARES FIT 
# ## CHEBYSHEV POLYNOME 8-TER ORDNUNG
# ## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
# ## ANGEWANDT AUF SEQUENZIERTES MODELL
# ######################################################################
# ##
# 
# #list.model.lon.seq <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = 8)
# cl <- makeCluster(getOption("cl.cores", n.cpu))
# list.model.lon.seq <- parApply(cl, model.max.lat.seq, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
# stopCluster(cl)
# 
# ## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
# model.max.lon.seq <- sapply(list.model.lon.seq, "[[", 2)
# rm(list.model.lon.seq)

## source('~/Master_Thesis/pckg.cheb/R/functions-chebyshev.r')
##
## library(devtools)
## library(roxygen2)
##
## Build and Reload Package:  'Ctrl + Shift + B'
## Check Package:             'Ctrl + Shift + E'
## Test Package:              'Ctrl + Shift + T'


##
#' @title Scaling of X-Axis
#' @param x.axis ursprüngliche beliebige X-Achse (Vektor)
#' @return x.cheb.scaled skalierte X-Achse (Vektor)
#' @description
#' \code{cheb.scale} skaliert beliebige X-Achse auf Achse, die für Polynom-fits verträglich ist.
#' @examples
#' x.axis <- c(0:30)
#' x.cheb.scaled <- cheb.scale(x.axis)
cheb.scale <- function(x.axis, x.val = NULL) {#, scale) {
  ## Funktion zur Skalierung von Stützpunkten
  ## von beliebigen Gittern auf [-1, 1]
  ## ##
  x.cheb.scaled <- 2 * (x.axis - min(x.axis)) / (max(x.axis) - min(x.axis)) -1
  if ( x.val == NULL) {
    return(x.cheb.scaled)
  }
  if (x.val != NULL) {
    x.val.scaled <- 2 * (x.val - min(x.axis)) / (max(x.axis) - min(x.axis)) - 1
    return(x.val.scaled)
  }
}


##
#' @title Rescaling of X-Axis
#' @param x.cheb skalierte X-Achse (Skalar oder Vektor)
#' @param x.axis beliebige X-Achse (Vektor)
#' @return x.rescaled reskalierte X-Achse (Skalar oder Sektor)
#' @description
#' cheb.rescale reskaliert die für den Fit erzeugte Achse auf die Ursprüngliche
#' @examples
#' x.rescaled <- cheb.rescale(x.cheb, x.axis)
cheb.rescale <- function(x.cheb, x.axis) {
  ## Funktion zur Reskalierung vom [-1, 1]-Gitter
  ## auf das Ursprungsgitter (in diesem Fall - Lat)
  ## ##
  if (x.cheb >= -1 & x.cheb <= 1) {
    x.rescaled <- (1/2 * (x.cheb + 1) * (max(x.axis) - min(x.axis))) + x.axis[1]
    return(x.rescaled)
  } else
    print("Error: x.cheb went out of boundaries (less -1 or greater 1).")
}


##
#' @title Generating Chebyshev Polynomials of first kind
#' @param x.axis beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.t Chebyshev-Polynome Erster Art (Vektor)
#' @description
#' cheb.1st erzeugt Chebyshev Polynome erster Art aus beliebiger X-Achse
#' @examples
#' cheb.t <- cheb.1st(x.axis, n)
cheb.1st <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Erster Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis  ### ###
  m <- n + 1
  # Rekursionsformel Wiki / Bronstein
  cheb.t.0 <- 1;  cheb.t.1 <- x.cheb;
  cheb.t <- cbind(cheb.t.0, cheb.t.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.t.i <- 2 * x.cheb * cheb.t[,(i - 1)] - cheb.t[,(i - 2)]
      cheb.t <- cbind(cheb.t, cheb.t.i)
      rm(cheb.t.i)
    }
  }
  return(cheb.t)
}


##
#' @title Generating Chebyshev Polynomials of second kind
#' @param x.axis beliebigie X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.u Chebyshev-Polynome Zweiter Art (Vektor)
#' @description
#' cheb.2nd erzeugt Chebyshev Polynome zweiter Art aus beliebiger X-Achse
#' @examples
#' cheb.u <- cheb.2nd(x.axis, n)
cheb.2nd <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Zweiter Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis
  m <- n + 1
  cheb.u.0 <- 1; cheb.u.1 <-  2*x.cheb
  cheb.u <- cbind(cheb.u.0, cheb.u.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.u.i <- 2 * x.cheb * cheb.u[,(i - 1)] - cheb.u[,(i - 2)]
      cheb.u <- cbind(cheb.u, cheb.u.i)
      rm(cheb.u.i)
    }
  }
  return(cheb.u)
}


##
#' @title Calculation of Values of the model fit
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model gefiltertes Modell (Skalar oder Vektor)
#' @description
#' cheb.model berechnet aus den Chebyshev-Koeffizienten die Y-Werte
#' @examples
#' cheb.model <- cheb.model.filter(x.axis, cheb.coeff)
cheb.model.filter <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte aus X-Stellen und Cheb-Koeffizienten
  ## ##
  n <- length(cheb.coeff) - 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.model <- cheb.t %*% cheb.coeff
  return(cheb.model)
}


##
#' @title Calculation of the values of the first derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv.1st Erste Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.1st berechnet aus den Chebyshev-Koeffizienten die Werte der ersten Ableitung
#' @examples
#' cheb.model.deriv <- cheb.deriv.1st(x.axis, cheb.coeff)
cheb.deriv.1st <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte der Ableitung des Modells
  ## aus X-Stellen und Chebyshev-Koeffizienten
  ## ##
  if (length(x.axis) != 0) { ### Überprüfen, ob nötig
    n <- length(cheb.coeff) - 1
    m <- n + 1
    cheb.u <- cheb.2nd(x.axis, n)

    # berechnung der ableitung der polynome erster art
    # rekursionsformel 0
    # dT/dx = n * U_(n-1)
    cheb.t.deriv <- if (length(x.axis) == 1) (2:m)*t(cheb.u[,1:n]) else t((2:m)*t(cheb.u[,1:n]))
    cheb.model.deriv.1st <- cheb.t.deriv %*% cheb.coeff[2:m]
    return(cheb.model.deriv.1st)
  }
}


##
#' @title Calculation of the values of the second derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv Zweite Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.2nd berechnet aus den Chebyshev-Koeffizienten die Werte der zweiten Ableitung
#' @examples
#' cheb.model.deriv.2nd <- cheb.deriv.2nd(x.axis, cheb.coeff)
cheb.deriv.2nd <- function(x.axis, cheb.coeff) {
  n <- length(cheb.coeff) - 1
  m <- n + 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.u <- cheb.2nd(x.axis, n)
  x.cheb <- cheb.scale(x.axis)
  cheb.t.deriv.2nd <- t((((1:m) ** 2) + (1:m)) %*% t(1 / (x.cheb ** 2 - 1)) * t(cheb.t - cheb.u))
  cheb.t.deriv.2nd[1,] <- (-1) * ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.t.deriv.2nd[length(x.cheb),] <- ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.model.deriv.2nd <- cheb.t.deriv.2nd %*% cheb.coeff
  return(cheb.model.deriv.2nd)
}


##
#' @title Curve Fitting with Chebyshev Polynomials
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit <- function(d, x.axis, n, bc.harmonic = FALSE){
  # Fallunterscheidung für harmonische Randbedingung
  if (bc.harmonic == FALSE) {
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  } else if (bc.harmonic == TRUE) {
    d <- c(d, d[1])
    x.axis <- c(x.axis, (x.axis[1] + 360))
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  }

  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # löschen des letzten eintrags für den harmonischen fall
  cheb.model <- if (bc.harmonic == TRUE) cheb.model[-(length(cheb.model))]

  # Übergabe der Variablen
  return(cheb.model)
}


##
#' @title Curve Fitting with Chebyshev Polynomials over Sequences
#' @description
#' Fittet ein Chebyshev Polynom beliebiger Ordnung an einen sequenzierten Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.fit.seq(d, x.axis, n, l)
cheb.fit.seq <- function(d, x.axis, n, l, bc.harmonic = FALSE){
  x.mat <- matrix(x.axis, ncol = l, byrow = TRUE)
  d.mat <- matrix(d, ncol = l, byrow = TRUE)
  end.loop <- length(x.mat[,1])

  # schleife über sequenzen des Datensatzes
  for (i in 1:end.loop) {
    # erstellung der sequenzen und fallunterscheidung für harmonische randbedingung
    if (bc.harmonic == FALSE) {
      d.seq <- if (i != end.loop) c(d.mat[i,], d.mat[(i + 1), 1]) else c(d.mat[i,])
      x.seq <- if (i != end.loop) c(x.mat[i,], x.mat[(i + 1), 1]) else c(x.mat[i,])
    } else if (bc.harmonic == TRUE) {
      d.seq <- if (i != end.loop) c(d.mat[i,], d.mat[(i + 1), 1]) else c(d.mat[i,], d.mat[1,1])
      x.seq <- if (i != end.loop) c(x.mat[i,], x.mat[(i + 1), 1]) else c(x.mat[i,], x.mat[1,1] + 360)
    }
    x.cheb.seq <- cheb.scale(x.seq)
    cheb.t.seq <- cheb.1st(x.seq, n)

    ## modell berechnungen
    # berechnung der koeffizienten des polyfits
    cheb.coeff.seq <- solve(t(cheb.t.seq) %*% cheb.t.seq) %*% t(cheb.t.seq) %*% d.seq
    cheb.coeff <- if (i == 1) cheb.coeff.seq else cbind(cheb.coeff, cheb.coeff.seq)
    # berechnung des gefilterten modells
    cheb.model.seq <- cheb.model.filter(x.cheb.seq, cheb.coeff.seq)
    if (bc.harmonic == FALSE) {
      cheb.model <- if (i == 1) cheb.model.seq[-(l + 1)] else if (i > 1 & i != end.loop) c(cheb.model, cheb.model.seq[-(l + 1)]) else c(cheb.model, cheb.model.seq)
    } else if (bc.harmonic == TRUE) {
      cheb.model <- if (i == 1) cheb.model.seq[-(l + 1)] else if (i > 1 & i != end.loop) c(cheb.model, cheb.model.seq[-(l + 1)]) else c(cheb.model, cheb.model.seq[-(l + 1)])
    }
  }

  ## übergabe der variable
  return(cheb.model)
}


##
#' @title Curve Fitting with Chebyshev Polynomials and Finding of its Roots
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit.roots <- function(d, x.axis, n, bc.harmonic = FALSE, roots.bound.l = NULL, roots.bound.u = NULL){
  library(rootSolve)
  # Fallunterscheidung für harmonische Randbedingung
  if (bc.harmonic == FALSE) {
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  } else if (bc.harmonic == TRUE){
    d <- c(d, d[1])
    x.axis <- c(x.axis, (x.axis[1] + 360))
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  }

  #  cheb.u <- cheb.2nd(x.axis, n)
  #  m <- n + 1
  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # berechnung des abgeleiteten modells
  cheb.model.deriv.1st <- cheb.deriv.1st(x.cheb, cheb.coeff)
  # löschen der letzten einträge des modells und der ableitung für den harmonischen fall
  cheb.model <- if (bc.harmonic == TRUE) cheb.model[-(length(cheb.model))]
  cheb.model.deriv.1st <- if (bc.harmonic == TRUE) cheb.model.deriv.1st[-(length(cheb.model.deriv.1st))]

  # berechnung der nullstellen
  lower <- cheb.scale(x.axis, x.val = roots.bound.l)
  upper <- cheb.scale(x.axis, x.val = roots.bound.u)
  extr <- rootSolve::uniroot.all(cheb.deriv.1st, cheb.coeff = cheb.coeff, lower, upper)
  # reskalierung der Nullstellen auf normale Lat- Achse
  x.extr <- if (length(extr) != 0) cheb.rescale(extr, x.axis = x.axis)
  y.extr <- if (length(extr) != 0) cheb.model.filter(x.axis = extr, cheb.coeff = cheb.coeff)

  cheb.list <- list(cheb.coeff = cheb.coeff, cheb.model = cheb.model, cheb.model.deriv.1st = cheb.model.deriv.1st, x.extr = x.extr, y.extr = y.extr)
  return(cheb.list)
}



## source('~/Master_Thesis/pckg.cheb/R/functions-chebyshev.r')
##
## library(devtools)
## library(roxygen2)
##
## Build and Reload Package:  'Ctrl + Shift + B'
## Check Package:             'Ctrl + Shift + E'
## Test Package:              'Ctrl + Shift + T'


##
#' @title Scaling of X-Axis
#' @param x.axis ursprüngliche beliebige X-Achse (Vektor)
#' @return x.cheb.scaled skalierte X-Achse (Vektor)
#' @description
#' \code{cheb.scale} skaliert beliebige X-Achse auf Achse, die für Polynom-fits verträglich ist.
#' @examples
#' x.axis <- c(0:30)
#' x.cheb.scaled <- cheb.scale(x.axis)
cheb.scale <- function(x.axis) {#, scale) {
  ## Funktion zur Skalierung von Stützpunkten
  ## von beliebigen Gittern auf [-1, 1]
  ## ##
  #  if (type == "cheb") {
  x.cheb.scaled <- (2 * (x.axis - x.axis[1]) / (max(x.axis) - min(x.axis))) - 1
  #  }
  return(x.cheb.scaled)
}


##
#' @title Rescaling of X-Axis
#' @param x.cheb skalierte X-Achse (Skalar oder Vektor)
#' @param x.axis beliebige X-Achse (Vektor)
#' @return x.rescaled reskalierte X-Achse (Skalar oder Sektor)
#' @description
#' cheb.rescale reskaliert die für den Fit erzeugte Achse auf die Ursprüngliche
#' @examples
#' x.rescaled <- cheb.rescale(x.cheb, x.axis)
cheb.rescale <- function(x.cheb, x.axis) {
  ## Funktion zur Reskalierung vom [-1, 1]-Gitter
  ## auf das Ursprungsgitter (in diesem Fall - Lat)
  ## ##
  if (x.cheb >= -1 & x.cheb <= 1) {
    x.rescaled <- (1/2 * (x.cheb + 1) * (max(x.axis) - min(x.axis))) + x.axis[1]
    return(x.rescaled)
  } else
    print("Error: x.cheb went out of boundaries (less -1 or greater 1).")
}


##
#' @title Generating Chebyshev Polynomials of first kind
#' @param x.axis beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.t Chebyshev-Polynome Erster Art (Vektor)
#' @description
#' cheb.1st erzeugt Chebyshev Polynome erster Art aus beliebiger X-Achse
#' @examples
#' cheb.t <- cheb.1st(x.axis, n)
cheb.1st <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Erster Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis  ### ###
  m <- n + 1
  # Rekursionsformel Wiki / Bronstein
  cheb.t.0 <- 1;  cheb.t.1 <- x.cheb;
  cheb.t <- cbind(cheb.t.0, cheb.t.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.t.i <- 2 * x.cheb * cheb.t[,(i - 1)] - cheb.t[,(i - 2)]
      cheb.t <- cbind(cheb.t, cheb.t.i)
      rm(cheb.t.i)
    }
  }
  return(cheb.t)
}


##
#' @title Generating Chebyshev Polynomials of second kind
#' @param x.axis beliebigie X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.u Chebyshev-Polynome Zweiter Art (Vektor)
#' @description
#' cheb.2nd erzeugt Chebyshev Polynome zweiter Art aus beliebiger X-Achse
#' @examples
#' cheb.u <- cheb.2nd(x.axis, n)
cheb.2nd <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Zweiter Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis
  m <- n + 1
  cheb.u.0 <- 1; cheb.u.1 <-  2*x.cheb
  cheb.u <- cbind(cheb.u.0, cheb.u.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.u.i <- 2 * x.cheb * cheb.u[,(i - 1)] - cheb.u[,(i - 2)]
      cheb.u <- cbind(cheb.u, cheb.u.i)
      rm(cheb.u.i)
    }
  }
  return(cheb.u)
}


##
#' @title Calculation of Values of the model fit
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model gefiltertes Modell (Skalar oder Vektor)
#' @description
#' cheb.model berechnet aus den Chebyshev-Koeffizienten die Y-Werte
#' @examples
#' cheb.model <- cheb.model.filter(x.axis, cheb.coeff)
cheb.model.filter <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte aus X-Stellen und Cheb-Koeffizienten
  ## ##
  n <- length(cheb.coeff) - 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.model <- cheb.t %*% cheb.coeff
  return(cheb.model)
}


##
#' @title Calculation of the values of the first derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv.1st Erste Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.1st berechnet aus den Chebyshev-Koeffizienten die Werte der ersten Ableitung
#' @examples
#' cheb.model.deriv <- cheb.deriv.1st(x.axis, cheb.coeff)
cheb.deriv.1st <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte der Ableitung des Modells
  ## aus X-Stellen und Chebyshev-Koeffizienten
  ## ##
  if (length(x.axis) != 0) { ### Überprüfen, ob nötig
    n <- length(cheb.coeff) - 1
    m <- n + 1
    cheb.u <- cheb.2nd(x.axis, n)

    # berechnung der ableitung der polynome erster art
    # rekursionsformel 0
    # dT/dx = n * U_(n-1)
    cheb.t.deriv <- if (length(x.axis) == 1) (2:m)*t(cheb.u[,1:n]) else t((2:m)*t(cheb.u[,1:n]))
    cheb.model.deriv.1st <- cheb.t.deriv %*% cheb.coeff[2:m]
    return(cheb.model.deriv.1st)
  }
}


##
#' @title Calculation of the values of the second derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv Zweite Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.2nd berechnet aus den Chebyshev-Koeffizienten die Werte der zweiten Ableitung
#' @examples
#' cheb.model.deriv.2nd <- cheb.deriv.2nd(x.axis, cheb.coeff)
cheb.deriv.2nd <- function(x.axis, cheb.coeff) {
  n <- length(cheb.coeff) - 1
  m <- n + 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.u <- cheb.2nd(x.axis, n)
  x.cheb <- cheb.scale(x.axis)
  cheb.t.deriv.2nd <- t((((1:m) ** 2) + (1:m)) %*% t(1 / (x.cheb ** 2 - 1)) * t(cheb.t - cheb.u))
  cheb.t.deriv.2nd[1,] <- (-1) * ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.t.deriv.2nd[length(x.cheb),] <- ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.model.deriv.2nd <- cheb.t.deriv.2nd %*% cheb.coeff
  return(cheb.model.deriv.2nd)
}


##
#' @title Curve Fitting with Chebyshev Polynomials
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit <- function(d, x.axis, n, harmonic = FALSE){
  # Fallunterscheidung für harmonische Randbedingung
  if (harmonic == FALSE) {
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  } else if (harmonic == TRUE) {
    d <- c(d, d[1])
    x.axis <- c(x.axis, (x.axis[1] + 360))
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  }

  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # löschen des letzten eintrags für den harmonischen fall
  cheb.model <- if (harmonic == TRUE) cheb.model[-(length(cheb.model))]

  # Übergabe der Variablen
  return(cheb.model)
}



##
#' @title Curve Fitting with Chebyshev Polynomials and Finding of its Roots
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit.roots <- function(d, x.axis, n){
  library(rootSolve)
  x.cheb <- cheb.scale(x.axis)
  cheb.t <- cheb.1st(x.axis, n)
  #  cheb.u <- cheb.2nd(x.axis, n)
  #  m <- n + 1
  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # berechnung des abgeleiteten modells
  cheb.model.deriv.1st <- cheb.deriv.1st(x.cheb, cheb.coeff)

  # berechnung der nullstellen
  extr <- rootSolve::uniroot.all(cheb.deriv.1st, cheb.coeff = cheb.coeff, lower = (-1), upper = 1)
  # reskalierung der Nullstellen auf normale Lat- Achse
  x.extr <- if (length(extr) != 0) cheb.rescale(extr, x.axis = x.axis)
  y.extr <- if (length(extr) != 0) cheb.model.filter(x.axis = extr, cheb.coeff = cheb.coeff)

  cheb.list <- list(cheb.coeff = cheb.coeff, cheb.model = cheb.model, cheb.model.deriv.1st = cheb.model.deriv.1st, x.extr = x.extr, y.extr = y.extr)
  return(cheb.list)
}



##
#' @title Curve Fitting with Chebyshev Polynomials over Sequences
#' @description
#' Fittet ein Chebyshev Polynom beliebiger Ordnung an einen sequenzierten Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.fit.seq(d, x.axis, n, l)
cheb.fit.seq <- function(d, x.axis, n, l, harmonic = FALSE){
  x.mat <- matrix(x.axis, ncol = l, byrow = TRUE)
  d.mat <- matrix(d, ncol = l, byrow = TRUE)
  end.loop <- length(x.mat[,1])

  # schleife über sequenzen des Datensatzes
  for (i in 1:end.loop) {
    # erstellung der sequenzen und fallunterscheidung für harmonische randbedingung
    if (harmonic == FALSE) {
      d.seq <- if (i != end.loop) c(d.mat[i,], d.mat[(i + 1), 1]) else c(d.mat[i,])
      x.seq <- if (i != end.loop) c(x.mat[i,], x.mat[(i + 1), 1]) else c(x.mat[i,])
    } else if (harmonic == TRUE) {
      d.seq <- if (i != end.loop) c(d.mat[i,], d.mat[(i + 1), 1]) else c(d.mat[i,], d.mat[1,1])
      x.seq <- if (i != end.loop) c(x.mat[i,], x.mat[(i + 1), 1]) else c(x.mat[i,], x.mat[1,1] + 360)
    }
    x.cheb.seq <- cheb.scale(x.seq)
    cheb.t.seq <- cheb.1st(x.seq, n)

    ## modell berechnungen
    # berechnung der koeffizienten des polyfits
    cheb.coeff.seq <- solve(t(cheb.t.seq) %*% cheb.t.seq) %*% t(cheb.t.seq) %*% d.seq
    cheb.coeff <- if (i == 1) cheb.coeff.seq else cbind(cheb.coeff, cheb.coeff.seq)
    # berechnung des gefilterten modells
    cheb.model.seq <- cheb.model.filter(x.cheb.seq, cheb.coeff.seq)
    if (harmonic == FALSE) {
      cheb.model <- if (i == 1) cheb.model.seq[-(l + 1)] else if (i > 1 & i != end.loop) c(cheb.model, cheb.model.seq[-(l + 1)]) else c(cheb.model, cheb.model.seq)
    } else if (harmonic == TRUE) {
      cheb.model <- if (i == 1) cheb.model.seq[-(l + 1)] else if (i > 1 & i != end.loop) c(cheb.model, cheb.model.seq[-(l + 1)]) else c(cheb.model, cheb.model.seq[-(l + 1)])
    }
  }

  ## übergabe der variable
  return(cheb.model)
}

#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        cancel = function(job_ids, user = private$user, host = private$host) {
            job_ids <- paste(job_ids, collapse = ",")

            stain_ssh(user, host, paste("scancel", job_ids))
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host,
                          submit_dir = "~/stain", dependency_list = "") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")

                # Add any dependencies to sbatch command.
                history <- self$submission_history()$job_id
                dependencies <- sbatch_dependency_list(dependency_list, history)

                if (nchar(dependencies) > 0) {
                    dependencies <- sbatch_opt("dependency")(dependencies)
                }

                submit_cmd <- paste("sbatch",
                                    dependencies,
                                    "submit.slurm")
                submit_cmd <- paste("cd", job_dir, "&&", submit_cmd)
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir = "~/stain") {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        submission_history = function() {
            # `stain_sub_history` will warn if submission history is empty.
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                return(history)
            }
        },
        fetch_job_states = function(user = private$user, host = private$host) {
            job_ids <- stain_sub_history(self$dir)$job_id

            verify_state_table <- function(state_table) {
                if (nrow(status_table) > 0) {
                    return(state_table)
                } else {
                    job_ids <- paste(job_ids, collapse = ", ")
                    message(paste("No statuses found for job ids:", job_ids))
                }
            }

            fetch_squeue_table <- function() {
                tryCatch({
                    squeue_table <- stain_ssh_squeue(user, host, job_ids)
                    squeue_table <- squeue_table[, c("JOBID", "STATE")]
                    colnames(squeue_table) <- c("job_id", "state")
                    # Will throw error if data frame has no rows.
                    squeue_table$exit_code <- NA
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    squeue_table <- data.frame()
                }, finally = return(squeue_table))
            }

            fetch_sacct_table <- function() {
                tryCatch({
                    sacct_table <- stain_ssh_sacct(user, host, job_ids)
                    colnames(sacct_table) <- c("job_id", "state", "exit_code")
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    sacct_table <- data.frame()
                }, finally = return(sacct_table))
            }

            squeue_table <- fetch_squeue_table()
            sacct_table <- fetch_sacct_table()
            states <- rbind(squeue_table, sacct_table)
            states <- aggregate(states, list(states$job_id), function(x) {
                na.omit(x)[1]
            })[,-1]

            return(states)
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container_dir, options) {
            private$options <- options

            private$cat_main_file_magic(container_dir)
            private$write_slurm_script(container_dir)
        }
    ),
    private = list(
        options = NA,
        cat_main_file_magic = function(dir) {
            main_file <- ".default_stain_main.R"
            file <- paste0(dir, "/.stain/sources/", main_file)
            sourcing <- paste("sapply(list.files('./.stain/sources', full.names = TRUE)[!(list.files('./.stain/sources')) %in%",
                              paste0("'", main_file, "'"), "], source)")
            loading <- paste("sapply(list.files('./.stain/objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./.stain $PFSDIR
mkdir ./output
cd $PFSDIR

mkdir ./data
mv ./.stain/data/* ./data

module load hpc-ods
module load pandoc

R CMD BATCH ./.stain/sources/.default_stain_main.R

rm -rf ./data ./.stain

cp -r * $SLURM_SUBMIT_DIR/output"

            write(paste(private$options$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, "submit.slurm", sep = "/"))
        }
    )
)
                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

# not used

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

# not used. and slow

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    list1 <- df1$id
    list2 <- df2$id
    for (j in 1:length(list2)) {
        id <- list2[j]
        list[id] <- NA
        i <- match(id, list1)
        if (!is.na(i)) {
            list[id] <- j - i
        }
    }
    return (list)
}

# slow. not used

getperiodmapold <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
#        list12 <- stocklistperiod[period, 2][[1]]
#        for (i in 1:max) {
#            print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
#        }
        for (i in 1:max) {
            id <- list11$id[i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
                if (is.null(rise)) {
                    rise <- 0
                }
            }
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), rise, list11$id[[i]]))
        }
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
                                        #    list12 <- stocklistperiod[period, 2][[1]]
                                        #
                                        #    len <- nrow(list12)
                                        #    len <- len + 1

                                        #    for (i in 1:max) {
                                        #        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
                                        #    }

                                        #    len <- nrow(list11)
                                        #    len <- len + 1

        len <- nrow(list11)
        len <- len + 1
        for (i in 1:max) {
            id <- list11$id[len - i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
                if (is.null(rise)) {
                    rise <- 0
                }
            }
            
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), rise, list11$id[[len - i]]))
        }
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, mynames, topbottom, periodtext, maindate, olddate, days) {
    dev.new()
    colours <- rainbow(topbottom)
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE, col = colours[i], pch = i)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o", lty = i, col = colours[i], pch = i)
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(mynames[1]))
        legend(1, g_range[2], mynames, cex=0.8, lty=1:6, pch=1:25, col=colours) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (type == pricetype) {
        return (df$price)
    }
    if (type == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    normalize <- 0
    if (length(ids) > 1) {
        if (periodtext == "price") {
            normalize <- 1
        }
        if (periodtext == "index") {
            normalize <- 1
        }
    }
    
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, pricetype)
        perioddata[["text"]] <- pairs
        perioddatamap[["price"]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, indextype)
        perioddata[["text"]] <- pairs
        perioddatamap[["index"]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    dayset <- list()
    ls <- list()
    mynames <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        if (normalize == 1) {
                            str("minmax")
                            str(l)
                            mymin <- abs(min(l))
                            mymax <- abs(max(l))
                            if (mymin > mymax) {
                                mymax <- mymin
                            }
                            for (j in 1:length(l)) {
                                l[j] <- l[j] * 100 / mymax;
                            }
                            str(l)
                        }
                        
                        dayset <- append(dayset, bigretl[[2]])
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        mynames[c] <- df$name
                    }
                }
            }
        }
    }
    daynames <- names(dayset)
    olddate <- min(daynames)
    newdate <- max(daynames)
    displaychart(ls, mynames, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

#' Import data from Wildlife Computers ".tab" text files
#' 
#' @param x filename to be imported or a TDR dataset to be formated.
#' @param dt if TRUE function will return a data.table object, else, a data.frame.
#' @param ... Arguments to be passed to \code{\link{file}} such as \code{encoding}.
#' @details Wildlife Computers > Instrument helper > Save instrument readings > R format
#' @export
#' @keywords raw_processing
#' @import sqldf data.table
read.wcih <- function(x, dt = TRUE, ...) {
  stopifnot(require("data.table"))
  stopifnot(require("sqldf"))
  if (is.character(x)) {
    f <- file(x, ...)
    nms <- unlist(read.table(x, skip = 3, as.is = TRUE, nrows = 1))
    fmt <- list(skip = 4, header = FALSE, row.names = FALSE, sep = " ")
    x <- sqldf("select * from f", dbname = tempfile(), file.format = fmt)[ , -1]
  } else {
    nms <- names(x)
  }
  
  new_nms <- c(
    "Time" = "time", "Depth" = "depth", 
    "External Temperature" = "temp", "Light Level" = "light", 
    "int aX" = "ax", "int aY" = "ay", "int aZ" = "az", 
    "int mX" = "mx", "int mY" = "my", "int mZ" = "mz", 
    "Velocity" = "spd"
  )
  
  x <- setnames(as.data.table(x), new_nms[nms])
  x <- x[ , lapply(.SD, as.numeric)]
  x <- x[ , time := as.POSIXct(floor(time), origin = "1970-01-01", tz = 'UTC')]
  
  x <- if (dt) 
    data.table(x, key = "time")
  else 
    as.data.frame(x)
}

#' Identify Prey Catch attempts
#' 
#' @param x 3 axes acceleration table with time in the first column and acceleration 
#' axes in the following columns. Variables must be entitled "time" for time, 
#' "ax", "ay", and "az" for x, y and z accelerometer axes.
#' @param fs sampling frequency of the input data (Hz).
#' @param fc Cut-off frequency for the butterworth high pass filter (Hz)
#' @return returns a logical vector of prey catch attempts at 1 Hz frequency. 
#' Value is TRUE if the record belong to prey catch attempt FALSE otherwise.
#' @import data.table signal RcppRoll
#' @export
#' @keywords raw_processing
prey_catch_attempts <- function(x, fs = 16, fc = 2.64) {
  stopifnot(require("data.table"))
  stopifnot(require("signal"))
  stopifnot(require("RcppRoll"))
  # Generate Butterworth filter 
  # Critical frequencies of the filter: f_cutoff / (f_sampling/2)
  bf_pca  <- butter(3, W = fc / (0.5*fs), type = 'high')
  
  # Apply filter
  if (!is.data.table(x)) x <- data.table(x, key = "time")
  .f <- function(x) as.numeric(filtfilt(bf_pca, x))
  x <- x[ , 2:4 := lapply(.SD, .f), .SDcols = 2:4]
  gc()
  
  # 1 s fixed window standard deviation + aggregate data to 1 Hz
  x <- x[ , lapply(.SD, sd, na.rm = TRUE), by = time]
  # In case of NAs set ACC to zero
  nas <- lapply(x[ , 2:4, with = FALSE], is.na)
  nas_vector <- Reduce("|", nas)
  if (any(nas_vector)) {
    warning("NAs found and replaced by 0. NA proportion:", mean(nas_vector))
    x$ax[nas$ax] <- 0
    x$ay[nas$ay] <- 0
    x$az[nas$az] <- 0
  }
  gc()
  
  # 5 s moving window standard deviation
  .f <- function(x) c(0,0,roll_sd(x, 5),0,0)
  x <- x[ , 2:4 := lapply(.SD, .f), .SDcols = 2:4]
  gc()
  
  # kmean clutering: "high" = TRUE vs "low" = FALSE
  .f <- function(x) { 
    km_mod <- kmeans(x, 2)
    high_state <- which.max(km_mod$centers)
    as.logical(km_mod$cluster == high_state)
  }
  x <- x[ , 2:4 := lapply(.SD, .f), .SDcols = 2:4]
  
  # Aggregate and return to data.frame
  # records classified as PCA if the three axis are simultaneously in high state
  Reduce("&", x[ , time := NULL])
}

#' Compute swimming effort
#' 
#' @param fc Cut-off frequencies for the butterworth band pass filter (Hz)
#' @inheritParams prey_catch_attempts
#' @param rms Should the root mean square be used (instead of mean of absolute values) 
#' when averaging the acceleration to 1 Hz ?
#' @return returns a vector of swimming effort values at 1 Hz.
#' @details Only Y accelerometer axe is used to compute swimming effort.
#' @import data.table signal
#' @export
#' @keywords raw_processing
swimming_effort <- function(x, fs = 16, fc = c(0.4416, 1.0176), rms = FALSE) {
  stopifnot(require("data.table"))
  stopifnot(require("signal"))
  # Generate a Butterworth filter 
  # Critical frequencies of the filter: f_filter / (f_sampling/2)
  bf_swm  <-  butter(3, W = fc / (0.5*fs), type = 'pass')
  
  # Apply filter
  if (!is.data.table(x)) x <- data.table(x, key = "time")
  x <- x[ , ay := abs(as.numeric(filtfilt(bf_swm, ay)))]
  x <- x[ , c(2, 4) := NULL, with = FALSE] # remove unused "ax" & "az" columns
  
  # 1 s fixed window average + aggregate data to 1 Hz
  if (!rms) {
    x <- x[ , lapply(.SD, function(x) mean(abs(x), na.rm = TRUE)), by = time]
  } else {
    x <- x[ , lapply(.SD, function(x) sqrt(mean(x^2, na.rm = TRUE))), by = time]
  }
  x <- x$ay
}
globalVariables("ay")

#' Static acceleration
#' 
#' The raw acceleration is first filtered using a low pass butterworth filter. 
#' Then , the extracted signal can be scaled so that the norm of the the vector 
#' G is 1 at each second.
#' 
#' @param fc Cut-off frequency for the butterworth low pass filter (Hz)
#' @param Gscale Should the values be scaled by the norm of the static 
#' acceleration vector ?
#' @param agg_1hz Should the input be aggregated to 1 Hz ?
#' @inheritParams prey_catch_attempts
#' @return returns a data.frame with time, and X, Y and Z static accelearyion at 1 Hz.
#' @details This filtered acceleration can be used to compute pitch and roll angles
#' @import data.table signal
#' @keywords raw_processing
#' @export
static_acc <- function(x, fs = 16, fc = 0.20, Gscale = TRUE, agg_1hz = TRUE) {
  stopifnot(require("data.table"))
  stopifnot(require("signal"))
  # Generate a Butterworth filter 
  # Critical frequencies of the filter: f_filter / (f_sampling/2)
  bf_grav  <-  butter(3, W = fc / (0.5*fs), type = 'low')
  
  # Apply filter
  if (!is.data.table(x)) x <- data.table(x, key = "time")
  x <- x[ , 2:4 := lapply(.SD, function(x) as.numeric(filtfilt(bf_grav, x))), 
          .SDcols = 2:4]
  
  # 1 s fixed window average + aggregate data to 1 Hz
  if (agg_1hz) {
    x <- x[ , lapply(.SD, mean, na.rm = TRUE), by = time]
  }
  x <- setnames(x, c('time', 'axG', 'ayG', 'azG'))
  
  # Scale axis
  if (Gscale) {
    Gnorm <- sqrt(x$axG^2 + x$ayG^2 + x$azG^2)
    x <- x[ , 2:4 := lapply(.SD, function(x) x / Gnorm), .SDcols = 2:4]
  }
  
  as.data.frame(x)
}

#' Dynamic (Body) acceleration DBA
#' 
#' DBA is calculated by smoothing data for each axis to calculate the static 
#' acceleration (\code{\link{static_acc}}), and then subtracting it from 
#' the raw acceleration.
#' 
#' @param ... Parameters to be passed to \code{\link{static_acc}} (e.g \code{fc}).
#' @inheritParams static_acc
#' @return returns a data.frame with time, and X, Y and Z static accelearyion at 1 Hz.
#' @details This filtered acceleration can be used to compute ODBA and VeDBA.
#' @import data.table signal
#' @export
#' @keywords raw_processing
dynamic_acc <- function(x, fs = 16, agg_1hz = TRUE, ...) {
  static <- static_acc(copy(x), fs = fs, Gscale = FALSE, agg_1hz = FALSE, ...)
  x <- x[ , `:=`(2:4, Map("-", x[ , 2:4, with = FALSE], static[ , 2:4])), with = FALSE]
  rm(list = "static") ; gc()
  if (agg_1hz) {
    x <- x[ , lapply(.SD, mean, na.rm = TRUE), by = time]
  }
  as.data.frame(setnames(x, c("time", "axD", "ayD", "azD")))
}

#' Attitude angles from static accelation
#' 
#' @param object A data frame or TDR table including static acceleration variables 
#' entitled "axG", "ayG", and "azG" for X, Y, and Z axes of the accelerometer.
#' @export
#' @keywords raw_processing
pitch <- function(object) {
  -atan(object$axG/sqrt(object$ayG^2 + object$azG^2))
}

#' @rdname pitch
#' @export
#' @details For roll angle, the x axe is not necessary.
#' @return A vector of pitch/roll of the same length as \code{object}.
#' @keywords raw_processing
roll <- function(object) {
  atan2(object$ayG^2, object$azG)
}

#' Overall Dynamic Body Acceleration (ODBA)
#' 
#' @param object A data frame or TDR table including dynamic acceleration variables 
#' entitled "axD", "ayD", and "azD" for X, Y, and Z axes of the accelerometer.
#' @export
#' @return A vector of ODBA of the same length as \code{object}.
#' @keywords raw_processing
overall_DBA <- function(object) {
  object <- as.data.table(object)
  object <- object[ , tot := abs(axD) + abs(ayD) + abs(azD)]
  object$tot
}

#' Vectorial Dynamic Body Acceleration (VeDBA)
#' 
#' @param object A data frame or TDR table including dynamic acceleration variables 
#' entitled "axD", "ayD", and "azD" for X, Y, and Z axes of the accelerometer.
#' @export
#' @return A vector of VeDBA of the same length as \code{object}.
#' @keywords raw_processing
vectorial_DBA <- function(object) {
  object <- as.data.table(object)
  object <- object[ , tot := sqrt(axD^2 + ayD^2 + azD^2)]
  object$tot
}
## source('~/Master_Thesis/pckg.cheb/R/functions-chebyshev.r')
##
## library(devtools)
## library(roxygen2)
##
## Build and Reload Package:  'Ctrl + Shift + B'
## Check Package:             'Ctrl + Shift + E'
## Test Package:              'Ctrl + Shift + T'


##
#' @title Scaling of X-Axis
#' @param x.axis ursprüngliche beliebige X-Achse (Vektor)
#' @return x.cheb.scaled skalierte X-Achse (Vektor)
#' @description
#' \code{cheb.scale} skaliert beliebige X-Achse auf Achse, die für Polynom-fits verträglich ist.
#' @examples
#' x.axis <- c(0:30)
#' x.cheb.scaled <- cheb.scale(x.axis)
cheb.scale <- function(x.axis) {#, scale) {
  ## Funktion zur Skalierung von Stützpunkten
  ## von beliebigen Gittern auf [-1, 1]
  ## ##
  #  if (type == "cheb") {
  x.cheb.scaled <- (2 * (x.axis - x.axis[1]) / (max(x.axis) - min(x.axis))) - 1
  #  }
  return(x.cheb.scaled)
}


##
#' @title Rescaling of X-Axis
#' @param x.cheb skalierte X-Achse (Skalar oder Vektor)
#' @param x.axis beliebige X-Achse (Vektor)
#' @return x.rescaled reskalierte X-Achse (Skalar oder Sektor)
#' @description
#' cheb.rescale reskaliert die für den Fit erzeugte Achse auf die Ursprüngliche
#' @examples
#' x.rescaled <- cheb.rescale(x.cheb, x.axis)
cheb.rescale <- function(x.cheb, x.axis) {
  ## Funktion zur Reskalierung vom [-1, 1]-Gitter
  ## auf das Ursprungsgitter (in diesem Fall - Lat)
  ## ##
  if (x.cheb >= -1 & x.cheb <= 1) {
    x.rescaled <- (1/2 * (x.cheb + 1) * (max(x.axis) - min(x.axis))) + x.axis[1]
    return(x.rescaled)
  } else
    print("Error: x.cheb went out of boundaries (less -1 or greater 1).")
}


##
#' @title Generating Chebyshev Polynomials of first kind
#' @param x.axis beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.t Chebyshev-Polynome Erster Art (Vektor)
#' @description
#' cheb.1st erzeugt Chebyshev Polynome erster Art aus beliebiger X-Achse
#' @examples
#' cheb.t <- cheb.1st(x.axis, n)
cheb.1st <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Erster Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis  ### ###
  m <- n + 1
  # Rekursionsformel Wiki / Bronstein
  cheb.t.0 <- 1;  cheb.t.1 <- x.cheb;
  cheb.t <- cbind(cheb.t.0, cheb.t.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.t.i <- 2 * x.cheb * cheb.t[,(i - 1)] - cheb.t[,(i - 2)]
      cheb.t <- cbind(cheb.t, cheb.t.i)
      rm(cheb.t.i)
    }
  }
  return(cheb.t)
}


##
#' @title Generating Chebyshev Polynomials of second kind
#' @param x.axis beliebigie X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.u Chebyshev-Polynome Zweiter Art (Vektor)
#' @description
#' cheb.2nd erzeugt Chebyshev Polynome zweiter Art aus beliebiger X-Achse
#' @examples
#' cheb.u <- cheb.2nd(x.axis, n)
cheb.2nd <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Zweiter Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis
  m <- n + 1
  cheb.u.0 <- 1; cheb.u.1 <-  2*x.cheb
  cheb.u <- cbind(cheb.u.0, cheb.u.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.u.i <- 2 * x.cheb * cheb.u[,(i - 1)] - cheb.u[,(i - 2)]
      cheb.u <- cbind(cheb.u, cheb.u.i)
      rm(cheb.u.i)
    }
  }
  return(cheb.u)
}


##
#' @title Calculation of Values of the model fit
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model gefiltertes Modell (Skalar oder Vektor)
#' @description
#' cheb.model berechnet aus den Chebyshev-Koeffizienten die Y-Werte
#' @examples
#' cheb.model <- cheb.model.filter(x.axis, cheb.coeff)
cheb.model.filter <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte aus X-Stellen und Cheb-Koeffizienten
  ## ##
  n <- length(cheb.coeff) - 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.model <- cheb.t %*% cheb.coeff
  return(cheb.model)
}


##
#' @title Calculation of the values of the first derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv.1st Erste Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.1st berechnet aus den Chebyshev-Koeffizienten die Werte der ersten Ableitung
#' @examples
#' cheb.model.deriv <- cheb.deriv.1st(x.axis, cheb.coeff)
cheb.deriv.1st <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte der Ableitung des Modells
  ## aus X-Stellen und Chebyshev-Koeffizienten
  ## ##
  if (length(x.axis) != 0) { ### Überprüfen, ob nötig
    n <- length(cheb.coeff) - 1
    m <- n + 1
    cheb.u <- cheb.2nd(x.axis, n)

    # berechnung der ableitung der polynome erster art
    # rekursionsformel 0
    # dT/dx = n * U_(n-1)
    cheb.t.deriv <- if (length(x.axis) == 1) (2:m)*t(cheb.u[,1:n]) else t((2:m)*t(cheb.u[,1:n]))
    cheb.model.deriv.1st <- cheb.t.deriv %*% cheb.coeff[2:m]
    return(cheb.model.deriv.1st)
  }
}


##
#' @title Calculation of the values of the second derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv Zweite Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.2nd berechnet aus den Chebyshev-Koeffizienten die Werte der zweiten Ableitung
#' @examples
#' cheb.model.deriv.2nd <- cheb.deriv.2nd(x.axis, cheb.coeff)
cheb.deriv.2nd <- function(x.axis, cheb.coeff) {
  n <- length(cheb.coeff) - 1
  m <- n + 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.u <- cheb.2nd(x.axis, n)
  x.cheb <- cheb.scale(x.axis)
  cheb.t.deriv.2nd <- t((((1:m) ** 2) + (1:m)) %*% t(1 / (x.cheb ** 2 - 1)) * t(cheb.t - cheb.u))
  cheb.t.deriv.2nd[1,] <- (-1) * ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.t.deriv.2nd[length(x.cheb),] <- ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.model.deriv.2nd <- cheb.t.deriv.2nd %*% cheb.coeff
  return(cheb.model.deriv.2nd)
}


##
#' @title Curve Fitting with Chebyshev Polynomials
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit <- function(d, x.axis, n, harmonic = FALSE){
  # Fallunterscheidung für harmonische Randbedingung
  if (harmonic == FALSE) {
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  } else if (harmonic == TRUE) {
    d <- c(d, d[1])
    x.axis <- c(x.axis, (x.axis[1] + 360))
    x.cheb <- cheb.scale(x.axis)
    cheb.t <- cheb.1st(x.axis, n)
  }

  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # löschen des letzten eintrags für den harmonischen fall
  cheb.model <- if (harmonic == TRUE) cheb.model[-(length(cheb.model))]

  # Übergabe der Variablen
  return(cheb.model)
}



##
#' @title Curve Fitting with Chebyshev Polynomials and Finding of its Roots
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit.roots <- function(d, x.axis, n){
  library(rootSolve)
  x.cheb <- cheb.scale(x.axis)
  cheb.t <- cheb.1st(x.axis, n)
  #  cheb.u <- cheb.2nd(x.axis, n)
  #  m <- n + 1
  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # berechnung des abgeleiteten modells
  cheb.model.deriv.1st <- cheb.deriv.1st(x.cheb, cheb.coeff)

  # berechnung der nullstellen
  extr <- rootSolve::uniroot.all(cheb.deriv.1st, cheb.coeff = cheb.coeff, lower = (-1), upper = 1)
  # reskalierung der Nullstellen auf normale Lat- Achse
  x.extr <- if (length(extr) != 0) cheb.rescale(extr, x.axis = x.axis)
  y.extr <- if (length(extr) != 0) cheb.model.filter(x.axis = extr, cheb.coeff = cheb.coeff)

  cheb.list <- list(cheb.coeff = cheb.coeff, cheb.model = cheb.model, cheb.model.deriv.1st = cheb.model.deriv.1st, x.extr = x.extr, y.extr = y.extr)
  return(cheb.list)
}



##
#' @title Curve Fitting with Chebyshev Polynomials over Sequences
#' @description
#' Fittet ein Chebyshev Polynom beliebiger Ordnung an einen sequenzierten Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.fit.seq(d, x.axis, n, l)
cheb.fit.seq <- function(d, x.axis, n, l, harmonic == FALSE){
  x.mat <- matrix(x.axis, ncol = l, byrow = TRUE)
  d.mat <- matrix(d, ncol = l, byrow = TRUE)
  end.loop <- length(x.mat[,1])

  # schleife über sequenzen des Datensatzes
  for (i in 1:end.loop) {
    # erstellung der sequenzen und fallunterscheidung für harmonische randbedingung
    if (harmonic == FALSE) {
      d.seq <- if (i != end.loop) c(d.mat[i,], d.mat[(i + 1), 1]) else c(d.mat[i,])
      x.seq <- if (i != end.loop) c(x.mat[i,], x.mat[(i + 1), 1]) else c(x.mat[i,])
    } else if (harmonic == TRUE) {
      d.seq <- if (i != end.loop) c(d.mat[i,], d.mat[(i + 1), 1]) else c(d.mat[i,], d.mat[1,1])
      x.seq <- if (i != end.loop) c(x.mat[i,], x.mat[(i + 1), 1]) else c(x.mat[i,], x.mat[1,1] + 360)
    }
    x.cheb.seq <- cheb.scale(x.seq)
    cheb.t.seq <- cheb.1st(x.seq, n)

    ## modell berechnungen
    # berechnung der koeffizienten des polyfits
    cheb.coeff.seq <- solve(t(cheb.t.seq) %*% cheb.t.seq) %*% t(cheb.t.seq) %*% d.seq
    cheb.coeff <- if (i == 1) cheb.coeff.seq else cbind(cheb.coeff, cheb.coeff.seq)
    # berechnung des gefilterten modells
    cheb.model.seq <- cheb.model.filter(x.cheb.seq, cheb.coeff.seq)
    cheb.model <- if (i == 1) cheb.model.seq[-l] else c(cheb.model, cheb.model.seq[-l])
  }

  ## übergabe der variable
  return(cheb.model)
}

## source('~/Master_Thesis/pckg.cheb/R/functions-chebyshev.r')
##
## library(devtools)
## library(roxygen2)
##
## Build and Reload Package:  'Ctrl + Shift + B'
## Check Package:             'Ctrl + Shift + E'
## Test Package:              'Ctrl + Shift + T'


##
#' @title Scaling of X-Axis
#' @param x.axis ursprüngliche beliebige X-Achse (Vektor)
#' @return x.cheb.scaled skalierte X-Achse (Vektor)
#' @description
#' \code{cheb.scale} skaliert beliebige X-Achse auf Achse, die für Polynom-fits verträglich ist.
#' @examples
#' x.axis <- c(0:30)
#' x.cheb.scaled <- cheb.scale(x.axis)
cheb.scale <- function(x.axis) {#, scale) {
  ## Funktion zur Skalierung von Stützpunkten
  ## von beliebigen Gittern auf [-1, 1]
  ## ##
  #  if (type == "cheb") {
  x.cheb.scaled <- (2 * (x.axis - x.axis[1]) / (max(x.axis) - min(x.axis))) - 1
  #  }
  return(x.cheb.scaled)
}


##
#' @title Rescaling of X-Axis
#' @param x.cheb skalierte X-Achse (Skalar oder Vektor)
#' @param x.axis beliebige X-Achse (Vektor)
#' @return x.rescaled reskalierte X-Achse (Skalar oder Sektor)
#' @description
#' cheb.rescale reskaliert die für den Fit erzeugte Achse auf die Ursprüngliche
#' @examples
#' x.rescaled <- cheb.rescale(x.cheb, x.axis)
cheb.rescale <- function(x.cheb, x.axis) {
  ## Funktion zur Reskalierung vom [-1, 1]-Gitter
  ## auf das Ursprungsgitter (in diesem Fall - Lat)
  ## ##
  if (x.cheb >= -1 & x.cheb <= 1) {
    x.rescaled <- (1/2 * (x.cheb + 1) * (max(x.axis) - min(x.axis))) + x.axis[1]
    return(x.rescaled)
  } else
    print("Error: x.cheb went out of boundaries (less -1 or greater 1).")
}


##
#' @title Generating Chebyshev Polynomials of first kind
#' @param x.axis beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.t Chebyshev-Polynome Erster Art (Vektor)
#' @description
#' cheb.1st erzeugt Chebyshev Polynome erster Art aus beliebiger X-Achse
#' @examples
#' cheb.t <- cheb.1st(x.axis, n)
cheb.1st <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Erster Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis  ### ###
  m <- n + 1
  # Rekursionsformel Wiki / Bronstein
  cheb.t.0 <- 1;  cheb.t.1 <- x.cheb;
  cheb.t <- cbind(cheb.t.0, cheb.t.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.t.i <- 2 * x.cheb * cheb.t[,(i - 1)] - cheb.t[,(i - 2)]
      cheb.t <- cbind(cheb.t, cheb.t.i)
      rm(cheb.t.i)
    }
  }
  return(cheb.t)
}


##
#' @title Generating Chebyshev Polynomials of second kind
#' @param x.axis beliebigie X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.u Chebyshev-Polynome Zweiter Art (Vektor)
#' @description
#' cheb.2nd erzeugt Chebyshev Polynome zweiter Art aus beliebiger X-Achse
#' @examples
#' cheb.u <- cheb.2nd(x.axis, n)
cheb.2nd <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Zweiter Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis
  m <- n + 1
  cheb.u.0 <- 1; cheb.u.1 <-  2*x.cheb
  cheb.u <- cbind(cheb.u.0, cheb.u.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.u.i <- 2 * x.cheb * cheb.u[,(i - 1)] - cheb.u[,(i - 2)]
      cheb.u <- cbind(cheb.u, cheb.u.i)
      rm(cheb.u.i)
    }
  }
  return(cheb.u)
}


##
#' @title Calculation of Values of the model fit
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model gefiltertes Modell (Skalar oder Vektor)
#' @description
#' cheb.model berechnet aus den Chebyshev-Koeffizienten die Y-Werte
#' @examples
#' cheb.model <- cheb.model.filter(x.axis, cheb.coeff)
cheb.model.filter <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte aus X-Stellen und Cheb-Koeffizienten
  ## ##
  n <- length(cheb.coeff) - 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.model <- cheb.t %*% cheb.coeff
  return(cheb.model)
}


##
#' @title Calculation of the values of the first derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv.1st Erste Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.1st berechnet aus den Chebyshev-Koeffizienten die Werte der ersten Ableitung
#' @examples
#' cheb.model.deriv <- cheb.deriv.1st(x.axis, cheb.coeff)
cheb.deriv.1st <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte der Ableitung des Modells
  ## aus X-Stellen und Chebyshev-Koeffizienten
  ## ##
  if (length(x.axis) != 0) { ### Überprüfen, ob nötig
    n <- length(cheb.coeff) - 1
    m <- n + 1
    cheb.u <- cheb.2nd(x.axis, n)

    # berechnung der ableitung der polynome erster art
    # rekursionsformel 0
    # dT/dx = n * U_(n-1)
    cheb.t.deriv <- if (length(x.axis) == 1) (2:m)*t(cheb.u[,1:n]) else t((2:m)*t(cheb.u[,1:n]))
    cheb.model.deriv.1st <- cheb.t.deriv %*% cheb.coeff[2:m]
    return(cheb.model.deriv.1st)
  }
}


##
#' @title Calculation of the values of the second derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv Zweite Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.2nd berechnet aus den Chebyshev-Koeffizienten die Werte der zweiten Ableitung
#' @examples
#' cheb.model.deriv.2nd <- cheb.deriv.2nd(x.axis, cheb.coeff)
cheb.deriv.2nd <- function(x.axis, cheb.coeff) {
  n <- length(cheb.coeff) - 1
  m <- n + 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.u <- cheb.2nd(x.axis, n)
  x.cheb <- cheb.scale(x.axis)
  cheb.t.deriv.2nd <- t((((1:m) ** 2) + (1:m)) %*% t(1 / (x.cheb ** 2 - 1)) * t(cheb.t - cheb.u))
  cheb.t.deriv.2nd[1,] <- (-1) * ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.t.deriv.2nd[length(x.cheb),] <- ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.model.deriv.2nd <- cheb.t.deriv.2nd %*% cheb.coeff
  return(cheb.model.deriv.2nd)
}


##
#' @title Curve Fitting with Chebyshev Polynomials
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit <- function(d, x.axis, n, tp.return = 'NULL'){
  x.cheb <- cheb.scale(x.axis)
  cheb.t <- cheb.1st(x.axis, n)
  # Fallunterscheidung
  if (tp.return == 'all') {
    ## modell berechnungen
    # berechnung der koeffizienten des polyfits
    cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
    # berechnung des gefilterten modells
    cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
    # berechnung des abgeleiteten modells
    cheb.model.deriv.1st <- cheb.deriv.1st(x.cheb, cheb.coeff)
    ## Übergabe der Var.
    cheb.list <- list(cheb.coeff = cheb.coeff, cheb.model = cheb.model, cheb.model.deriv.1st = cheb.model.deriv.1st)
    return(cheb.list)
  } else {
    ## modell berechnungen
    # berechnung der koeffizienten des polyfits
    cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
    # berechnung des gefilterten modells
    cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
    # Übergabe der Var.
    return(cheb.model)
  }
}


##
#' @title Curve Fitting with Chebyshev Polynomials
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit.roots <- function(d, x.axis, n){
  library(rootSolve)
  x.cheb <- cheb.scale(x.axis)
  cheb.t <- cheb.1st(x.axis, n)
  #  cheb.u <- cheb.2nd(x.axis, n)
  #  m <- n + 1
  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # berechnung des abgeleiteten modells
  cheb.model.deriv.1st <- cheb.deriv.1st(x.cheb, cheb.coeff)

  # berechnung der nullstellen
  extr <- rootSolve::uniroot.all(cheb.deriv.1st, cheb.coeff = cheb.coeff, lower = (-1), upper = 1)
  # reskalierung der Nullstellen auf normale Lat- Achse
  x.extr <- if (length(extr) != 0) cheb.rescale(extr, x.axis = x.axis)
  y.extr <- if (length(extr) != 0) cheb.model.filter(x.axis = extr, cheb.coeff = cheb.coeff)

  cheb.list <- list(cheb.coeff = cheb.coeff, cheb.model = cheb.model, cheb.model.deriv.1st = cheb.model.deriv.1st, x.extr = x.extr, y.extr = y.extr)
  return(cheb.list)
}



##
#' @title Curve Fitting with Chebyshev Polynomials over Sequences
#' @description
#' Fittet ein Chebyshev Polynom beliebiger Ordnung an einen sequenzierten Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.fit.seq(d, x.axis, n, l)
cheb.fit.seq <- function(d, x.axis, n, l){
  library(rootSolve)
  x.mat <- matrix(x.axis, ncol = l, byrow = TRUE)
  d.mat <- matrix(d, ncol = l, byrow = TRUE)

  # schleife über sequenzen des Datensatzes
  for (i in 1:length(x.mat[,1])) {
    # print(i)
    # erstellung der sequenzen
    x.seq <- if (i == 1) c(x.mat[i,]) else c(x.mat[(i - 1), dim(x.mat)[2]], x.mat[i,])
    x.cheb.seq <- cheb.scale(x.seq)
    d.seq <- if (i == 1) c(d.mat[i,]) else c(d.mat[(i - 1), dim(d.mat)[2]], d.mat[i,])
    cheb.t.seq <- cheb.1st(x.seq, n)
    ## modell berechnungen
    # berechnung der koeffizienten des polyfits
    cheb.coeff.seq <- solve(t(cheb.t.seq) %*% cheb.t.seq) %*% t(cheb.t.seq) %*% d.seq
    cheb.coeff <- if (i == 1) cheb.coeff.seq else cbind(cheb.coeff, cheb.coeff.seq)
    # berechnung des gefilterten modells
    cheb.model.seq <- cheb.model.filter(x.cheb.seq, cheb.coeff.seq)
    cheb.model <- if (i == 1) cheb.model.seq else c(cheb.model, cheb.model.seq[2:(l+1)])
    # berechnung des abgeleiteten modells
    cheb.model.deriv.1st.seq <- cheb.deriv.1st(x.cheb.seq, cheb.coeff.seq)
    cheb.model.deriv.1st <- if (i == 1) cheb.model.deriv.1st.seq else c(cheb.model.deriv.1st, cheb.model.deriv.1st.seq[2:(l+1)])

    # berechnung der nullstellen
    extr.seq <- rootSolve::uniroot.all(cheb.deriv.1st, cheb.coeff = cheb.coeff.seq, lower = (-1), upper = 1)
    # reskalierung der Nullstellen auf normale Lat- Achse
    x.extr.seq <- if (length(extr.seq) != 0) cheb.rescale(extr.seq, x.axis = x.seq)
    y.extr.seq <- if (length(extr.seq) != 0) cheb.model.filter(x.axis = extr.seq, cheb.coeff = cheb.coeff.seq)
    #
    if (exists("x.extr.seq") == TRUE & exists("x.extr") == FALSE) {
      x.extr <- x.extr.seq
      y.extr <- y.extr.seq
    } else if (exists("x.extr.seq") == TRUE & exists("x.extr") == TRUE) {
      x.extr <- c(x.extr, x.extr.seq)
      y.extr <- c(y.extr, y.extr.seq)
    }
  }

  ## übergabe der variablen als liste
  cheb.list <- list(cheb.model = cheb.model, cheb.model.deriv.1st = cheb.model.deriv.1st, extr.x = x.extr, extr.y = y.extr)
  return(cheb.list)
}

#!/usr/bin/env Rscript
# Copyright (c) 2015 Mikkel Schubert <MSchubert@snm.ku.dk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# Required for 'read.tree'
library(ape)
library(ggplot2)
library(grid)
library(methods)


TTBar <- setRefClass("TTBar",
            fields = list(leftmax = "numeric",
                          left = "numeric",
                          right = "numeric",
                          rightmax = "numeric"))


TTNode <- setRefClass("TTNode",
            fields = list(children = "list",
                          bar = 'TTBar',
                          len = "numeric",
                          label = "character",
                          group = "character"
                          ),
            methods = list(
                "initialize" = function(children = NULL, bar = NULL, len = 0,
                                        label = "", group = "") {
                    .self$children <- as.list(children)
                    if (!is.null(bar)) {
                        .self$bar <- bar
                    }
                    .self$len <- len
                    .self$label <- label
                    .self$group <- group
                },

                "show" = function() {
                    print(node$pformat())
                },

                "pformat" = function() {
                    return(paste(to_str(), ";", sep=""))
                },

                "to_str" = function() {
                    fields <- NULL
                    if (length(children)) {
                        child_str <- NULL
                        for (child in children) {
                            child_str <- c(child_str, child$to_str())
                        }

                        fields <- c(fields, "(", paste(child_str, sep="", collapse=","), ")")
                    }

                    if (nchar(label) > 0) {
                        fields <- c(fields, label)
                    }

                    if (length(len) > 0) {
                        fields <- c(fields, ":", len)
                    }

                    return(paste(fields, sep="", collapse=""))
                },

                "height_above" = function() {
                    total <- ifelse(length(children) > 0, 0, 1)
                    for (child in children_above()) {
                        total <- total + child$height_above() + child$height_below()
                    }

                    return(total)
                },

                "height_below" = function() {
                    total <- ifelse(length(children) > 0, 0, 1)
                    for (child in children_below()) {
                        total <- total + child$height_above() + child$height_below()
                    }

                    return(total)
                },

                "height" = function() {
                    return(height_above() + height_below())
                },

                "width" = function() {
                    total <- 0

                    for (child in children) {
                        total <- max(total, child$width())
                    }

                    if (length(len) > 0) {
                        total <- total + len
                    }

                    return(total)
                },

                "to_tables" = function(from_x=0, from_y=0) {
                    current_x <- from_x + ifelse(length(len) > 0, len, 0)

                    # Horizontal line
                    tables <- list(
                        labels=data.frame(
                            start_x=current_x,
                            start_y=from_y + calc_offset(from_y),
                            label=label,
                            group=get_labelgroup()
                        ),
                        segments=data.frame(
                            start_x=from_x,
                            start_y=from_y + calc_offset(from_y),
                            end_x=current_x,
                            end_y=from_y + calc_offset(from_y),
                            group=get_linegroup()),
                        bars=to_bar(current_x, from_y + calc_offset(from_y)))

                    max_y <- from_y
                    current_y <- max_y
                    for (child in children_above()) {
                        current_y <- current_y + child$height_below()
                        tables <- merge_tables(tables, child$to_tables(current_x, current_y))
                        max_y <- current_y + child$calc_offset(current_y)
                        current_y <- current_y + child$height_above()
                    }

                    min_y <- from_y
                    current_y <- min_y
                    for (child in children_below()) {
                        current_y <- current_y - child$height_above()
                        tables <- merge_tables(tables, child$to_tables(current_x, current_y))
                        min_y <- current_y + child$calc_offset(current_y)
                        current_y <- current_y - child$height_below()
                    }

                    # Vertical line
                    tables$segments <- rbind(tables$segments,
                        data.frame(
                            start_x=current_x,
                            start_y=max_y,
                            end_x=current_x,
                            end_y=min_y,
                            group=get_linegroup()))

                    return(tables)
                },

                "to_bar" = function(current_x, current_y) {
                    if (length(c(bar$leftmax, bar$left, bar$right, bar$rightmax)) != 4) {
                        return(data.frame())
                    }

                    return(data.frame(
                        start_x=c(bar$leftmax, bar$left, bar$right) + current_x,
                        end_x=c(bar$left, bar$right, bar$rightmax) + current_x,
                        start_y=current_y - c(0.25, 0.5, 0.25),
                        end_y=current_y + c(0.25, 0.5, 0.25)))
                },

                "merge_tables" = function(tbl_a, tbl_b) {
                    result <- list()
                    for (name in unique(names(tbl_a), names(tbl_b))) {
                        result[[name]] <- rbind(tbl_a[[name]], tbl_b[[name]])
                    }
                    return(result)
                },

                "clade" = function(taxa) {
                    # FIXME: Handle multiple tips with identical label
                    if (length(intersect(taxa, tips())) != length(taxa)) {
                        return(NULL)
                    }

                    for (child in children) {
                        if (length(intersect(taxa, child$tips())) == length(taxa)) {
                            return(child$clade(taxa))
                        }
                    }

                    return(.self)
                },

                "tips" = function(taxa) {
                    if (length(children) == 0) {
                        return(label)
                    } else {
                        result <- NULL
                        for (child in children) {
                            result <- c(result, child$tips())
                        }
                        return(result)
                    }
                },

                "calc_offset" = function(from_y) {
                    max_y <- from_y
                    current_y <- from_y
                    for (child in children_above()) {
                        current_y <- current_y + child$height_below()
                        max_y <- current_y + child$calc_offset(current_y)
                        current_y <- current_y + child$height_above()
                    }

                    min_y <- from_y
                    current_y <- from_y
                    for (child in children_below()) {
                        current_y <- current_y - child$height_above()
                        min_y <- current_y + child$calc_offset(current_y)
                        current_y <- current_y - child$height_below()
                    }

                    return(max_y - from_y - (max_y - min_y) / 2)
                },

                "children_above" = function() {
                    if (length(children) < 1) {
                        return(list())
                    }
                    return(children[1:ceiling(length(children) / 2)])
                },

                "children_below" = function() {
                    if (length(children) < 1) {
                        return(list())
                    }
                    return(children[(ceiling(length(children) / 2) + 1):length(children)])
                },

                "get_labelgroup" = function(prefix=NULL) {
                    if (is.null(prefix)) {
                        prefix <- ifelse(length(children) > 0, "node", "leaf")
                    }

                    if (nchar(group) > 0) {
                        prefix <- paste(prefix, ":", group, sep="")
                    }

                    return(prefix)
                },

                "get_linegroup" = function() {
                    prefix <- "line"
                    if (nchar(group) > 0) {
                        prefix <- paste(prefix, ":", group, sep="")
                    }

                    return(prefix)
                },

                "set_group" = function(value=NULL) {
                    .self$group <- ifelse(is.null(value), "line", value)
                    for (child in children) {
                        child$set_group(value)
                    }
                },

                "is_leaf" = function() {
                    '
                    Convinience function; returns true if the node is a leaf.
                    '
                    return(length(children) == 0)
                },

                "collect" = function() {
                    '
                    Returns a vector of all in the tree, including this node.
                    '
                    result <- .self
                    for (child in children) {
                        result <- c(result, child$collect())
                    }
                    return(result)
                },

                "sort_nodes" = function() {
                    if (!is_leaf()) {
                        widths <- NULL
                        for (child in children) {
                            widths <- c(widths, child$width())
                            child$sort_nodes()
                        }

                        .self$children <- children[order(widths, decreasing=FALSE)]
                    }
                }))


print.TTNode <- function(node)
{
    print(node$pformat())
}


tinytree.phylo.to.tt <- function(phylo)
{
    nnodes <- nrow(phylo$edge) + 1
    lengths <- phylo$edge.length
    to.node <- phylo$edge[, 2]
    from.node <- phylo$edge[, 1]

    nodes <- list()
    labels <- c(phylo$tip.label, phylo$node.label)
    for (edge in 1:nnodes) {
        len <- lengths[to.node == edge]
        nodes[[edge]] <- TTNode(label = labels[edge],
                                len = as.numeric(len))
    }

    for (edge in 1:nnodes) {
        from <- from.node[to.node == edge]
        if (length(from) != 0 && from != 0) {
            children <- nodes[[from]]$children
            children[[length(children) + 1]] <- nodes[[edge]]
            nodes[[from]]$children <- children
        }
    }

    root <- nodes[[length(phylo$tip.label) + 1]]
    root$len <- 0

    return(root)
}


tinytree.read.newick <- function(filename)
{
	return(tinytree.phylo.to.tt(read.tree(filename)))
}


tinytree.defaults.collect <- function(tt, defaults, values)
{
    stopifnot(!any(is.null(names(values))) || length(values) == 0)

    # Overwrite using user supplied values
    for (idx in seq(values)) {
        defaults[[names(values)[idx]]] <- values[[idx]]
    }

    # Set default values based on type (line, node, leaf, etc.)
    for (node in tt$collect()) {
        for (type in c(node$get_labelgroup(), node$get_linegroup())) {
            if (!(type %in% names(defaults))) {
                root <- unlist(strsplit(type, ":"))[[1]]
                stopifnot(root %in% names(defaults))
                defaults[[type]] <- defaults[[root]]
            }
        }
    }

    return(defaults)
}


tinytree.default.colours <- function(pp, tt, ...)
{
    defaults <- c("line"="black",
                  "node"="darkgrey",
                  "leaf"="black",
                  "bar"="blue")
    defaults <- tinytree.defaults.collect(tt, defaults, list(...))

    return(pp +
           scale_colour_manual(values=defaults) +
           scale_fill_manual(values=defaults))
}


tinytree.default.sizes <- function(pp, tt, ...)
{
    defaults <- c("line"=0.5,
                  "node"=4,
                  "leaf"=5)
    defaults <- tinytree.defaults.collect(tt, defaults, list(...))

    return(pp + scale_size_manual(values=defaults))
}


tinytree.draw <- function(tt, default.scales=TRUE, xaxis="scales", padding=0.3)
{
    tbl <- tt$to_tables(-tt$len)

    pp <- ggplot()
    pp <- pp + geom_segment(data=tbl$segments, lineend="round",
                            aes(x=start_x, y=start_y, xend=end_x, yend=end_y,
                                color=group, size=group))

    if (nrow(tbl$bars) > 0) {
        pp <- pp + geom_rect(data=tbl$bars, alpha=0.3,
                             aes(xmin=start_x, xmax=end_x, ymin=start_y, ymax=end_y,
                                 fill="bar"))
    }

    if (any(!is.na(tbl$labels$label))) {
        labels <- tbl$labels[!is.na(tbl$labels$label),]
        pp <- pp + geom_text(data=labels, hjust=0,
                             aes(label=sprintf(" %s", label),
                                 x=start_x, y=start_y, color=group, size=group))
    }

    pp <- pp + theme_minimal()

    # Disable legend
    pp <- pp + theme(legend.position="none",
    # Disable y axis + y axis labels + grid
                     axis.ticks.y=element_blank(),
                     axis.text.y=element_blank(),
                     panel.grid.minor.y=element_blank(),
                     panel.grid.major.y=element_blank(),
                     panel.grid.major  = element_line(colour = "grey90", size = 0.4),
                     panel.grid.minor  = element_line(colour = "grey90", size = 0.2))

    if (xaxis != "axis") {
        stopifnot(xaxis %in% c("scales", "none"))
        pp <- pp + theme(axis.ticks.x=element_blank(),
                         axis.text.x=element_blank(),
                         panel.grid.minor.x=element_blank(),
                         panel.grid.major.x=element_blank())

        if (xaxis == "scales") {
            y_offset <- min(tbl$segments$start_y, tbl$segments$end_y) - 3
            x_offset <- max(tbl$segments$end_x) * 0.2

            df <- data.frame(x=0, y=y_offset, xend=x_offset, yend=y_offset)
            pp <- pp + geom_segment(data=df,
                                    aes(color="line", size="line",
                                        x=x, xend=xend, y=y, yend=yend))

            df <- data.frame(x=x_offset, y=y_offset, label=paste("", signif(x_offset, 2)))
            pp <- pp + geom_text(data=df, aes(x=x, y=y, hjust=0, label=label,
                                              size="leaf", colour="leaf"))
        }
    }

    # Disable axis labels by default
    pp <- pp + xlab(NULL)
    pp <- pp + ylab(NULL)

    # Default colors; may be overwritten
    if (default.scales) {
        pp <- tinytree.default.sizes(pp, tt)
        pp <- tinytree.default.colours(pp, tt)
    }

    range <- max(tbl$segments$end_x) - min(tbl$segments$start_x)
    pp <- pp + coord_cartesian(xlim=c(min(tbl$segments$start_x),
                                      max(tbl$segments$end_x) + padding * range))

    return(pp)
}


plot.tree <- function(filename, sample_names, padding=0.3)
{
    samples <- read.table(sample_names, as.is=TRUE, comment.char="", header=TRUE)
    tt <- tinytree.read.newick(filename)
    tt$sort_nodes()

    for (node in tt$collect()) {
        if (node$is_leaf()) {
            node$set_group(node$label)
        }
    }

    pp <- tinytree.draw(tt,
                        default.scales=FALSE,
                        padding=padding)
    pp <- tinytree.default.sizes(pp, tt, "node"=3, "leaf"=4, "line"=0.75)

    defaults <- c("line"="black",
                  "node"="darkgrey",
                  "leaf"="black",
                  "bar"="blue")
    defaults <- tinytree.defaults.collect(tt, defaults, list())

    for (row in 1:nrow(samples)) {
        row <- samples[row, , drop=FALSE]
        key <- sprintf("leaf:%s", row$Name)
        print(c(key, row$Color))

        defaults[[key]] <- row$Color
    }
    print(defaults)

    return(pp +
           scale_colour_manual(values=defaults) +
           scale_fill_manual(values=defaults))
}


args <- commandArgs(trailingOnly = TRUE)
if (length(args) != 3) {
    cat("Usage: ggtinytree.R <input_file> <sample_names> <output_prefix>\n", file=stderr())
    quit(status=1)
}

input_file <- args[1]
sample_names <- args[2]
output_prefix <- args[3]

pdf(paste(output_prefix, ".pdf", sep=""))
plot.tree(input_file, sample_names)
dev.off()

# bitmap is preferred, since it works in a headless environment
bitmap(paste(output_prefix, ".png", sep=""), height=6, width=6, res=96, taa=4, gaa=4)
plot.tree(input_file, sample_names)
dev.off()

#' ssh with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param cmds A sting of one or more commands to run on the remote host.
#'
#' @param intern Indicates whether to capture the output of the command
#' as an R character vector.
#'
stain_ssh <- function(user, host, cmds = "", intern = FALSE) {
    if (is.null(user) | is.null(host)) {
        stop("No user or host specified.", call. = FALSE)
    }

    if (!stain_ssh_key_exists()) {
        invisible(stain_ssh_key_gen())
    }

    remote_host <- paste(user, host, sep = "@")
    system(paste("ssh", remote_host, "-t -t -i ~/.ssh/stain_rsa",
                 paste0("\"", cmds, "\"")),
           intern = intern)
}


#' scp with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param from The directory or file to copy.
#'
#' @param to The destination.
stain_scp <- function(from, to) {
    system(paste("scp -i ~/.ssh/stain_rsa -r", from, to))
}


#' Get squeue info on certain jobs.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param job_ids A collection of job ids for which to fetch statuses.
#'
#' @return A data frame with columns corresponding to those produced
#' by the \code{squeue -l} command.
stain_ssh_squeue <- function(user, host, job_ids) {
    job_ids <- paste(job_ids, collapse = ",")
    remote_host <- paste(user, host, sep = "@")

    squeue_cmd <- paste("squeue -l -j", job_ids)
    output <- stain_ssh(user, host, squeue_cmd, intern = TRUE)

    output_table <- sapply(output, USE.NAMES = FALSE, function(row) {
        tokens <- strsplit(row, " ")[[1]]
        return(tokens[tokens != ""])
    })

    csv_header <- paste(output_table[[2]], collapse = "\t")
    csv_header <-  gsub("[\r]", "", csv_header)

    if (length(output_table) > 2) {
        csv_body <- paste(lapply(output_table[3:length(output_table)], function(row) {
            row <- paste(row, collapse = "\t")
            row <-  gsub("[\r]", "", row)
            return(row)
        }), collapse = "\n")
        csv <- paste(csv_header, csv_body, sep = "\n")
    } else {
        csv <- csv_header
    }

    state_table <- utils::read.delim(textConnection(csv))

    return(state_table)
}


#' Get sacct info on certain jobs.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param job_ids A collection of job ids for which to fetch statuses.
#'
#' @return A data frame with columns corresponding to those produced
#' by the \code{sacct --brief --jobs} command.
stain_ssh_sacct <- function(user, host, job_ids) {
    job_ids <- paste(job_ids, collapse = ",")
    remote_host <- paste(user, host, sep = "@")

    sacct_cmd <- paste("sacct --brief --jobs", job_ids)
    output <- stain_ssh(user, host, sacct_cmd, intern = TRUE)
    output[2] <- NA
    output <- output[!is.na(output)]

    output_table <- t(sapply(output, USE.NAMES = FALSE, function(row) {
        tokens <- strsplit(row, " ")[[1]]
        return(tokens[tokens != "" & tokens != "\r"])
    }))

    csv_header <- output_table[1, ]
    csv_body <- output_table[-1, ]
    state_table <- as.data.frame(csv_body)

    if (nrow(state_table) > 0) {
        colnames(state_table) <- csv_header
        state_table <- state_table[seq(1, length(state_table[, 1]), by = 2), ]
    }

    return(state_table)
}


#' Check for a Stain ssh key.
#'
#' @return If a public/private key pair exists in \code{~/.ssh/} with the name
#' \code{stain_rsa}, return TRUE, otherwise return FALSE.
stain_ssh_key_exists <- function() {
    return("stain_rsa" %in% list.files("~/.ssh/"))
}


#' Generate a Stain ssh key.
#'
#' A 4096 bit key will be generated and stored in \code{~/.ssh/} with the name
#' \code{stain_rsa}.
#'
#' @param overwrite Should an existing Stain ssh key be overwritten. Default
#' value is FALSE.
stain_ssh_key_gen <- function(overwrite = FALSE) {
    if (overwrite | !(overwrite | stain_ssh_key_exists())) {
        system("ssh-keygen -b 4096 -f ~/.ssh/stain_rsa -N ''")
    }
}


#' Create bash code for ssh setup.
#'
#' In order for a remote submission to work, an ssh public key for Stain must
#' be present in the remote host's \code{~/.ssh/authorized_keys} list. This
#' process requires two steps. 1) To \code{scp} the public key and 2) to add
#' the key to \code{~/.ssh/authorized_keys}. This function will autogenerate
#' the necessary bash code to complete these steps.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @return A single bash command to run.
#'
#' @export
stain_ssh_setup <- function(user, host) {
    remote_host <- paste(user, host, sep = "@")
    scp <- paste0("scp ~/.ssh/stain_rsa.pub ", remote_host, ":~/.ssh/stain_rsa.pub")
    ssh <- paste("ssh", remote_host, "'echo `cat ~/.ssh/stain_rsa.pub` >> ~/.ssh/authorized_keys'")
    cmd <- paste(scp, "&&", ssh)

    if (Sys.info()["sysname"] == "Darwin") {
        cat("The bash command to setup remote submission has been copied to your clipboard. Run it in your terminal.")
        utils::write.table(cmd, file = pipe("pbcopy"), sep = "\t",
                           col.names = F, row.names = F , quote = F)
    } else {
        cat("Run the following bash command in your terminal to setup remote submission:")
        cat(cmd)
    }
}
#' ssh with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param cmds A sting of one or more commands to run on the remote host.
#'
#' @param intern Indicates whether to capture the output of the command
#' as an R character vector.
#'
stain_ssh <- function(user, host, cmds = "", intern = FALSE) {
    if (is.null(user) | is.null(host)) {
        stop("No user or host specified.", call. = FALSE)
    }

    if (!stain_ssh_key_exists()) {
        invisible(stain_ssh_key_gen())
    }

    remote_host <- paste(user, host, sep = "@")
    system(paste("ssh", remote_host, "-t -t -i ~/.ssh/stain_rsa",
                 paste0("\"", cmds, "\"")),
           intern = intern)
}


#' scp with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param from The directory or file to copy.
#'
#' @param to The destination.
stain_scp <- function(from, to) {
    system(paste("scp -i ~/.ssh/stain_rsa -r", from, to))
}


#' Get squeue info on certain jobs.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param job_ids A collection of job ids for which to fetch statuses.
#'
#' @return A data frame with columns corresponding to those produced
#' by the \code{squeue -l} command.
stain_ssh_squeue <- function(user, host, job_ids) {
    job_ids <- paste(job_ids, collapse = ",")
    remote_host <- paste(user, host, sep = "@")

    squeue_cmd <- paste("squeue -l -j", job_ids)
    output <- stain_ssh(user, host, squeue_cmd, intern = TRUE)

    output_table <- sapply(output, USE.NAMES = FALSE, function(row) {
        tokens <- strsplit(row, " ")[[1]]
        return(tokens[tokens != ""])
    })

    csv_header <- paste(output_table[[2]], collapse = "\t")
    csv_header <-  gsub("[\r]", "", csv_header)

    if (length(output_table) > 2) {
        csv_body <- paste(lapply(output_table[3:length(output_table)], function(row) {
            row <- paste(row, collapse = "\t")
            row <-  gsub("[\r]", "", row)
            return(row)
        }), collapse = "\n")
        csv <- paste(csv_header, csv_body, sep = "\n")
    } else {
        csv <- csv_header
    }

    state_table <- utils::read.delim(textConnection(csv))

    return(state_table)
}


#' Get sacct info on certain jobs.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param job_ids A collection of job ids for which to fetch statuses.
#'
#' @return A data frame with columns corresponding to those produced
#' by the \code{sacct --brief --jobs} command.
stain_ssh_sacct <- function(user, host, job_ids) {
    job_ids <- paste(job_ids, collapse = ",")
    remote_host <- paste(user, host, sep = "@")

    sacct_cmd <- paste("sacct --brief --jobs", job_ids)
    output <- stain_ssh(user, host, sacct_cmd, intern = TRUE)
    output[2] <- NA
    output <- output[!is.na(output)]

    output_table <- t(sapply(output, USE.NAMES = FALSE, function(row) {
        tokens <- strsplit(row, " ")[[1]]
        return(tokens[tokens != "" & tokens != "\r"])
    }))

    csv_header <- output_table[1, ]
    csv_body <- output_table[-1, ]
    state_table <- as.data.frame(csv_body)

    if (nrow(state_table) > 0) {
        colnames(state_table) <- csv_header
        state_table <- state_table[seq(1, length(state_table[, 1]), by = 2), ]
    }

    return(state_table)
}


#' Check for a Stain ssh key.
#'
#' @return If a public/private key pair exists in \code{~/.ssh/} with the name
#' \code{stain_rsa}, return TRUE, otherwise return FALSE.
stain_ssh_key_exists <- function() {
    return("stain_rsa" %in% list.files("~/.ssh/"))
}


#' Generate a Stain ssh key.
#'
#' A 4096 bit key will be generated and stored in \code{~/.ssh/} with the name
#' \code{stain_rsa}.
#'
#' @param overwrite Should an existing Stain ssh key be overwritten. Default
#' value is FALSE.
stain_ssh_key_gen <- function(overwrite = FALSE) {
    if (overwrite | !(overwrite | stain_ssh_key_exists())) {
        system("ssh-keygen -b 4096 -f ~/.ssh/stain_rsa -N ''")
    }
}


#' Create bash code for ssh setup.
#'
#' In order for a remote submission to work, an ssh public key for Stain must
#' be present in the remote host's \code{~/.ssh/authorized_keys} list. This
#' process requires two steps. 1) To \code{scp} the public key and 2) to add
#' the key to \code{~/.ssh/authorized_keys}. This function will autogenerate
#' the necessary bash code to complete these steps.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @return A single bash command to run.
#'
#' @export
stain_ssh_setup <- function(user, host) {
    remote_host <- paste(user, host, sep = "@")
    scp <- paste0("scp ~/.ssh/stain_rsa.pub", remote_host, ":~/.ssh/stain_rsa.pub")
    ssh <- paste0("ssh ", scp, " 'echo `cat ~/.ssh/stain_rsa.pub` >> ~/.ssh/authorized_keys'")
    cmd <- paste0(scp, " && ", ssh)

    if (Sys.info()["sysname"] == "Darwin") {
        cat("The bash command to setup remote submission has been copied to your clipboard. Run it in your terminal.")
        utils::write.table(cmd, file = pipe("pbcopy"), sep = "\t",
                           col.names = F, row.names = F , quote = F)
    } else {
        cat("Run the following bash command in your terminal to setup remote submission:")
        cat(cmd)
    }
}
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        cancel = function(job_ids, user = private$user, host = private$host) {
            job_ids <- paste(job_ids, collapse = ",")

            stain_ssh(user, host, paste("scancel", job_ids))
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host,
                          submit_dir = "~/stain", dependency_list = "") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")

                # Add any dependencies to sbatch command.
                history <- self$submission_history()$job_id
                dependencies <- sbatch_dependency_list(dependency_list, history)
                submit_cmd <- paste("sbatch submit.slurm",
                                    sbatch_opt("dependency")(dependencies))
                submit_cmd <- paste("cd", job_dir, "&&", submit_cmd)
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir = "~/stain") {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        submission_history = function() {
            # `stain_sub_history` will warn if submission history is empty.
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                return(history)
            }
        },
        fetch_job_states = function(user = private$user, host = private$host) {
            job_ids <- stain_sub_history(self$dir)$job_id

            verify_state_table <- function(state_table) {
                if (nrow(status_table) > 0) {
                    return(state_table)
                } else {
                    job_ids <- paste(job_ids, collapse = ", ")
                    message(paste("No statuses found for job ids:", job_ids))
                }
            }

            fetch_squeue_table <- function() {
                tryCatch({
                    squeue_table <- stain_ssh_squeue(user, host, job_ids)
                    squeue_table <- squeue_table[, c("JOBID", "STATE")]
                    colnames(squeue_table) <- c("job_id", "state")
                    # Will throw error if data frame has no rows.
                    squeue_table$exit_code <- NA
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    squeue_table <- data.frame()
                }, finally = return(squeue_table))
            }

            fetch_sacct_table <- function() {
                tryCatch({
                    sacct_table <- stain_ssh_sacct(user, host, job_ids)
                    colnames(sacct_table) <- c("job_id", "state", "exit_code")
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    sacct_table <- data.frame()
                }, finally = return(sacct_table))
            }

            squeue_table <- fetch_squeue_table()
            sacct_table <- fetch_sacct_table()
            states <- rbind(squeue_table, sacct_table)
            states <- aggregate(states, list(states$job_id), function(x) {
                na.omit(x)[1]
            })[,-1]

            return(states)
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
## source('~/Master_Thesis/pckg.cheb/R/functions-chebyshev.r')
##
## library(devtools)
## library(roxygen2)
##
## Build and Reload Package:  'Ctrl + Shift + B'
## Check Package:             'Ctrl + Shift + E'
## Test Package:              'Ctrl + Shift + T'


##
#' @title Scaling of X-Axis
#' @param x.axis ursprüngliche beliebige X-Achse (Vektor)
#' @return x.cheb.scaled skalierte X-Achse (Vektor)
#' @description
#' \code{cheb.scale} skaliert beliebige X-Achse auf Achse, die für Polynom-fits verträglich ist.
#' @examples
#' x.axis <- c(0:30)
#' x.cheb.scaled <- cheb.scale(x.axis)
cheb.scale <- function(x.axis) {#, scale) {
  ## Funktion zur Skalierung von Stützpunkten
  ## von beliebigen Gittern auf [-1, 1]
  ## ##
  #  if (type == "cheb") {
  x.cheb.scaled <- (2 * (x.axis - x.axis[1]) / (max(x.axis) - min(x.axis))) - 1
  #  }
  return(x.cheb.scaled)
}


##
#' @title Rescaling of X-Axis
#' @param x.cheb skalierte X-Achse (Skalar oder Vektor)
#' @param x.axis beliebige X-Achse (Vektor)
#' @return x.rescaled reskalierte X-Achse (Skalar oder Sektor)
#' @description
#' cheb.rescale reskaliert die für den Fit erzeugte Achse auf die Ursprüngliche
#' @examples
#' x.rescaled <- cheb.rescale(x.cheb, x.axis)
cheb.rescale <- function(x.cheb, x.axis) {
  ## Funktion zur Reskalierung vom [-1, 1]-Gitter
  ## auf das Ursprungsgitter (in diesem Fall - Lat)
  ## ##
  x.rescaled <- (1/2 * (x.cheb + 1) * (max(x.axis) - min(x.axis))) + x.axis[1]
  return(x.rescaled)
}


##
#' @title Generating Chebyshev Polynomials of first kind
#' @param x.axis beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.t Chebyshev-Polynome Erster Art (Vektor)
#' @description
#' cheb.1st erzeugt Chebyshev Polynome erster Art aus beliebiger X-Achse
#' @examples
#' cheb.t <- cheb.1st(x.axis, n)
cheb.1st <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Erster Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis  ### ###
  m <- n + 1
  # Rekursionsformel Wiki / Bronstein
  cheb.t.0 <- 1;  cheb.t.1 <- x.cheb;
  cheb.t <- cbind(cheb.t.0, cheb.t.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.t.i <- 2 * x.cheb * cheb.t[,(i - 1)] - cheb.t[,(i - 2)]
      cheb.t <- cbind(cheb.t, cheb.t.i)
      rm(cheb.t.i)
    }
  }
  return(cheb.t)
}


##
#' @title Generating Chebyshev Polynomials of second kind
#' @param x.axis beliebigie X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.u Chebyshev-Polynome Zweiter Art (Vektor)
#' @description
#' cheb.2nd erzeugt Chebyshev Polynome zweiter Art aus beliebiger X-Achse
#' @examples
#' cheb.u <- cheb.2nd(x.axis, n)
cheb.2nd <- function(x.axis, n){
  ## Funktion zur Erzeugung von Chebyshev-Polynomen Zweiter Art
  ## ##
  x.cheb <- if (max(x.axis) - min(x.axis) > 2) cheb.scale(x.axis) else x.axis
  m <- n + 1
  cheb.u.0 <- 1; cheb.u.1 <-  2*x.cheb
  cheb.u <- cbind(cheb.u.0, cheb.u.1)
  if (n >= 2) {
    for (i in 3:m) {
      cheb.u.i <- 2 * x.cheb * cheb.u[,(i - 1)] - cheb.u[,(i - 2)]
      cheb.u <- cbind(cheb.u, cheb.u.i)
      rm(cheb.u.i)
    }
  }
  return(cheb.u)
}


##
#' @title Calculation of Values of the model fit
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model gefiltertes Modell (Skalar oder Vektor)
#' @description
#' cheb.model berechnet aus den Chebyshev-Koeffizienten die Y-Werte
#' @examples
#' cheb.model <- cheb.model.filter(x.axis, cheb.coeff)
cheb.model.filter <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte aus X-Stellen und Cheb-Koeffizienten
  ## ##
  n <- length(cheb.coeff) - 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.model <- cheb.t %*% cheb.coeff
  return(cheb.model)
}


##
#' @title Calculation of the values of the first derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv.1st Erste Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.1st berechnet aus den Chebyshev-Koeffizienten die Werte der ersten Ableitung
#' @examples
#' cheb.model.deriv <- cheb.deriv.1st(x.axis, cheb.coeff)
cheb.deriv.1st <- function(x.axis, cheb.coeff) {
  ## Funktion zur Berechnung der Y-Werte der Ableitung des Modells
  ## aus X-Stellen und Chebyshev-Koeffizienten
  ## ##
  if (length(x.axis) != 0) { ### Überprüfen, ob nötig
    n <- length(cheb.coeff) - 1
    m <- n + 1
    cheb.u <- cheb.2nd(x.axis, n)

    # berechnung der ableitung der polynome erster art
    # rekursionsformel 0
    # dT/dx = n * U_(n-1)
    cheb.t.deriv <- if (length(x.axis) == 1) (2:m)*t(cheb.u[,1:n]) else t((2:m)*t(cheb.u[,1:n]))
    cheb.model.deriv.1st <- cheb.t.deriv %*% cheb.coeff[2:m]
    return(cheb.model.deriv.1st)
  }
}


##
#' @title Calculation of the values of the second derivation
#' @param x.axis beliebige X-Achse (Skalar oder Vektor)
#' @param cheb.coeff Chebyshev-Koeffizienten aus Least-Squares-Verfahren (Vektor)
#' @return cheb.model.deriv Zweite Ableitung des gefilterten Modells (Skalar oder Vektor)
#' @description
#' cheb.deriv.2nd berechnet aus den Chebyshev-Koeffizienten die Werte der zweiten Ableitung
#' @examples
#' cheb.model.deriv.2nd <- cheb.deriv.2nd(x.axis, cheb.coeff)
cheb.deriv.2nd <- function(x.axis, cheb.coeff) {
  n <- length(cheb.coeff) - 1
  m <- n + 1
  cheb.t <- cheb.1st(x.axis, n)
  cheb.u <- cheb.2nd(x.axis, n)
  x.cheb <- cheb.scale(x.axis)
  cheb.t.deriv.2nd <- t((((1:m) ** 2) + (1:m)) %*% t(1 / (x.cheb ** 2 - 1)) * t(cheb.t - cheb.u))
  cheb.t.deriv.2nd[1,] <- (-1) * ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.t.deriv.2nd[length(x.cheb),] <- ((1:m) ** 4 - (1:m) ** 2) / (3)
  cheb.model.deriv.2nd <- cheb.t.deriv.2nd %*% cheb.coeff
  return(cheb.model.deriv.2nd)
}


##
#' @title Curve Fitting with Chebyshev Polynomials
#' @param d Zu fittender Datensatz/Zeitreihe (Vektor)
#' @param x.axis Beliebige X-Achse (Vektor)
#' @param n Ordnung des Polynoms (Skalar)
#' @return cheb.list Berechnete Parameter (Koeffizienten, gefiltertes Modell, erste und zweite Ableitung des gefilterten Modells, Extremstellen und -Werte) (Liste)
#' @description
#' \code{cheb.fit} fittet ein Chebyshev-Polynom beliebiger Ordnung an einen Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.list <- cheb.fit(d, x.axis, n)
cheb.fit <- function(d, x.axis, n){
  library(rootSolve)
  x.cheb <- cheb.scale(x.axis)
  cheb.t <- cheb.1st(x.axis, n)
#  cheb.u <- cheb.2nd(x.axis, n)
#  m <- n + 1
  ## modell berechnungen
  # berechnung der koeffizienten des polyfits
  cheb.coeff <- solve(t(cheb.t) %*% cheb.t) %*% t(cheb.t) %*% d
  # berechnung des gefilterten modells
  cheb.model <- cheb.model.filter(x.cheb, cheb.coeff)
  # berechnung des abgeleiteten modells
  cheb.model.deriv.1st <- cheb.deriv.1st(x.cheb, cheb.coeff)

  # berechnung der nullstellen
  extr <- rootSolve::uniroot.all(cheb.deriv.1st, cheb.coeff = cheb.coeff, lower = (-1), upper = 1)
  # reskalierung der Nullstellen auf normale Lat- Achse
  x.extr <- if (length(extr) != 0) cheb.rescale(extr, x.axis = x.axis)
  y.extr <- if (length(extr) != 0) cheb.model.filter(x.axis = extr, cheb.coeff = cheb.coeff)

  cheb.list <- list(cheb.coeff = cheb.coeff, cheb.model = cheb.model, cheb.model.deriv.1st = cheb.model.deriv.1st, x.extr = x.extr, y.extr = y.extr)
  return(cheb.list)
}



##
#' @title Curve Fitting with Chebyshev Polynomials over Sequences
#' @description
#' Fittet ein Chebyshev Polynom beliebiger Ordnung an einen sequenzierten Datensatz/Zeitreihe mittels Least Squares Verfahren
#' @examples
#' cheb.fit.seq(d, x.axis, n, l)
cheb.fit.seq <- function(d, x.axis, n, l){
  library(rootSolve)
  x.mat <- matrix(x.axis, ncol = l, byrow = TRUE)
  d.mat <- matrix(d, ncol = l, byrow = TRUE)

  # schleife über sequenzen des Datensatzes
  for (i in 1:length(x.mat[,1])) {
    # print(i)
    # erstellung der sequenzen
    x.seq <- if (i == 1) c(x.mat[i,]) else c(x.mat[(i - 1), dim(x.mat)[2]], x.mat[i,])
    x.cheb.seq <- cheb.scale(x.seq)
    d.seq <- if (i == 1) c(d.mat[i,]) else c(d.mat[(i - 1), dim(d.mat)[2]], d.mat[i,])
    cheb.t.seq <- cheb.1st(x.seq, n)
    ## modell berechnungen
    # berechnung der koeffizienten des polyfits
    cheb.coeff.seq <- solve(t(cheb.t.seq) %*% cheb.t.seq) %*% t(cheb.t.seq) %*% d.seq
    cheb.coeff <- if (i == 1) cheb.coeff.seq else cbind(cheb.coeff, cheb.coeff.seq)
    # berechnung des gefilterten modells
    cheb.model.seq <- cheb.model.filter(x.cheb.seq, cheb.coeff.seq)
    cheb.model <- if (i == 1) cheb.model.seq else c(cheb.model, cheb.model.seq[2:(l+1)])
    # berechnung des abgeleiteten modells
    cheb.model.deriv.1st.seq <- cheb.deriv.1st(x.cheb.seq, cheb.coeff.seq)
    cheb.model.deriv.1st <- if (i == 1) cheb.model.deriv.1st.seq else c(cheb.model.deriv.1st, cheb.model.deriv.1st.seq[2:(l+1)])

    # berechnung der nullstellen
    extr.seq <- rootSolve::uniroot.all(cheb.deriv.1st, cheb.coeff = cheb.coeff.seq, lower = (-1), upper = 1)
    # reskalierung der Nullstellen auf normale Lat- Achse
    x.extr.seq <- if (length(extr.seq) != 0) cheb.rescale(extr.seq, x.axis = x.seq)
    y.extr.seq <- if (length(extr.seq) != 0) cheb.model.filter(x.axis = extr.seq, cheb.coeff = cheb.coeff.seq)
    #
    if (exists("x.extr.seq") == TRUE & exists("x.extr") == FALSE) {
      x.extr <- x.extr.seq
      y.extr <- y.extr.seq
    } else if (exists("x.extr.seq") == TRUE & exists("x.extr") == TRUE) {
      x.extr <- c(x.extr, x.extr.seq)
      y.extr <- c(y.extr, y.extr.seq)
    }
  }

  ## übergabe der variablen als liste
  cheb.list <- list(cheb.model = cheb.model, cheb.model.deriv.1st = cheb.model.deriv.1st, extr.x = x.extr, extr.y = y.extr)
  return(cheb.list)
}

#' Create an SBATCH option
#'
#' @param key The key for the sbatch option.
#'
#' @return A function that takes a single argument representing
#' the value for the \code{key}.
sbatch_opt <- function(key) {
    return(function(value) {
        return(paste0("--", key, "=", value))
    })
}


#' Test sbatch options for equality.
#'
#' sbatch option equallity is achieved if the keys of the options
#' are the same.
#'
#' @param opt_1 An sbatch option string.
#'
#' @param opt_2 An sbatch option string.
#'
#' @return A boolean value.
sbatch_opts_equal <- function(opt_1, opt_2) {
    return(sbatch_opt_key(opt_1) == sbatch_opt_key(opt_2))
}


#' Insert an sbatch option into a set.
#'
#' @param opt The sbatch option to insert
#'
#' @param opts A set of sbatch options. Default value is the empty
#' set.
#'
#' @return A set with \code{opt} inserted.
sbatch_opts_insert <- function(opt, opts = c()) {
    did_set <- FALSE

    for (i in 1:length(opts)) {
        if (sbatch_opts_equal(opt, opts[i])) {
            opts[i] = opt
            did_set = TRUE
        }
    }

    if(!did_set) {
        opts <- c(opts, opt)
    }

    return(opts)
}


#' Get the key of an sbatch.
#'
#' @param opt An sbatch option string.
#'
#' @return The \code{opt}'s key.
sbatch_opt_key <- function(opt) {
    return(strsplit(opt, "=")[[1]][1])
}


#' Get the value of an sbatch option.
#'
#' @param opt An sbatch option string.
#'
#' @return The \code{opt}'s value.
sbatch_opt_value <- function(opt) {
    return(strsplit(opt, "=")[[1]][2])
}


#' A list of sbatch options.
#'
#' The value of each item in the list is a string or a function
#' which takes a string as a parameter, using \code{sbatch_opt}.
#'
#' To ensure proper formatting, the \code{mail_type} option should
#' be set using \code{sbatch_mail_types}. Multiple mail types need
#' to be comma seperated.
#'
#' @export
sbatch_opts <- list (
    begin = sbatch_opt("begin"),
    cpus_per_task = sbatch_opt("cpus-per-task"),
    mail_user = sbatch_opt("mail-user"),
    memory = sbatch_opt("mem"),
    nodes = sbatch_opt("nodes"),
    output = sbatch_opt("output"),
    time = sbatch_opt("time")
)


#' A list of sbatch mail types.
#'
#' The value of each item in the list is a string representing
#' a mail type option.
#'
#' @export
sbatch_mail_type_opts <- list(
    all = sbatch_opt("mail-type")("ALL"),
    begin = sbatch_opt("mail-type")("BEGIN"),
    end = sbatch_opt("mail-type")("END"),
    fail = sbatch_opt("mail-type")("FAIL"),
    none = sbatch_opt("mail-type")("NONE"),
    requeue = sbatch_opt("mail-type")("REQUEUE"),
    stage_out = sbatch_opt("mail-type")("STAGE_OUT"),
    time_limit = sbatch_opt("mail-type")("TIME_LIMIT"),
    time_limit_90 = sbatch_opt("mail-type")("TIME_LIMIT_90"),
    time_limit_80 = sbatch_opt("mail-type")("TIME_LIMIT_80"),
    time_limit_50 = sbatch_opt("mail-type")("TIME_LIMIT_50")
)


#' Create single sbatch mail type key value pair.
#'
#' A user may specific multiple \code{sbatch_mail_type_opts},
#' which must be combined into a single key value pair that
#' contains the options seperated by commas.
#'
#' @param opts A list of sbatch mail type options.
sbatch_mail_type_combine <- function(opts) {
    opt_keys <- sapply(opts, sbatch_opt_key, USE.NAMES = FALSE)
    mail_type_opts <- which(opt_keys == "--mail-type")

    mail_type_opt_vals <- sapply(opts[mail_type_opts], sbatch_opt_value,
                                 USE.NAMES = FALSE)
    mail_type_opt_val <- paste(unique(mail_type_opt_vals), collapse = ",")
    mail_type_opt <- sbatch_opt("mail-type")(mail_type_opt_val)

    return(c(opts[-mail_type_opts], mail_type_opt))
}


#' Fill in dependency list placeholders.
#'
#' The placeholders \code{PREVIOUS(ALL)} and \code{PREVIOUS(<n>)} can be used in
#' a sbatch dependency list and are replaced by all or n of the previous
#' submission job ids.
#'
#' @param dep_list The string dependency list value of the key-value pair
#' for a sbatch dependency list options.
#'
#' @param job_id_sub_history An array of job ids ordered oldest to newest.
#'
#' @return A dependency list with the proper job ids in the list.
sbatch_dependency_list <- function(dep_list, job_id_sub_history) {
    # Order from newest to oldest.
    job_id_sub_history <- rev(job_id_sub_history)

    regex <- "PREVIOUS[(]([1-9]+)[)]"
    to_replace <- stringr::str_match_all(dep_list, regex)[[1]]

    if (length(to_replace) > 0) {
        to_replace <- as.data.frame(to_replace)
        colnames(to_replace) <- c("regexp", "n")
        to_replace$n <- as.numeric(as.character(to_replace$n))
        to_replace$regexp <- as.character(to_replace$regexp)

        # Create a literal parentheses regex expression.
        to_replace$regexp <- sapply(to_replace$regexp, function(exp) {
            exp <- gsub("[(]", "[(]", exp)
            exp <- gsub("[)]", "[)]", exp)
            return(exp)
        })

        prev_n_jobs <- function(n) {
            job_ids <- job_id_sub_history[1:n]
            is.na(job_ids) <- NULL
            return(paste(job_ids, collapse = ":"))
        }

        to_replace$replacement <- sapply(to_replace$n, prev_n_jobs)

        for (i in length(to_replace$replacement)) {
            row <- to_replace[i, ]
            dep_list <- gsub(row$regexp, row$replacement, dep_list)
        }
    }

    regex <- "PREVIOUS[(]ALL[)]"
    dep_list <- gsub(regex, paste(job_id_sub_history, collapse = ":"), dep_list)

    return(dep_list)
}
context("sbatch")


test_that("All options are formated correctly", {
    expect_equal(sbatch_opts$begin("00:00:01"), "--begin=00:00:01")
    expect_equal(sbatch_opts$cpus_per_task(12), "--cpus-per-task=12")
    expect_equal(sbatch_opts$mail_user("user@address"),
                 "--mail-user=user@address")
    expect_equal(sbatch_opts$memory(1200), "--mem=1200")
    expect_equal(sbatch_opts$memory("16g"), "--mem=16g")
    expect_equal(sbatch_opts$nodes(1), "--nodes=1")
    expect_equal(sbatch_opts$output("file.txt"), "--output=file.txt")
    expect_equal(sbatch_opts$time("00:00:01"), "--time=00:00:01")
})

test_that("sbatch_opt creates a new key-value option.", {
    expect_equal(sbatch_opt("key")("value"), "--key=value")
})

test_that("Options equality is base on option keys.", {
    a <- sbatch_opt("a")("true")
    b <- sbatch_opt("b")("false")
    a_ <- sbatch_opt("a")("false")

    expect_true(sbatch_opts_equal(a, a_))
    expect_false(sbatch_opts_equal(a, b))

    expect_equal(sbatch_opts_insert(a_, c(a, b)), c(a_, b))
    expect_equal(sbatch_opts_insert(a, c(b)), c(b, a))
})

test_that("Multiple sbatch mail type options are combined while other options
          remain the same.", {
    # Note that the option duplication is on purpose.
    opts <- c(
        sbatch_mail_type_opts$begin,
        sbatch_mail_type_opts$begin,
        sbatch_mail_type_opts$end,
        sbatch_mail_type_opts$fail,
        sbatch_opts$memory("16g")
    )

    expected <- c(
        sbatch_opts$memory("16g"),
        sbatch_opt("mail-type")("BEGIN,END,FAIL")
    )

    expect_equal(sbatch_mail_type_combine(opts), expected)
})

test_that("Dependency list macros are replaced with correct job ids.", {
    job_history <- c("1", "2", "3", "4")
    expect_equal(sbatch_dependency_list("after:PREVIOUS(2)", job_history),
                 "after:4:3")

})
#formats and combines phenotype (of a single trait)
#and genotype datasets of multiple
#populations

options(echo = FALSE)

library(stats)
library(stringr)
library(randomForest)
library(plyr)
library(lme4)
library(data.table)


allArgs <- commandArgs()

inFile <- grep("input_files",
               allArgs,
               ignore.case = TRUE,
               perl = TRUE,
               value = TRUE
               )

outFile <- grep("output_files",
                allArgs,
                ignore.case = TRUE,
                perl = TRUE,
                value = TRUE
                )

outFiles <- scan(outFile,
                 what = "character"
                 )

combinedGenoFile <- grep("genotype_data",
                         outFiles,
                         ignore.case = TRUE,
                         fixed = FALSE,
                         value = TRUE
                         )

combinedPhenoFile <- grep("phenotype_data",
                          outFiles,
                          ignore.case = TRUE,
                          fixed = FALSE,
                          value = TRUE
                          )

inFiles <- scan(inFile,
                what = "character"
                )
print(inFiles)

traitFile <- grep("trait_",
                  inFiles,
                  ignore.case = TRUE,
                  fixed = FALSE,
                  value = TRUE
                  )

trait <- scan(traitFile,
              what = "character",
              )

traitInfo<-strsplit(trait, "\t");
traitId<-traitInfo[[1]]
traitName<-traitInfo[[2]]

#extract trait phenotype data from all populations
#and combine them into one dataset

allPhenoFiles <- grep("phenotype_data",
                  inFiles,
                  ignore.case = TRUE,
                  fixed = FALSE,
                  value = TRUE
                  )
message("phenotype files: ", allPhenoFiles)

allGenoFiles <- grep("genotype_data",
                  inFiles,
                  ignore.case = TRUE,
                  fixed = FALSE,
                  value = TRUE
                  )

popsPhenoSize     <- length(allPhenoFiles)
popsGenoSize      <- length(allGenoFiles)
popIds            <- c()
combinedPhenoPops <- c()

for (popPhenoNum in 1:popsPhenoSize)
  {
    popId <- str_extract(allPhenoFiles[[popPhenoNum]], "\\d+")
    popIds <- append(popIds, popId)

    phenoData <- fread(allPhenoFiles[[popPhenoNum]],
                            na.strings = c("NA", " ", "--", "-", "."),
                           )


    phenoTrait <- subset(phenoData,
                         select = c("object_name", "object_id", "design", "block", "replicate", traitName)
                         )
  
    experimentalDesign <- phenoTrait[2, 'design']
    
    if (is.na(experimentalDesign) == TRUE) {experimentalDesign <- c('No Design')}

    if ((experimentalDesign == 'Augmented' || experimentalDesign == 'RCBD')  &&  unique(phenoTrait$block) > 1) { 

      message("experimental design: ", experimentalDesign)

      augData <- subset(phenoTrait,
                        select = c("object_name", "object_id",  "block",  traitName)
                        )

      colnames(augData)[1] <- "genotypes"
      colnames(augData)[4] <- "trait"

      model <- try(lmer(trait ~ 0 + genotypes + (1|block),
                        augData,
                        na.action = na.omit
                        ))
     
      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
        
        colnames(phenoTrait) <- traitName

        nn <- gsub('genotypes', '', rownames(phenoTrait))  
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
  
        formattedPhenoData[, traitName] <- phenoTrait
      }
      
    } else if (experimentalDesign == 'Alpha') {

      alphaData <-  phenoTrait 

      colnames(alphaData)[1] <- "genotypes"
      colnames(alphaData)[5] <- "trait"
         
      model <- try(lmer(trait ~ 0 + genotypes + (1|replicate/block),
                        alphaData,
                        na.action = na.omit
                        ))
        
      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
      
        colnames(phenoTrait) <- traitName

        nn <- gsub('genotypes', '', rownames(phenotrait))     
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)

        formattedPhenoData[, i] <- phenoTrait
      }
      
  } else {

    phenoTrait <- subset(phenoData,
                         select = c("object_name", "stock_id", traitName)
                         )
    
    if (sum(is.na(phenoTrait)) > 0) {
      message("No. of pheno missing values: ", sum(is.na(phenoTrait))) 
     
      phenoTrait <- na.omit(phenoTrait)
       
      #calculate mean of reps/plots of the same accession and
      #create new df with the accession means
      phenoTrait$stock_id <- NULL
      phenoTrait   <- phenoTrait[order(row.names(phenoTrait)), ]
   
      print('phenotyped lines before averaging')
      print(length(row.names(phenoTrait)))
        
      phenoTrait<-ddply(phenoTrait, "object_name", colwise(mean))
        
      print('phenotyped lines after averaging')
      print(length(row.names(phenoTrait)))
   
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1] <- NULL

      phenoTrait <- round(phenoTrait, digits = 2)

    } else {
      print ('No missing data')
      phenoTrait$stock_id <- NULL
      phenoTrait   <- phenoTrait[order(row.names(phenoTrait)), ]
   
      print('phenotyped lines before averaging')
      print(length(row.names(phenoTrait)))
      
      phenoTrait<-ddply(phenoTrait, "object_name", colwise(mean))
      
      print('phenotyped lines after averaging')
      print(length(row.names(phenoTrait)))

      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1] <- NULL

      phenoTrait <- round(phenoTrait, digits = 2)

    }
  }    
    newTraitName = paste(traitName, popId, sep = "_")
    colnames(phenoTrait)[1] <- newTraitName

    if (popPhenoNum == 1 )
      {
        print('no need to combine, yet')       
        combinedPhenoPops <- phenoTrait
        
      } else {
      print('combining...') 
      combinedPhenoPops <- merge(combinedPhenoPops, phenoTrait,
                            by = 0,
                            all=TRUE,
                            )

      rownames(combinedPhenoPops) <- combinedPhenoPops[, 1]
      combinedPhenoPops$Row.names <- NULL
      
    }   
}

#fill in missing data in combined phenotype dataset
#using row means
naIndices <- which(is.na(combinedPhenoPops), arr.ind=TRUE)
combinedPhenoPops <- as.matrix(combinedPhenoPops)
combinedPhenoPops[naIndices] <- rowMeans(combinedPhenoPops, na.rm=TRUE)[naIndices[,1]]
combinedPhenoPops <- as.data.frame(combinedPhenoPops)

message("combined total number of stocks in phenotype dataset (before averaging): ", length(rownames(combinedPhenoPops)))

combinedPhenoPops$Average<-round(apply(combinedPhenoPops,
                                       1,
                                       function(x)
                                       { mean(x) }
                                       ),
                                 digits = 2
                                 )

markersList      <- c()
combinedGenoPops <- c()

for (popGenoNum in 1:popsGenoSize)
  {
    popId <- str_extract(allGenoFiles[[popGenoNum]], "\\d+")
    popIds <- append(popIds, popId)

    genoData <- fread(allGenoFiles[[popGenoNum]],
                            na.strings = c("NA", " ", "--", "-"),
                           )

    genoData           <- as.data.frame(genoData)
    rownames(genoData) <- genoData[, 1]
    genoData[, 1]      <- NULL
    
    popMarkers <- colnames(genoData)
    message("No of markers from population ", popId, ": ", length(popMarkers))
    #print(popMarkers)
  
    if (sum(is.na(genoData)) > 0)
      {
        message("sum of geno missing values: ", sum(is.na(genoData)))
        genoData <- na.roughfix(genoData)
        message("total number of stocks for pop ", popId,": ", length(rownames(genoData)))
      }

    if (popGenoNum == 1 )
      {
        print('no need to combine, yet')       
        combinedGenoPops <- genoData
        
      } else {
        print('combining genotype datasets...') 
        combinedGenoPops <-rbind(combinedGenoPops, genoData)
      }   
    
 
  }
message("combined total number of stocks in genotype dataset: ", length(rownames(combinedGenoPops)))
#discard duplicate clones
combinedGenoPops <- unique(combinedGenoPops)
message("combined unique number of stocks in genotype dataset: ", length(rownames(combinedGenoPops)))

message("writing data into files...")
#if(length(combinedPhenoFile) != 0 )
#  {
      write.table(combinedPhenoPops,
                  file = combinedPhenoFile,
                  sep = "\t",
                  quote = FALSE,
                  col.names = NA,
                  )
#  }

#if(length(combinedGenoFile) != 0 )
#  {
      write.table(combinedGenoPops,
                  file = combinedGenoFile,
                  sep = "\t",
                  quote = FALSE,
                  col.names = NA,
                  )
#  }

q(save = "no", runLast = FALSE)
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #

#             dddddddd                                                                    
#             d::::::d  iiii                                          RRRRRRRRRRRRRRRRR   
#             d::::::d i::::i                                         R::::::::::::::::R  
#             d::::::d  iiii                                          R::::::RRRRRR:::::R 
#             d:::::d                                                 RR:::::R     R:::::R
#     ddddddddd:::::d iiiiiiivvvvvvv           vvvvvvvaaaaaaaaaaaaa     R::::R     R:::::R
#   dd::::::::::::::d i:::::i v:::::v         v:::::v a::::::::::::a    R::::R     R:::::R
#  d::::::::::::::::d  i::::i  v:::::v       v:::::v  aaaaaaaaa:::::a   R::::RRRRRR:::::R 
# d:::::::ddddd:::::d  i::::i   v:::::v     v:::::v            a::::a   R:::::::::::::RR  
# d::::::d    d:::::d  i::::i    v:::::v   v:::::v      aaaaaaa:::::a   R::::RRRRRR:::::R 
# d:::::d     d:::::d  i::::i     v:::::v v:::::v     aa::::::::::::a   R::::R     R:::::R
# d:::::d     d:::::d  i::::i      v:::::v:::::v     a::::aaaa::::::a   R::::R     R:::::R
# d:::::d     d:::::d  i::::i       v:::::::::v     a::::a    a:::::a   R::::R     R:::::R
# d::::::ddddd::::::ddi::::::i       v:::::::v      a::::a    a:::::a RR:::::R     R:::::R
#  d:::::::::::::::::di::::::i        v:::::v       a:::::aaaa::::::a R::::::R     R:::::R
#   d:::::::::ddd::::di::::::i         v:::v         a::::::::::aa:::aR::::::R     R:::::R
#    ddddddddd   dddddiiiiiiii          vvv           aaaaaaaaaa  aaaaRRRRRRRR     RRRRRRR

#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #

# # # bug in plot_train for continuous? or two feature?
# # # bug in plot where those stray points appear at origin and max

# # # load utilities script
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
source('utils.r')

# # # Initialize model parameters
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
model <- list(num_blocks    = 20,
			  num_inits     = 5,
			  wts_range     = 1,
			  num_hids      = 3,
			  learning_rate = 0.15,
			  beta_val      = 5,
			  out_rule      = 'sigmoid') # linear / tan not implemented

# # # run demo ? 
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
demo <- TRUE  # run demo
# demo <- FALSE # do something else

if (demo == TRUE) {
  # # # create training results 
  training = matrix(rep(0, model$num_blocks * 7), ncol = 7)
  
  # # # initialize model and run it on each SHJ category structure
  for (shj in 1:7) { 

    # # # get shj stimuli
    cases <- shj_cats(shj)
    model$inputs <- cases$inputs
    model$labels <- cases$labels

    # # # train model
    result <- run_diva(model)

  # # # add result to training matrix
  training[,shj] <- result$training

  }

  # # # display results
  print(training)
  train_plot(training)
  save.image('diva_run.rdata')
}

# warnings()


suppressMessages (library(shiny))
suppressMessages (library(ggplot2))
suppressMessages (library(ggrepel))
suppressMessages (library(scales))
suppressMessages (library(DT))
suppressMessages (library(tidyr))
suppressMessages (library(dplyr))
suppressMessages (library(ggkm))
suppressMessages (library(Hmisc))
suppressMessages (library(quantreg))




stat_sum_df <- function(fun, geom="point", ...) {
  stat_summary(fun.data=fun,  geom=geom,  ...)
}
stat_sum_single <- function(fun, geom="point", ...) {
  stat_summary(fun.y=fun,  geom=geom,  ...)
}

median.n <- function(x){
  return(c(y = ifelse(median(x)<0,median(x),median(x)),
           label = round(median(x),2))) 
}
give.n <- function(x){
  return(c(y = min(x)*1,  label = length(x))) 
}

options(shiny.maxRequestSize=100*1024^2) 
#options(shiny.reactlog=TRUE) 
tableau10 <- c("#1F77B4","#FF7F0E","#2CA02C","#D62728","#9467BD",
               "#8C564B","#E377C2","#7F7F7F","#BCBD22","#17BECF")



ui  <-  fluidPage(
    titlePanel("Hello GHAP HBGDki Member!"),
    sidebarLayout(
  sidebarPanel(
    tabsetPanel(
      tabPanel("Inputs", 
               fileInput("datafile", "Choose csv file to upload",
                         multiple = FALSE, accept = c("csv")),
               uiOutput("ycol"),uiOutput("xcol"),
               tabsetPanel(id = "filtercategorize",
                           tabPanel("Categorize/Rename", 
                                    uiOutput("catvar"),
                                    uiOutput("ncuts"),
                                    uiOutput("catvar2"),
                                    uiOutput("catvar3"),
                                    uiOutput("ncuts2"),
                                    uiOutput("asnumeric"),
                                    textOutput("bintext"),
                                    uiOutput("catvar4"),
                                    textOutput("labeltext"),
                                    uiOutput("nlabels")
                                    ),
                           
                           tabPanel("Combine Variables", 
                                    uiOutput("pastevar")
                           ),
                           tabPanel("Filters", 
                                    uiOutput("maxlevels"),
                                    uiOutput("filtervar1"),
                                    uiOutput("filtervar1values"),
                                    uiOutput("filtervar2"),
                                    uiOutput("filtervar2values"),
                                    uiOutput("filtervar3"),
                                    uiOutput("filtervar3values"),
                                    uiOutput("filtervarcont1"),
                                    uiOutput("fslider1"),
                                    uiOutput("filtervarcont2"),
                                    uiOutput("fslider2"),
                                    uiOutput("filtervarcont3"),
                                    uiOutput("fslider3")
                           ),
                           tabPanel("Simple Rounding",
                                    uiOutput("roundvar"),
                                    numericInput("rounddigits",label = "N Digits",value = 0,min=0,max=10) 
                           ),
                           tabPanel("Reorder Variables", 
                                    uiOutput("reordervar"),
                                    conditionalPanel(condition = "input.reordervarin!='' " ,
                                                     selectizeInput(  "functionordervariable", 'The:',
                                                                      choices =c("Median","Mean","Minimum","Maximum") ,multiple=FALSE)
                                    ),
                                    uiOutput("variabletoorderby"),
                                    conditionalPanel(condition = "input.reordervarin!='' " ,
                                                     checkboxInput('reverseorder', 'Reverse Order ?', value = FALSE) ),
                                    
                                    uiOutput("reordervar2"),
                                    uiOutput("reordervar2values")
                           )
               ),
               hr()
      ), # tabsetPanel
      
      
      tabPanel("Graph Options",
               tabsetPanel(id = "graphicaloptions",
                           tabPanel(  "X/Y Log /Labels",
                                      hr(),
                                      textInput('ylab', 'Y axis label', value = "") ,
                                      textInput('xlab', 'X axis label', value = "") ,
                                      hr(),
                                      checkboxInput('logy', 'Log Y axis', value = FALSE) ,
                                      checkboxInput('logx', 'Log X axis', value = FALSE) ,
                                      conditionalPanel(condition = "!input.logy" ,
                                                       checkboxInput('scientificy', 'Comma separated Y axis ticks', value = FALSE)),
                                      conditionalPanel(condition = "!input.logx" ,
                                                       checkboxInput('scientificx', 'Comma separated X axis ticks', value = FALSE)),
                                      checkboxInput('rotateyticks', 'Rotate/Justify Y axis Ticks ?', value = FALSE),
                                      checkboxInput('rotatexticks', 'Rotate/Justify X axis Ticks ?', value = FALSE),
                                      conditionalPanel(condition = "input.rotateyticks" , 
                                                       sliderInput("yticksrotateangle", "Y axis ticks angle:", min=0, max=360, value=c(0),step=10),
                                                       sliderInput("ytickshjust", "Y axis ticks horizontal justification:", min=0, max=1, value=c(0.5),step=0.1),
                                                       sliderInput("yticksvjust", "Y axis ticks vertical justification:", min=0, max=1, value=c(0.5),step=0.1)
                                      ),
                                      conditionalPanel(condition = "input.rotatexticks" , 
                                                       sliderInput("xticksrotateangle", "X axis ticks angle:", min=0, max=360, value=c(20),step=10),
                                                       sliderInput("xtickshjust", "X axis ticks horizontal justification:", min=0, max=1, value=c(1),step=0.1),
                                                       sliderInput("xticksvjust", "X axis ticks vertical justification:", min=0, max=1, value=c(1),step=0.1)
                                      )
                                      
                           ),
                           tabPanel(  "Graph Size/Zoom",
                                      sliderInput("height", "Plot Height", min=1080/4, max=1080, value=480, animate = FALSE),
                                      h6("X Axis Zoom only works if facet x scales are not set to be free."),
                                      uiOutput("xaxiszoom")
                                      
                           ),
                           
                           tabPanel(  "Background Color and Legend Position",
                                      selectInput('backgroundcol', label ='Background Color',
                                                  choices=c("Gray" ="gray97","White"="white","Dark Gray"="grey90"),
                                                  multiple=FALSE, selectize=TRUE,selected="white"),
                                      selectInput('legendposition', label ='Legend Position',
                                                  choices=c("left", "right", "bottom", "top","none"),
                                                  multiple=FALSE, selectize=TRUE,selected="bottom"),
                                      selectInput('legenddirection', label ='Layout of Items in Legends',
                                                  choices=c("horizontal", "vertical"),
                                                  multiple=FALSE, selectize=TRUE,selected="horizontal"),
                                      selectInput('legendbox', label ='Arrangement of Multiple Legends ',
                                                  choices=c("horizontal", "vertical"),
                                                  multiple=FALSE, selectize=TRUE,selected="vertical")
                           ),
                           tabPanel(  "Facets Options",
                                      
                                      uiOutput("facetscales"),
                                      selectInput('facetspace' ,'Facet Spaces:',c("fixed","free_x","free_y","free")),
                                      
                                      selectizeInput(  "facetswitch", "Facet Switch to Near Axis:",
                                                       choices = c("x","y","both"),
                                                       options = list(  maxItems = 1 ,
                                                                        placeholder = 'Please select an option',
                                                                        onInitialize = I('function() { this.setValue(""); }')  )  ),
                                      checkboxInput('facetmargin', 'Show Facet(s) Margin(s) ?'),
                                      
                                      selectInput('facetlabeller' ,'Facet Label:',c(
                                        "Variable(s) Name(s) and Value(s)" ="label_both",
                                        "Value(s)"="label_value",
                                        "Parsed Expression" ="label_parsed"),
                                        selected="label_both"),
                                      
                                      checkboxInput('facetwrap', 'Use facet_wrap?'),
                                      conditionalPanel(condition = "input.facetwrap" ,
                                                       checkboxInput('customncolnrow', 'Control N columns an N rows?')),
                                      conditionalPanel(condition = "input.customncolnrow" ,
                                                       h6("An error (nrow*ncol >= n is not TRUE) will show up if the total number of facets/panels is greater than the product of the specified  N columns x N rows. Increase the N columns and/or N rows to avoid the error. The default empty values will use ggplot automatic algorithm."),        
                                                       numericInput("wrapncol",label = "N columns",value =NA,min=1,max =10) ,
                                                       numericInput("wrapnrow",label = "N rows",value = NA,min=1,max=10) 
                                      )
                                      
                           ) ,
                           
                           tabPanel(  "Reference Lines",
                                      checkboxInput('identityline', 'Identity Line')    ,   
                                      checkboxInput('horizontalzero', 'Horizontol Zero Line'),
                                      checkboxInput('customline1', 'Vertical Line'),
                                      conditionalPanel(condition = "input.customline1" , 
                                                       numericInput("vline",label = "",value = 1) ),
                                      checkboxInput('customline2', 'Horizontal Line'),
                                      conditionalPanel(condition = "input.customline2" , 
                                                       numericInput("hline",label = "",value = 1) )
                           ),
                           tabPanel(  "Additional Themes Options",
                                      sliderInput("themebasesize", "Theme Size (affects all text elements in the plot):", min=1, max=100, value=c(16),step=1),
                                      checkboxInput('themetableau', 'Use Tableau Colors and Fills ? (maximum of 10 colours are provided)',value=TRUE),
                                      conditionalPanel(condition = "input.themetableau" ,
                                                       h6("If you have more than 10 color groups the plot will not work and you get /Error: Insufficient values in manual scale. ## needed but only 10 provided./  Uncheck Use Tableau Colors and Fills to use default ggplot2 colors.")),
                                      checkboxInput('themecolordrop', 'Keep All levels of Colors and Fills ?',value=TRUE) , 
                                      
                                      checkboxInput('themebw', 'Use Black and White Theme ?',value=TRUE), 
                                      checkboxInput('themeaspect', 'Use custom aspect ratio ?')   ,  
                                      conditionalPanel(condition = "input.themeaspect" , 
                                                       numericInput("aspectratio",label = "Y/X ratio",
                                                                    value = 1,min=0.1,max=10,step=0.01)),
                                      checkboxInput('sepguides', 'Separate Legend Guides for Median/PI ?',value = TRUE),       
                                      checkboxInput('labelguides', 'Hide the Names of the Guides ?',value = FALSE)  
                           ) #tabpanel
               )#tabsetpanel
      ), # tabpanel
      #) ,#tabsetPanel(),
      
      tabPanel("How To",
               h5("1. Upload your data file in CSV format. R default options for read.csv will apply except for missing values where both (NA) and dot (.) are treated as missing. If your data has columns with other non-numeric missing value codes then they be treated as factors."),
               h5("2. The UI is dynamic and changes depending on your choices of options, x ,y, filter, group and so on."),
               h5("3. It is assumed that your data is tidy and ready for plotting (long format)."),
               h5("4. x and y variable(s) input allow numeric and factor variables."),
               h5("5. You can now select more than one y variable. The data will always be automatically stacked using tidyr::gather and result in yvars and yvalues variables.if you select factor and continuous variables, all selected variables will be transformed to factor. The internal variable yvalues is used for y variable mapping and you can select yvars for facetting. The app automatically select additional row split as yvars and set Facet Scales to free_y. To change Facet Scales and many other options go to Graph Options tab."),
               h5("6. Inputs, Categorize, Recode into Binned Categories: Include the numeric variable to change to categorical in the list and then choose a number of cuts (default is 3). This helps when you want to group or color by cuts of a continuous variable."),
               h5("7. Inputs, Categorize, Treat as Categories: This changes a numeric variable to factor without binning. This helps when you want to group or color by numerical variable that has few unique values e.g. 1,2,3."),
               h5("8. Inputs, Categorize, Custom cuts: You can cut a numeric variable to factor using specified cutoffs, by default the min, median, max are used."),
               h5("9.Inputs, Categorize, Treat as Numeric: This checkbox recodes categorical/factor variables to numeric values that start with 0. This is useful to recode Yes/No to 1/0 and overlay a logistic smooth. Numeric Codes/values correspondence are shown in text below the checkbox."),
               h5("10.Inputs, Categorize, Combine Variables: This allows to paste together two variables (e.g. Sex with values: Male and Female and Treatment with values: TRT1, TRT2 and TRT3) to construct a new one called combinedvariable with values: Male TRT1, Male TRT2, Male TRT3, Female TRT1, Female TRT2, Female TRT3. Once specified the combinedvariable becomes available to color, group and any other mapping"),
               h5("11. Inputs, Filters: There is six slots for Filter variables. Filter variables 1, 2,3,4,5 and 6 are applied sequentially. Values shown for filter variable 2 will depend on your selected data exclusions using filter variable 1 and so on. The first three filters accept numeric and non numeric columns while the last three are sliders and only work with numeric variables. For performance improvement the first three filters only show variables with a default maximum number of levels of 500 but you can increase it to your needs."),
               
               h5("12. New ! You can use additional smoothing functions including linear and logistic fits. Please make sure that data is compatible with the smoothing used i.e. for logistic a 0/1 variable is expected."),
               h5("13. Additional support to include boxplots. More work/feedback needed. Boxplots grouping might not be what is intented when the x axis variable is continuous, you can change the Group By: variable in the Color/Group/Split/Size/Fill Mappings (?) to better reflect your needs."),
               h5("14. Initial support to enable Kaplan-Meier Plots."),
               h5("15. Download the plot using the options on the 'Download' tab. This section is based on code from Mason DeCamillis ggplotLive app."),
               h5("16. Visualize the data table in the 'Data' tab. You can reorder the columns, filter and much more."),
               p(),
               h5("Samer Mouksassi 2016"),
               h5("Contact me @ samermouksassi@gmail.com for feedback/Bugs/features requests!")
               
      )# tabpanel 
    )
  ), #sidebarPanel
  mainPanel(
    tabsetPanel(
      tabPanel("Plot"  , 
               uiOutput('ui_plot'),
               hr(),
               uiOutput("clickheader"),
               tableOutput("plot_clickedpoints"),
               uiOutput("brushheader"),
               tableOutput("plot_brushedpoints"),
               #actionButton("plotButton", "Update Plot"),
               uiOutput("optionsmenu") ,
               
               conditionalPanel(
                 condition = "input.showplottypes" , 
                 
                 fluidRow(
                   
                   column (12, hr()),
                   column (3,
                           radioButtons("Points", "Points/Jitter:",
                                        c("Points" = "Points",
                                          "Jitter" = "Jitter",
                                          "None" = "None")),
                           conditionalPanel( " input.Points!= 'None' ",
                                             sliderInput("pointstransparency", "Points Transparency:", min=0, max=1, value=c(0.5),step=0.01),
                                             checkboxInput('pointignorecol', 'Ignore Mapped Color')
                           )),
                   column(3,
                          conditionalPanel( " input.Points!= 'None' ",
                                            sliderInput("pointsizes", "Points Size:", min=0, max=4, value=c(1),step=0.1),
                                            numericInput('pointtypes','Points Type:',16, min = 1, max = 25),
                                            conditionalPanel( " input.pointignorecol ",
                                                              selectInput('colpoint', label ='Points Color', choices=colors(),multiple=FALSE, selectize=TRUE, selected="black") 
                                            )
                          )
                   ),                  
                   column(3,
                          radioButtons("line", "Lines:",
                                       c("Lines" = "Lines",
                                         "None" = "None"),selected="None"),
                          conditionalPanel( " input.line== 'Lines' ",
                                            sliderInput("linestransparency", "Lines Transparency:", min=0, max=1, value=c(0.5),step=0.01),
                                            checkboxInput('lineignorecol', 'Ignore Mapped Color')
                          )
                          
                   ),
                   column(3,
                          conditionalPanel( " input.line== 'Lines' ",
                                            sliderInput("linesize", "Lines Size:", min=0, max=4, value=c(1),step=0.1),
                                            selectInput('linetypes','Lines Type:',c("solid","dotted")),
                                            conditionalPanel( " input.lineignorecol ",
                                                              selectInput('colline', label ='Lines Color', choices=colors(),multiple=FALSE, selectize=TRUE,selected="black") 
                                            )
                          ),
                          checkboxInput('boxplotaddition', 'Add a Boxplot ? (makes sense if x variable is categorical and
                                        you Group By a sensible choice. By default the x variable is used for grouping)'),
                          checkboxInput('boxplotignoregroup', 'Ignore Mapped Group ? (can me helpful to superpose a loess or median on top of the boxplot)')
                          
                   ),
                   column (12, h6("Points and Lines Size will apply only if Size By: in the Color Group Split Size Fill Mappings are set to None"))
                   
                 )#fluidrow
               ) ,
               conditionalPanel(
                 condition = "input.showfacets" , 
                 fluidRow(
                   column (12, hr()),
                   column (3, uiOutput("colour"),uiOutput("group")),
                   column(3, uiOutput("facet_col"),uiOutput("facet_row")),
                   column (3, uiOutput("facet_col_extra"),uiOutput("facet_row_extra")),
                   column (3, uiOutput("pointsize"),uiOutput("fill")),
                   column (12, h6("Make sure not to choose a variable that is in the y variable(s) list otherwise you will get an error Variable not found. These variables are stacked and become yvars and yvalues." ))
                   
                 )
               ),
               
               #rqss quantile regression
               conditionalPanel(
                 condition = "input.showrqss" , 
                 
                 fluidRow(
                   column(12,hr()),
                   column(3,
                          checkboxInput('Tauvalue', 'Dynamic and Preset Quantiles', value = FALSE),
                          h5("Preset Quantiles"),
                          checkboxInput('up', '95%'),
                          checkboxInput('ninetieth', '90%'),
                          checkboxInput('mid', '50%', value = FALSE),
                          checkboxInput('tenth', '10%'),
                          checkboxInput('low', '5%')
                   ),
                   column(5,
                          sliderInput("Tau", label = "Dynamic Quantile Value:",
                                      min = 0, max = 1, value = 0.5, step = 0.01)  ,
                          sliderInput("Penalty", label = "Spline sensitivity adjustment:",
                                      min = 0, max = 10, value = 1, step = 0.1)  ,
                          selectInput("Constraints", label = "Spline constraints:",
                                      choices = c("N","I","D","V","C","VI","VD","CI","CD"), selected = "N")
                   ),
                   column(3,
                          checkboxInput('ignorecolqr', 'Ignore Mapped Color'),
                          checkboxInput('ignoregroupqr', 'Ignore Mapped Group',value = TRUE),
                          checkboxInput('hidedynamic', 'Hide Dynamic Quantile'),
                          selectInput('colqr', label ='QR Color', choices=colors(),multiple=FALSE, selectize=TRUE,selected="black")
                   )
                   
                 )#fluidrow
               ),
               
               conditionalPanel(
                 condition = "input.showSmooth" , 
                 
                 fluidRow(
                   column(12,hr()),
                   column (3, 
                           radioButtons("Smooth", "Smooth:",
                                        c("Smooth" = "Smooth",
                                          "Smooth and SE" = "Smooth and SE",
                                          "None" = "None"),selected="None")
                   ),
                   column (3, 
                           conditionalPanel( " input.Smooth!= 'None' ",
                                             selectInput('smoothmethod', label ='Smoothing Method',
                                                         choices=c("Loess" ="loess","Linear Fit"="lm","Logistic"="glm"),
                                                         multiple=FALSE, selectize=TRUE,selected="loess"),
                                             
                                             sliderInput("loessens", "Loess Span:", min=0, max=1, value=c(0.75),step=0.05)
                           ) 
                   ),
                   
                   
                   
                   
                   
                   column (3,  conditionalPanel( " input.Smooth!= 'None' ",
                                                 checkboxInput('ignorecol', 'Ignore Mapped Color'),
                                                 uiOutput("weight")
                   )
                   ),
                   column (3, conditionalPanel( " input.Smooth!= 'None' ",
                                                checkboxInput('ignoregroup', 'Ignore Mapped Group',value = TRUE),
                                                conditionalPanel( " input.ignorecol ",
                                                                  selectInput('colsmooth', label ='Smooth Color', choices=colors(),multiple=FALSE, selectize=TRUE,selected="black") )
                   ) )
                   
                 )#fluidrow
               )
               ,
               ### Mean CI section
               conditionalPanel(
                 condition = "input.showMean" , 
                 
                 fluidRow(
                   column(12,hr()),
                   column (3, 
                           radioButtons("Mean", "Mean:",
                                        c("Mean" = "Mean",
                                          "Mean (95% CI)" = "Mean (95% CI)",
                                          "None" = "None") ,selected="None") 
                   ),
                   column (3,
                           
                           conditionalPanel( " input.Mean== 'Mean (95% CI)' ",
                                             sliderInput("CI", "CI %:", min=0, max=1, value=c(0.95),step=0.01),
                                             numericInput( inputId = "errbar",label = "CI bar width:",value = 2,min = 1,max = NA)      
                           )
                           
                   )
                   ,
                   column (3,
                           conditionalPanel( " input.Mean!= 'None' ",
                                             checkboxInput('meanpoints', 'Show points') ,
                                             checkboxInput('meanlines', 'Show lines', value=TRUE),
                                             checkboxInput('meanignorecol', 'Ignore Mapped Color') ,
                                             conditionalPanel( " input.meanignorecol ",
                                                               selectInput('colmean', label ='Mean Color', choices=colors(),multiple=FALSE, selectize=TRUE,selected="black") )
                                             
                           ) ),
                   
                   
                   column(3,
                          conditionalPanel( " input.Mean!= 'None' ",
                                            checkboxInput('meanignoregroup', 'Ignore Mapped Group',value = TRUE),
                                            sliderInput("meanlinesize", "Mean(s) Line(s) Size:", min=0, max=3, value=1,step=0.05)
                          ) 
                   )
                 ) #fluidrow
               ), # conditional panel for mean
               
               ### median PI section
               
               
               conditionalPanel(
                 condition = "input.showMedian" , 
                 fluidRow(
                   column(12,hr()),
                   column (3,
                           radioButtons("Median", "Median:",
                                        c("Median" = "Median",
                                          "Median/PI" = "Median/PI",
                                          "None" = "None") ,selected="None") ,
                           conditionalPanel( " input.Median!= 'None' ",
                                             checkboxInput('medianvalues', 'Label Values?') ,
                                             checkboxInput('medianN', 'Label N?') )
                           
                   ),
                   column (3,
                           conditionalPanel( " input.Median== 'Median' ",
                                             checkboxInput('medianpoints', 'Show points') ,
                                             checkboxInput('medianlines', 'Show lines',value=TRUE)),
                           conditionalPanel( " input.Median== 'Median/PI' ",
                                             sliderInput("PI", "PI %:", min=0, max=1, value=c(0.95),step=0.01),
                                             sliderInput("PItransparency", "PI Transparency:", min=0, max=1, value=c(0.2),step=0.01)
                           )
                   ),
                   column (3,
                           conditionalPanel( " input.Median!= 'None' ",
                                             checkboxInput('medianignorecol', 'Ignore Mapped Color'),
                                             conditionalPanel( " input.medianignorecol ",
                                                               selectInput('colmedian', label ='Median Color', choices=colors(),multiple=FALSE, selectize=TRUE,selected="black") )
                                             
                           ) ),
                   column (3,
                           conditionalPanel( " input.Median!= 'None' ",
                                             
                                             checkboxInput('medianignoregroup', 'Ignore Mapped Group',value = TRUE),
                                             sliderInput("medianlinesize", "Median(s) Line(s) Size:", min=0, max=4, value=c(1),step=0.1)
                                             
                           )
                   )
                   
                 )#fluidrow
               ),
               ### median PI section
               
               ### KM section
               
               
               conditionalPanel(
                 condition = "input.showKM" , 
                 fluidRow(
                   column(12,hr()),
                   column (12, h6("KM curves support is currently experimental some features might not work. When a KM curve is added nothing else will be plotted (e.g. points, lines etc.).Color/Fill/Group/Facets are expected to work." )),
                   column (3,
                           radioButtons("KM", "KM:",
                                        c("KM" = "KM",
                                          "KM/CI" = "KM/CI",
                                          "None" = "None") ,selected="None") 
                   ),
                   column (3,
                           conditionalPanel( " input.KM!= 'None' ",
                                             checkboxInput('censoringticks', 'Show Censoring Ticks?') ,
                                             conditionalPanel( " input.KM== 'KM/CI' ",
                                                               sliderInput("KMCI", "KM CI:", min=0, max=1, value=c(0.95),step=0.01),
                                                               sliderInput("KMCItransparency", "KM CI Transparency:", min=0, max=1, value=c(0.2),step=0.01)
                                             )
                           )),
                   
                   column (3,
                           conditionalPanel( " input.KM!= 'None' ",
                                             selectInput('KMtrans', label ='KM Transformation',
                                                         choices=c("None" ="identity","event"="event","cumhaz"="cumhaz","cloglog"="cloglog"),
                                                         multiple=FALSE, selectize=TRUE,selected="loess")  
                           )
                   )
                 )#fluidrow
               )
               ### KM section
               
               ),#tabPanel1
      tabPanel("Download", 
               selectInput(
                 inputId = "downloadPlotType",
                 label   = h5("Select download file type"),
                 choices = list("PDF"  = "pdf","BMP"  = "bmp","JPEG" = "jpeg","PNG"  = "png")),
               
               # Allow the user to set the height and width of the plot download.
               h5(HTML("Set download image dimensions<br>(units are inches for PDF, pixels for all other formats)")),
               numericInput(
                 inputId = "downloadPlotHeight",label = "Height (inches)",value = 7,min = 1,max = 100),
               numericInput(
                 inputId = "downloadPlotWidth",label = "Width (inches)",value = 7,min = 1,max = 100),
               # Choose download filename.
               textInput(
                 inputId = "downloadPlotFileName",
                 label = h5("Enter file name for download")),
               
               # File downloads when this button is clicked.
               downloadButton(
                 outputId = "downloadPlot", 
                 label    = "Download Plot")
      ),
      
      tabPanel('Data',  dataTableOutput("mytablex") 
      )#tabPanel2
    )#tabsetPanel
  )#mainPanel
  )#sidebarLayout
)#fluidPage
server <-  function(input, output, session) {
  filedata <- reactive({
    infile <- input$datafile
    if (is.null(infile)) {
      # User has not uploaded a file yet
      return(NULL)
    }
    read.csv(infile$datapath,na.strings = c("NA","."))
    
    
  })
  
  
  
  myData <- reactive({
    df=filedata()
    if (is.null(df)) return(NULL)
  })
  
  output$optionsmenu <-  renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    
    fluidRow(
      column (12, h6("Select the checkbox(es) for the options to be showed")),
      hr(),
      column(4,checkboxInput('showplottypes',
                             'Plot types, Points, Lines (?)',
                             value = TRUE)),
      column(4,checkboxInput('showfacets',
                             'Color/Group/Split/Size/Fill Mappings (?)',
                             value = TRUE) ),
      column(4,checkboxInput('showrqss',
                             'Quantile Regression (?)',
                             value = TRUE)),
      column(4,checkboxInput('showSmooth',
                             'Smooth/Linear/Logistic Regressions (?)',
                             value = TRUE)),
      column(4,checkboxInput('showMean' , 'Mean CI (?)', value = FALSE)),
      column(4,checkboxInput('showMedian','Median PIs (?)', value = FALSE)),
      column(3,checkboxInput('showKM','Kaplan-Meier (?)', value = FALSE))
      
    )
  })
  
  output$ycol <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    selectInput("y", "y variable(s):",choices=items,selected = items[1],multiple=TRUE,selectize=TRUE)
  })
  
  output$xcol <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    selectInput("x", "x variable:",items,selected=items[2])
    
  })
  
  outputOptions(output, "ycol", suspendWhenHidden=FALSE)
  outputOptions(output, "xcol", suspendWhenHidden=FALSE)
  
  output$catvar <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    MODEDF <- sapply(df, function(x) is.numeric(x))
    NAMESTOKEEP2<- names(df)  [ MODEDF ]
    selectInput('catvarin',label = 'Recode into Binned Categories:',choices=NAMESTOKEEP2,multiple=TRUE)
  })
  
  
  output$ncuts <- renderUI({
    if (length(input$catvarin ) <1)  return(NULL)
    sliderInput('ncutsin',label = 'N of Cut Breaks:', min=2, max=10, value=c(3),step=1)
  })
  
  output$catvar2 <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    MODEDF <- sapply(df, function(x) is.numeric(x))
    NAMESTOKEEP2<- names(df)  [ MODEDF ]
    if (length(input$catvarin ) >=1) {
      NAMESTOKEEP2<-NAMESTOKEEP2 [ !is.element(NAMESTOKEEP2,input$catvarin) ]
    }
    
    selectInput('catvar2in',label = 'Treat as Categories:',choices=NAMESTOKEEP2,multiple=TRUE)
    
  })
  
  output$catvar3 <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    MODEDF <- sapply(df, function(x) is.numeric(x))
    NAMESTOKEEP2<- names(df)  [ MODEDF ]
    if (length(input$catvarin ) >=1) {
      NAMESTOKEEP2<-NAMESTOKEEP2 [ !is.element(NAMESTOKEEP2,input$catvarin) ]
    }
    if (length(input$catvar2in ) >=1) {
      NAMESTOKEEP2<-NAMESTOKEEP2 [ !is.element(NAMESTOKEEP2,input$catvar2in) ]
    }
    selectizeInput(  "catvar3in", 'Custom cuts of this variable, defaults to min, median, max before any applied filtering:',
                     choices =NAMESTOKEEP2 ,multiple=FALSE,
                     options = list(    placeholder = 'Please select a variable',
                                        onInitialize = I('function() { this.setValue(""); }')
                     )
    )
  })
  output$ncuts2 <- renderUI({
    df <-filedata()
    if (length(input$catvar3in ) <1)  return(NULL)
    if ( input$catvar3in!=""){
      textInput("xcutoffs", label =  paste(input$catvar3in,"Cuts"),
                value = as.character(paste(
                  min(df[,input$catvar3in] ,na.rm=T),
                  median(df[,input$catvar3in],na.rm=T),
                  max(df[,input$catvar3in],na.rm=T) ,sep=",")
                )
      )
    }
    
  })
  

  
  output$asnumeric <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    if (length(input$catvar3in ) <1)  return(NULL)
    if ( input$catvar3in!=""){
      column(12,
             checkboxInput('asnumericin', 'Treat as Numeric (helpful to overlay a smooth/regression line on top of a boxplot or to convert a variable into 0/1 and overlay a logistic fit', value = FALSE)
             #,checkboxInput('useasxaxislabels', 'Use the Categories Names as x axis label (makes sense only if you really chose it as x axis variable)', value = FALSE), 
             #checkboxInput('useasyaxislabels', 'Use the Categories Names as y axis label (makes sense only if you really chose it as y axis variable)', value = FALSE) 
      )
    }
  })
  
  
  outputOptions(output, "catvar", suspendWhenHidden=FALSE)
  outputOptions(output, "ncuts", suspendWhenHidden=FALSE)
  outputOptions(output, "catvar2", suspendWhenHidden=FALSE)
  outputOptions(output, "catvar3", suspendWhenHidden=FALSE)
  outputOptions(output, "ncuts2", suspendWhenHidden=FALSE)
  outputOptions(output, "asnumeric", suspendWhenHidden=FALSE)

  
  
    
  recodedata1  <- reactive({
    df <- filedata() 
    if (is.null(df)) return(NULL)
    if(length(input$catvarin ) >=1) {
      for (i in 1:length(input$catvarin ) ) {
        varname<- input$catvarin[i]
        df[,varname] <- cut(df[,varname],input$ncutsin)
        df[,varname]   <- as.factor( df[,varname])
      }
    }
    df
  })
  
  
  recodedata2  <- reactive({
    df <- recodedata1()
    if (is.null(df)) return(NULL)
    if(length(input$catvar2in ) >=1) {
      for (i in 1:length(input$catvar2in ) ) {
        varname<- input$catvar2in[i]
        df[,varname]   <- as.factor( df[,varname])
      }
    }
    df
  })
  
  recodedata3  <- reactive({
    df <- recodedata2()
    if (is.null(df)) return(NULL)
    if(input$catvar3in!="") {
      varname<- input$catvar3in
      xlimits <- input$xcutoffs 
      nxintervals <- length(as.numeric(unlist (strsplit(xlimits, ",")) )) -1
      df[,varname] <- cut( as.numeric ( as.character(  df[,varname])),
                           breaks=   as.numeric(unlist (strsplit(xlimits, ","))),include.lowest=TRUE)
      df[,"custombins"] <-   df[,varname] 
      
      if(input$asnumericin) {
        df[,varname] <- as.numeric(as.factor(df[,varname]) ) -1 
      }
    }
    
    df
  })
  output$bintext <- renderText({
    df <- recodedata3()
    if (is.null(df)) return(NULL)
    bintextout <- ""
    if(input$catvar3in!="") {
      varname<- input$catvar3in
      if(!input$asnumericin){
        bintextout <- levels(df[,"custombins"] )
      }
      if(input$asnumericin){
        bintextout <- paste( sort(unique(as.numeric(as.factor(df[,varname]) ) -1))  ,levels(df[,"custombins"] ),sep="/") 
      }}
    bintextout   
  })   
  #  xaxislabels <-levels(cut( as.numeric ( as.character( dataedafilter$month_ss)), breaks=   as.numeric(unlist (strsplit(ageglimits, ",") )),include.lowest=TRUE))
  #+ scale_x_continuous(breaks=seq(0,length(xaxislabels)-1),labels=xaxislabels )   useasxaxislabels
  output$catvar4 <- renderUI({
    df <-recodedata3()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    MODEDF <- sapply(df, function(x) is.numeric(x))
    NAMESTOKEEP2<- names(df)  [! MODEDF ]
    
    selectizeInput(  "catvar4in", 'Change labels of this variable:',
                     choices =NAMESTOKEEP2 ,multiple=FALSE,
                     options = list(    placeholder = 'Please select a variable',
                                        onInitialize = I('function() { this.setValue(""); }')
                     )
    )
  })
  
  output$labeltext <- renderText({
    df <- recodedata3()
    if (is.null(df)) return(NULL)
    labeltextout <- ""
    if(input$catvar4in!="") {
      varname<- input$catvar4in
      labeltextout <- c("Old labels",levels(df[,varname] ))
    }
    labeltextout   
  })   
  
  
  
  
  output$nlabels <- renderUI({
    df <-recodedata3()
    if (length(input$catvar4in ) <1)  return(NULL)
    if ( input$catvar4in!=""){
      nlevels <- length( unique( levels(as.factor( df[,input$catvar4in] ))))
      levelsvalues <- levels(as.factor( df[,input$catvar4in] ))
      textInput("customvarlabels", label =  paste(input$catvar4in,"requires",nlevels,"new labels,
                                                  type in a comma separated list below"),
                value =
                  # paste("\"",as.character(levelsvalues),"\"",collapse=", ",sep="")
                  #paste("'",as.character(1:nlevels),"'",collapse=", ",sep="")
                  paste(as.character(1:nlevels),collapse=", ",sep="")
      )
    }
    
  })
  
  outputOptions(output, "catvar4", suspendWhenHidden=FALSE)
  outputOptions(output, "nlabels", suspendWhenHidden=FALSE)
  
  
  recodedata4  <- reactive({
    df <- recodedata3()
    if (is.null(df)) return(NULL)
    if(input$catvar4in!="") {
      varname<- input$catvar4in
      xlabels <- input$customvarlabels 
     # xlabels <- c("a","b")
      nxxlabels <- length(as.numeric(unlist (strsplit(xlabels, ",")) )) -1
      df[,varname] <- as.factor(df[,varname])
      levels(df[,varname])  <-  unlist (strsplit(xlabels, ",") )
    }
    #print(head(df))
    df
  })
  
  
  output$pastevar <- renderUI({
    df <- recodedata4()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    MODEDF <- sapply(df, function(x) is.numeric(x))
    NAMESTOKEEP2<- names(df)  [! MODEDF ]
    selectizeInput("pastevarin", "Combine the categories of these two variables:", choices = NAMESTOKEEP2,multiple=TRUE,
                   options = list(
                     maxItems = 2 ,
                     placeholder = 'Please select some variables',
                     onInitialize = I('function() { this.setValue(""); }'),
                     plugins = list('remove_button', 'drag_drop')
                   )
    )
  })
  
  
  outputOptions(output, "pastevar", suspendWhenHidden=FALSE)
  outputOptions(output, "bintext", suspendWhenHidden=FALSE)
  
  
  
  
  output$maxlevels <- renderUI({
    df <-recodedata4()
    if (is.null(df)) return(NULL)
    numericInput( inputId = "inmaxlevels",label = "Max number of unique values for Filter variable (1),(2),(3) (this is to avoid performance issues):",value = 500,min = 1,max = NA)
    
  })
  outputOptions(output, "maxlevels", suspendWhenHidden=FALSE)
  
  
  output$filtervar1 <- renderUI({
    df <-recodedata4()
    if (is.null(df)) return(NULL)
    NUNIQUEDF <- sapply(df, function(x) length(unique(x)))
    NAMESTOKEEP<- names(df)  [ NUNIQUEDF  < input$inmaxlevels ]
    selectInput("infiltervar1" , "Filter variable (1):",c('None',NAMESTOKEEP ) )
  })
  
  output$filtervar2 <- renderUI({
    df <- recodedata4()
    if (is.null(df)) return(NULL)
    NUNIQUEDF <- sapply(df, function(x) length(unique(x)))
    NAMESTOKEEP<- names(df)  [ NUNIQUEDF  < input$inmaxlevels ]
    #NAMESTOKEEP<-  NAMESTOKEEP[ NAMESTOKEEP!=input$infiltervar1 ]
    selectInput("infiltervar2" , "Filter variable (2):",c('None',NAMESTOKEEP ) )
  })
  
  output$filtervar3 <- renderUI({
    df <- recodedata4()
    if (is.null(df)) return(NULL)
    NUNIQUEDF <- sapply(df, function(x) length(unique(x)))
    NAMESTOKEEP<- names(df)  [ NUNIQUEDF  < input$inmaxlevels ]
    #NAMESTOKEEP<-  NAMESTOKEEP[ NAMESTOKEEP!=input$infiltervar1 ]# allow nested filters
    #NAMESTOKEEP<-  NAMESTOKEEP[ NAMESTOKEEP!=input$infiltervar2 ]
    selectInput("infiltervar3" , "Filter variable (3):",c('None',NAMESTOKEEP ) )
  })
  
  
  output$filtervarcont1 <- renderUI({
    df <-recodedata4()
    if (is.null(df)) return(NULL)
    NUNIQUEDF <- sapply(df, function(x) length(unique(x)))
    NAMESTOKEEP<- names(df)
    NAMESTOKEEP<- NAMESTOKEEP[ is.element ( NAMESTOKEEP,names(df[sapply(df,is.numeric)]))]
    selectInput("infiltervarcont1" , "Filter continuous (1):",c('None',NAMESTOKEEP ) )
  })
  output$filtervarcont2 <- renderUI({
    df <-recodedata4()
    if (is.null(df)) return(NULL)
    NUNIQUEDF <- sapply(df, function(x) length(unique(x)))
    NAMESTOKEEP<- names(df)  
    NAMESTOKEEP<- NAMESTOKEEP[ is.element ( NAMESTOKEEP,names(df[sapply(df,is.numeric)]))]
    selectInput("infiltervarcont2" , "Filter continuous (2):",c('None',NAMESTOKEEP ) )
  })
  output$filtervarcont3 <- renderUI({
    df <-recodedata4()
    if (is.null(df)) return(NULL)
    NUNIQUEDF <- sapply(df, function(x) length(unique(x)))
    NAMESTOKEEP<- names(df)  
    NAMESTOKEEP<- NAMESTOKEEP[ is.element ( NAMESTOKEEP,names(df[sapply(df,is.numeric)]))]
    selectInput("infiltervarcont3" , "Filter continuous (3):",c('None',NAMESTOKEEP ) )
  })
  output$filtervar1values <- renderUI({
    df <-recodedata4()
    validate(       need(!is.null(df), "Please select a data set"))
    
    if (is.null(df)) return(NULL)
    if(input$infiltervar1=="None") {return(NULL)}
    if(input$infiltervar1!="None" )  {
      choices <- levels(as.factor(df[,input$infiltervar1]))
      selectInput('infiltervar1valuesnotnull',
                  label = paste("Select values", input$infiltervar1),
                  choices = c(choices),
                  selected = choices,
                  multiple=TRUE, selectize=FALSE)   
    }
  }) 
  
  filterdata  <- reactive({
    if (is.null(filedata())) return(NULL)
    df <-   recodedata4()
    if (is.null(df)) return(NULL)
    if(is.null(input$infiltervar1)) {
      df <-  df 
    }
    if(!is.null(input$infiltervar1)&input$infiltervar1!="None") {
      
      df <-  df [ is.element(df[,input$infiltervar1],input$infiltervar1valuesnotnull),]
    }
    
    df
  })
  
  output$filtervar2values <- renderUI({
    df <- filterdata()
    if (is.null(df)) return(NULL)
    if(input$infiltervar2=="None") {
      selectInput('infiltervar2valuesnull',
                  label ='No filter variable 2 specified', 
                  choices = list(""),multiple=TRUE, selectize=FALSE)   
    }
    if(input$infiltervar2!="None"&!is.null(input$infiltervar2) )  {
      choices <- levels(as.factor(as.character(df[,input$infiltervar2])))
      selectInput('infiltervar2valuesnotnull',
                  label = paste("Select values", input$infiltervar2),
                  choices = c(choices),
                  selected = choices,
                  multiple=TRUE, selectize=TRUE)   
    }
  })
  
  filterdata2  <- reactive({
    df <- filterdata()
    if (is.null(df)) return(NULL)
    if(!is.null(input$infiltervar2)&input$infiltervar2!="None") {
      df <-  df [ is.element(df[,input$infiltervar2],input$infiltervar2valuesnotnull),]
    }
    if(input$infiltervar2=="None") {
      df 
    }
    df
  }) 
  output$filtervar3values <- renderUI({
    df <- filterdata2()
    if (is.null(df)) return(NULL)
    if(input$infiltervar3=="None") {
      selectInput('infiltervar3valuesnull',
                  label ='No filter variable 2 specified', 
                  choices = list(""),multiple=TRUE, selectize=FALSE)   
    }
    if(input$infiltervar3!="None"&!is.null(input$infiltervar3) )  {
      choices <- levels(as.factor(as.character(df[,input$infiltervar3])))
      selectInput('infiltervar3valuesnotnull',
                  label = paste("Select values", input$infiltervar3),
                  choices = c(choices),
                  selected = choices,
                  multiple=TRUE, selectize=TRUE)   
    }
  })
  
  filterdata3  <- reactive({
    df <- filterdata2()
    if (is.null(df)) return(NULL)
    if(!is.null(input$infiltervar3)&input$infiltervar3!="None") {
      df <-  df [ is.element(df[,input$infiltervar3],input$infiltervar3valuesnotnull),]
    }
    if(input$infiltervar3=="None") {
      df 
    }
    df
  })  
  
  output$fslider1 <- renderUI({ 
    df <-  filterdata3()
    if (is.null(df)) return(NULL)
    xvariable<- input$infiltervarcont1
    if(input$infiltervarcont1=="None" ){
      return(NULL)  
    }
    if (!is.numeric(df[,xvariable]) ) return(NULL)
    if(input$infiltervarcont1!="None" ){
      sliderInput("infSlider1", paste("Select",xvariable,"Range"),
                  min=min(df[,xvariable],na.rm=T),
                  max=max(df[,xvariable],na.rm=T),
                  value=c(min(df[,xvariable],na.rm=T),max(df[,xvariable],na.rm=T)) 
      )
    }             
  })
  filterdata4  <- reactive({
    df <- filterdata3()
    if (is.null(df)) return(NULL)
    if(input$infiltervarcont1!="None" ){
      if(is.numeric( input$infSlider1[1]) & is.numeric(df[,input$infiltervarcont1])) {
        df <- df [!is.na(df[,input$infiltervarcont1]),]
        df <-  df [df[,input$infiltervarcont1] >= input$infSlider1[1]&df[,input$infiltervarcont1] <= input$infSlider1[2],]
      }
    }
    
    df
  })
  output$fslider2 <- renderUI({ 
    df <-  filterdata4()
    if (is.null(df)) return(NULL)
    xvariable<- input$infiltervarcont2
    if(input$infiltervarcont2=="None" ){
      return(NULL)  
    }
    if (!is.numeric(df[,xvariable]) ) return(NULL)
    if(input$infiltervarcont2!="None" ){
      sliderInput("infSlider2", paste("Select",xvariable,"Range"),
                  min=min(df[,xvariable],na.rm=T),
                  max=max(df[,xvariable],na.rm=T),
                  value=c(min(df[,xvariable],na.rm=T),max(df[,xvariable],na.rm=T)) 
      )
    }             
  })
  
  
  filterdata5  <- reactive({
    df <- filterdata4()
    if (is.null(df)) return(NULL)
    if(input$infiltervarcont2!="None" ){
      if(is.numeric( input$infSlider2[1]) & is.numeric(df[,input$infiltervarcont2])) {
        df<- df [!is.na(df[,input$infiltervarcont2]),]
        df<-df [df[,input$infiltervarcont2] >= input$infSlider2[1]&df[,input$infiltervarcont2] <= input$infSlider2[2],]
      }
    }
    
    df
  })
  
  output$fslider3 <- renderUI({ 
    df <-  filterdata5()
    if (is.null(df)) return(NULL)
    xvariable<- input$infiltervarcont3
    if(input$infiltervarcont3=="None" ){
      return(NULL)  
    }
    if (!is.numeric(df[,xvariable]) ) return(NULL)
    if(input$infiltervarcont3!="None" ){
      sliderInput("infSlider3", paste("Select",xvariable,"Range"),
                  min=min(df[,xvariable],na.rm=T),
                  max=max(df[,xvariable],na.rm=T),
                  value=c(min(df[,xvariable],na.rm=T),max(df[,xvariable],na.rm=T)) 
      )
    }             
  })
  
  
  filterdata6  <- reactive({
    df <- filterdata5()
    if (is.null(df)) return(NULL)
    if(input$infiltervarcont3!="None" ){
      if(is.numeric( input$infSlider3[1]) & is.numeric(df[,input$infiltervarcont3])) {
        df<- df [!is.na(df[,input$infiltervarcont3]),]
        df<-df [df[,input$infiltervarcont3] >= input$infSlider3[1]&df[,input$infiltervarcont3] <= input$infSlider3[2],]
      }
    }
    
    df
  })
  
  outputOptions(output, "filtervar1", suspendWhenHidden=FALSE)
  outputOptions(output, "filtervar2", suspendWhenHidden=FALSE)
  outputOptions(output, "filtervar3", suspendWhenHidden=FALSE)
  
  outputOptions(output, "filtervarcont1", suspendWhenHidden=FALSE)
  outputOptions(output, "filtervarcont2", suspendWhenHidden=FALSE)
  outputOptions(output, "filtervarcont3", suspendWhenHidden=FALSE)
  outputOptions(output, "filtervar1values", suspendWhenHidden=FALSE)
  outputOptions(output, "filtervar2values", suspendWhenHidden=FALSE)
  outputOptions(output, "filtervar3values", suspendWhenHidden=FALSE)
  
  outputOptions(output, "fslider1", suspendWhenHidden=FALSE)
  outputOptions(output, "fslider2", suspendWhenHidden=FALSE)
  outputOptions(output, "fslider3", suspendWhenHidden=FALSE)
  
  
  
  output$roundvar <- renderUI({
    df <- filterdata6()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    MODEDF <- sapply(df, function(x) is.numeric(x))
    NAMESTOKEEP2<- names(df)  [MODEDF]
    selectizeInput(  "roundvarin", "Round the Values to the Specified N Digits:", choices = NAMESTOKEEP2,multiple=TRUE,
                     options = list(
                       placeholder = 'Please select some variables',
                       onInitialize = I('function() { this.setValue(""); }')
                     )
    )
    
  }) 
  outputOptions(output, "roundvar", suspendWhenHidden=FALSE)
  
  stackdata <- reactive({
    
    df <- filterdata6() 
    
    if (is.null(df)) return(NULL)
    if (!is.null(df)){
      validate(  need(!is.element(input$x,input$y) , "Please select a different x variable or remove the x variable from the list of y variable(s)"))
      #   validate(
      #    need(!is.null(length(input$y)| length(input$y) <1) , 
      #         "Please select a at least one y variable"))
      
      
      if(       all( sapply(df[,as.vector(input$y)], is.numeric)) )
      {
        tidydata <- df %>%
          gather_( "yvars", "yvalues", gather_cols=as.vector(input$y) ) %>%
          mutate(combinedvariable="Choose two variables to combine first")
      }
      if(       any( sapply(df[,as.vector(input$y)], is.factor)) |
                any( sapply(df[,as.vector(input$y)], is.character)))
      {
        tidydata <- df %>%
          gather_( "yvars", "yvalues", gather_cols=as.vector(input$y) ) %>%
          mutate(yvalues=as.factor(as.factor(as.character(yvalues)) ))%>%
          mutate(combinedvariable="Choose two variables to combine first")
      } 
      
      if(       all( sapply(df[,as.vector(input$y)], is.factor)) |
                all( sapply(df[,as.vector(input$y)], is.character)))
      {
        tidydata <- df %>%
          gather_( "yvars", "yvalues", gather_cols=as.vector(input$y) ) %>%
          mutate(yvalues=as.factor(as.character(yvalues) ))%>%
          mutate(combinedvariable="Choose two variables to combine first")
      }    
      
      
    }
    
    if( !is.null(input$pastevarin)   ) {
      if (length(input$pastevarin) > 1) {
        tidydata <- tidydata %>%
          unite_("combinedvariable" , c(input$pastevarin[1], input$pastevarin[2] ),
                 remove=FALSE)
      }
    }
    
    tidydata
  })
  
  rounddata <- reactive({
    if (is.null(df)) return(NULL)
    df <- stackdata()
    if(length(input$roundvarin ) >=1) {
      for (i in 1:length(input$roundvarin ) ) {
        varname<- input$roundvarin[i]
        df[,varname]   <- round( df[,varname],input$rounddigits)
      }
    }
    df
  })  
  
  
  output$reordervar <- renderUI({
    df <- rounddata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    MODEDF <- sapply(df, function(x) is.numeric(x))
    NAMESTOKEEP2<- names(df)  [ !MODEDF ]
    selectizeInput(  "reordervarin", 'Reorder This Variable By:',
                     choices =NAMESTOKEEP2 ,multiple=FALSE,
                     options = list(    placeholder = 'Please select a variable',
                                        onInitialize = I('function() { this.setValue(""); }')
                     )
    )
  })
  
  
  
  output$variabletoorderby <- renderUI({
    if (is.null(df)) return(NULL)
    if (length(input$reordervarin ) <1)  return(NULL)
    if ( input$reordervarin!=""){
      df <-rounddata()
      yinputs <- input$y
      items=names(df)
      names(items)=items
      MODEDF <- sapply(df, function(x) is.numeric(x))
      NAMESTOKEEP2<- names(df)  [ MODEDF ]
      selectInput('varreorderin',label = 'Of this Variable:', choices=NAMESTOKEEP2,multiple=FALSE)
    }
  })
  
  

  
  outputOptions(output, "reordervar", suspendWhenHidden=FALSE)
  outputOptions(output, "variabletoorderby", suspendWhenHidden=FALSE)
  
  
  
  reorderdata <- reactive({
    df <- rounddata()
    if (is.null(df)) return(NULL)
    
    if(length(input$reordervarin ) >=1 &
       length(input$varreorderin ) >=1 & input$reordervarin!=""  ) {
      varname<- input$reordervarin[1]
      if(input$functionordervariable=="Median" )  {
        df[,varname]   <- reorder( df[,varname],df[,input$varreorderin], FUN=function(x) median(x[!is.na(x)]))
      }
      if(input$functionordervariable=="Mean" )  {
        df[,varname]   <- reorder( df[,varname],df[,input$varreorderin],  FUN=function(x) mean(x[!is.na(x)]))
      }
      if(input$functionordervariable=="Minimum" )  {
        df[,varname]   <- reorder( df[,varname],df[,input$varreorderin],  FUN=function(x) min(x[!is.na(x)]))
      }
      if(input$functionordervariable=="Maximum" )  {
        df[,varname]   <- reorder( df[,varname],df[,input$varreorderin],  FUN=function(x) max(x[!is.na(x)]))
      }
      if(input$reverseorder )  {
        df[,varname] <- factor( df[,varname], levels=rev(levels( df[,varname])))
        
      }
    }
    df
  })  
  
  
    output$reordervar2 <- renderUI({
      df <- reorderdata()
      if (is.null(df)) return(NULL)
      MODEDF <- sapply(df, function(x) is.numeric(x))
      NAMESTOKEEP<- names(df)  [ !MODEDF ]
      if(length(input$reordervarin ) >=1  ){
        NAMESTOKEEP<- NAMESTOKEEP  [ NAMESTOKEEP!=input$reordervarin ]
        
      }
      selectInput("reordervar2in" , "Custom Reorder this variable:",c('None',NAMESTOKEEP ) )
    })

      output$reordervar2values <- renderUI({
        df <- reorderdata()
        if (is.null(df)) return(NULL)
        if(input$reordervar2in=="None") {
          selectInput('reordervar2valuesnull',
                      label ='No reorder variable specified', 
                      choices = list(""),multiple=TRUE, selectize=FALSE)   
        }
        if(input$reordervar2in!="None"&!is.null(input$reordervar2in) )  {
          choices <- levels(as.factor(as.character(df[,input$reordervar2in])))
          selectizeInput('reordervar2valuesnotnull',
                      label = paste("Drag/Drop to reorder",input$reordervar2in, "values"),
                      choices = c(choices),
                      selected = choices,
                      multiple=TRUE,  options = list(
                      plugins = list('drag_drop')
                      )
                      )   
        }
      })
    outputOptions(output, "reordervar2", suspendWhenHidden=FALSE)
    outputOptions(output, "reordervar2values", suspendWhenHidden=FALSE)
    
    reorderdata2 <- reactive({
      df <- reorderdata()
      if (is.null(df)) return(NULL)
      
      if(input$reordervar2in!="None"  ) {
df [,input$reordervar2in] <- factor(df [,input$reordervar2in],
                                    levels = input$reordervar2valuesnotnull)

}
      df
    })
    
  output$xaxiszoom <- renderUI({
    df <-reorderdata2()
    if (is.null(df)| !is.numeric(df[,input$x] ) ) return(NULL)
    if (is.numeric(df[,input$x]) &
        input$facetscalesin!="free_x"&
        input$facetscalesin!="free"){
      xvalues <- df[,input$x][!is.na( df[,input$x])]
      xmin <- min(xvalues)
      xmax <- max(xvalues)
      xstep <- (xmax -xmin)/100
      sliderInput('xaxiszoomin',label = 'Zoom to X variable range:', min=xmin, max=xmax, value=c(xmin,xmax),step=xstep)
      
    }
    
    
  })
  outputOptions(output, "xaxiszoom", suspendWhenHidden=FALSE)
  
  
  output$colour <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    selectInput("colorin", "Colour By:",c("None",items,"yvars", "yvalues","combinedvariable") )
    
  })
  
  
  output$group <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items 
    
    if (input$boxplotaddition ){
      items= c(input$x,"None",items[items!=input$x], "yvars","yvalues","combinedvariable")    
    }
    if (!input$boxplotaddition ){
      items= c("None",input$x,items[items!=input$x],"yvars", "yvalues","combinedvariable")    
    }
    selectInput("groupin", "Group By:",items)
  })
  
  
  output$facet_col <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    selectInput("facetcolin", "Column Split:",c(None='.',items,"yvars", "yvalues","combinedvariable"))
  })
  output$facet_row <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    selectInput("facetrowin", "Row Split:",    c(None=".",items,"yvars", "yvalues","combinedvariable"))
  })
  
  output$facet_col_extra <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    selectInput("facetcolextrain", "Extra Column Split:",c(None='.',items,"yvars", "yvalues","combinedvariable"))
  })
  output$facet_row_extra <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    if (length(input$y) > 1 ){
      items= c("yvars",None=".",items, "yvalues","combinedvariable")    
    }
    if (length(input$y) < 2 ){
      items= c(None=".",items,"yvars", "yvalues","combinedvariable")    
    }
    selectInput("facetrowextrain", "Extra Row Split:",items)
  })
  
  
  output$facetscales <- renderUI({
    if (length(input$y) > 1 ){
      items= c("free_y","fixed","free_x","free")    
    }
    if (length(input$y) < 2 ){
      items= c("fixed","free_x","free_y","free")   
    }
    selectInput('facetscalesin','Facet Scales:',items)
  })
  outputOptions(output, "facetscales", suspendWhenHidden=FALSE)
  
  
  
  output$pointsize <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    selectInput("pointsizein", "Size By:",c("None",items,"yvars", "yvalues","combinedvariable") )
    
  })
  
  output$fill <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    selectInput("fillin", "Fill By:"    ,c("None",items,"yvars", "yvalues","combinedvariable") )
  })
  
  output$weight <- renderUI({
    df <-filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    items= items #[!is.element(items,input$y)]
    selectInput("weightin", "Weight By:",c("None",items,"yvars", "yvalues","combinedvariable") )
  })
  outputOptions(output, "weight", suspendWhenHidden=FALSE)
  
  
  output$mytablex = renderDataTable({
    datatable( recodedata4() , # reorderdata2
               extensions = c('ColReorder','Buttons','FixedColumns'),
               options = list(dom = 'Bfrtip',
                              searchHighlight = TRUE,
                              pageLength=-1 ,
                              lengthMenu = list(c(5, 10, 15, -1), c('5','10', '15', 'All')),
                              colReorder = list(realtime = TRUE),
                              buttons = 
                                list('colvis', 'pageLength','print','copy', list(
                                  extend = 'collection',
                                  buttons = list(
                                    list(extend='csv'  ,filename = 'plotdata'),
                                    list(extend='excel',filename = 'plotdata'),
                                    list(extend='pdf'  ,filename = 'plotdata')),
                                  text = 'Download'
                                )),
                              scrollX = TRUE,scrollY = 400,
                              fixedColumns = TRUE
               ), 
               filter = 'bottom',
               style = "bootstrap")
  })
  
  
  
  plotObject <- reactive({
    validate(
      need(!is.null(reorderdata2()), "Please select a data set") 
    )
    
    plotdata <- reorderdata2()
    
    
    if(!is.null(plotdata)) {
      
      if (input$themetableau){
        scale_colour_discrete <- function(...) 
          scale_colour_manual(..., values = tableau10,drop=!input$themecolordrop)
        scale_fill_discrete <- function(...) 
          scale_fill_manual(..., values = tableau10,drop=!input$themecolordrop)
      }
      
      p <- ggplot(plotdata, aes_string(x=input$x, y="yvalues")) 
      
      if (input$colorin != 'None')
        p <- p + aes_string(color=input$colorin)
      if (input$fillin != 'None')
        p <- p + aes_string(fill=input$fillin)
      if (input$pointsizein != 'None')
        p <- p  + aes_string(size=input$pointsizein)
      
      # if (input$groupin != 'None' & !is.factor(plotdata[,input$x]))
      if (input$groupin != 'None')
        p <- p + aes_string(group=input$groupin)
      if (input$groupin == 'None' & !is.numeric(plotdata[,input$x]) 
          & input$colorin == 'None')
        p <- p + aes(group=1)
      
      if (input$Points=="Points"&input$pointsizein == 'None'&!input$pointignorecol)
        p <- p + geom_point(,alpha=input$pointstransparency,shape=input$pointtypes,size=input$pointsizes)  
      if (input$Points=="Points"&input$pointsizein != 'None'&!input$pointignorecol)
        p <- p + geom_point(,alpha=input$pointstransparency,shape=input$pointtypes)
      
      if (input$Points=="Jitter"&input$pointsizein == 'None'&!input$pointignorecol)
        p <- p + geom_jitter(,alpha=input$pointstransparency,shape=input$pointtypes,size=input$pointsizes)
      if (input$Points=="Jitter"&input$pointsizein != 'None'&!input$pointignorecol)
        p <- p + geom_jitter(,alpha=input$pointstransparency,shape=input$pointtypes)
      
      
      if (input$Points=="Points"&input$pointsizein == 'None'&input$pointignorecol)
        p <- p + geom_point(,alpha=input$pointstransparency,shape=input$pointtypes,size=input$pointsizes,colour=input$colpoint)  
      if (input$Points=="Points"&input$pointsizein != 'None'&input$pointignorecol)
        p <- p + geom_point(,alpha=input$pointstransparency,shape=input$pointtypes,colour=input$colpoint)
      
      if (input$Points=="Jitter"&input$pointsizein == 'None'&input$pointignorecol)
        p <- p + geom_jitter(,alpha=input$pointstransparency,shape=input$pointtypes,size=input$pointsizes,colour=input$colpoint)
      if (input$Points=="Jitter"&input$pointsizein != 'None'&input$pointignorecol)
        p <- p + geom_jitter(,alpha=input$pointstransparency,shape=input$pointtypes,colour=input$colpoint)
      
      
      
      if (input$line=="Lines"&input$pointsizein == 'None'& !input$lineignorecol)
        p <- p + geom_line(,size=input$linesize,alpha=input$linestransparency,linetype=input$linetypes)
      if (input$line=="Lines"&input$pointsizein != 'None'& !input$lineignorecol)
        p <- p + geom_line(,alpha=input$linestransparency,linetype=input$linetypes)
      if (input$line=="Lines"&input$pointsizein == 'None'&input$lineignorecol)
        p <- p + geom_line(,size=input$linesize,alpha=input$linestransparency,linetype=input$linetypes,colour=input$colline)
      if (input$line=="Lines"&input$pointsizein != 'None'& input$lineignorecol)
        p <- p + geom_line(,alpha=input$linestransparency,linetype=input$linetypes,colour=input$colline)
      
      
      if (input$boxplotaddition){
        if (input$groupin != 'None'& !input$boxplotignoregroup ){
          p <- p + aes_string(group=input$groupin)
          p <- p + geom_boxplot()
        }
        if (input$groupin == 'None'){
          p <- p + geom_boxplot(aes(group=NULL))
        }  
        if (input$boxplotignoregroup ){
          p <- p + geom_boxplot(aes(group=NULL))
        } 
        
        
      }
      
      
      ###### Mean section  START 
      
      
      if (!input$meanignoregroup) {
        if (!input$meanignorecol) {
          
          if (input$Mean=="Mean") {
            if(input$meanlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line")
            if(input$meanlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line",size=input$meanlinesize)
            
            
            if(input$meanpoints)           
              p <- p + 
                stat_sum_single(mean, geom = "point")
            
          }
          
          if (input$Mean=="Mean (95% CI)"){
            p <- p + 
              stat_sum_df("mean_cl_normal", geom = "errorbar",fun.args=list(conf.int=input$CI),width=input$errbar)
            if(input$meanlines&input$pointsizein != 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line")
            if(input$meanlines&input$pointsizein == 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line",size=input$meanlinesize)
            if(input$meanpoints)           
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "point")
            
          }
        }
        
        
        if (input$meanignorecol) {
          meancol <- input$colmean
          if (input$Mean=="Mean") {
            if(input$meanlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line",col=meancol)
            
            if(input$meanlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line",col=meancol,size=input$meanlinesize)
            
            if(input$meanpoints)           
              p <- p + 
                stat_sum_single(mean, geom = "point",col=meancol)
            
          }
          
          if (input$Mean=="Mean (95% CI)"){
            p <- p + 
              stat_sum_df("mean_cl_normal", geom = "errorbar",fun.args=list(conf.int=input$CI),width=input$errbar, col=meancol)
            if(input$meanlines&input$pointsizein != 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line", col=meancol)
            if(input$meanlines&input$pointsizein == 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line", col=meancol,size=input$meanlinesize)
            
            if(input$meanpoints)           
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "point", col=meancol)
            
          }
        }
      }
      
      if (input$meanignoregroup) {
        if (!input$meanignorecol) {
          
          if (input$Mean=="Mean") {
            if(input$meanlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line",aes(group=NULL))
            if(input$meanlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line",aes(group=NULL),size=input$meanlinesize)
            
            if(input$meanpoints)           
              p <- p + 
                stat_sum_single(mean, geom = "point",aes(group=NULL))
            
          }
          
          if (input$Mean=="Mean (95% CI)"){
            p <- p + 
              stat_sum_df("mean_cl_normal", geom = "errorbar",fun.args=list(conf.int=input$CI), width=input$errbar,aes(group=NULL))
            if(input$meanlines&input$pointsizein != 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line",aes(group=NULL))
            if(input$meanlines&input$pointsizein == 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line",aes(group=NULL),size=input$meanlinesize)
            if(input$meanpoints)           
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "point",aes(group=NULL))
            
          }
        }
        
        
        if (input$meanignorecol) {
          meancol <- input$colmean
          if (input$Mean=="Mean") {
            if(input$meanlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line",col=meancol,aes(group=NULL))
            if(input$meanlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(mean, geom = "line",col=meancol,aes(group=NULL),size=input$meanlinesize)
            
            
            if(input$meanpoints)           
              p <- p + 
                stat_sum_single(mean, geom = "point",col=meancol,aes(group=NULL))
            
          }
          
          if (input$Mean=="Mean (95% CI)"){
            p <- p + 
              stat_sum_df("mean_cl_normal", geom = "errorbar",fun.args=list(conf.int=input$CI), width=input$errbar, col=meancol, aes(group=NULL))
            if(input$meanlines&input$pointsizein != 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line",col=meancol,aes(group=NULL))
            if(input$meanlines&input$pointsizein == 'None')  
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "line",col=meancol,aes(group=NULL),size=input$meanlinesize)
            
            if(input$meanpoints)           
              p <- p + 
                stat_sum_df("mean_cl_normal", geom = "point",col=meancol,aes(group=NULL))
            
          }
        }
      }
      ###### Mean section  END 
      
      ###### Smoothing Section START
      if(!is.null(input$Smooth) ){
        familyargument <- ifelse(input$smoothmethod=="glm","binomial","gaussian") 
        
        if ( input$ignoregroup) {
          if (!input$ignorecol) {
            spanplot <- input$loessens
            if (input$Smooth=="Smooth")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot,aes(group=NULL))
            
            if (input$Smooth=="Smooth and SE")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot,aes(group=NULL))
            
            if (input$Smooth=="Smooth"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot,aes(group=NULL))+  
                aes_string(weight=input$weightin)
            
            if (input$Smooth=="Smooth and SE"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot,aes(group=NULL))+  
                aes_string(weight=input$weightin)
          }
          if (input$ignorecol) {
            spanplot <- input$loessens
            colsmooth <- input$colsmooth
            if (input$Smooth=="Smooth")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot,col=colsmooth,aes(group=NULL))
            
            if (input$Smooth=="Smooth and SE")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot,col=colsmooth,aes(group=NULL))
            
            if (input$Smooth=="Smooth"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot,col=colsmooth,aes(group=NULL))+  
              aes_string(weight=input$weightin)
            
            if (input$Smooth=="Smooth and SE"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot,col=colsmooth,aes(group=NULL))+  
              aes_string(weight=input$weightin)
          }
          
        }
        
        if ( !input$ignoregroup) {
          if (!input$ignorecol) {
            spanplot <- input$loessens
            if (input$Smooth=="Smooth")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot)
            
            if (input$Smooth=="Smooth and SE")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot)
            
            if (input$Smooth=="Smooth"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot)+  
                aes_string(weight=input$weightin)
            
            if (input$Smooth=="Smooth and SE"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot)+  
                aes_string(weight=input$weightin)
          }
          if (input$ignorecol) {
            spanplot <- input$loessens
            colsmooth <- input$colsmooth
            if (input$Smooth=="Smooth")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot,col=colsmooth)
            
            if (input$Smooth=="Smooth and SE")
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot,col=colsmooth)
            
            if (input$Smooth=="Smooth"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=F,span=spanplot,col=colsmooth)+  
              aes_string(weight=input$weightin)
            
            if (input$Smooth=="Smooth and SE"& input$weightin != 'None')
              p <- p + geom_smooth(method=input$smoothmethod,
                                   method.args = list(family = familyargument),
                                   size=1.5,se=T,span=spanplot,col=colsmooth)+  
              aes_string(weight=input$weightin)
          }
          
        }
        
        ###### smooth Section END
      }
      
      
      ###### Median PI section  START  
      if (!input$medianignoregroup) {
        
        if (!input$medianignorecol) {
          
          if (input$Median=="Median") {
            if(input$medianlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line")
            
            if(input$medianlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line",size=input$medianlinesize)
            
            
            if(input$medianpoints)           
              p <- p + 
                stat_sum_single(median, geom = "point")
            
          }
          
          if (input$Median=="Median/PI"&input$pointsizein == 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon",fun.args=list(conf.int=input$PI) ,size=input$medianlinesize,alpha=input$PItransparency,col=NA)+ 
              stat_sum_df("median_hilow", geom = "smooth",fun.args=list(conf.int=input$PI) ,size=input$medianlinesize,alpha=0)
            
            if ( input$sepguides )
              p <-   p + 
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
            
          }
          
          if (input$Median=="Median/PI"&input$pointsizein != 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon",fun.args=list(conf.int=input$PI), alpha=input$PItransparency,col=NA)+
              stat_sum_df("median_hilow", geom = "smooth"  ,fun.args=list(conf.int=input$PI),alpha=0)
            
            if ( input$sepguides )
              p <-   p +
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
            
          }
          
          if (input$Median!="None" & input$medianvalues )  {
            p <-   p   +
              stat_summary(fun.data = median.n,geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold",
                           show.legend=FALSE,size=6)}
          if (input$Median!="None" & input$medianN)  {
            p <-   p   +
              stat_summary(fun.data = give.n, geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold", 
                           show.legend=FALSE,size=6)      
          }  
        }
        
        
        
        if (input$medianignorecol) {
          mediancol <- input$colmedian
          if (input$Median=="Median") {
            if(input$medianlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line",col=mediancol)
            
            if(input$medianlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line",col=mediancol,size=input$medianlinesize)
            
            if(input$medianpoints)           
              p <- p + 
                stat_sum_single(median, geom = "point",col=mediancol)
            
          }
          
          if (input$Median=="Median/PI"&input$pointsizein == 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon", fun.args=list(conf.int=input$PI), alpha=input$PItransparency,col=NA)+
              stat_sum_df("median_hilow", geom = "smooth", fun.args=list(conf.int=input$PI), size=input$medianlinesize,col=mediancol,alpha=0)
            
            if ( input$sepguides )
              p <-   p +
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
          }
          if (input$Median=="Median/PI"&input$pointsizein != 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon",fun.args=list(conf.int=input$PI),alpha=input$PItransparency,col=NA)+
              stat_sum_df("median_hilow", geom = "smooth",fun.args=list(conf.int=input$PI),col=mediancol,
                          alpha=0)          
            
            if ( input$sepguides )
              p <-   p +
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
          }
          if (input$Median!="None" & input$medianvalues )  {
            p <-   p   +
              stat_summary(fun.data = median.n,geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold",colour=mediancol,
                           show.legend=FALSE,size=6)}
          if (input$Median!="None" & input$medianN)  {
            p <-   p   +
              stat_summary(fun.data = give.n, geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold", colour=mediancol,
                           show.legend=FALSE,size=6)      
          }       
          
        }
      }
      
      
      if (input$medianignoregroup) {
        if (!input$medianignorecol) {
          if (input$Median=="Median") {
            if(input$medianlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line",aes(group=NULL))
            if(input$medianlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line",aes(group=NULL),size=input$medianlinesize)
            
            if(input$medianpoints)           
              p <- p + 
                stat_sum_single(median, geom = "point",aes(group=NULL))
            
          }
          
          if (input$Median=="Median/PI"&input$pointsizein == 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon",fun.args=list(conf.int=input$PI),aes(group=NULL),alpha=input$PItransparency,col=NA)+ 
              stat_sum_df("median_hilow", geom = "smooth",fun.args=list(conf.int=input$PI),aes(group=NULL),size=input$medianlinesize,alpha=0)   
            if ( input$sepguides )
              p <-   p +
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
          }
          
          if (input$Median=="Median/PI"&input$pointsizein != 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon",fun.args=list(conf.int=input$PI),aes(group=NULL),alpha=input$PItransparency,col=NA)+ 
              stat_sum_df("median_hilow", geom = "smooth",fun.args=list(conf.int=input$PI),aes(group=NULL),alpha=0)
            if ( input$sepguides )
              p <-   p +
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
          }
          if (input$Median!="None" & input$medianvalues )  {
            p <-   p   +
              stat_summary(fun.data = median.n, aes(group=NULL),geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold",fill="white",
                           show.legend=FALSE,
                           size=6)}
          if (input$Median!="None" & input$medianN)  {
            p <-   p   +
              stat_summary(fun.data = give.n, aes(group=NULL), geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold", fill="white",
                           show.legend=FALSE,size=6)      
          }
          
          
        }
        
        
        if (input$medianignorecol) {
          mediancol <- input$colmedian
          if (input$Median=="Median") {
            if(input$medianlines&input$pointsizein != 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line",col=mediancol,aes(group=NULL))
            if(input$medianlines&input$pointsizein == 'None')           
              p <- p + 
                stat_sum_single(median, geom = "line",col=mediancol,aes(group=NULL),size=input$medianlinesize)
            
            if(input$medianpoints)           
              p <- p + 
                stat_sum_single(median, geom = "point",col=mediancol,aes(group=NULL))
            
          }
          
          if (input$Median=="Median/PI"&input$pointsizein == 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon",fun.args=list(conf.int=input$PI),aes(group=NULL),alpha=input$PItransparency,col=NA)+ 
              stat_sum_df("median_hilow", geom = "smooth",fun.args=list(conf.int=input$PI),col=mediancol,aes(group=NULL),size=input$medianlinesize,alpha=0)
            if ( input$sepguides )
              p <-   p +
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
          }
          if (input$Median=="Median/PI"&input$pointsizein != 'None'){
            p <- p + 
              stat_sum_df("median_hilow", geom = "ribbon",fun.args=list(conf.int=input$PI),aes(group=NULL),alpha=input$PItransparency,col=NA)+ 
              stat_sum_df("median_hilow", geom = "smooth",fun.args=list(conf.int=input$PI),col=mediancol,aes(group=NULL),alpha=0)
            
            
            
            if ( input$sepguides )
              p <-   p +
                guides(
                  color = guide_legend(paste("Median"),
                                       override.aes = list(shape =NA,fill=NA)),
                  fill  = guide_legend(paste( 100*input$PI,"% prediction interval"),
                                       override.aes = list(shape =NA ,linetype =0,alpha=0.5 )
                  ) )
          }
          
          
          if (input$Median!="None" & input$medianvalues )  {
            p <-   p   +
              stat_summary(fun.data = median.n, aes(group=NULL),geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold",colour=mediancol,
                           show.legend=FALSE,size=6)}
          if (input$Median!="None" & input$medianN)  {
            p <-   p   +
              stat_summary(fun.data = give.n, aes(group=NULL), geom = "label_repel",alpha=0.1,
                           fun.y = median, fontface = "bold", colour=mediancol,
                           show.legend=FALSE,size=6)      
          }
          
        }
      }
      
      
      
      ###### Median PI section  END
      
      
      
      ###### RQSS SECTION START  
      if (!input$ignoregroupqr) {
        if (!input$ignorecolqr) {
          if (input$Tauvalue) {
            if(!input$hidedynamic){
              p <- p +  stat_quantile(method = "rqss",quantiles =input$Tau,size=1.5,
                                      linetype="solid", 
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))       
            }
            
            if (input$mid)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.5,size=1.5,
                                      linetype="solid",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$ninetieth)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.90,size=1,
                                      linetype="dashed",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$tenth)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.1,size=1,
                                      linetype="dashed",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$up)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.95,size=1,
                                      linetype="dashed",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$low) 
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.05,size=1,
                                      linetype="dashed",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            
            
          }
        }
        if (input$ignorecolqr) {
          colqr <- input$colqr
          if (input$Tauvalue) {
            if(!input$hidedynamic){
              p <- p +  stat_quantile(method = "rqss",quantiles =input$Tau,size=1.5,
                                      linetype="solid", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty)) 
            }
            
            
            if (input$mid)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.5,size=1.5,
                                      linetype="solid", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$ninetieth)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.90,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$tenth)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.1,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$up)
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.95,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$low) 
              p <- p +  stat_quantile(method = "rqss",quantiles = 0.05,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            
            
          }
        }
      }
      
      
      if (input$ignoregroupqr) {
        if (!input$ignorecolqr) {
          if (input$Tauvalue) {
            if(!input$hidedynamic){
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles =input$Tau,size=1.5,
                                      linetype="solid",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty)) 
            }
            
            if (input$mid)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.5,size=1.5,
                                      linetype="solid",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$ninetieth)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.90,size=1,
                                      linetype="dashed", 
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$tenth)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.1,size=1,
                                      linetype="dashed",
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$up)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.95,size=1,
                                      linetype="dashed", 
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$low) 
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.05,size=1,
                                      linetype="dashed", 
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
          }
        }
        if (input$ignorecolqr) {
          colqr <- input$colqr
          if (input$Tauvalue) {
            if(!input$hidedynamic){
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles =input$Tau,size=1.5,
                                      linetype="solid",col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))     
            }
            
            
            if (input$mid)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.5,size=1.5,
                                      linetype="solid", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$ninetieth)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.90,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            if (input$tenth)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.1,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$up)
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.95,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
            if (input$low) 
              p <- p +  stat_quantile(aes(group=NULL),method = "rqss",quantiles = 0.05,size=1,
                                      linetype="dashed", col=colqr,
                                      formula=y ~ qss(x, constraint= input$Constraints,
                                                      lambda=input$Penalty))
            
          }
        }
      }
      
      
      ###### RQSS SECTION END
      
      ###### KM SECTION START
      
      if (input$KM!="None") {
        p <- ggplot(plotdata, aes_string(time=input$x, status="yvalues")) 
        if (input$colorin != 'None')
          p <- p + aes_string(color=input$colorin)
        if (input$fillin != 'None')
          p <- p + aes_string(fill=input$fillin)
        if (input$groupin != 'None' & !is.factor(plotdata[,input$x]))
          p <- p + aes_string(group=input$groupin)
      }
      
      if (input$KM=="KM/CI") {
        p <- p +
          geom_kmband(alpha=input$KMCItransparency,conf.int = input$KMCI,trans=input$KMtrans)                 }
      
      
      if (input$KM!="None") {
        p  <- p +
          geom_smooth(stat="km",trans=input$KMtrans)
      }
      if (input$censoringticks) {
        p  <- p +
          geom_kmticks(trans=input$KMtrans)
      }
      
      
      
      
      ###### KM SECTION END
      
      
      facets <- paste(input$facetrowin,'~', input$facetcolin)
      
      if (input$facetrowextrain !="."&input$facetrowin !="."){
        facets <- paste(input$facetrowextrain ,"+", input$facetrowin, '~', input$facetcolin)
      }  
      if (input$facetrowextrain !="."&input$facetrowin =="."){
        facets <- paste( input$facetrowextrain, '~', input$facetcolin)
      }  
      
      if (input$facetcolextrain !="."){
        facets <- paste( facets, "+",input$facetcolextrain)
      }  
      if (facets != '. ~ .')
        p <- p + facet_grid(facets,scales=input$facetscalesin,space=input$facetspace
                            ,labeller=input$facetlabeller,margins=input$facetmargin )
      
      if (facets != '. ~ .' & input$facetswitch!="" )
        
        p <- p + facet_grid(facets,scales=input$facetscalesin,space=input$facetspace,
                            switch=input$facetswitch
                            , labeller=input$facetlabeller,
                            margins=input$facetmargin )
      
      if (facets != '. ~ .'&input$facetwrap) {
        p <- p + facet_wrap(    c(input$facetrowextrain ,input$facetrowin,input$facetcolin,input$facetcolextrain ) [
          c(input$facetrowextrain ,input$facetrowin,input$facetcolin,input$facetcolextrain )!="."]
          ,scales=input$facetscalesin)
        
        if (input$facetwrap&input$customncolnrow) {
          p <- p + facet_wrap(    c(input$facetrowextrain ,input$facetrowin,input$facetcolin,input$facetcolextrain ) [
            c(input$facetrowextrain ,input$facetrowin,input$facetcolin,input$facetcolextrain )!="."]
            ,scales=input$facetscalesin,ncol=input$wrapncol,nrow=input$wrapnrow)
        }
      }
      
      
      
      
      if (input$logy)
        p <- p + scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),
                               labels = trans_format("log10", math_format(10^.x))) 
      
      if (input$logx)
        p <- p + scale_x_log10(breaks = trans_breaks("log10", function(x) 10^x),
                               labels = trans_format("log10", math_format(10^.x))) 
      
      
      
      if (input$scientificy )
        p <- p  + 
        scale_y_continuous(labels=comma )
      
      if (input$scientificx )
        p <- p  + 
        scale_x_continuous(labels=comma) 
      
      
      
      
      if (length(input$y) >= 2 & input$ylab=="" ){
        p <- p + ylab("Y variable(s)")
      }
      if (length(input$y) < 2 & input$ylab=="" ){
        p <- p + ylab(input$y)
      }
      
      if (input$xlab!="")
        p <- p + xlab(input$xlab)
      if (input$ylab!="")
        p <- p + ylab(input$ylab)
      
      
      if (input$horizontalzero)
        p <-    p+
        geom_hline(aes(yintercept=0))
      
      if (input$customline1)
        p <-    p+
        geom_vline(xintercept=input$vline)
      
      
      if (input$customline2)
        p <-    p+
        geom_hline(yintercept=input$hline)
      
      
      
      if (input$identityline)
        p <-    p+ geom_abline(intercept = 0, slope = 1)
      
      if (input$themebw) {
        p <-    p+
          theme_bw(base_size=input$themebasesize)     
      }
      
      
      if (!input$themebw){
        p <- p +
          theme_gray(base_size=input$themebasesize)+
          theme(  
            #axis.title.y = element_text(size = rel(1.5)),
            #axis.title.x = element_text(size = rel(1.5))#,
            #strip.text.x = element_text(size = 16),
            #strip.text.y = element_text(size = 16)
          )
      }
      
      
      p <-    p+theme(
        legend.position=input$legendposition,
        legend.box=input$legendbox,
        legend.direction=input$legenddirection,
        panel.background = element_rect(fill=input$backgroundcol))
      
      if (input$labelguides)
        p <-    p+
        theme(legend.title=element_blank())
      if (input$themeaspect)
        p <-    p+
        theme(aspect.ratio=input$aspectratio)
      if (!input$themetableau){
        p <-  p +
          scale_colour_hue(drop=!input$themecolordrop)+
          scale_fill_hue(drop=!input$themecolordrop)
      }
      
      if (grepl("^\\s+$", input$ylab) ){
        p <- p + theme(
          axis.title.y=element_blank())
      }
      if (grepl("^\\s+$", input$xlab) ){
        p <- p + theme(
          axis.title.x=element_blank())
      }
      
      if (input$rotatexticks ){
        p <-  p+
          theme(axis.text.x = element_text(angle = input$xticksrotateangle,
                                           hjust = input$xtickshjust,
                                           vjust = input$xticksvjust) )
        
      }
      if (input$rotateyticks ){
        p <-  p+
          theme(axis.text.y = element_text(angle = input$yticksrotateangle,
                                           hjust = input$ytickshjust,
                                           vjust = input$yticksvjust) )                              
      }    
      
      if (!is.null(input$xaxiszoomin[1])&
          is.numeric(plotdata[,input$x] )&
          input$facetscalesin!="free_x"&
          input$facetscalesin!="free"
      ){
        p <- p +
          coord_cartesian(xlim= c(input$xaxiszoomin[1],input$xaxiszoomin[2])  )
      }
      
      #p <- ggplotly(p)
      p
    }
  })
  
  output$plot <- renderPlot({
    plotObject()
  })
  
  
  output$ui_plot <-  renderUI({                 
    plotOutput('plot',  width = "100%" ,height = input$height,
               click = "plot_click",
               hover = hoverOpts(id = "plot_hover", delayType = "throttle"),
               brush = brushOpts(id = "plot_brush"))
  })
  
  output$plotinfo <- renderPrint({
    df<- reorderdata2()  
    if (is.null(df)) return(NULL)
    nearPoints( reorderdata2(), input$plot_click, threshold = 5, maxpoints = 5,
                addDist = TRUE) #,xvar=input$x, yvar=input$y
  })
  
  
  output$clickheader <-  renderUI({
    df <-reorderdata2()
    if (is.null(df)) return(NULL)
    h4("Clicked points")
  })
  
  output$brushheader <-  renderUI({
    df <- reorderdata2()
    if (is.null(df)) return(NULL)
    h4("Brushed points")
    
  })
  
  output$plot_clickedpoints <- renderTable({
    # For base graphics, we need to specify columns, though for ggplot2,
    # it's usually not necessary.
    df<- reorderdata2()  
    if (is.null(df)) return(NULL)
    
    res <- nearPoints(reorderdata2(), input$plot_click, input$x, "yvalues")
    if (nrow(res) == 0|is.null(res))
      return(NULL)
    res
  })
  output$plot_brushedpoints <- renderTable({
    df<- reorderdata2()  
    if (is.null(df)) return(NULL)
    res <- brushedPoints(reorderdata2(), input$plot_brush, input$x,"yvalues")
    if (nrow(res) == 0|is.null(res))
      return(NULL)
    res
  })
  
  
  
  
  downloadPlotType <- reactive({
    input$downloadPlotType  
  })
  
  observe({
    plotType    <- input$downloadPlotType
    plotTypePDF <- plotType == "pdf"
    plotUnit    <- ifelse(plotTypePDF, "inches", "pixels")
    plotUnitDef <- ifelse(plotTypePDF, 7, 480)
    
    updateNumericInput(
      session,
      inputId = "downloadPlotHeight",
      label = sprintf("Height (%s)", plotUnit),
      value = plotUnitDef)
    
    updateNumericInput(
      session,
      inputId = "downloadPlotWidth",
      label = sprintf("Width (%s)", plotUnit),
      value = plotUnitDef)
    
  })
  
  
  # Get the download dimensions.
  downloadPlotHeight <- reactive({
    input$downloadPlotHeight
  })
  
  downloadPlotWidth <- reactive({
    input$downloadPlotWidth
  })
  
  # Get the download file name.
  downloadPlotFileName <- reactive({
    input$downloadPlotFileName
  })
  
  # Include a downloadable file of the plot in the output list.
  output$downloadPlot <- downloadHandler(
    filename = function() {
      paste(downloadPlotFileName(), downloadPlotType(), sep=".")   
    },
    # The argument content below takes filename as a function
    # and returns what's printed to it.
    content = function(con) {
      # Gets the name of the function to use from the 
      # downloadFileType reactive element. Example:
      # returns function pdf() if downloadFileType == "pdf".
      plotFunction <- match.fun(downloadPlotType())
      plotFunction(con, width = downloadPlotWidth(), height = downloadPlotHeight())
      print(plotObject())
      dev.off(which=dev.cur())
    }
  )
  
  
}

shinyApp(ui = ui, server = server,  options = list(height = 1000))
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        cancel = function(job_ids, user = private$user, host = private$host) {
            job_ids <- paste(job_ids, collapse = ",")

            stain_ssh(user, host, paste("scancel", job_ids))
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host, submit_dir = "~/stain") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir = "~/stain") {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        submission_history = function() {
            # `stain_sub_history` will warn if submission history is empty.
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                return(history)
            }
        },
        fetch_job_states = function(user = private$user, host = private$host) {
            job_ids <- stain_sub_history(self$dir)$job_id

            verify_state_table <- function(state_table) {
                if (nrow(status_table) > 0) {
                    return(state_table)
                } else {
                    job_ids <- paste(job_ids, collapse = ", ")
                    message(paste("No statuses found for job ids:", job_ids))
                }
            }

            fetch_squeue_table <- function() {
                tryCatch({
                    squeue_table <- stain_ssh_squeue(user, host, job_ids)
                    squeue_table <- squeue_table[, c("JOBID", "STATE")]
                    colnames(squeue_table) <- c("job_id", "state")
                    # Will throw error if data frame has no rows.
                    squeue_table$exit_code <- NA
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    squeue_table <- data.frame()
                }, finally = return(squeue_table))
            }

            fetch_sacct_table <- function() {
                tryCatch({
                    sacct_table <- stain_ssh_sacct(user, host, job_ids)
                    colnames(sacct_table) <- c("job_id", "state", "exit_code")
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    sacct_table <- data.frame()
                }, finally = return(sacct_table))
            }

            squeue_table <- fetch_squeue_table()
            sacct_table <- fetch_sacct_table()
            states <- rbind(squeue_table, sacct_table)
            states <- aggregate(states, list(states$job_id), function(x) {
                na.omit(x)[1]
            })[,-1]

            return(states)
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' Create an SBATCH option
#'
#' @param key The key for the sbatch option.
#'
#' @return A function that takes a single argument representing
#' the value for the \code{key}.
sbatch_opt <- function(key) {
    return(function(value) {
        return(paste0("--", key, "=", value))
    })
}


#' Test sbatch options for equality.
#'
#' sbatch option equallity is achieved if the keys of the options
#' are the same.
#'
#' @param opt_1 An sbatch option string.
#'
#' @param opt_2 An sbatch option string.
#'
#' @return A boolean value.
sbatch_opts_equal <- function(opt_1, opt_2) {
    return(sbatch_opt_key(opt_1) == sbatch_opt_key(opt_2))
}


#' Insert an sbatch option into a set.
#'
#' @param opt The sbatch option to insert
#'
#' @param opts A set of sbatch options. Default value is the empty
#' set.
#'
#' @return A set with \code{opt} inserted.
sbatch_opts_insert <- function(opt, opts = c()) {
    did_set <- FALSE

    for (i in 1:length(opts)) {
        if (sbatch_opts_equal(opt, opts[i])) {
            opts[i] = opt
            did_set = TRUE
        }
    }

    if(!did_set) {
        opts <- c(opts, opt)
    }

    return(opts)
}


#' Get the key of an sbatch.
#'
#' @param opt An sbatch option string.
#'
#' @return The \code{opt}'s key.
sbatch_opt_key <- function(opt) {
    return(strsplit(opt, "=")[[1]][1])
}


#' Get the value of an sbatch option.
#'
#' @param opt An sbatch option string.
#'
#' @return The \code{opt}'s value.
sbatch_opt_value <- function(opt) {
    return(strsplit(opt, "=")[[1]][2])
}


#' A list of sbatch options.
#'
#' The value of each item in the list is a string or a function
#' which takes a string as a parameter, using \code{sbatch_opt}.
#'
#' To ensure proper formatting, the \code{mail_type} option should
#' be set using \code{sbatch_mail_types}. Multiple mail types need
#' to be comma seperated.
#'
#' @export
sbatch_opts <- list (
    begin = sbatch_opt("begin"),
    cpus_per_task = sbatch_opt("cpus-per-task"),
    mail_user = sbatch_opt("mail-user"),
    memory = sbatch_opt("mem"),
    nodes = sbatch_opt("nodes"),
    ouput = sbatch_opt("ouput"),
    time = sbatch_opt("time")
)


#' A list of sbatch mail types.
#'
#' The value of each item in the list is a string representing
#' a mail type option.
#'
#' @export
sbatch_mail_type_opts <- list(
    all = sbatch_opt("mail-type")("ALL"),
    begin = sbatch_opt("mail-type")("BEGIN"),
    end = sbatch_opt("mail-type")("END"),
    fail = sbatch_opt("mail-type")("FAIL"),
    none = sbatch_opt("mail-type")("NONE"),
    requeue = sbatch_opt("mail-type")("REQUEUE"),
    stage_out = sbatch_opt("mail-type")("STAGE_OUT"),
    time_limit = sbatch_opt("mail-type")("TIME_LIMIT"),
    time_limit_90 = sbatch_opt("mail-type")("TIME_LIMIT_90"),
    time_limit_80 = sbatch_opt("mail-type")("TIME_LIMIT_80"),
    time_limit_50 = sbatch_opt("mail-type")("TIME_LIMIT_50")
)


#' Create single sbatch mail type key value pair.
#'
#' A user may specific multiple \code{sbatch_mail_type_opts},
#' which must be combined into a single key value pair that
#' contains the options seperated by commas.
#'
#' @param opts A list of sbatch mail type options.
sbatch_mail_type_combine <- function(opts) {
    opt_keys <- sapply(opts, sbatch_opt_key, USE.NAMES = FALSE)
    mail_type_opts <- which(opt_keys == "--mail-type")

    mail_type_opt_vals <- sapply(opts[mail_type_opts], sbatch_opt_value,
                                 USE.NAMES = FALSE)
    mail_type_opt_val <- paste(unique(mail_type_opt_vals), collapse = ",")
    mail_type_opt <- sbatch_opt("mail-type")(mail_type_opt_val)

    return(c(opts[-mail_type_opts], mail_type_opt))
}

#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        cancel = function(job_ids, user = private$user, host = private$host) {
            job_ids <- paste(job_ids, collapse = ",")

            stain_ssh(user, host, paste("scancel", job_ids))
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host, submit_dir = "~/stain") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir = "~/stain") {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        view_submission_history = function() {
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                View(history)
                invisible(history)
            }
        },
        fetch_job_states = function(user = private$user, host = private$host) {
            job_ids <- stain_sub_history(self$dir)$job_id

            verify_state_table <- function(state_table) {
                if (nrow(status_table) > 0) {
                    return(state_table)
                } else {
                    job_ids <- paste(job_ids, collapse = ", ")
                    message(paste("No statuses found for job ids:", job_ids))
                }
            }

            fetch_squeue_table <- function() {
                tryCatch({
                    squeue_table <- stain_ssh_squeue(user, host, job_ids)
                    squeue_table <- squeue_table[, c("JOBID", "STATE")]
                    colnames(squeue_table) <- c("job_id", "state")
                    # Will throw error if data frame has no rows.
                    squeue_table$exit_code <- NA
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    squeue_table <- data.frame()
                }, finally = return(squeue_table))
            }

            fetch_sacct_table <- function() {
                tryCatch({
                    sacct_table <- stain_ssh_sacct(user, host, job_ids)
                    colnames(sacct_table) <- c("job_id", "state", "exit_code")
                },
                error = function(e) {
                    # An empty data frame without columns will successfully row
                    # bind with any other data frame.
                    sacct_table <- data.frame()
                }, finally = return(sacct_table))
            }

            squeue_table <- fetch_squeue_table()
            sacct_table <- fetch_sacct_table()
            states <- rbind(squeue_table, sacct_table)
            states <- aggregate(states, list(states$job_id), function(x) {
                na.omit(x)[1]
            })[,-1]

            return(states)
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        cancel = function(job_ids, user = private$user, host = private$host) {
            job_ids <- paste(job_ids, collapse = ",")

            stain_ssh(user, host, paste("scancel", job_ids))
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host, submit_dir = "~/stain") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir = "~/stain") {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        view_submission_history = function() {
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                View(history)
                invisible(history)
            }
        },
        view_statuses = function(user = private$user, host = private$host, should_view = TRUE) {
            job_ids <- stain_sub_history(self$dir)$job_id

            tryCatch({
                status_table <- stain_ssh_squeue(user, host, job_ids)
            }, warning = function(w) {
                message(paste("No statuses found for job ids:", job_ids))
                invisible()
            })


            if (nrow(status_table) > 0) {
                if (should_view) { View(status_table) }
            } else {
                job_ids <- paste(job_ids, collapse = ", ")
                message(paste("No statuses found for job ids:", job_ids))
            }

            invisible(status_table)
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
###############################################################################################################################################################
# Timetable Model
# Author Mufy 
# Date 24/09/2016
# Description --  This script models the teaching hours per academic based on their teaching load.  The data for the model is extracted from the timetabling 
#  spreadsheet.

###############################################################################################################################################################

#library(readxl)
require(xlsx)
#library(RODBC)
library(hashmap)

#Set path to the timetable
setwd("/Users/mufy/Dropbox/teaching/UEL/2015-2016/timetable")

#Change the filename if changes or updated
file.name <- "CSI 2016-17-v7.xlsx"
sheet.name <- "ML"

tAllocation <- read.xlsx(file.name, 4, header=FALSE, keepFormulas=FALSE, startRow = 2, endRow =25)
timetable <- read.xlsx(file.name, 3, header=FALSE, keepFormulas=FALSE, startRow = 2, endRow =172)

# Get the current list of staff names 
staffNames <- tAllocation[1]

#get all the teaching allocated staff names 
allocatedStaffNamesOnTimetable <- timetable[12];

#TODO -- Not very efficient algorithm, improve the algorith from 0(N^2) to (NLogN) 
#IMPROVEMENT -- consider using HashMAP


for (i in 1: nrow (staffNames)){
	print (toString(staffNames[i,1]))
	
	totalAllocation <- 0
	totalModuleLeadership <-0
	
	for (j in 1: nrow(allocatedStaffNamesOnTimetable)) {
		if (toString(staffNames[i,1]) == toString(allocatedStaffNamesOnTimetable[j,1])){
			if (toString(timetable[j:j,4]) == "Lecture"){
							
				#calculate mornalized teaching time 			
				normalizedHours <- calculateLectureHours (toString(timetable[j:j,5]), (as.numeric(toString(timetable[j:j,9])))*24) 
				totalAllocation <- totalAllocation + normalizedHours							

				# calculate module leadership 
				moduleLeadership <- calculateModuleLeadership(toString(timetable[j:j,5]), (as.numeric(toString(timetable[j:j,11]))))			
				totalModuleLeadership <- totalModuleLeadership+ moduleLeadership;
							
				cat ("current lec allocation: ", normalizedHours, "total allocation: ",totalAllocation, " module code: ",toString(timetable[j:j,2]), "module size:", (as.numeric(toString(timetable[j:j,11]))),  " ;semester: ", toString(timetable[j:j,5]), "; hours: ", (as.numeric(toString(timetable[j:j,9])))*24, "module leadership: ", moduleLeadership, "\n")
			}else{

				normalizedHours <- calculateLectureHours (toString(timetable[j:j,5]), (as.numeric(toString(timetable[j:j,9])))*24) 
				totalAllocation <- totalAllocation + normalizedHours

				cat ("current tut allocation: ", normalizedHours, "total allocation: ",totalAllocation, " module code: ",toString(timetable[j:j,2]), "module size:", (as.numeric(toString(timetable[j:j,11]))), " ;semester: ", toString(timetable[j:j,5]), "; hours: ", (as.numeric(toString(timetable[j:j,9])))*24, "\n")				
			}
			
			#Handle joint module leaders 
		}else{ 
		
			if (regexpr("/", toString(allocatedStaffNamesOnTimetable[j,1]))[1]!=-1){
				namesList <- unlist(strsplit(toString(allocatedStaffNamesOnTimetable[j,1]), "/"))

				for (k in 1: length(namesList)){
				
					if (toString(staffNames[i,1]) == namesList[k]){
						if (toString(timetable[j:j,4]) == "Lecture"){
							
							#calculate mornalized teaching time 			
							normalizedHours <- calculateLectureHours (toString(timetable[j:j,5]), ((as.numeric(toString(timetable[j:j,9])))*24)/length(namesList)) 
							totalAllocation <- totalAllocation + normalizedHours							

								cat ("Shared current lec allocation: ", normalizedHours, "total allocation: ",totalAllocation, " module code: " , toString(timetable[j:j,2]), "module size:", (as.numeric(toString(timetable[j:j,11]))), " ;semester: ", toString(timetable[j:j,5]), "; hours: ", (as.numeric(toString(timetable[j:j,9])))*24, "module leadership: ", moduleLeadership, "\n")


							# calculate module leadership, only the first person is the module leader 
							if (k ==1){				
								moduleLeadership <- calculateModuleLeadership(toString(timetable[j:j,5]), (as.numeric(toString(timetable[j:j,11]))))			
								totalModuleLeadership <- totalModuleLeadership+ moduleLeadership;
							
								cat ("Shared current lec allocation, with module leadership: ", normalizedHours, "total allocation: ",totalAllocation, " module code: " , toString(timetable[j:j,2]), "module size:", (as.numeric(toString(timetable[j:j,11]))), " ;semester: ", toString(timetable[j:j,5]), "; hours: ", (as.numeric(toString(timetable[j:j,9])))*24, "module leadership: ", moduleLeadership, "\n")
							}					
						}else{

							normalizedHours <- calculateLectureHours (toString(timetable[j:j,5]), ((as.numeric(toString(timetable[j:j,9])))*24)/length(namesList)) 
							totalAllocation <- totalAllocation + normalizedHours

							cat ("Shared current tut allocation: ", normalizedHours, "total allocation: ",totalAllocation, " module code: " ,toString(timetable[j:j,2]),  "module size:", (as.numeric(toString(timetable[j:j,11]))), " ;semester: ", toString(timetable[j:j,5]), "; hours: ", (as.numeric(toString(timetable[j:j,9])))*24, "\n")				
						}
						
					break	
					}
				}				
			}
		}
		
	}
	
	totalAllocation <- totalAllocation + totalModuleLeadership;
 	cat (" Total Allocation time with module leadership for: ",toString(staffNames[i,1]), " is: ", totalAllocation, "\n")
	totalAllocation <- 0
	totalModuleLeadership <-0
		
}

calculateLectureHours <- function(semester, hours, npar=TRUE,print=TRUE){
	
	hourCalc <- 0
	
	
	#cat ("\n calc semester: ", semester, " : hours: ", hours, "\n")
	
	if (toString(semester) == "1 & 2"){
		
		hourCalc =	(2* hours * 24)/43
	#	cat ("\n hour calc: ", hourCalc, "\n")
		return (hourCalc)
		
	}else{
		hourCalc =	(2*hours * 12)/43
	#	cat ("\n hour calc: ", hourCalc, "\n")
		return (hourCalc)
		
	}
}

calculateTutorialHours <- function(semester, hours, npar=TRUE,print=TRUE){
	
	hourCalc <- 0
	
	if (semester == "1 & 2"){		
		hourCalc <-	(1.5* hours * 24)/43
	}else{
		hourCalc <-	(1.5* hours * 12)/43
	}
	
	return (hourCalc)
}

#TODO - Should take into account the module length, currently only module size
calculateModuleLeadership <- function(semester, moduleSize, npar=TRUE,print=TRUE){
		
	small <- 25
	medium <- 75
		
	#cat ("\n module size: ", moduleSize, "\n")	
	
	if (as.numeric(moduleSize) < small) {
		return (1)
	}else if ((as.numeric(moduleSize) > small) & (as.numeric(moduleSize) < medium)){
		return (1.5)
	}else{
		return (2)
	}
}
##predefined_condition_begin

rootdir<-"H:/shengquanhu/projects/20160701_smallRNA_3018-KCV-77_78_79_mouse/class_independent/deseq2_top100Reads/result"
inputfile<-"KCV-77_78_79.design"

showLabelInPCA<-1
showDEGeneCluster<-1
pvalue<-0.05
foldChange<-1.5
minMedianInGroup<-2
addCountOne<-1

##predefined_condition_end

library("DESeq2")
library("heatmap3")
library("lattice")
library("reshape")
library("ggplot2")
library("grid")
library("scales")
library("reshape2")
library("VennDiagram")
library("RColorBrewer")

setwd(rootdir)  
comparisons_data<-read.table(inputfile, header=T, check.names=F , sep="\t", stringsAsFactors = F)

##Solving node stack overflow problem start###
#when there are too many genes, drawing dendrogram may failed due to node stack overflow,
#It could be solved by forcing stats:::plotNode to be run as interpreted code rather then byte-compiled code via a nasty hack.
#http://stackoverflow.com/questions/16559250/error-in-heatmap-2-gplots/25877485#25877485

# Convert a byte-compiled function to an interpreted-code function 
unByteCode <- function(fun)
{
  FUN <- eval(parse(text=deparse(fun)))
  environment(FUN) <- environment(fun)
  FUN
}

# Replace function definition inside of a locked environment **HACK** 
assignEdgewise <- function(name, env, value)
{
  unlockBinding(name, env=env)
  assign( name, envir=env, value=value)
  lockBinding(name, env=env)
  invisible(value)
}

# Replace byte-compiled function in a locked environment with an interpreted-code
# function
unByteCodeAssign <- function(fun)
{
  name <- gsub('^.*::+','', deparse(substitute(fun)))
  FUN <- unByteCode(fun)
  retval <- assignEdgewise(name=name,
                           env=environment(FUN),
                           value=FUN
  )
  invisible(retval)
}

# Use the above functions to convert stats:::plotNode to interpreted-code:
unByteCodeAssign(stats:::plotNode)

# Now raise the interpreted code recursion limit (you may need to adjust this,
#  decreasing if it uses to much memory, increasing if you get a recursion depth error ).
options(expressions=5e4)

##Solving node stack overflow problem end###

hmcols <- colorRampPalette(c("green", "black", "red"))(256)

drawHCA<-function(prefix, rldselect, ispaired, designData, conditionColors, gnames){
  htfile<-paste0(prefix, "_DESeq2-vsd-heatmap.png")
  cat("saving HCA to ", htfile, "\n")
  genecount<-nrow(rldselect)
  if(genecount > 2){
    png(filename=htfile, width=3000, height=3000, res=300)
    cexCol = max(1.0, 0.2 + 1/log10(ncol(rldselect)))
    if(ispaired){
      htColors<-rainbow(length(unique(designData$Paired)))
      gsColors<-as.matrix(data.frame(Group=conditionColors, Sample=htColors[designData$Paired]))
    }else{
      gsColors = conditionColors;
    }
    heatmap3(rldselect, 
             col = hmcols, 
             ColSideColors = gsColors, 
             margins=c(12,5), 
             scale="r", 
             dist=dist, 
             labRow=NA,
             main=paste0("Hierarchical Cluster Using ", genecount, " Genes"),  
             cexCol=cexCol, 
             useRaster=FALSE,
             legendfun=function() showLegend(legend=paste0("Group ", gnames), col=c("red","blue"),cex=1.0,x="center"))
    dev.off()
  }
}

drawPCA<-function(prefix, rldmatrix, showLabelInPCA, designData, conditionColors){
  #filename<-paste0(prefix, "_DESeq2-vsd-pca.png")
  filename<-paste0(prefix, "_DESeq2-vsd-pca.pdf")
  genecount<-nrow(rldmatrix)
  if(genecount > 2){
    cat("saving PCA to ", filename, "\n")
    #png(filename=filename, width=3000, height=3000, res=300) # 10 X 10 inches
    pdf(filename, width=10, height=10)
    pca<-prcomp(t(rldmatrix))
    supca<-summary(pca)$importance
    pcadata<-data.frame(pca$x)
    pcalabs=paste0(colnames(pcadata), "(", round(supca[2,] * 100), "%)")
    pcadata["sample"]<-row.names(pcadata)
    
    if(showLabelInPCA){
      g <- ggplot(pcadata, aes(x=PC1, y=PC2, label=sample)) + 
        geom_text(vjust=-0.6, size=4) +
        geom_point(col=conditionColors, size=4) + 
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) +
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) + 
        xlab(pcalabs[1]) + ylab(pcalabs[2])
    }else{
      g <- ggplot(pcadata, aes(x=PC1, y=PC2)) + 
        geom_point(col=conditionColors, size=4) + 
        labs(color = "Group") +
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) + 
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) +
        xlab(pcalabs[1]) + ylab(pcalabs[2]) + 
        theme(legend.position="top")
    }
    
    print(g)
    dev.off()
  }
}

#for volcano plot
reverselog_trans <- function(base = exp(1)) {
  trans <- function(x) -log(x, base)
  inv <- function(x) base^(-x)
  trans_new(paste0("reverselog-", format(base)), trans, inv, 
            log_breaks(base = base), 
            domain = c(1e-100, Inf))
}

countfiles<-unlist(unique(comparisons_data$CountFile))

countfile_index = 1
for(countfile_index in c(1:length(countfiles))){
  countfile = countfiles[countfile_index]
  comparisons = comparisons_data[comparisons_data$CountFile == countfile,]
  
  if (grepl(".csv$",countfile)) {
    data<-read.csv(countfile,header=T,row.names=1,as.is=T,check.names=FALSE)
  } else {
    data<-read.delim(countfile,header=T,row.names=1,as.is=T,check.names=FALSE)
  }
  
  data<-data[,colnames(data) != "Feature_length"]
  colClass<-sapply(data, class)
  countNotNumIndex<-which(colClass!="numeric" & colClass!="integer")
  if (length(countNotNumIndex)==0) {
    index<-1;
    indecies<-c()
  } else {
    index<-max(countNotNumIndex)+1
    indecies<-c(1:(index-1))
  }
  
  countData<-data[,c(index:ncol(data))]
  countData[is.na(countData)] <- 0
  countData<-round(countData)
  
  if(addCountOne){
    countData<-countData+1
  }
  
  comparisonNames=comparisons$ComparisonName
  
  dir.create("details", showWarnings = FALSE)
  
  pairedspearman<-list()
  resultAllOut<-data
  resultAllOutVar<-c("log2FoldChange","pvalue","padj")
  
  comparison_index = 1
  for(comparison_index in c(1:nrow(comparisons))){
    comparisonName=comparisons$ComparisonName[comparison_index]
    str(comparisonName)
    designFile=comparisons$ConditionFile[comparison_index]
    gnames=unlist(comparisons[comparison_index, c("ReferenceGroupName", "SampleGroupName")])
    
    designData<-read.table(designFile, sep="\t", header=T)
    designData$Condition<-factor(designData$Condition, levels=gnames)
    
    if(ncol(designData) >= 3){
      cat("Data with covariances!\n")
    }else{
      cat("Data without covariances!\n")
    }
    if (any(colnames(designData)=="Paired")) {
      ispaired<-TRUE
      cat("Paired Data!\n")
    }else{
      ispaired<-FALSE
      cat("Not Paired Data!\n")
    }
    temp<-apply(designData,2,function(x) length(unique(x)))
    if (any(temp==1)) {
      cat(paste0("Factors with only 1 level in design matrix: ",colnames(designData)[which(temp==1)],"\n"))
      cat("They will be removed")
      cat("\n")
      designData<-designData[,which(temp!=1)]
    }
    temp<-apply(designData[,-1,drop=F],2,rank)
    if (length(unique(rowSums(temp)))==1 | identical(temp[,1],temp[,-1])) {
      cat(paste0("The model matrix is not full rank, so the model cannot be fit as specified"))
      cat("\n")
      cat("Only Condition variable will be kept.")
      cat("\n")
      designData<-designData[,which(colnames(designData)%in% c("Sample","Condition"))]
    }
    
    comparisonData<-countData[,colnames(countData) %in% as.character(designData$Sample),drop=F]
    if(ncol(comparisonData) != nrow(designData)){
      message=paste0("Data not matched, there are ", nrow(designData), " samples in design file ", designFile, " but ", ncol(comparisonData), " samples in data ")
      warning(message)
      writeLines(message,paste0(comparisonName,".error"))
      next
    }
    comparisonData<-comparisonData[,as.character(designData$Sample)]
    
    prefix<-comparisonName
    curdata<-data
    if(minMedianInGroup > 0){
      conds<-unique(designData$Condition)
      data1<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[1]]]
      data2<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[2]]]
      med1<-apply(data1, 1, median) >= minMedianInGroup
      med2<-apply(data2, 1, median) >= minMedianInGroup
      med<-med1 | med2
      comparisonData<-comparisonData[med,]
      cat(nrow(comparisonData), " genes with minimum median count in group larger or equals than ", minMedianInGroup, "\n")
      
      if (nrow(comparisonData)==0) {
        message=paste0("Error: 0 Genes can be used in DESeq2 analysis in comparison ",comparisonName," \n")
        warning(message)
        writeLines(message,paste0(comparisonName,".error"))
        next;
      }
      
      prefix<-paste0(comparisonName, "_min", minMedianInGroup)
      curdata<-data[med,]
    }
    
    if(ispaired){
      pairedSamples = unique(designData$Paired)
      
      spcorr<-unlist(lapply(c(1:length(pairedSamples)), function(x){
        samples<-designData$Sample[designData$Paired==pairedSamples[x]]
        cor(comparisonData[,samples[1]],comparisonData[,samples[2]],method="spearman")
      }))
      
      
      sptable<-data.frame(Name=pairedSamples, Spcorr=spcorr)
      write.csv(sptable, file=paste0(prefix, "_Spearman.csv"), row.names=FALSE)
      
      lapply(c(1:length(pairedSamples)), function(x){
        samples<-designData$Sample[designData$Paired==pairedSamples[x]]
        log2c1<-log2(comparisonData[,samples[1]]+1)
        log2c2<-log2(comparisonData[,samples[2]]+1)
        png(paste0("details/", prefix, "_Spearman_", pairedSamples[x], ".png"), width=2000, height=2000, res=300)
        plot(log2c1, log2c2, xlab=paste0(samples[1], " [log2(Count + 1)]"), ylab=paste0(samples[2], " [log2(Count + 1)]"))
        text(3,15,paste0("SpearmanCorr=", sprintf("%0.3f", spcorr[x])))
        dev.off()
      })
      
      pairedspearman[[comparisonName]]<-spcorr
    }
    
    notEmptyData<-apply(comparisonData, 1, max) > 0
    comparisonData<-comparisonData[notEmptyData,]
    curdata<-curdata[notEmptyData,]
    
    if(ispaired){
      colnames(comparisonData)<-unlist(lapply(c(1:ncol(comparisonData)), function(i){paste0(designData$Paired[i], "_", colnames(comparisonData)[i])}))
    }
    rownames(designData)<-colnames(comparisonData)
    conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
    
    write.csv(comparisonData, file=paste0(prefix, ".csv"))
    
    #some basic graph
    dds=DESeqDataSetFromMatrix(countData = comparisonData,
                               colData = designData,
                               design = ~1)
    
    colnames(dds)<-colnames(comparisonData)
    
    #draw density graph
    rldmatrix<-as.matrix(log2(counts(dds,normalized=FALSE) + 1))
    rsdata<-melt(rldmatrix)
    colnames(rsdata)<-c("Gene", "Sample", "log2Count")
    png(filename=paste0(prefix, "_DESeq2-log2-density.png"), width=4000, height=3000, res=300)
    g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + xlab("DESeq2 log2 transformed count")
    print(g)
    dev.off()
    
    width=max(4000, ncol(rldmatrix) * 40 + 1000)
    height=max(3000, ncol(rldmatrix) * 40)
    png(filename=paste0(prefix, "_DESeq2-log2-density-individual.png"), width=width, height=height, res=300)
    g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + facet_wrap(~Sample, scales = "free") + xlab("DESeq2 log2 transformed count")
    print(g)
    dev.off()
    
    
    #varianceStabilizingTransformation
    
    allDesignData<-designData
    allComparisonData<-comparisonData
    
    excludedSample<-c()
    zeronumbers<-apply(comparisonData, 2, function(x){sum(x==0)})
    zeronumbers<-names(zeronumbers[order(zeronumbers)])
    percent10<-max(1, round(length(zeronumbers) * 0.1))
    
    removed<-0
    
    excludedCountFile<-paste0(prefix, "_DESeq2-exclude-count.csv")
    excludedDesignFile<-paste0(prefix, "_DESeq2-exclude-design.csv")
    if(file.exists(excludedCountFile)){
      file.remove(excludedCountFile)
    }
    if(file.exists(excludedDesignFile)){
      file.remove(excludedDesignFile)
    }
    
    fitType<-"parametric"
    while(1){
      #varianceStabilizingTransformation
      vsdres<-try(vsd <- varianceStabilizingTransformation(dds, blind=TRUE,fitType=fitType))
      if(class(vsdres) == "try-error" && grepl("every gene contains at least one zero", vsdres[1])){
        removed<-removed+1
        keptNumber<-length(zeronumbers) - percent10 * removed
        keptSample<-zeronumbers[1:keptNumber]
        excludedSample<-zeronumbers[(keptNumber+1):length(zeronumbers)]
        
        comparisonData<-comparisonData[, colnames(comparisonData) %in% keptSample]
        designData<-designData[rownames(designData) %in% keptSample,]
        dds=DESeqDataSetFromMatrix(countData = comparisonData,
                                   colData = designData,
                                   design = ~1)
        
        colnames(dds)<-colnames(comparisonData)
      } else if (class(vsdres) == "try-error" && grepl("newsplit: out of vertex space", vsdres[1])) {
        message=paste0("Warning: varianceStabilizingTransformation function can't run. fitType was set to local to try again")
        warning(message)
        fitType<-"mean"
        writeLines(message,paste0(comparisonName,".error"))
      } else{
        conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
        break
      }
    }
    if (nrow(comparisonData)<=1) {
      message=paste0("Error: All genes in ",comparisonName," has at least one 0 value. Can't do DESeq2.")
      warning(message)
      writeLines(message,paste0(comparisonName,".error"))
      next;
    }
    
    if(length(excludedSample) > 0){
      excludedCountData<-allComparisonData[,colnames(allComparisonData) %in% excludedSample]
      write.csv(file=excludedCountFile, excludedCountData)
      excludedDesignData<-allDesignData[rownames(allDesignData) %in% excludedSample,]
      write.csv(file=excludedDesignFile, excludedDesignData)
    }
    
    assayvsd<-assay(vsd)
    write.csv(assayvsd, file=paste0(prefix, "_DESeq2-vsd.csv"))
    
    vsdiqr<-apply(assayvsd, 1, IQR)
    assayvsd<-assayvsd[order(vsdiqr, decreasing=T),]
    
    rldmatrix=as.matrix(assayvsd)
    
    #draw pca graph
    drawPCA(paste0(prefix,"_geneAll"), rldmatrix, showLabelInPCA, designData, conditionColors)
    
    #draw heatmap
    #drawHCA(paste0(prefix,"_gene500"), rldmatrix[1:min(500, nrow(rldmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
    drawHCA(paste0(prefix,"_geneAll"), rldmatrix, ispaired, designData, conditionColors, gnames)
    
    #different expression analysis
    designFormula=as.formula(paste0("~",paste0(c(colnames(designData)[-c(1:2)],"Condition"),collapse="+")))
    dds=DESeqDataSetFromMatrix(countData = comparisonData,
                               colData = designData,
                               design = designFormula)
    
    dds <- DESeq(dds,fitType=fitType)
    res<-results(dds,cooksCutoff=FALSE)
    
    cat("DESeq2 finished.\n")
    
    select<-(!is.na(res$padj)) & (res$padj<pvalue) & ((res$log2FoldChange >= log2(foldChange)) | (res$log2FoldChange <= -log2(foldChange)))
    
    if(length(indecies) > 0){
      inddata<-curdata[,indecies,drop=F]
      tbb<-cbind(inddata, comparisonData, res)
    }else{
      tbb<-cbind(comparisonData, res)
    }
    tbb$FoldChange<-2^tbb$log2FoldChange
    tbbselect<-tbb[select,,drop=F]
    tbbAllOut<-as.data.frame(tbb[,resultAllOutVar,drop=F])
    tbbAllOut$Significant<-select
    colnames(tbbAllOut)<-paste0(colnames(tbbAllOut)," (",comparisonName,")")
    resultAllOut<-cbind(resultAllOut,tbbAllOut[row.names(resultAllOut),])
    
    tbb<-tbb[order(tbb$padj),,drop=F]
    write.csv(as.data.frame(tbb),paste0(prefix, "_DESeq2.csv"))
    
    tbbselect<-tbbselect[order(tbbselect$padj),,drop=F]
    write.csv(as.data.frame(tbbselect),paste0(prefix, "_DESeq2_sig.csv"))
    
    if("Feature_gene_name" %in% colnames(tbb)){
      write.table(tbb[,c("Feature_gene_name", "stat"),drop=F],paste0(prefix, "_DESeq2_GSEA.rnk"),row.names=F,col.names=F,sep="\t", quote=F)
      write.table(tbbselect[,c("Feature_gene_name"),drop=F], paste0(prefix, "_DESeq2_sig_genename.txt"),row.names=F,col.names=F,sep="\t", quote=F)
    }
    
    if(showDEGeneCluster){
      siggenes<-rownames(rldmatrix) %in% rownames(tbbselect)
      
      nonDEmatrix<-rldmatrix[!siggenes,,drop=F]
      DEmatrix<-rldmatrix[siggenes,,drop=F]
      
      drawPCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, showLabelInPCA, designData, conditionColors)
      drawHCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, ispaired, designData, conditionColors, gnames)
      
      drawPCA(paste0(prefix,"_geneDE"),DEmatrix , showLabelInPCA, designData, conditionColors)
      drawHCA(paste0(prefix,"_geneDE"),DEmatrix , ispaired, designData, conditionColors, gnames)
      #drawHCA(paste0(prefix,"_gene500NotDE"), nonDEmatrix[1:min(500, nrow(nonDEmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
    }
    
    #Top 25 Significant genes barplot
    sigDiffNumber<-nrow(tbbselect)
    if (sigDiffNumber>0) {
      if (sigDiffNumber>25) {
        print(paste0("More than 25 genes were significant. Only the top 25 genes will be used in barplot"))
        diffResultSig<-tbbselect[order(tbbselect$padj)[1:25],]
      } else {
        diffResultSig<-tbbselect
      }
      if("Feature_gene_name" %in% colnames(diffResultSig)){
        diffResultSig$Name<-as.character(diffResultSig$Feature_gene_name)
      }else{
        diffResultSig$Name<-sapply(strsplit(row.names(diffResultSig),";"),function(x) x[1])
      }
      diffResultSig$Name <- factor(diffResultSig$Name, levels=diffResultSig$Name[order(diffResultSig$log2FoldChange)])
      diffResultSig<-as.data.frame(diffResultSig)
      
      png(filename=paste0(prefix, "_DESeq2_sig_barplot.png"), width=3000, height=3000, res=300)
      #	  pdf(paste0(prefix,"_DESeq2_sig_barplot.pdf"))
      p<-ggplot(diffResultSig,aes(x=Name,y=log2FoldChange,order=log2FoldChange))+geom_bar(stat="identity")+
        coord_flip()+
        #			geom_abline(slope=0,intercept=1,colour="red",linetype = 2)+
        scale_y_continuous(name=bquote(log[2]~Fold~Change))+
        theme(axis.text = element_text(colour = "black"))
      print(p)
      dev.off()
    } else {
      print(paste0("No gene with adjusted p value less than ",pvalue," and fold change larger than ",foldChange))
    }
    
    #volcano plot
    changeColours<-c(grey="grey",blue="blue",red="red")
    diffResult<-as.data.frame(tbb)
    diffResult$log10BaseMean<-log10(diffResult$baseMean)
    diffResult$colour<-"grey"
    diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange>=log2(foldChange))]<-"red"
    diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange<=-log2(foldChange))]<-"blue"
    png(filename=paste0(prefix, "_DESeq2_volcanoPlot.png"), width=3000, height=3000, res=300)
    #  pdf(paste0(prefix,"_DESeq2_volcanoPlot.pdf"))
    p<-ggplot(diffResult,aes(x=log2FoldChange,y=padj))+
      geom_point(aes(size=log10BaseMean,colour=colour))+
      scale_color_manual(values=changeColours,guide = FALSE)+
      scale_y_continuous(trans=reverselog_trans(10),name=bquote(Adjusted~p~value))+
      scale_x_continuous(name=bquote(log[2]~Fold~Change))+
      geom_hline(yintercept = 1,colour="grey",linetype = "dotted")+
      geom_vline(xintercept = 0,colour="grey",linetype = "dotted")+
      guides(size=guide_legend(title=bquote(log[10]~Base~Mean)))+
      theme_bw()+
      scale_size(range = c(3, 7))+
      theme(axis.text = element_text(colour = "black",size=30),
            axis.title = element_text(size=30),
            legend.text= element_text(size=30),
            legend.title= element_text(size=30))
    print(p)
    dev.off()
  }
  
  #write a file with all information
  write.csv(resultAllOut,paste0(comparisonName, "_DESeq2.csv"))
  
  if(length(pairedspearman) > 0){
    #draw pca graph
    filename<-ifelse(minMedianInGroup > 0, paste0("spearman_min", minMedianInGroup, ".png"), "spearman.png")
    png(filename=filename, width=1000 * length(pairedspearman), height=2000, res=300)
    boxplot(pairedspearman)
    dev.off()
  }
  
  #Venn for all significant genes
  allSigNameList<-list()
  allSigDirectionList<-list()
  sigTableAll<-NULL
  sigTableAllVar<-c("baseMean","log2FoldChange","lfcSE","stat","pvalue","padj","FoldChange")
  for(comparisonName in comparisonNames){
    if (minMedianInGroup > 0) {
      prefix<-paste0(comparisonName, "_min", minMedianInGroup)
    } else {
      prefix<-comparisonName
    }
    sigFile<-paste0(prefix, "_DESeq2_sig.csv")
    if (file.exists(sigFile)) {
      sigTable<-read.csv(sigFile,header=TRUE,as.is=TRUE,row.names=1)
      if (nrow(sigTable)>0) {
        allSigNameList[[comparisonName]]<-row.names(sigTable)
        allSigDirectionList[[comparisonName]]<-sign(sigTable$log2FoldChange)
		sigTable$comparisonName<-comparisonName
		sigTableAll<-rbind(sigTableAll,sigTable[,c("comparisonName",sigTableAllVar),drop=FALSE])
      } else {
        warning(paste0("No significant genes in ",comparisonName))
        #		allSigNameList[[comparisonName]]<-""
      }
    }
  }
  #Output all significant genes table
  write.csv(sigTableAll,paste0(inputfile,"_min", minMedianInGroup,"_DESeq2_allSig.csv"))
  
  #Do venn if length between 2-5
  if (length(allSigNameList)>=2 & length(allSigNameList)<=5) {
    venn.diagram1<-function (x, filename, height = 3000, width = 3000, resolution = 500, 
                             units = "px", compression = "lzw", na = "stop", main = NULL, 
                             sub = NULL, main.pos = c(0.5, 1.05), main.fontface = "plain", 
                             main.fontfamily = "serif", main.col = "black", main.cex = 1, 
                             main.just = c(0.5, 1), sub.pos = c(0.5, 1.05), sub.fontface = "plain", 
                             sub.fontfamily = "serif", sub.col = "black", sub.cex = 1, 
                             sub.just = c(0.5, 1), category.names = names(x), force.unique = TRUE,
                             fill=NA,
                             ...) 
    {
      if (is.na(fill[1])) {
        if (length(x)==5) {
          fill = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3")
        } else if (length(x)==4) {
          fill = c("dodgerblue", "goldenrod1",  "seagreen3", "orchid3")
        } else if (length(x)==3) {
          fill = c("dodgerblue", "goldenrod1", "seagreen3")
        } else if (length(x)==2) {
          fill = c("dodgerblue", "goldenrod1")
        }
      }
      if (force.unique) {
        for (i in 1:length(x)) {
          x[[i]] <- unique(x[[i]])
        }
      }
      if ("none" == na) {
        x <- x
      }
      else if ("stop" == na) {
        for (i in 1:length(x)) {
          if (any(is.na(x[[i]]))) {
            stop("NAs in dataset", call. = FALSE)
          }
        }
      }
      else if ("remove" == na) {
        for (i in 1:length(x)) {
          x[[i]] <- x[[i]][!is.na(x[[i]])]
        }
      }
      else {
        stop("Invalid na option: valid options are \"none\", \"stop\", and \"remove\"")
      }
      if (0 == length(x) | length(x) > 5) {
        stop("Incorrect number of elements.", call. = FALSE)
      }
      if (1 == length(x)) {
        list.names <- category.names
        if (is.null(list.names)) {
          list.names <- ""
        }
        grob.list <- VennDiagram::draw.single.venn(area = length(x[[1]]), 
                                                   category = list.names, ind = FALSE,fill=fill, ...)
      }
      else if (2 == length(x)) {
        grob.list <- VennDiagram::draw.pairwise.venn(area1 = length(x[[1]]), 
                                                     area2 = length(x[[2]]), cross.area = length(intersect(x[[1]], 
                                                                                                           x[[2]])), category = category.names, ind = FALSE, 
                                                     fill=fill,
                                                     ...)
      }
      else if (3 == length(x)) {
        A <- x[[1]]
        B <- x[[2]]
        C <- x[[3]]
        list.names <- category.names
        nab <- intersect(A, B)
        nbc <- intersect(B, C)
        nac <- intersect(A, C)
        nabc <- intersect(nab, C)
        grob.list <- VennDiagram::draw.triple.venn(area1 = length(A), 
                                                   area2 = length(B), area3 = length(C), n12 = length(nab), 
                                                   n23 = length(nbc), n13 = length(nac), n123 = length(nabc), 
                                                   category = list.names, ind = FALSE, list.order = 1:3, 
                                                   fill=fill,
                                                   ...)
      }
      else if (4 == length(x)) {
        A <- x[[1]]
        B <- x[[2]]
        C <- x[[3]]
        D <- x[[4]]
        list.names <- category.names
        n12 <- intersect(A, B)
        n13 <- intersect(A, C)
        n14 <- intersect(A, D)
        n23 <- intersect(B, C)
        n24 <- intersect(B, D)
        n34 <- intersect(C, D)
        n123 <- intersect(n12, C)
        n124 <- intersect(n12, D)
        n134 <- intersect(n13, D)
        n234 <- intersect(n23, D)
        n1234 <- intersect(n123, D)
        grob.list <- VennDiagram::draw.quad.venn(area1 = length(A), 
                                                 area2 = length(B), area3 = length(C), area4 = length(D), 
                                                 n12 = length(n12), n13 = length(n13), n14 = length(n14), 
                                                 n23 = length(n23), n24 = length(n24), n34 = length(n34), 
                                                 n123 = length(n123), n124 = length(n124), n134 = length(n134), 
                                                 n234 = length(n234), n1234 = length(n1234), category = list.names, 
                                                 ind = FALSE, fill=fill,...)
      }
      else if (5 == length(x)) {
        A <- x[[1]]
        B <- x[[2]]
        C <- x[[3]]
        D <- x[[4]]
        E <- x[[5]]
        list.names <- category.names
        n12 <- intersect(A, B)
        n13 <- intersect(A, C)
        n14 <- intersect(A, D)
        n15 <- intersect(A, E)
        n23 <- intersect(B, C)
        n24 <- intersect(B, D)
        n25 <- intersect(B, E)
        n34 <- intersect(C, D)
        n35 <- intersect(C, E)
        n45 <- intersect(D, E)
        n123 <- intersect(n12, C)
        n124 <- intersect(n12, D)
        n125 <- intersect(n12, E)
        n134 <- intersect(n13, D)
        n135 <- intersect(n13, E)
        n145 <- intersect(n14, E)
        n234 <- intersect(n23, D)
        n235 <- intersect(n23, E)
        n245 <- intersect(n24, E)
        n345 <- intersect(n34, E)
        n1234 <- intersect(n123, D)
        n1235 <- intersect(n123, E)
        n1245 <- intersect(n124, E)
        n1345 <- intersect(n134, E)
        n2345 <- intersect(n234, E)
        n12345 <- intersect(n1234, E)
        grob.list <- VennDiagram::draw.quintuple.venn(area1 = length(A), 
                                                      area2 = length(B), area3 = length(C), area4 = length(D), 
                                                      area5 = length(E), n12 = length(n12), n13 = length(n13), 
                                                      n14 = length(n14), n15 = length(n15), n23 = length(n23), 
                                                      n24 = length(n24), n25 = length(n25), n34 = length(n34), 
                                                      n35 = length(n35), n45 = length(n45), n123 = length(n123), 
                                                      n124 = length(n124), n125 = length(n125), n134 = length(n134), 
                                                      n135 = length(n135), n145 = length(n145), n234 = length(n234), 
                                                      n235 = length(n235), n245 = length(n245), n345 = length(n345), 
                                                      n1234 = length(n1234), n1235 = length(n1235), n1245 = length(n1245), 
                                                      n1345 = length(n1345), n2345 = length(n2345), n12345 = length(n12345), 
                                                      category = list.names, ind = FALSE,fill=fill, ...)
      }
      else {
        stop("Invalid size of input object")
      }
      if (!is.null(sub)) {
        grob.list <- add.title(gList = grob.list, x = sub, pos = sub.pos, 
                               fontface = sub.fontface, fontfamily = sub.fontfamily, 
                               col = sub.col, cex = sub.cex)
      }
      if (!is.null(main)) {
        grob.list <- add.title(gList = grob.list, x = main, pos = main.pos, 
                               fontface = main.fontface, fontfamily = main.fontfamily, 
                               col = main.col, cex = main.cex)
      }
      grid.newpage()
      grid.draw(grob.list)
      return(1)
      #	return(grob.list)
    }
    makeColors<-function(n,colorNames="Set1") {
      maxN<-brewer.pal.info[colorNames,"maxcolors"]
      if (n<=maxN) {
        colors<-brewer.pal(n, colorNames)
      } else {
        colors<-colorRampPalette(brewer.pal(maxN, colorNames))(n)
      }
      return(colors)
    }
    colors<-makeColors(length(allSigNameList))
    png(paste0(comparisonName,"_significantVenn.png"),res=300,height=2000,width=2000)
    venn.diagram1(allSigNameList,cex=2,cat.cex=2,cat.col=colors,fill=colors)
    dev.off()
  }
  #Do heatmap significant genes if length larger or equal than 2
  if (length(allSigNameList)>=2) {
    temp<-cbind(unlist(allSigNameList),unlist(allSigDirectionList))
    colnames(temp)<-c("Gene","Direction")
    temp<-cbind(temp,comparisonName=rep(names(allSigNameList),sapply(allSigNameList,length)))
    temp<-data.frame(temp)
    dataForFigure<-temp
    #geting dataForFigure order in figure
    temp$Direction<-as.integer(as.character(temp$Direction))
    temp<-acast(temp, Gene~comparisonName ,value.var="Direction")
    temp<-temp[do.call(order, data.frame(temp)),]
    maxNameChr<-max(nchar(row.names(temp)))
    if (maxNameChr>70) {
      row.names(temp)<-substr(row.names(temp),0,70)
      dataForFigure$Gene<-substr(dataForFigure$Gene,0,70)
      warning(paste0("The gene names were too long (",maxNameChr,"). Only first 70 letters were kept."))
    }
    dataForFigure$Gene<-factor(dataForFigure$Gene,levels=row.names(temp))
    
    width=max(2500, 60 * length(unique(dataForFigure$comparisonName)))
    height=max(2000, 40 * length(unique(dataForFigure$Gene)))
    png(paste0(comparisonName,"_significantHeatmap.png"),res=300,height=height,width=width)
    g<-ggplot(dataForFigure, aes(comparisonName, Gene))+
      geom_tile(aes(fill=Direction), color="white") +
      scale_fill_manual(values=c("light green", "red")) +
      theme(axis.text.x = element_text(angle=90, vjust=0.5, size=11, hjust=0.5, face="bold"),
            axis.text.y = element_text(size=11, face="bold")) +
      coord_equal()
    print(g)
    dev.off()
  }
}#SNOPSIS
#calculates genomic estimated breeding values (GEBVs) using rrBLUP,
#GBLUP method

#AUTHOR
# Isaak Y Tecle (iyt2@cornell.edu)

options(echo = FALSE)

library(rrBLUP)
library(plyr)
library(stringr)
library(lme4)
library(randomForest)
library(data.table)
#library(genetics)

allArgs <- commandArgs()

inputFiles  <- scan(grep("input_files", allArgs, ignore.case = TRUE, perl = TRUE, value = TRUE),
                   what = "character")

outputFiles <- scan(grep("output_files", allArgs, ignore.case = TRUE,perl = TRUE, value = TRUE),
                    what = "character")

traitsFile <- grep("traits", inputFiles, ignore.case = TRUE, value = TRUE)
traitFile  <- grep("trait_info", inputFiles, ignore.case = TRUE, value = TRUE)
traitInfo  <- scan(traitFile, what = "character",)
traitInfo  <- strsplit(traitInfo, "\t");
traitId    <- traitInfo[[1]]
trait      <- traitInfo[[2]]

datasetInfoFile <- grep("dataset_info", inputFiles, ignore.case = TRUE, value = TRUE)
datasetInfo     <- c()

if (length(datasetInfoFile) != 0 ) { 
    datasetInfo <- scan(datasetInfoFile, what = "character")    
    datasetInfo <- paste(datasetInfo, collapse = " ")   
  } else {   
    datasetInfo <- c('single population')  
  }

validationTrait <- paste("validation", trait, sep = "_")
validationFile  <- grep(validationTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(validationFile)) {
  stop("Validation output file is missing.")
}

kinshipTrait <- paste("kinship", trait, sep = "_")
blupFile     <- grep(kinshipTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(blupFile)) {
  stop("GEBVs file is missing.")
}
markerTrait <- paste("marker", trait, sep = "_")
markerFile  <- grep(markerTrait, outputFiles, ignore.case = TRUE, value = TRUE)

traitPhenoFile <- paste("phenotype_trait", trait, sep = "_")
traitPhenoFile <- grep(traitPhenoFile, outputFiles,ignore.case = TRUE, value = TRUE)

varianceComponentsFile <- grep("variance_components", outputFiles, ignore.case = TRUE, value = TRUE)
filteredGenoFile       <- grep("filtered_genotype_data", outputFiles, ignore.case = TRUE, value = TRUE)
formattedPhenoFile     <- grep("formatted_phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE)

formattedPhenoData <- c()
phenoData          <- c()

genoFile <- grep("genotype_data", inputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(genoFile)) {
  stop("genotype data file is missing.")
}

if (file.info(genoFile)$size == 0) {
  stop("genotype data file is empty.")
}

usedFilteredGenoData <- c()
filteredGenoData <- c()
if (length(filteredGenoFile) != 0 && file.info(filteredGenoFile)$size != 0) {
  filteredGenoData <- fread(filteredGenoFile, na.strings = c("NA", " ", "--", "-"),  header = TRUE)
  usedFilteredGenoData <- 1
  message('read in filtered geno data')
}

genoData <- c()
if (is.null(filteredGenoData)) {
  genoData <- fread(genoFile, na.strings = c("NA", " ", "--", "-"),  header = TRUE)
  message('read in unfiltered geno data')
}

if (length(formattedPhenoFile) != 0 && file.info(formattedPhenoFile)$size != 0) {
  formattedPhenoData <- as.data.frame(fread(formattedPhenoFile,
                                            na.strings = c("NA", " ", "--", "-", ".")
                                            ))
      
  row.names(formattedPhenoData) <- formattedPhenoData[, 1]
  formattedPhenoData[, 1]       <- NULL    
} else {
  phenoFile <- grep("\\/phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE, perl = TRUE)

  if (is.null(phenoFile)) {
    stop("phenotype data file is missing.")
  }

  if (file.info(phenoFile)$size == 0) {
    stop("phenotype data file is empty.")
  }
  
  phenoData <- fread(phenoFile, na.strings = c("NA", " ", "--", "-", "."), header = TRUE) 
}

phenoData  <- as.data.frame(phenoData)
phenoTrait <- c()

if (datasetInfo == 'combined populations') {
  
   if (!is.null(formattedPhenoData)) {
      phenoTrait <- subset(formattedPhenoData, select = trait)
      phenoTrait <- na.omit(phenoTrait)
   
    } else {
      dropColumns <- grep(trait, names(phenoData), ignore.case = TRUE, value = TRUE)
      phenoTrait  <- phenoData[, !(names(phenoData) %in% dropColumns)]
   
      phenoTrait            <- as.data.frame(phenoTrait)
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1]       <- NULL
      colnames(phenoTrait)  <- trait
    }
   
} else {

  if (!is.null(formattedPhenoData)) {
    phenoTrait <- subset(formattedPhenoData, select = trait)
    phenoTrait <- na.omit(phenoTrait)
   
  } else {
    dropColumns <- c("uniquename", "stock_name")
    phenoData   <- phenoData[, !(names(phenoData) %in% dropColumns)]
    
    phenoTrait <- subset(phenoData, select = c("object_name", "object_id", "design", "block", "replicate", trait))
   
    experimentalDesign <- phenoTrait[2, 'design']
  
    if (class(phenoTrait[, trait]) != 'numeric') {
      phenoTrait[, trait] <- as.numeric(as.character(phenoTrait[, trait]))
    }
      
    if (is.na(experimentalDesign) == TRUE) {experimentalDesign <- c('No Design')}
    
    if ((experimentalDesign == 'Augmented' || experimentalDesign == 'RCBD')  &&  unique(phenoTrait$block) > 1) {

      message("GS experimental design: ", experimentalDesign)

      augData <- subset(phenoTrait, select = c("object_name", "object_id",  "block",  trait))

      colnames(augData)[1] <- "genotypes"
      colnames(augData)[4] <- "trait"

      model <- try(lmer(trait ~ 0 + genotypes + (1|block),
                        augData,
                        na.action = na.omit))

      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
        
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))  
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
      }
            
    } else if (experimentalDesign == 'Alpha') {
   
      message("Experimental desgin: ", experimentalDesign)
      
      alphaData <- subset(phenoData,
                            select = c("object_name", "object_id","block", "replicate", trait)
                            )
      
      colnames(alphaData)[1] <- "genotypes"
      colnames(alphaData)[5] <- "trait"
         
      model <- try(lmer(trait ~ 0 + genotypes + (1|replicate/block),
                        alphaData,
                        na.action = na.omit))
        
      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
      
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))     
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
        
      }
      
    } else {

      phenoTrait <- subset(phenoData,
                           select = c("object_name", "object_id",  trait))
       
      if (sum(is.na(phenoTrait)) > 0) {
        message("No. of pheno missing values: ", sum(is.na(phenoTrait)))      
        phenoTrait <- na.omit(phenoTrait)
      }

        #calculate mean of reps/plots of the same accession and
        #create new df with the accession means    
     
      phenoTrait   <- phenoTrait[order(row.names(phenoTrait)), ]
      phenoTrait   <- data.frame(phenoTrait)
      message('phenotyped lines before averaging: ', length(row.names(phenoTrait)))
   
      phenoTrait<-ddply(phenoTrait, "object_name", colwise(mean))
      message('phenotyped lines after averaging: ', length(row.names(phenoTrait)))
        
      phenoTrait <- subset(phenoTrait, select = c("object_name", trait))
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1] <- NULL
       
        #format all-traits population phenotype dataset
        ## formattedPhenoData <- phenoData
        ## dropColumns <- c("object_id", "stock_id", "design", "block", "replicate" )

        ## formattedPhenoData <- formattedPhenoData[, !(names(formattedPhenoData) %in% dropColumns)]
        ## formattedPhenoData <- ddply(formattedPhenoData,
        ##                             "object_name",
        ##                             colwise(mean)
        ##                             )

        ## row.names(formattedPhenoData) <- formattedPhenoData[, 1]
        ## formattedPhenoData[, 1] <- NULL

        ## formattedPhenoData <- round(formattedPhenoData,
        ##                             digits=3
        ##                             )     
    }
  }
}

if (is.null(filteredGenoData)) {

  #remove markers with > 60% missing marker data
  message('no of markers before filtering out: ', ncol(genoData))
  genoData[, which(colSums(is.na(genoData)) >= nrow(genoData) * 0.6) := NULL]
  message('no of markers after filtering out 60% missing: ', ncol(genoData))

  #remove indls with > 80% missing marker data
  genoData[, noMissing := apply(.SD, 1, function(x) sum(is.na(x)))]
  genoData <- genoData[noMissing <= ncol(genoData) * 0.8]
  genoData[, noMissing := NULL]
  message('no of indls after filtering out ones with 80% missing: ', nrow(genoData))

                                        #remove monomorphic markers
  message('marker no before monomorphic markers cleaning ', ncol(genoData))
  genoData[, which(apply(genoData, 2,  function(x) length(unique(x))) < 2) := NULL ]
  message('marker no after monomorphic markers cleaning ', ncol(genoData))

  ### MAF calculation ###
  calculateMAF <- function(x) {
    a0 <-  length(x[x==0])
    a1 <-  length(x[x==1])
    a2 <-  length(x[x==2])
    aT <- a0 + a1 + a2

    p   <- ((2*a0)+a1)/(2*aT)
    q   <- 1- p
    maf <- min(p, q)
  
    return (maf)

  }

  #remove markers with MAF < 5%
  genoData[, which(apply(genoData, 2,  calculateMAF) < 0.05) := NULL ]
  message('marker no after MAF cleaning ', ncol(genoData))

  genoData           <- as.data.frame(genoData)
  rownames(genoData) <- genoData[, 1]
  genoData[, 1]      <- NULL
  filteredGenoData   <- genoData 
} else {
  genoData           <- as.data.frame(filteredGenoData)
  rownames(genoData) <- genoData[, 1]
  genoData[, 1]      <- NULL
}

predictionTempFile <- grep("prediction_population", inputFiles, ignore.case = TRUE, value = TRUE)
predictionFile     <- c()

message('prediction temp genotype file: ', predictionTempFile)

if (length(predictionTempFile) !=0 ) {
  predictionFile <- scan(predictionTempFile, what = "character")
}

message('prediction genotype file: ', predictionFile)

predictionPopGEBVsFile <- grep("prediction_pop_gebvs", outputFiles, ignore.case = TRUE, value = TRUE)
message("prediction gebv file: ",  predictionPopGEBVsFile)

predictionData <- c()

if (length(predictionFile) !=0 ) {
  
  predictionData <- fread(predictionFile, na.strings = c("NA", " ", "--", "-"),)

  predictionData[, which(apply(predictionData, 2,  function(x) length(unique(x))) < 2) := NULL ]
  
  message('selection population: no of markers before filtering out: ', ncol(genoData))
  predictionData[, which(colSums(is.na(predictionData)) >= nrow(predictionData) * 0.6) := NULL]

  #remove indls with > 80% missing marker data
  predictionData[, noMissing := apply(.SD, 1, function(x) sum(is.na(x)))]
  predictionData <- predictionData[noMissing <= ncol(predictionData) * 0.8]
  predictionData[, noMissing := NULL]
  
  predictionData[, which(apply(predictionData, 2,  calculateMAF) < 0.05) := NULL ]
  message('selection pop marker no after MAF cleaning ', ncol(preditionData))
  predictionData           <- as.data.frame(predictionData)
  rownames(predictionData) <- predictionData[, 1]
  predictionData[, 1]      <- NULL
 
}

#impute genotype values for obs with missing values,
#based on mean of neighbouring 10 (arbitrary) obs
genoDataMissing <- c()

if (sum(is.na(genoData)) > 0) {
  genoDataMissing<- c('yes')

  message("sum of geno missing values, ", sum(is.na(genoData)) )  
  genoData <- na.roughfix(genoData)
  genoData <- data.matrix(genoData)
}

genoData <- genoData[order(row.names(genoData)), ]

#create phenotype and genotype datasets with
#common stocks only
message('phenotyped lines: ', length(row.names(phenoTrait)))
message('genotyped lines: ', length(row.names(genoData)))

#extract observation lines with both
#phenotype and genotype data only.
commonObs <- intersect(row.names(phenoTrait), row.names(genoData))
commonObs <- data.frame(commonObs)
rownames(commonObs)<-commonObs[, 1]

message('lines with both genotype and phenotype data: ', length(row.names(commonObs)))

#include in the genotype dataset only observation lines
#with phenotype data
message("genotype lines before filtering for phenotyped only: ", length(row.names(genoData)))        
genoDataFilteredObs <- genoData[(rownames(genoData) %in% rownames(commonObs)), ]
message("genotype lines after filtering for phenotyped only: ", length(row.names(genoDataFilteredObs)))

#drop observation lines without genotype data
message("phenotype lines before filtering for genotyped only: ", length(row.names(phenoTrait)))        
phenoTrait <- merge(data.frame(phenoTrait), commonObs, by=0, all=FALSE)
rownames(phenoTrait) <- phenoTrait[, 1]
phenoTrait <- subset(phenoTrait, select=trait)

message("phenotype lines after filtering for genotyped only: ", length(row.names(phenoTrait)))
#a set of only observation lines with genotype data

traitPhenoData   <- data.frame(round(phenoTrait, digits = 2))           
phenoTrait       <- data.matrix(phenoTrait)
genoDataFilteredObs <- data.matrix(genoDataFilteredObs)

#impute missing data in prediction data
predictionDataMissing <- c()
if (length(predictionData) != 0) {
  #purge markers unique to both populations
  commonMarkers       <- intersect(names(data.frame(genoDataFilteredObs)), names(predictionData))
  predictionData      <- subset(predictionData, select = commonMarkers)
  genoDataFilteredObs <- subset(genoDataFilteredObs, select= commonMarkers)
  
  if (sum(is.na(predictionData)) > 0) {
    predictionDataMissing <- c('yes')
    message("sum of geno missing values, ", sum(is.na(predictionData)) )  
    predictionData <- data.matrix(na.roughfix(predictionData))
    
  }
}

relationshipMatrixFile <- grep("relationship_matrix", outputFiles, ignore.case = TRUE, value = TRUE)

message("relationship matrix file: ", relationshipMatrixFile)

relationshipMatrix <- c()
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size > 0 ) {
    relationshipDf <- as.data.frame(fread(relationshipMatrixFile))

    rownames(relationshipDf) <- relationshipDf[, 1]
    relationshipDf[, 1]      <- NULL
    relationshipMatrix       <- data.matrix(relationshipDf)
  }
}


#change genotype coding to [-1, 0, 1], to use the A.mat ) if  [0, 1, 2]
genoTrCode <- grep("2", genoDataFilteredObs[1, ], value = TRUE)
if(length(genoTrCode) != 0) {
  genoDataFilteredObs <- genoDataFilteredObs - 1
}

if (length(predictionData) != 0 ) {
  genoSlCode <- grep("2", predictionData[1, ], value = TRUE)
  if (length(genoSlCode) != 0 ) {
    predictionData <- predictionData - 1
  }
}

ordered.markerEffects <- c()
if ( length(predictionData) == 0 ) {
  markerEffects <- mixed.solve(y = phenoTrait,
                               Z = genoDataFilteredObs
                               )

  ordered.markerEffects <- data.matrix(markerEffects$u)
  ordered.markerEffects <- data.matrix(ordered.markerEffects [order (-ordered.markerEffects[, 1]), ])
  ordered.markerEffects <- round(ordered.markerEffects, digits=5)

  colnames(ordered.markerEffects) <- c("Marker Effects")

}

#additive relationship model
#calculate the inner products for
#genotypes (realized relationship matrix)
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size == 0) {
    relationshipMatrix <- tcrossprod(data.matrix(genoData))
  }
}
relationshipMatrixFiltered <- relationshipMatrix[(rownames(relationshipMatrix) %in% rownames(commonObs)),]
relationshipMatrixFiltered <- relationshipMatrixFiltered[, (colnames(relationshipMatrixFiltered) %in% rownames(commonObs))]

#construct an identity matrix for genotypes
identityMatrix <- diag(nrow(phenoTrait))

relationshipMatrixFiltered <- data.matrix(relationshipMatrixFiltered)

iGEBV  <- mixed.solve(y = phenoTrait, Z = identityMatrix, K = relationshipMatrixFiltered) 
iGEBVu <- iGEBV$u

heritability  <- c()

if ( is.null(predictionFile) == TRUE ) {
  additiveEffects <- data.frame(iGEBVu)
 
  pN <- nrow(phenoTrait)
  aN <- nrow(additiveEffects)

  if (pN <= 1 || pN != aN) {
    stop("phenoTrait and additiveEffects have different lengths: ",
         pN, " and ", aN, ".")
  }
      
  if (TRUE %in% is.na(phenoTrait) || TRUE %in% is.na(additiveEffects)) {
    stop(" Arguments phenoTrait and additiveEffects have missing values.")
  }
  
  phenoVariance <- var(phenoTrait)
  gebvVariance  <- var(additiveEffects)
  heritability  <- round((gebvVariance / phenoVariance), digits = 2)
      
  cat("\n", file = varianceComponentsFile,  append = FALSE)
  cat('Error variance', iGEBV$Ve, file = varianceComponentsFile, sep = "\t", append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Additive genetic variance',  iGEBV$Vu, file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Phenotype mean', iGEBV$beta,file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Heritability (h)', heritability, file = varianceComponentsFile, sep = '\t', append = TRUE)
}

iGEBV         <- data.matrix(iGEBVu)
ordered.iGEBV <- as.data.frame(iGEBV[order(-iGEBV[, 1]), ])
ordered.iGEBV <- round(ordered.iGEBV, digits = 3)

combinedGebvsFile <- grep('selected_traits_gebv', outputFiles, ignore.case = TRUE,value = TRUE)

allGebvs<-c()
if (length(combinedGebvsFile) != 0) {
    fileSize <- file.info(combinedGebvsFile)$size
    if (fileSize != 0 ) {
        combinedGebvs <- as.data.frame(fread(combinedGebvsFile))

        rownames(combinedGebvs) <- combinedGebvs[,1]
        combinedGebvs[,1]       <- NULL

        colnames(ordered.iGEBV) <- c(trait)
      
        traitGEBV <- as.data.frame(ordered.iGEBV)
        allGebvs <- merge(combinedGebvs, traitGEBV,
                          by = 0,
                          all = TRUE                     
                          )

        rownames(allGebvs) <- allGebvs[,1]
        allGebvs[,1] <- NULL
     }
  }

colnames(ordered.iGEBV) <- c(trait)
                  
#cross-validation
validationAll <- c()

if(is.null(predictionFile)) {
  genoNum <- nrow(phenoTrait)
if(genoNum < 20 ) {
  warning(genoNum, " is too small number of genotypes.")
}
  
reps <- round_any(genoNum, 10, f = ceiling) %/% 10

genotypeGroups <-c()

if (genoNum %% 10 == 0) {
    genotypeGroups <- rep(1:10, reps)
  } else {
    genotypeGroups <- rep(1:10, reps) [- (genoNum %% 10) ]
  }

set.seed(4567)                                   
genotypeGroups <- genotypeGroups[ order (runif(genoNum)) ]

for (i in 1:10) {
  tr <- paste("trPop", i, sep = ".")
  sl <- paste("slPop", i, sep = ".")
 
  trG <- which(genotypeGroups != i)
  slG <- which(genotypeGroups == i)
  
  assign(tr, trG)
  assign(sl, slG)

  kblup <- paste("rKblup", i, sep = ".")
  
  result <- kinship.BLUP(y = phenoTrait[trG, ],
                         G.train = genoDataFilteredObs[trG, ],
                         G.pred = genoDataFilteredObs[slG, ],                      
                         mixed.method = "REML",
                         K.method = "RR",
                         )
 
  assign(kblup, result)

#calculate cross-validation accuracy  
  valCorData <- merge(phenoTrait[slG, ], result$g.pred, by=0, all=FALSE)
  rownames(valCorData) <- valCorData[, 1]
  valCorData[, 1]      <- NULL
 
  accuracy <- try(cor(valCorData))
  validation <- paste("validation", i, sep = ".")

  cvTest <- paste("Validation test", i, sep = " ")

  if ( class(accuracy) != "try-error")
    {
      accuracy <- round(accuracy[1,2], digits = 3)
      accuracy <- data.matrix(accuracy)
    
      colnames(accuracy) <- c("correlation")
      rownames(accuracy) <- cvTest

      assign(validation, accuracy)
      
      if (!is.na(accuracy[1,1])) {
        validationAll <- rbind(validationAll, accuracy)
      }    
    }
}

validationAll <- data.matrix(validationAll[order(-validationAll[, 1]), ])
     
if (!is.null(validationAll)) {
    validationMean <- data.matrix(round(colMeans(validationAll), digits = 2))
   
    rownames(validationMean) <- c("Average")
     
    validationAll <- rbind(validationAll, validationMean)
    colnames(validationAll) <- c("Correlation")
  }
}

predictionPopResult <- c()
predictionPopGEBVs  <- c()

if (length(predictionData) != 0) {
    message("running prediction for selection candidates...marker data", ncol(predictionData), " vs. ", ncol(genoDataFilteredObs))

    predictionPopResult <- kinship.BLUP(y = phenoTrait,
                                        G.train = genoDataFilteredObs,
                                        G.pred = predictionData,
                                        mixed.method = "REML",
                                        K.method = "RR"
                                        )
 message("running prediction for selection candidates...DONE!!")

    predictionPopGEBVs <- round(data.matrix(predictionPopResult$g.pred), digits = 3)
    predictionPopGEBVs <- data.matrix(predictionPopGEBVs[order(-predictionPopGEBVs[, 1]), ])
   
    colnames(predictionPopGEBVs) <- c(trait)
  
}

if (!is.null(predictionPopGEBVs) & length(predictionPopGEBVsFile) != 0)  {
    write.table(predictionPopGEBVs,
                file = predictionPopGEBVsFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if(!is.null(validationAll)) {
    write.table(validationAll,
                file = validationFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.markerEffects)) {
    write.table(ordered.markerEffects,
                file = markerFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.iGEBV)) {
    write.table(ordered.iGEBV,
                file = blupFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (length(combinedGebvsFile) != 0 ) {
    if(file.info(combinedGebvsFile)$size == 0) {
        write.table(ordered.iGEBV,
                    file = combinedGebvsFile,
                    sep = "\t",
                    col.names = NA,
                    quote = FALSE,
                    )
      } else {
      write.table(allGebvs,
                  file = combinedGebvsFile,
                  sep = "\t",
                  quote = FALSE,
                  col.names = NA,
                  )
    }
}

if (!is.null(traitPhenoData) & length(traitPhenoFile) != 0) {
    write.table(traitPhenoData,
                file = traitPhenoFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                )
}

if (!is.null(filteredGenoData) && is.null(usedFilteredGenoData)) {
  write.table(filteredGenoData,
              file = filteredGenoFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
            )

}

## if (!is.null(genoDataMissing)) {
##   write.table(genoData,
##               file = genoFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##             )

## }

## if (!is.null(predictionDataMissing)) {
##   write.table(predictionData,
##               file = predictionFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##               )
## }


if (file.info(relationshipMatrixFile)$size == 0) {
  write.table(relationshipMatrix,
              file = relationshipMatrixFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}


if (file.info(formattedPhenoFile)$size == 0 && !is.null(formattedPhenoData) ) {
  write.table(formattedPhenoData,
              file = formattedPhenoFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}

message("Done.")

q(save = "no", runLast = FALSE)
#' Function to batch download single location DAYMET data
#'
#' This function downloads DAYMET data for several single pixel
#' location.
#' @param file_location : file with several site locations and coordinates
#' in a format site, latitude, longitude
#' @param start_yr : start of the range of years over which to download data
#' @param end_yr : end of the range of years over which to download data
#' @param internal : TRUE or FALSE, load data into workspace or save to disc
#' @keywords DAYMET, climate data
#' @export
#' @examples
#' 
#' # NOT RUN
#' # batch.download("yourlocations.csv")

batch.download.daymet <- function(file_location,
                                  start_yr=1980,
                                  end_yr=as.numeric(format(Sys.time(), "%Y"))-1,
                                  internal=FALSE){
  
  # read table with sites and coordinates
  locations = read.table(file_location,sep=',')

  # loop over all lines in the file
  for (i in 1:dim(locations)[1]){
    site = as.character(locations[i,1])
    lat = as.numeric(locations[i,2])
    lon = as.numeric(locations[i,3])
    try(downloader::download.daymet(site=site,lat=lat,lon=lon,start_yr=start_yr,end_yr=end_yr,internal=internal),silent=FALSE)
  }
}#' Function to batch download gridded DAYMET data
#'
#' This function downloads DAYMET data 
#' @param lat1 : top left latitude (decimal degrees)
#' @param lon1 : top left longitude (decimal degrees)
#' @param lat2 : bottom right latitude (decimal degrees)
#' @param lon2 : bottom right longitude(decimal degrees)
#' @param start_yr : start of the range of years over which to download data
#' @param end_yr : end of the range of years over which to download data
#' @param param : climate variable you want to download vapour pressure (vp), 
#' minimum and maximum temperature (tmin,tmax), snow water equivalent (swe), 
#' solar radiation (srad), precipitation (prcp) , day length (dayl).
#' The default setting is ALL, this will download all the previously mentioned
#' climate variables.
#' @keywords DAYMET, climate data
#' @export
#' @examples
#' download.daymet.tiles(lat1=35.6737,
#'                       lon1=-86.3968,
#'                       start_yr=1980,
#'                       end_yr=1980,
#'                       param="ALL")

download.daymet.tiles = function(lat1=35.6737,
                                 lon1=-86.3968,
                                 lat2=NA,
                                 lon2=NA,
                                 start_yr=1980,
                                 end_yr=1980,
                                 param="ALL"){
  
  # determine system
  OS = Sys.info()[['sysname']]
  
  # load DAYMET grid associated with the package
  # (this is an imported shapefile)
  # I do not store any additional data in the .rdata
  # file to keep the code transparent.
  #data("DAYMET_grid")
  
  # grab the projection string. This is a LCC projection.
  projection = sp::CRS(sp::proj4string(tile_outlines))
  
  # extract tile IDs (vector shape) and the DAYMET IDs associated
  # with them
  tile_nrs = tile_outlines@data[,1]
  
  # if argument 3 or 4 are the default grab only the tile
  # of the first coordinate set, if 4 arguments are given
  # extract all tile numbers within this region of interest
  if ( is.na(lat2) | is.na(lon2)){
    
        # create coordinate pairs, with original coordinate  system
        location = sp::SpatialPoints(cbind(lon1,lat1), projection)
        
        # extract tile for this location
        tiles = sp::over(location,tile_outlines)$TileID
        
        # do not continue if outside range
        if (is.na(tiles)){
          stop("Your defined range is outside DAYMET coverage,
               check your coordinate values!")
        }

      }else{
        
        # this is some juggling to define a polygon (vector format)
        # which I will convert to LCC and use as a mask to extract
        # tile numbers. As such I avoid artefacts due to resampling.
        rect_corners = cbind(c(lon1,rep(lon2,2),lon1),
                             c(rep(lat2,2),rep(lat1,2)))
        ROI = sp::SpatialPoints(cbind(rect_corners[,1],
                                      rect_corners[,2]), projection)
        
        # set original projection
        sp::proj4string(ROI) = projection
        
        # extract unique tiles overlapping the rectangular ROI
        tiles = unique(sp::over(ROI,tile_outlines)$TileID)
        
        if (is.null(tiles)){
          stop("Your defined range is outside DAYMET coverage,
               check your coordinate values!")
        }
  }
  
  # calculate the end of the range of years to download
  # conservative setting based upon the current date -1 year
  max_year = as.numeric(format(Sys.time(), "%Y"))-1
  
  # check validaty of the range of years to download
  # I'm not sure when new data is released so this might be a
  # very conservative setting, remove it if you see more recent data
  # on the website
  
  if (start_yr < 1980){
    stop("Start year preceeds valid data range!")
  }
  rect_corners = cbind(c(lon1,rep(lon2,2),lon1),c(rep(lat2,2),rep(lat1,2)))
  
  if (end_yr > max_year){
    stop("End year exceeds valid data range!")
  }
  
  # if the year range is valid, create a string of valid years
  year_range = seq(start_yr,end_yr,by=1)

  # check the parameters we want to download
  if (param == "ALL"){
    param = c('vp','tmin','tmax','swe','srad','prcp','dayl')
  }

  for ( i in year_range ){
    for ( j in tiles ){
      for ( k in param ){
        
        # create download string / url  
        download_string = sprintf("http://thredds.daac.ornl.gov/thredds/fileServer/ornldaac/1328/tiles/%s/%s_%s/%s.nc",i,j,i,k)
                
        # create filename for the output file
        daymet_file = paste(k,"_",i,"_",j,".nc",sep='')
        
        # provide some feedback
        cat(paste('Downloading DAYMET data for tile: ',j,
                  '; year: ',i,
                  '; product: ',k,
                  '\n',sep=''))
        
        # download data, force binary data mode
        try(downloader::download(download_string,
                                 daymet_file,
                                 quiet=TRUE,
                                 mode="wb"),silent=FALSE)  
      }
    }
  }
}
#' Function to batch download gridded DAYMET data
#'
#' This function downloads DAYMET data 
#' @param lat1 : top left latitude (decimal degrees)
#' @param lon1 : top left longitude (decimal degrees)
#' @param lat2 : bottom right latitude (decimal degrees)
#' @param lon2 : bottom right longitude(decimal degrees)
#' @param start_yr : start of the range of years over which to download data
#' @param end_yr : end of the range of years over which to download data
#' @param param : climate variable you want to download vapour pressure (vp), 
#' minimum and maximum temperature (tmin,tmax), snow water equivalent (swe), 
#' solar radiation (srad), precipitation (prcp) , day length (dayl).
#' The default setting is ALL, this will download all the previously mentioned
#' climate variables.
#' @keywords DAYMET, climate data
#' @export
#' @examples
#' download.daymet.tiles(lat1=36.0133,
#'                       lon1=-84.2625,
#'                       start_yr=1980,
#'                       end_yr=2000,
#'                       param="ALL")

download.daymet.tiles = function(lat1=36.0133,
                                 lon1=-84.2625,
                                 lat2=NA,
                                 lon2=NA,
                                 start_yr=1980,
                                 end_yr=1980,
                                 param="ALL"){
  
  # determine system
  OS = Sys.info()[['sysname']]
  
  # load DAYMET grid associated with the package
  # (this is an imported shapefile)
  # I do not store any additional data in the .rdata
  # file to keep the code transparent.
  data("DAYMET_grid")
  
  # grab the projection string. This is a LCC projection.
  projection = sp::CRS(sp::proj4string(tile_outlines))
  
  # extract tile IDs (vector shape) and the DAYMET IDs associated
  # with them
  tile_nrs = tile_outlines@data[,1]
  
  # if argument 3 or 4 are the default grab only the tile
  # of the first coordinate set, if 4 arguments are given
  # extract all tile numbers within this region of interest
  if ( is.na(lat2) | is.na(lon2)){
    
        # create coordinate pairs, with original coordinate  system
        location = sp::SpatialPoints(cbind(lon1,lat1), projection)
        
        # extract tile for this location
        tiles = sp::over(location,tile_outlines)$TileID
        
        # do not continue if outside range
        if (is.na(tiles)){
          stop("Your defined range is outside DAYMET coverage,
               check your coordinate values!")
        }

      }else{
      
        # create coordinate pairs, with original coordinate system
        topleft = sp::SpatialPoints(cbind(lon1,lat1), projection)
        bottomright = sp::SpatialPoints(cbind(lon2,lat2), projection)

        # this is some juggling to define a polygon (vector format)
        # which I will convert to LCC and use as a mask to extract
        # tile numbers. As such I avoid artefacts due to resampling.
        poly_corners = matrix(NA,5,2)
        poly_corners[1,] = c(lon1,lat2)
        poly_corners[2,] = c(lon2,lat2)
        poly_corners[3,] = c(lon2,lat1)
        poly_corners[4,] = c(lon1,lat1)
        poly_corners[5,] = c(lon1,lat2)
        
        # make into a polygon object
        ROI = sp::SpatialPolygons(list(sp::Polygons(list(sp::Polygon(poly_corners)),1)))
        
        # set original projection
        sp::proj4string(ROI) = projection
        
        # extract pixels within the ROI
        r = rgeos::gIntersection(ROI,tile_outlines,byid=TRUE)
        
        if (is.null(r)){
          stop("Your defined range is outside DAYMET coverage,
               check your coordinate values!")
        }
        
        # extract tile IDs and match to DAYMET grid IDs
        polygon_nr = as.numeric(sapply(r@polygons,function(x)unlist(strsplit(x@ID,split=' '))[2])) + 1
        tiles = tile_nrs[polygon_nr]
  }
  
  # calculate the end of the range of years to download
  # conservative setting based upon the current date
  # -1 year
  max_year = as.numeric(format(Sys.time(), "%Y"))-1
  
  # check validaty of the range of years to download
  # I'm not sure when new data is released so this might be a
  # very conservative setting, remove it if you see more recent data
  # on the website
  
  if (start_yr < 1980){
    stop("Start year preceeds valid data range!")
  }
  
  if (end_yr > max_year){
    stop("End year exceeds valid data range!")
  }
  
  # if the year range is valid, create a string of valid years
  year_range = seq(start_yr,end_yr,by=1)

  # check the parameters we want to download
  if (param == "ALL"){
    param = c('vp','tmin','tmax','swe','srad','prcp','dayl')
  }

  for ( i in year_range ){
    for ( j in tiles ){
      for ( k in param ){
        
        # create download string / url  
        download_string = sprintf("http://thredds.daac.ornl.gov/thredds/catalog/ornldaac/1328/tiles/%s/%s_%s/%s.nc",i,j,i,k)
                
        # create filename for the output file
        daymet_file = paste(k,"_",i,"_",j,".nc",sep='')
        
        # provide some feedback
        cat(paste('Downloading DAYMET data for tile: ',j,
                  '; year: ',i,
                  '; product: ',k,
                  '\n',sep=''))
        
        # download data, force binary data mode
        try(downloader::download(download_string,
                                 daymet_file,
                                 quiet=TRUE,
                                 mode="wb"),silent=FALSE)  
      }
    }
  }
}
#Setup
# setwd("D:\\Users\\Greg Sanders\\Documents\\Development\\Lookup-Tables")
setwd("K:\\Development\\Lookup-Tables")
source("SQLimportTools.r")

#******Importing into Errorlogging.FSRSviolatesConstraint
#Match up Errorlogging.FSRSviolatesType to Errorlogging.FSRSviolatesConstraint
OriginTableType.df<-ReadCreateTable("ErrorLogging_FSRSviolatesType.txt")
DestTableType.df<-ReadCreateTable("ErrorLogging_FSRSviolatesConstraint.txt")
OriginTableType.df<-TranslateName(OriginTableType.df)
MergeType.df<-MergeSourceAndCSISnameTables(OriginTableType.df,DestTableType.df)

#Create Try Convert
TryConvertList<-Create_Try_Converts(MergeType.df,"Errorlogging","FSRSviolatesType")
write(TryConvertList,"FSRStryConvertList.txt")

#Transfer from Errorlogging.FSRSviolatesType to Errorlogging.FSRSviolatesConstraint
InsertList<-CreateInsert(MergeType.df,
             "ErrorLogging",
             "FSRSviolatesType",
             "ErrorLogging",
             "FSRSviolatesConstraint",
             DateType=101)
write(InsertList,"FSRSinsert.txt")
write(CreateCSISdates("Contract","FSRS"),"CSISdates.txt")

#******Importing into Contract.FSRS 
#Match up Errorlogging.FSRSviolatesConstraint to Contract.FSRS 
DestTableConstraint.df<-ReadCreateTable("Contract_FSRS.txt")
OriginTableConstraint.df<-ReadCreateTable("ErrorLogging_FSRSviolatesConstraint.txt")
OriginTableConstraint.df<-TranslateName(OriginTableConstraint.df)
MergeConstraint.df<-MergeSourceAndCSISnameTables(OriginTableConstraint.df,DestTableConstraint.df)


#Transfer from Errorlogging.FSRSviolatesConstraint to Contract.FSRS
ConstTable.df<-TranslateName(DestTableConstraint.df)
MergeConst<-MergeSourceAndCSISnameTables(ConstTable.df,ConstTable.df)
InsertList<-CreateInsert(MergeConst,
                         "ErrorLogging",
                         "FSRSviolatesConstraint",
                         "Contract",
                         "FSRS",
                         DateType=101)
write(InsertList,"Insert2.txt")



fkTable.df<-ReadCreateTable("Contract_FSRS.txt")

  debug(ConvertFieldToForeignKey)
  Output<-ConvertFieldToForeignKey("Contract","FSRS","[PrimeAwardReportID]",
                           fkTable.df,
                           "Contract","PrimeAwardReportID")
  write(Output,"ConvertfieldToForeignKey.txt")
  
  ConvertFieldToForeignKey("Contract","FSRS","[SubAwardeeDunsnumber]",
                           fkTable.df,
                           "Contractor","Dunsnumber")
  
  ConvertFieldToForeignKey("Contract","FSRS","[SubAwardeeParentDuns]",
                           fkTable.df,
                           "Contractor","Dunsnumber")
  
  
  #SNOPSIS
#calculates genomic estimated breeding values (GEBVs) using rrBLUP,
#GBLUP method

#AUTHOR
# Isaak Y Tecle (iyt2@cornell.edu)

options(echo = FALSE)

library(rrBLUP)
library(plyr)
library(stringr)
library(lme4)
library(randomForest)
library(data.table)
#library(genetics)

allArgs <- commandArgs()

inputFiles  <- scan(grep("input_files", allArgs, ignore.case = TRUE, perl = TRUE, value = TRUE),
                   what = "character")

outputFiles <- scan(grep("output_files", allArgs, ignore.case = TRUE,perl = TRUE, value = TRUE),
                    what = "character")

traitsFile <- grep("traits", inputFiles, ignore.case = TRUE, value = TRUE)
traitFile  <- grep("trait_info", inputFiles, ignore.case = TRUE, value = TRUE)
traitInfo  <- scan(traitFile, what = "character",)
traitInfo  <- strsplit(traitInfo, "\t");
traitId    <- traitInfo[[1]]
trait      <- traitInfo[[2]]

datasetInfoFile <- grep("dataset_info", inputFiles, ignore.case = TRUE, value = TRUE)
datasetInfo     <- c()

if (length(datasetInfoFile) != 0 ) { 
    datasetInfo <- scan(datasetInfoFile, what = "character")    
    datasetInfo <- paste(datasetInfo, collapse = " ")   
  } else {   
    datasetInfo <- c('single population')  
  }

validationTrait <- paste("validation", trait, sep = "_")
validationFile  <- grep(validationTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(validationFile)) {
  stop("Validation output file is missing.")
}

kinshipTrait <- paste("kinship", trait, sep = "_")
blupFile     <- grep(kinshipTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(blupFile)) {
  stop("GEBVs file is missing.")
}
markerTrait <- paste("marker", trait, sep = "_")
markerFile  <- grep(markerTrait, outputFiles, ignore.case = TRUE, value = TRUE)

traitPhenoFile <- paste("phenotype_trait", trait, sep = "_")
traitPhenoFile <- grep(traitPhenoFile, outputFiles,ignore.case = TRUE, value = TRUE)

varianceComponentsFile <- grep("variance_components", outputFiles, ignore.case = TRUE, value = TRUE)
filteredGenoFile       <- grep("filtered_genotype_data", outputFiles, ignore.case = TRUE, value = TRUE)
formattedPhenoFile     <- grep("formatted_phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE)

formattedPhenoData <- c()
phenoData          <- c()

genoFile <- grep("genotype_data", inputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(genoFile)) {
  stop("genotype data file is missing.")
}

if (file.info(genoFile)$size == 0) {
  stop("genotype data file is empty.")
}


filteredGenoData <- c()
if (length(filteredGenoFile) != 0  && file.info(filteredGenoFile)$size != 0) {
  filteredGenoData <- fread(filteredGenoFile, na.strings = c("NA", " ", "--", "-"),  header = TRUE)
  message('read in filtered geno data')
}

genoData <- c()
if (is.null(filteredGenoData)) {
  genoData <- fread(genoFile, na.strings = c("NA", " ", "--", "-"),  header = TRUE)
  message('read in unfiltered geno data')
}

if (length(formattedPhenoFile) != 0 && file.info(formattedPhenoFile)$size != 0) {
  formattedPhenoData <- as.data.frame(fread(formattedPhenoFile,
                                            na.strings = c("NA", " ", "--", "-", ".")
                                            ))
      
  row.names(formattedPhenoData) <- formattedPhenoData[, 1]
  formattedPhenoData[, 1]       <- NULL    
} else {
  phenoFile <- grep("\\/phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE, perl = TRUE)

  if (is.null(phenoFile)) {
    stop("phenotype data file is missing.")
  }

  if (file.info(phenoFile)$size == 0) {
    stop("phenotype data file is empty.")
  }
  
  phenoData <- fread(phenoFile, na.strings = c("NA", " ", "--", "-", "."), header = TRUE) 
}

phenoData  <- as.data.frame(phenoData)
phenoTrait <- c()

if (datasetInfo == 'combined populations') {
  
   if (!is.null(formattedPhenoData)) {
      phenoTrait <- subset(formattedPhenoData, select = trait)
      phenoTrait <- na.omit(phenoTrait)
   
    } else {
      dropColumns <- grep(trait, names(phenoData), ignore.case = TRUE, value = TRUE)
      phenoTrait  <- phenoData[, !(names(phenoData) %in% dropColumns)]
   
      phenoTrait            <- as.data.frame(phenoTrait)
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1]       <- NULL
      colnames(phenoTrait)  <- trait
    }
   
} else {

  if (!is.null(formattedPhenoData)) {
    phenoTrait <- subset(formattedPhenoData, select = trait)
    phenoTrait <- na.omit(phenoTrait)
   
  } else {
    dropColumns <- c("uniquename", "stock_name")
    phenoData   <- phenoData[, !(names(phenoData) %in% dropColumns)]
    
    phenoTrait <- subset(phenoData, select = c("object_name", "object_id", "design", "block", "replicate", trait))
   
    experimentalDesign <- phenoTrait[2, 'design']
  
    if (class(phenoTrait[, trait]) != 'numeric') {
      phenoTrait[, trait] <- as.numeric(as.character(phenoTrait[, trait]))
    }
      
    if (is.na(experimentalDesign) == TRUE) {experimentalDesign <- c('No Design')}
    
    if ((experimentalDesign == 'Augmented' || experimentalDesign == 'RCBD')  &&  unique(phenoTrait$block) > 1) {

      message("GS experimental design: ", experimentalDesign)

      augData <- subset(phenoTrait, select = c("object_name", "object_id",  "block",  trait))

      colnames(augData)[1] <- "genotypes"
      colnames(augData)[4] <- "trait"

      model <- try(lmer(trait ~ 0 + genotypes + (1|block),
                        augData,
                        na.action = na.omit))

      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
        
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))  
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
      }
            
    } else if (experimentalDesign == 'Alpha') {
   
      message("Experimental desgin: ", experimentalDesign)
      
      alphaData <- subset(phenoData,
                            select = c("object_name", "object_id","block", "replicate", trait)
                            )
      
      colnames(alphaData)[1] <- "genotypes"
      colnames(alphaData)[5] <- "trait"
         
      model <- try(lmer(trait ~ 0 + genotypes + (1|replicate/block),
                        alphaData,
                        na.action = na.omit))
        
      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
      
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))     
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
        
      }
      
    } else {

      phenoTrait <- subset(phenoData,
                           select = c("object_name", "object_id",  trait))
       
      if (sum(is.na(phenoTrait)) > 0) {
        message("No. of pheno missing values: ", sum(is.na(phenoTrait)))      
        phenoTrait <- na.omit(phenoTrait)
      }

        #calculate mean of reps/plots of the same accession and
        #create new df with the accession means    
     
      phenoTrait   <- phenoTrait[order(row.names(phenoTrait)), ]
      phenoTrait   <- data.frame(phenoTrait)
      message('phenotyped lines before averaging: ', length(row.names(phenoTrait)))
   
      phenoTrait<-ddply(phenoTrait, "object_name", colwise(mean))
      message('phenotyped lines after averaging: ', length(row.names(phenoTrait)))
        
      phenoTrait <- subset(phenoTrait, select = c("object_name", trait))
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1] <- NULL
       
        #format all-traits population phenotype dataset
        ## formattedPhenoData <- phenoData
        ## dropColumns <- c("object_id", "stock_id", "design", "block", "replicate" )

        ## formattedPhenoData <- formattedPhenoData[, !(names(formattedPhenoData) %in% dropColumns)]
        ## formattedPhenoData <- ddply(formattedPhenoData,
        ##                             "object_name",
        ##                             colwise(mean)
        ##                             )

        ## row.names(formattedPhenoData) <- formattedPhenoData[, 1]
        ## formattedPhenoData[, 1] <- NULL

        ## formattedPhenoData <- round(formattedPhenoData,
        ##                             digits=3
        ##                             )     
    }
  }
}

if (is.null(filteredGenoData)) {

  #remove markers with > 60% missing marker data
  message('no of markers before filtering out: ', ncol(genoData))
  genoData[, which(colSums(is.na(genoData)) >= nrow(genoData) * 0.6) := NULL]
  message('no of markers after filtering out 60% missing: ', ncol(genoData))

  #remove indls with > 80% missing marker data
  genoData[, noMissing := apply(.SD, 1, function(x) sum(is.na(x)))]
  genoData <- genoData[noMissing <= ncol(genoData) * 0.8]
  genoData[, noMissing := NULL]
  message('no of indls after filtering out ones with 80% missing: ', nrow(genoData))

                                        #remove monomorphic markers
  message('marker no before monomorphic markers cleaning ', ncol(genoData))
  genoData[, which(apply(genoData, 2,  function(x) length(unique(x))) < 2) := NULL ]
  message('marker no after monomorphic markers cleaning ', ncol(genoData))

  ### MAF calculation ###
  calculateMAF <- function(x) {
    a0 <-  length(x[x==0])
    a1 <-  length(x[x==1])
    a2 <-  length(x[x==2])
    aT <- a0 + a1 + a2

    p   <- ((2*a0)+a1)/(2*aT)
    q   <- 1- p
    maf <- min(p, q)
  
    return (maf)

  }

  #remove markers with MAF < 5%
  genoData[, which(apply(genoData, 2,  calculateMAF) < 0.05) := NULL ]
  message('marker no after MAF cleaning ', ncol(genoData))
  filteredGenoData <- genoData
} else {

  genoData <- filteredGenoData
  
}


genoData           <- as.data.frame(genoData)
rownames(genoData) <- genoData[, 1]
genoData[, 1]      <- NULL

predictionTempFile <- grep("prediction_population", inputFiles, ignore.case = TRUE, value = TRUE)
predictionFile     <- c()

message('prediction temp genotype file: ', predictionTempFile)

if (length(predictionTempFile) !=0 ) {
  predictionFile <- scan(predictionTempFile, what = "character")
}

message('prediction genotype file: ', predictionFile)

predictionPopGEBVsFile <- grep("prediction_pop_gebvs", outputFiles, ignore.case = TRUE, value = TRUE)
message("prediction gebv file: ",  predictionPopGEBVsFile)

predictionData <- c()

if (length(predictionFile) !=0 ) {
  
  predictionData <- fread(predictionFile, na.strings = c("NA", " ", "--", "-"),)

  predictionData[, which(apply(predictionData, 2,  function(x) length(unique(x))) < 2) := NULL ]
  
  message('selection population: no of markers before filtering out: ', ncol(genoData))
  predictionData[, which(colSums(is.na(predictionData)) >= nrow(predictionData) * 0.6) := NULL]

  #remove indls with > 80% missing marker data
  predictionData[, noMissing := apply(.SD, 1, function(x) sum(is.na(x)))]
  predictionData <- predictionData[noMissing <= ncol(predictionData) * 0.8]
  predictionData[, noMissing := NULL]
  
  predictionData[, which(apply(predictionData, 2,  calculateMAF) < 0.05) := NULL ]
  message('selection pop marker no after MAF cleaning ', ncol(preditionData))
  predictionData           <- as.data.frame(predictionData)
  rownames(predictionData) <- predictionData[, 1]
  predictionData[, 1]      <- NULL
 
}

#impute genotype values for obs with missing values,
#based on mean of neighbouring 10 (arbitrary) obs
genoDataMissing <- c()

if (sum(is.na(genoData)) > 0) {
  genoDataMissing<- c('yes')

  message("sum of geno missing values, ", sum(is.na(genoData)) )  
  genoData <- na.roughfix(genoData)
  genoData <- data.matrix(genoData)
}

genoData <- genoData[order(row.names(genoData)), ]

#create phenotype and genotype datasets with
#common stocks only
message('phenotyped lines: ', length(row.names(phenoTrait)))
message('genotyped lines: ', length(row.names(genoData)))

#extract observation lines with both
#phenotype and genotype data only.
commonObs <- intersect(row.names(phenoTrait), row.names(genoData))
commonObs <- data.frame(commonObs)
rownames(commonObs)<-commonObs[, 1]

message('lines with both genotype and phenotype data: ', length(row.names(commonObs)))

#include in the genotype dataset only observation lines
#with phenotype data
message("genotype lines before filtering for phenotyped only: ", length(row.names(genoData)))        
genoDataFilteredObs <- genoData[(rownames(genoData) %in% rownames(commonObs)), ]
message("genotype lines after filtering for phenotyped only: ", length(row.names(genoDataFilteredObs)))

#drop observation lines without genotype data
message("phenotype lines before filtering for genotyped only: ", length(row.names(phenoTrait)))        
phenoTrait <- merge(data.frame(phenoTrait), commonObs, by=0, all=FALSE)
rownames(phenoTrait) <- phenoTrait[, 1]
phenoTrait <- subset(phenoTrait, select=trait)

message("phenotype lines after filtering for genotyped only: ", length(row.names(phenoTrait)))
#a set of only observation lines with genotype data

traitPhenoData   <- data.frame(round(phenoTrait, digits = 2))           
phenoTrait       <- data.matrix(phenoTrait)
genoDataFilteredObs <- data.matrix(genoDataFilteredObs)

#impute missing data in prediction data
predictionDataMissing <- c()
if (length(predictionData) != 0) {
  #purge markers unique to both populations
  commonMarkers       <- intersect(names(data.frame(genoDataFilteredObs)), names(predictionData))
  predictionData      <- subset(predictionData, select = commonMarkers)
  genoDataFilteredObs <- subset(genoDataFilteredObs, select= commonMarkers)
  
 # predictionData <- data.matrix(predictionData)
 
  if (sum(is.na(predictionData)) > 0) {
    predictionDataMissing <- c('yes')
    message("sum of geno missing values, ", sum(is.na(predictionData)) )  
    predictionData <- data.matrix(na.roughfix(predictionData))
    
  }
}

relationshipMatrixFile <- grep("relationship_matrix", outputFiles, ignore.case = TRUE, value = TRUE)

message("relationship matrix file: ", relationshipMatrixFile)

relationshipMatrix <- c()
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size > 0 ) {
    relationshipDf <- as.data.frame(fread(relationshipMatrixFile))

    rownames(relationshipDf) <- relationshipDf[, 1]
    relationshipDf[, 1]      <- NULL
    relationshipMatrix       <- data.matrix(relationshipDf)
  }
}


#change genotype coding to [-1, 0, 1], to use the A.mat ) if  [0, 1, 2]
genoTrCode <- grep("2", genoDataFilteredObs[1, ], value = TRUE)
if(length(genoTrCode) != 0) {
  genoDataFilteredObs <- genoDataFilteredObs - 1
}

if (length(predictionData) != 0 ) {
  genoSlCode <- grep("2", predictionData[1, ], value = TRUE)
  if (length(genoSlCode) != 0 ) {
    predictionData <- predictionData - 1
  }
}

ordered.markerEffects <- c()
if ( length(predictionData) == 0 ) {
  markerEffects <- mixed.solve(y = phenoTrait,
                               Z = genoDataFilteredObs
                               )

  ordered.markerEffects <- data.matrix(markerEffects$u)
  ordered.markerEffects <- data.matrix(ordered.markerEffects [order (-ordered.markerEffects[, 1]), ])
  ordered.markerEffects <- round(ordered.markerEffects, digits=5)

  colnames(ordered.markerEffects) <- c("Marker Effects")

}

#additive relationship model
#calculate the inner products for
#genotypes (realized relationship matrix)
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size == 0) {
    relationshipMatrix <- tcrossprod(data.matrix(genoData))
  }
}
relationshipMatrixFiltered <- relationshipMatrix[(rownames(relationshipMatrix) %in% rownames(commonObs)),]
relationshipMatrixFiltered <- relationshipMatrixFiltered[, (colnames(relationshipMatrixFiltered) %in% rownames(commonObs))]

#construct an identity matrix for genotypes
identityMatrix <- diag(nrow(phenoTrait))

relationshipMatrixFiltered <- data.matrix(relationshipMatrixFiltered)

iGEBV  <- mixed.solve(y = phenoTrait, Z = identityMatrix, K = relationshipMatrixFiltered) 
iGEBVu <- iGEBV$u

heritability  <- c()

if ( is.null(predictionFile) == TRUE ) {
  additiveEffects <- data.frame(iGEBVu)
 
  pN <- nrow(phenoTrait)
  aN <- nrow(additiveEffects)

  if (pN <= 1 || pN != aN) {
    stop("phenoTrait and additiveEffects have different lengths: ",
         pN, " and ", aN, ".")
  }
      
  if (TRUE %in% is.na(phenoTrait) || TRUE %in% is.na(additiveEffects)) {
    stop(" Arguments phenoTrait and additiveEffects have missing values.")
  }
  
  phenoVariance <- var(phenoTrait)
  gebvVariance  <- var(additiveEffects)
  heritability  <- round((gebvVariance / phenoVariance), digits = 2)
      
  cat("\n", file = varianceComponentsFile,  append = FALSE)
  cat('Error variance', iGEBV$Ve, file = varianceComponentsFile, sep = "\t", append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Additive genetic variance',  iGEBV$Vu, file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Phenotype mean', iGEBV$beta,file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Heritability (h)', heritability, file = varianceComponentsFile, sep = '\t', append = TRUE)
}

iGEBV         <- data.matrix(iGEBVu)
ordered.iGEBV <- as.data.frame(iGEBV[order(-iGEBV[, 1]), ])
ordered.iGEBV <- round(ordered.iGEBV, digits = 3)

combinedGebvsFile <- grep('selected_traits_gebv', outputFiles, ignore.case = TRUE,value = TRUE)

allGebvs<-c()
if (length(combinedGebvsFile) != 0) {
    fileSize <- file.info(combinedGebvsFile)$size
    if (fileSize != 0 ) {
        combinedGebvs <- as.data.frame(fread(combinedGebvsFile))

        rownames(combinedGebvs) <- combinedGebvs[,1]
        combinedGebvs[,1]       <- NULL

        colnames(ordered.iGEBV) <- c(trait)
      
        traitGEBV <- as.data.frame(ordered.iGEBV)
        allGebvs <- merge(combinedGebvs, traitGEBV,
                          by = 0,
                          all = TRUE                     
                          )

        rownames(allGebvs) <- allGebvs[,1]
        allGebvs[,1] <- NULL
     }
  }

colnames(ordered.iGEBV) <- c(trait)
                  
#cross-validation
validationAll <- c()

if(is.null(predictionFile)) {
  genoNum <- nrow(phenoTrait)
if(genoNum < 20 ) {
  warning(genoNum, " is too small number of genotypes.")
}
  
reps <- round_any(genoNum, 10, f = ceiling) %/% 10

genotypeGroups <-c()

if (genoNum %% 10 == 0) {
    genotypeGroups <- rep(1:10, reps)
  } else {
    genotypeGroups <- rep(1:10, reps) [- (genoNum %% 10) ]
  }

set.seed(4567)                                   
genotypeGroups <- genotypeGroups[ order (runif(genoNum)) ]

for (i in 1:10) {
  tr <- paste("trPop", i, sep = ".")
  sl <- paste("slPop", i, sep = ".")
 
  trG <- which(genotypeGroups != i)
  slG <- which(genotypeGroups == i)
  
  assign(tr, trG)
  assign(sl, slG)

  kblup <- paste("rKblup", i, sep = ".")
  
  result <- kinship.BLUP(y = phenoTrait[trG, ],
                         G.train = genoDataFilteredObs[trG, ],
                         G.pred = genoDataFilteredObs[slG, ],                      
                         mixed.method = "REML",
                         K.method = "RR",
                         )
 
  assign(kblup, result)

#calculate cross-validation accuracy  
  valCorData <- merge(phenoTrait[slG, ], result$g.pred, by=0, all=FALSE)
  rownames(valCorData) <- valCorData[, 1]
  valCorData[, 1]      <- NULL
 
  accuracy <- try(cor(valCorData))
  validation <- paste("validation", i, sep = ".")

  cvTest <- paste("Validation test", i, sep = " ")

  if ( class(accuracy) != "try-error")
    {
      accuracy <- round(accuracy[1,2], digits = 3)
      accuracy <- data.matrix(accuracy)
    
      colnames(accuracy) <- c("correlation")
      rownames(accuracy) <- cvTest

      assign(validation, accuracy)
      
      if (!is.na(accuracy[1,1])) {
        validationAll <- rbind(validationAll, accuracy)
      }    
    }
}

validationAll <- data.matrix(validationAll[order(-validationAll[, 1]), ])
     
if (!is.null(validationAll)) {
    validationMean <- data.matrix(round(colMeans(validationAll), digits = 2))
   
    rownames(validationMean) <- c("Average")
     
    validationAll <- rbind(validationAll, validationMean)
    colnames(validationAll) <- c("Correlation")
  }
}

predictionPopResult <- c()
predictionPopGEBVs  <- c()

if (length(predictionData) != 0) {
    message("running prediction for selection candidates...marker data", ncol(predictionData), " vs. ", ncol(genoDataFilteredObs))

    predictionPopResult <- kinship.BLUP(y = phenoTrait,
                                        G.train = genoDataFilteredObs,
                                        G.pred = predictionData,
                                        mixed.method = "REML",
                                        K.method = "RR"
                                        )
 message("running prediction for selection candidates...DONE!!")

    predictionPopGEBVs <- round(data.matrix(predictionPopResult$g.pred), digits = 3)
    predictionPopGEBVs <- data.matrix(predictionPopGEBVs[order(-predictionPopGEBVs[, 1]), ])
   
    colnames(predictionPopGEBVs) <- c(trait)
  
}

if (!is.null(predictionPopGEBVs) & length(predictionPopGEBVsFile) != 0)  {
    write.table(predictionPopGEBVs,
                file = predictionPopGEBVsFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if(!is.null(validationAll)) {
    write.table(validationAll,
                file = validationFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.markerEffects)) {
    write.table(ordered.markerEffects,
                file = markerFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.iGEBV)) {
    write.table(ordered.iGEBV,
                file = blupFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (length(combinedGebvsFile) != 0 ) {
    if(file.info(combinedGebvsFile)$size == 0) {
        write.table(ordered.iGEBV,
                    file = combinedGebvsFile,
                    sep = "\t",
                    col.names = NA,
                    quote = FALSE,
                    )
      } else {
      write.table(allGebvs,
                  file = combinedGebvsFile,
                  sep = "\t",
                  quote = FALSE,
                  col.names = NA,
                  )
    }
}

if (!is.null(traitPhenoData) & length(traitPhenoFile) != 0) {
    write.table(traitPhenoData,
                file = traitPhenoFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                )
}

if (!is.null(filteredGenoData)) {
  write.table(filteredGenoData,
              file = filteredGenoFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
            )

}

## if (!is.null(genoDataMissing)) {
##   write.table(genoData,
##               file = genoFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##             )

## }

## if (!is.null(predictionDataMissing)) {
##   write.table(predictionData,
##               file = predictionFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##               )
## }


if (file.info(relationshipMatrixFile)$size == 0) {
  write.table(relationshipMatrix,
              file = relationshipMatrixFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}


if (file.info(formattedPhenoFile)$size == 0 && !is.null(formattedPhenoData) ) {
  write.table(formattedPhenoData,
              file = formattedPhenoFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}

message("Done.")

q(save = "no", runLast = FALSE)
require(plyr)

ReadCreateTable<-function(FileName){
  TargetTable.df<-read.csv(file.path("ImportAids\\",FileName),header=FALSE,sep=" ")
  
  #For now we're ignoring everything except the lines describing variable types
  CreateRow<-which(TargetTable.df$V1=="CREATE")
  TargetTable.df<-TargetTable.df[-c(1:CreateRow),]
  EndRow<-which(TargetTable.df$V1==")")
  TargetTable.df<-TargetTable.df[-c(EndRow:nrow(TargetTable.df)),]
  TargetTable.df$V1<-as.character(TargetTable.df$V1)
  #Once we have the table in, the next step is to clean up anything seperated on spaces
  #that should not have been for our purposes.
  # 
  TargetTable.df$V2<-as.character(TargetTable.df$V2)
  TargetTable.df$V2[substring(TargetTable.df$V2,1,9)=="[decimal]"]<-paste(
    TargetTable.df$V2[substring(TargetTable.df$V2,1,9)=="[decimal]"],
    TargetTable.df$V3[substring(TargetTable.df$V2,1,9)=="[decimal]"]
  )
  #Just in case the only Not NULL is a decimal
  TargetTable.df$V3<-as.character(TargetTable.df$V3)
  TargetTable.df$V3[substring(TargetTable.df$V2,1,9)=="[decimal]"]<-
    as.character(TargetTable.df$V4[substring(TargetTable.df$V2,1,9)=="[decimal]"])
  TargetTable.df$V4[substring(TargetTable.df$V2,1,9)=="[decimal]"]<-""
  
  TargetTable.df<-TargetTable.df[,c(1:3)]
  colnames(TargetTable.df)<-c("VariableName",
                              "VariableType",
                              "Nullable")
  TargetTable.df$Nullable<-gsub(",","",TargetTable.df$Nullable)
  TargetTable.df$VariableName<-gsub("\t","",TargetTable.df$VariableName)
  TargetTable.df
}

ConvertAllOfType<-function(TargetTable.df,
                           OldType,
                           NewType,
                           Schema,
                           TableName){
  #Limit it to just relevant variables
  TargetTable.df<-TargetTable.df[TargetTable.df$VariableType==OldType,]
  if(nrow(TargetTable.df)==0)
    stop("OldType not found in table")
  ChangeList<-paste(
    "Alter Table ",Schema,".",TableName,"\n",
    "Alter Column ",TargetTable.df$VariableName," ",
    NewType," ",TargetTable.df$Nullable,sep="")
  ChangeList
}

ListProblemType<-function(TargetTable.df){
  TargetTable.df[TargetTable.df$VariableType=="[varchar](max)",]
}


TranslateName<-function(TargetTable.df){
  lookup.NameConversion<-read.csv("ImportAids\\NameConversion.csv",
                                  stringsAsFactors = FALSE)
  if(!"SourceVariableName" %in% colnames(TargetTable.df)){
    colnames(TargetTable.df)[1]<-"SourceVariableName" 
  }
  TargetTable.df<-plyr::join(TargetTable.df,lookup.NameConversion)
  # TargetTable.df$VariableName<-gsub("_","",TargetTable.df$VariableName)
  
  TargetTable.df$CSISvariableName[TargetTable.df$SourceVariableName %in% 
                   lookup.NameConversion$CSISvariableName]<-
    TargetTable.df$SourceVariableName[TargetTable.df$SourceVariableName %in% 
                     lookup.NameConversion$CSISvariableName]
  
  TargetTable.df
}



MergeSourceAndCSISnameTables<-function(SourceTable.df,CSIStable.df){
  colnames(SourceTable.df)[1:3]<-c("SourceVariableName",
                                   "SourceVariableType",
                                   "SourceNullable")
  SourceTable.df$SourceVariableName<-as.character(SourceTable.df$SourceVariableName)
  colnames(CSIStable.df)[1:3]<-c("CSISvariableName",
                                 "CSISvariableType",
                                 "CSISnullable")
  CSIStable.df$CSISvariableName<-as.character(CSIStable.df$CSISvariableName)
  SourceTable.df<-plyr::join(SourceTable.df,CSIStable.df)
}



CreateCSISdates<-function(Schema,TableName){
  paste("ALTER TABLE ",Schema,".",TableName,"\n",
        "CREATE CSISmodifiedDate datetime2 NOT NULL default gettime(),\n",
        "CSIScreatedDate datetime2 NOT NULL default gettime()\n",
        sep="")
}

ConvertSwitch<-function(MergeTable.df,DateType=101,IsTryConvert=FALSE){
  #I swear I had this working, but then it broke hard and every time I tried to 
  #debug it, the crash took minutes to resolve.
  # OneSwitch<-function(VariableName,
  #                     VariableShortType,
  #                     VariableFullType){
  #   ConvertText<-ifelse(IsTryConvert,"Try_Convert","Convert")
  #   Outcome<-switch(VariableShortType,
  #                   "[decimal]"=paste(ConvertText,"(",VariableFullType,
  #                                     ", ",ConvertText,"(real,",
  #                                     VariableName,"))",
  #                                     sep=""
  #                   ),
  #                   "[date]"=paste(ConvertText,"([date], ",
  #                                  VariableName,
  #                                  ",",as.character(DateType),")",
  #                                  sep=""
  #                   ),
  #                   paste(ConvertText,"(",VariableFullType,", ",
  #                         VariableName,
  #                         ")",
  #                         sep=""
  #                   )
  #   )
  #   Outcome
  # }
  # 
  # 
  # MergeTable.df$VariableShortType<-substr(MergeTable.df$CSISvariableType,1,
  #                                         regexpr(']',MergeTable.df$CSISvariableType))
  # 
  # MergeTable.df<-
  #   ddply(MergeTable.df,
  #                      .(SourceVariableName,VariableShortType,CSISvariableType),
  #          transform,
  #                      ConvertList=OneSwitch(SourceVariableName,
  #                                            VariableShortType,
  #                                            CSISvariableType))
  # MergeTable.df
  
    ConvertText<-ifelse(IsTryConvert,"Try_Convert","Convert")
    MergeTable.df$VariableShortType<-substr(MergeTable.df$CSISvariableType,1,
                                            regexpr(']',MergeTable.df$CSISvariableType))

    MergeTable.df$ConvertList<-NA
    SwitchList<-MergeTable.df$SourceVariableType==MergeTable.df$CSISvariableType
    MergeTable.df$ConvertList[SwitchList]<-MergeTable.df$SourceVariableName[SwitchList]
    
    SwitchList<-MergeTable.df$VariableShortType %in% c("[decimal]","[smallint]","[bigint]")&
      is.na(MergeTable.df$ConvertList)
    MergeTable.df$ConvertList[SwitchList]<-
      paste(ConvertText,"(",
                                      MergeTable.df$CSISvariableType[SwitchList] ,
                                      ", ",ConvertText,"(real,",
                                      MergeTable.df$SourceVariableName[SwitchList] ,"))",
                                      sep=""
                    )
    
    SwitchList<-MergeTable.df$VariableShortType=="[bit]"&
        is.na(MergeTable.df$ConvertList)
        MergeTable.df$ConvertList[SwitchList]<-
        paste(ConvertText,"(",
              MergeTable.df$CSISvariableType[SwitchList] ,", ",
              "(SELECT ReturnBit from Errorlogging.ConvertYNtoBit(",
              MergeTable.df$SourceVariableName[SwitchList] ,
              ")))",
              sep=""
        )
    
    SwitchList<-MergeTable.df$VariableShortType=="[date]"&
      is.na(MergeTable.df$ConvertList)
    MergeTable.df$ConvertList[SwitchList]<-
      paste(ConvertText,"([date], ",
                                   MergeTable.df$SourceVariableName[SwitchList] ,
                                   ",",as.character(DateType),")",
                                   sep=""
                    )
    SwitchList<-is.na(MergeTable.df$ConvertList)
    MergeTable.df$ConvertList[SwitchList]<-
                    paste(ConvertText,"(",
                          MergeTable.df$CSISvariableType[SwitchList] ,", ",
                          MergeTable.df$SourceVariableName[SwitchList] ,
                          ")",
                          sep=""
                    )
    MergeTable.df
}


LengthCheck<-function(MergeTable.df){

    MergeTable.df$LengthCheck<-""

    MergeTable.df$VariableTypeNumber<-as.numeric(
        (substr(MergeTable.df$CSISvariableType,
                regexpr('[(]',MergeTable.df$CSISvariableType)+1,
                regexpr('[)]',MergeTable.df$CSISvariableType)-1)
        ))
        

    SwitchList<-MergeTable.df$VariableShortType=="[varchar]"&
        MergeTable.df$LengthCheck==""&
        !is.na(MergeTable.df$VariableTypeNumber)
    MergeTable.df$LengthCheck[SwitchList]<-
        paste("OR len(",MergeTable.df$SourceVariableName[SwitchList] ,")",
              ">",MergeTable.df$VariableTypeNumber[SwitchList],"\n"
        )

    MergeTable.df
}


Create_Try_Converts<-function(MergeTable.df,
                              Schema,
                              TableName,
                              DateType=101){
  #Limit it to just cases where the variable type is changing
  MergeTable.df<-subset(MergeTable.df,SourceVariableType!=MergeTable.df$CSISvariableType)
  if(nrow(MergeTable.df)==0)
    stop("No try_converts necessary")
  MergeTable.df<-ConvertSwitch(MergeTable.df,101,TRUE)
  MergeTable.df<-LengthCheck(MergeTable.df)
  
  ConvertList<-paste(
    "SELECT DISTINCT ",
    MergeTable.df$SourceVariableName,",\n",
    "len(",MergeTable.df$SourceVariableName,") as Length,\n",
    "'",MergeTable.df$CSISvariableType,"' as DestinationType","\n",
    "FROM ",Schema,".",TableName,"\n",
    "WHERE (",
    MergeTable.df$ConvertList,
    " IS NULL AND\n",
    "NULLIF(",MergeTable.df$SourceVariableName,",'') IS NOT NULL)\n",
    MergeTable.df$LengthCheck,
    sep="")
  ConvertList
}


CreateInsert<-function(MergeTable.df,
                       SourceSchema,
                       SourceTableName,
                       TargetSchema,
                       TargetTableName,
                       DateType=101){
  MergeTable.df<-ConvertSwitch(MergeTable.df,101,FALSE)
  
  InsertList<-paste("INSERT INTO ",TargetSchema,".",TargetTableName,"\n",
                    "(",sep="")
  InsertList<-c(InsertList,paste(MergeTable.df$CSISvariableName,",",sep=""))
  #Remove the comma from the last insert list column
  InsertList[length(InsertList)]<-gsub(",","",InsertList[length(InsertList)])
  InsertList<-c(InsertList,")\n SELECT ")
  InsertList<-c(InsertList,paste(MergeTable.df$ConvertList,",",sep=""))
  #Remove the comma from the select list column
  InsertList[length(InsertList)]<-substr(InsertList[length(InsertList)],
                                       1,
                                       nchar(InsertList[length(InsertList)])-1)
  
  InsertList<-c(InsertList,
                    paste("FROM ",SourceSchema,".",SourceTableName,sep="")
  )
  InsertList
}



ConvertFieldToForeignKey<-function(PKschema,
                                   PKname){

  TargetTable.df<-read.csv(file.path("ImportAids",FileName),header=FALSE,sep=" ")
  #Test if the field can be converted to the primary keys typed.

}require(plyr)

ReadCreateTable<-function(FileName){
  TargetTable.df<-read.csv(file.path("ImportAids\\",FileName),header=FALSE,sep=" ")
  
  #For now we're ignoring everything except the lines describing variable types
  CreateRow<-which(TargetTable.df$V1=="CREATE")
  TargetTable.df<-TargetTable.df[-c(1:CreateRow),]
  EndRow<-which(TargetTable.df$V1==")")
  TargetTable.df<-TargetTable.df[-c(EndRow:nrow(TargetTable.df)),]
  TargetTable.df$V1<-as.character(TargetTable.df$V1)
  #Once we have the table in, the next step is to clean up anything seperated on spaces
  #that should not have been for our purposes.
  # 
  TargetTable.df$V2<-as.character(TargetTable.df$V2)
  TargetTable.df$V2[substring(TargetTable.df$V2,1,9)=="[decimal]"]<-paste(
    TargetTable.df$V2[substring(TargetTable.df$V2,1,9)=="[decimal]"],
    TargetTable.df$V3[substring(TargetTable.df$V2,1,9)=="[decimal]"]
  )
  #Just in case the only Not NULL is a decimal
  TargetTable.df$V3<-as.character(TargetTable.df$V3)
  TargetTable.df$V3[substring(TargetTable.df$V2,1,9)=="[decimal]"]<-
    as.character(TargetTable.df$V4[substring(TargetTable.df$V2,1,9)=="[decimal]"])
  TargetTable.df$V4[substring(TargetTable.df$V2,1,9)=="[decimal]"]<-""
  
  TargetTable.df<-TargetTable.df[,c(1:3)]
  colnames(TargetTable.df)<-c("VariableName",
                              "VariableType",
                              "Nullable")
  TargetTable.df$Nullable<-gsub(",","",TargetTable.df$Nullable)
  TargetTable.df$VariableName<-gsub("\t","",TargetTable.df$VariableName)
  TargetTable.df
}

ConvertAllOfType<-function(TargetTable.df,
                           OldType,
                           NewType,
                           Schema,
                           TableName){
  #Limit it to just relevant variables
  TargetTable.df<-TargetTable.df[TargetTable.df$VariableType==OldType,]
  if(nrow(TargetTable.df)==0)
    stop("OldType not found in table")
  ChangeList<-paste(
    "Alter Table ",Schema,".",TableName,"\n",
    "Alter Column ",TargetTable.df$VariableName," ",
    NewType," ",TargetTable.df$Nullable,sep="")
  ChangeList
}

ListProblemType<-function(TargetTable.df){
  TargetTable.df[TargetTable.df$VariableType=="[varchar](max)",]
}


TranslateName<-function(TargetTable.df){
  lookup.NameConversion<-read.csv("ImportAids\\NameConversion.csv",
                                  stringsAsFactors = FALSE)
  if(!"SourceVariableName" %in% colnames(TargetTable.df)){
    colnames(TargetTable.df)[1]<-"SourceVariableName" 
  }
  TargetTable.df<-plyr::join(TargetTable.df,lookup.NameConversion)
  # TargetTable.df$VariableName<-gsub("_","",TargetTable.df$VariableName)
  
  TargetTable.df$CSISvariableName[TargetTable.df$SourceVariableName %in% 
                   lookup.NameConversion$CSISvariableName]<-
    TargetTable.df$SourceVariableName[TargetTable.df$SourceVariableName %in% 
                     lookup.NameConversion$CSISvariableName]
  
  TargetTable.df
}



MergeSourceAndCSISnameTables<-function(SourceTable.df,CSIStable.df){
  colnames(SourceTable.df)[1:3]<-c("SourceVariableName",
                                   "SourceVariableType",
                                   "SourceNullable")
  SourceTable.df$SourceVariableName<-as.character(SourceTable.df$SourceVariableName)
  colnames(CSIStable.df)[1:3]<-c("CSISvariableName",
                                 "CSISvariableType",
                                 "CSISnullable")
  CSIStable.df$CSISvariableName<-as.character(CSIStable.df$CSISvariableName)
  SourceTable.df<-plyr::join(SourceTable.df,CSIStable.df)
}



CreateCSISdates<-function(Schema,TableName){
  paste("ALTER TABLE ",Schema,".",TableName,"\n",
        "CREATE CSISmodifiedDate datetime2 NOT NULL default gettime(),\n",
        "CSIScreatedDate datetime2 NOT NULL default gettime()\n",
        sep="")
}

ConvertSwitch<-function(MergeTable.df,DateType=101,IsTryConvert=FALSE){
  #I swear I had this working, but then it broke hard and every time I tried to 
  #debug it, the crash took minutes to resolve.
  # OneSwitch<-function(VariableName,
  #                     VariableShortType,
  #                     VariableFullType){
  #   ConvertText<-ifelse(IsTryConvert,"Try_Convert","Convert")
  #   Outcome<-switch(VariableShortType,
  #                   "[decimal]"=paste(ConvertText,"(",VariableFullType,
  #                                     ", ",ConvertText,"(real,",
  #                                     VariableName,"))",
  #                                     sep=""
  #                   ),
  #                   "[date]"=paste(ConvertText,"([date], ",
  #                                  VariableName,
  #                                  ",",as.character(DateType),")",
  #                                  sep=""
  #                   ),
  #                   paste(ConvertText,"(",VariableFullType,", ",
  #                         VariableName,
  #                         ")",
  #                         sep=""
  #                   )
  #   )
  #   Outcome
  # }
  # 
  # 
  # MergeTable.df$VariableShortType<-substr(MergeTable.df$CSISvariableType,1,
  #                                         regexpr(']',MergeTable.df$CSISvariableType))
  # 
  # MergeTable.df<-
  #   ddply(MergeTable.df,
  #                      .(SourceVariableName,VariableShortType,CSISvariableType),
  #          transform,
  #                      ConvertList=OneSwitch(SourceVariableName,
  #                                            VariableShortType,
  #                                            CSISvariableType))
  # MergeTable.df
  
    ConvertText<-ifelse(IsTryConvert,"Try_Convert","Convert")
    MergeTable.df$VariableShortType<-substr(MergeTable.df$CSISvariableType,1,
                                            regexpr(']',MergeTable.df$CSISvariableType))

    MergeTable.df$ConvertList<-NA
    SwitchList<-MergeTable.df$SourceVariableType==MergeTable.df$CSISvariableType
    MergeTable.df$ConvertList[SwitchList]<-MergeTable.df$SourceVariableName[SwitchList]
    
    SwitchList<-MergeTable.df$VariableShortType %in% c("[decimal]","[smallint]","[bigint]")&
      is.na(MergeTable.df$ConvertList)
    MergeTable.df$ConvertList[SwitchList]<-
      paste(ConvertText,"(",
                                      MergeTable.df$CSISvariableType[SwitchList] ,
                                      ", ",ConvertText,"(real,",
                                      MergeTable.df$SourceVariableName[SwitchList] ,"))",
                                      sep=""
                    )
    
    SwitchList<-MergeTable.df$VariableShortType=="[bit]"&
        is.na(MergeTable.df$ConvertList)
        MergeTable.df$ConvertList[SwitchList]<-
        paste(ConvertText,"(",
              MergeTable.df$CSISvariableType[SwitchList] ,", ",
              "(SELECT ReturnBit from Errorlogging.ConvertYNtoBit(",
              MergeTable.df$SourceVariableName[SwitchList] ,
              ")))",
              sep=""
        )
    
    SwitchList<-MergeTable.df$VariableShortType=="[date]"&
      is.na(MergeTable.df$ConvertList)
    MergeTable.df$ConvertList[SwitchList]<-
      paste(ConvertText,"([date], ",
                                   MergeTable.df$SourceVariableName[SwitchList] ,
                                   ",",as.character(DateType),")",
                                   sep=""
                    )
    SwitchList<-is.na(MergeTable.df$ConvertList)
    MergeTable.df$ConvertList[SwitchList]<-
                    paste(ConvertText,"(",
                          MergeTable.df$CSISvariableType[SwitchList] ,", ",
                          MergeTable.df$SourceVariableName[SwitchList] ,
                          ")",
                          sep=""
                    )
    MergeTable.df
}


LengthCheck<-function(MergeTable.df){

    MergeTable.df$LengthCheck<-""

    MergeTable.df$VariableTypeNumber<-as.numeric(
        (substr(MergeTable.df$CSISvariableType,
                regexpr('[(]',MergeTable.df$CSISvariableType)+1,
                regexpr('[)]',MergeTable.df$CSISvariableType)-1)
        ))
        

    SwitchList<-MergeTable.df$VariableShortType=="[varchar]"&
        MergeTable.df$LengthCheck==""&
        !is.na(MergeTable.df$VariableTypeNumber)
    MergeTable.df$LengthCheck[SwitchList]<-
        paste("OR len(",MergeTable.df$SourceVariableName[SwitchList] ,")",
              ">",MergeTable.df$VariableTypeNumber[SwitchList],"\n"
        )

    MergeTable.df
}


Create_Try_Converts<-function(MergeTable.df,
                              Schema,
                              TableName,
                              DateType=101){
  #Limit it to just cases where the variable type is changing
  MergeTable.df<-subset(MergeTable.df,SourceVariableType!=MergeTable.df$CSISvariableType)
  if(nrow(MergeTable.df)==0)
    stop("No try_converts necessary")
  MergeTable.df<-ConvertSwitch(MergeTable.df,101,TRUE)
  MergeTable.df<-LengthCheck(MergeTable.df)
  
  ConvertList<-paste(
    "SELECT DISTINCT ",
    MergeTable.df$SourceVariableName,",\n",
    "len(",MergeTable.df$SourceVariableName,") as Length,\n",
    "'",MergeTable.df$CSISvariableType,"' as DestinationType","\n",
    "FROM ",Schema,".",TableName,"\n",
    "WHERE (",
    MergeTable.df$ConvertList,
    " IS NULL AND\n",
    "NULLIF(",MergeTable.df$SourceVariableName,",'') IS NOT NULL)\n",
    MergeTable.df$LengthCheck,
    sep="")
  ConvertList
}


CreateInsert<-function(MergeTable.df,
                       SourceSchema,
                       SourceTableName,
                       TargetSchema,
                       TargetTableName,
                       DateType=101){
  MergeTable.df<-ConvertSwitch(MergeTable.df,101,FALSE)
  
  InsertList<-paste("INSERT INTO ",TargetSchema,".",TargetTableName,"\n",
                    "(",sep="")
  InsertList<-c(InsertList,paste(MergeTable.df$CSISvariableName,",",sep=""))
  #Remove the comma from the last insert list column
  InsertList[length(InsertList)]<-gsub(",","",InsertList[length(InsertList)])
  InsertList<-c(InsertList,")\n SELECT ")
  InsertList<-c(InsertList,paste(MergeTable.df$ConvertList,",",sep=""))
  #Remove the comma from the select list column
  InsertList[length(InsertList)]<-substr(InsertList[length(InsertList)],
                                       1,
                                       nchar(InsertList[length(InsertList)])-1)
  
  InsertList<-c(InsertList,
                    paste("FROM ",SourceSchema,".",SourceTableName,sep="")
  )
  InsertList
}
###########################################
# process_cfsv2_ts_ncdc.r
# processes grib2 files from ncdc cfsv2 archive
# aggregates 6-hrly forecasts to 24hr and 5-day accumulations
# regrids and maps to river basins using correspondence file
# saves data in csv format
###########################################

## load libraries
library(data.table)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(tidyr)
library(tools)
library(akima)

## user inputs
dir_scratch = ''
dir_dom = ''
dir_dom_proc = ''

# define sub-domain of raw forecast
lat_dom = c(1, 16)
lon_dom = c(32, 49)

# new 0.1º grid
xp1 = seq(from = 33.05, by = 0.1, length.out = 150)
yp1 = seq(from = 2.05, by = 0.1, length.out = 130)

# correspondence file 
c_file = fread('')

# extension for outfile
fileout_dom = '_ethiopia_24hraccum.csv'

## set up
setwd(dir_scratch)

dom_file_list = list.files(dir_dom, pattern = '*.grb2')
nfiles_dom = length(dom_file_list)
# 21600 sec / 6hr
weight_tbl = data.table(fcst_hour = c(0, 6, 12, 18, 24), weight = c(0.5, 1, 1, 1, 0.5))

## process files
for(i in 1:nfiles_dom){
	dom_file_sel = paste0(dir_dom, dom_file_list[i])
	file_out = paste0(dir_dom_proc, file_path_sans_ext(dom_file_list[i]), fileout_dom)
	if(file.exists(file_out) == F){
		system(paste0("wgrib2 ", dom_file_sel, " -csv temp.csv"))
		tryCatch({
			fcst_dat = fread('temp.csv') %>% setnames(c('date_init', 'date_fcst', 'var', 'level', 'lon', 'lat', 'value')) %>% select(-var, -level)
			fcst_dat = fcst_dat %>% filter(lon >= lon_dom[1], lon <= lon_dom[2], lat >= lat_dom[1], lat <= lat_dom[2]) %>% mutate(date_init = as.POSIXct(date_init), date_fcst = as.POSIXct(date_fcst), value = value * 21600) %>% mutate(fcst_hour = hour(date_fcst)) %>% mutate(date_init = as.Date(date_init), date_fcst = as.Date(date_fcst))

			fcst_dat_24z = fcst_dat %>% filter(fcst_hour == 0) %>% mutate(date_fcst = date_fcst - days(1), fcst_hour = 24)

			fcst_dat = bind_rows(fcst_dat, fcst_dat_24z)
			fcst_dat_24hraccum = fcst_dat %>% left_join(weight_tbl) %>% mutate(value = value * weight, date_fcst = date_fcst + days(1)) %>% group_by(date_init, date_fcst, lon, lat) %>% dplyr::summarise(value = sum(value)) 
			date_init_temp = unique(fcst_dat_24hraccum $date_init)
			date_fcst_list = sort(unique(fcst_dat_24hraccum$date_fcst))
			nfcst = length(date_fcst_list)
			fcst_dat_24hraccum_interp = NULL
			for(j in 1:nfcst){
				date_fcst_temp = date_fcst_list[j]
				fcst_dat_24hraccum_fl = filter(fcst_dat_24hraccum, date_fcst == date_fcst_temp)

				x_temp = fcst_dat_24hraccum_fl$lon
				y_temp = fcst_dat_24hraccum_fl$lat
				z_temp = fcst_dat_24hraccum_fl$value
				interp_raw = interp(x_temp, y_temp, z_temp, xo = xp1, yo = yp1)
				fcst_dat_24hraccum_interp_temp = data.table(date_init = date_init_temp, date_fcst = date_fcst_temp, lon = interp_raw$x, lat = rep(interp_raw$y, each = length(interp_raw$x)), value = as.numeric(interp_raw$z)) %>% mutate(value = ifelse(value < 0, 0, value))%>% filter(!is.na(value))
				fcst_dat_24hraccum_interp = bind_rows(fcst_dat_24hraccum_interp, fcst_dat_24hraccum_interp_temp)
			}
			fcst_dat_24hraccum_basin = left_join(fcst_dat_24hraccum_interp, c_file) %>% filter(!is.na(name)) %>% group_by(date_init, date_fcst, ethbasin, ethbasin_I, name) %>% summarise(value = mean(value))
			write.csv(fcst_dat_24hraccum_basin, file_out)
		})
	}
}
require(knitr)
render_caption <- 
function(caption) {
  paste('<p class="caption">', caption, "</p>", sep="")
}
 
knit_hooks$set(html.cap <- function(before, options, envir) {
    if(!before) {
      render_caption(options$html.cap)
    } else {
      # Do nothing (or set isTable flag to render_caption at the top?
    }
  }
)

require(R6)
Caption =
R6Class("Caption",
  public <- list(
    label_=c(),
    text_=c(),
    type_=NA,
    initialize=function(type="Figure") {
      self$type_ <- type
    },
    label=function(l, t=NULL) {
        index <- length(self$label_) + 1
        if (l %in% self$label_) {
            index <- which(self$label_ == l)
        } else {
            self$label_[index] <- l
        }
        if (!is.null(t)) {
            self$text_[index] <- t
        }
        which(l == self$label_)
    },
    text=function(l, t=NULL) {
        if (!l %in% self$label_) stop("No such label")
        index <- which(l == self$label_)
        if (!is.null(t)) {
            self$text_[index] <- t
        }
        paste(self$type_, " ", which(l == self$label_), ". ", self$text_[index], sep="")
    }
  )
)

Footnote =
R6Class("Footnote",
  public <- list(
    label_=c(),
    text_=c(),
    label=function(l, t=NULL) {
      self$update(l, t)
      writeLines(paste('<a href="#', l, '">',
        '<span id="', l, '_back"><sup>',
        which(l == self$label_), '</sup></span></a>', sep=""))
    },
    update=function(l, t=NULL) {
        index <- length(self$label_) + 1
        if (l %in% self$label_) {
            index <- which(self$label_ == l)
        } else {
            self$label_[index] <- l
        }
        if (!is.null(t)) {
            self$text_[index] <- t
        }
    },
    render=function(head="Notes") {
        writeLines('<div class="footnotes">')
        writeLines(head)
        writeLines('<ol>')
        items <- paste('<li id="', self$label_, '">', self$text_,
                      ' <a href="#', self$label_,'_back">&#8617;</a>', '</li>', sep="")
        writeLines(items)
        writeLines('</ol></div>')
    }
  )
)

pkgs <- c(
	"alabama",
	"base64enc",
	"caret",
	"cubature",
	"data.table",
	"DEoptim",
	"devtools",
	"doParallel",
	"doSNOW",
	"dplyr",
	"dyn",
	"dynlm",
	"extrafont",
	"feather",
	"fAsianOptions",
	"fAssets",
	"fBasics",
	"fBonds",
	"fCopulae",
	"fExoticOptions",
	"fExtremes",
	"fGarch",
	"fImport",
	"fMultivar",
	"fNonlinear",
	"fOptions",
	"fPortfolio",
	"fRegression",
	"fTrading",
	"fUnitRoots",
	"foreach",
	"forecast",
	"glmnet",
	"gmailr",
	"ggfortify",
	"ggplot2",
	"ggthemes",
	"gmp",
	"Hmisc",
	"knitr",
	"leaps",
	"linprog",
	"lubridate",
	"lpSolve",
	"lpSolveAPI",
	"mail",
	"mapproj",
	"maptools",
	"microbenchmark",
	"mongolite",
	"NMOF",
	"openxlsx",
	"parcor",
	"party",
	"pbivnorm",
	"plm",
	"plotly",
	"PythonInR",
	"quantmod",
	"R.cache",
	"randomForest",
	"Rcpp",
	"RCurl",
	"rJava",
	"readr",
	"reshape",
	"rmarkdown",
	"Rmpfr",
	"rjson",
	"roxygen2",
	"RQuantLib",
	"RSelenium",
	"RSQLite",
	"rvest",
	"scales",
	"sqldf",
	"stringr",
	"Synth",
	"plyr",
	"TSA",
	"tikzDevice",
	"x12",
	"xlsx",
	"XML",
	"xml2",
	"xts",
	"zoo"
	)

install.packages(pkgs)

# rjulia
devtools::install_github("armgong/rjulia", ref="master")

# http://bioconductor.org/packages/release/bioc/html/rhdf5.html
source("https://bioconductor.org/biocLite.R")
biocLite("rhdf5", ask=F) # HDF5 interface to R
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        cancel = function(job_ids, user = private$user, host = private$host) {
            job_ids <- paste(job_ids, collapse = ",")

            stain_ssh(user, host, paste("scancel", job_ids))
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host, submit_dir = "~/stain") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        view_submission_history = function() {
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                View(history)
                invisible(history)
            }
        },
        view_statuses = function(user = private$user, host = private$host, should_view = TRUE) {
            job_ids <- stain_sub_history(self$dir)$job_id

            tryCatch({
                status_table <- stain_ssh_squeue(user, host, job_ids)
            }, warning = function(w) {
                message(paste("No statuses found for job ids:", job_ids))
                invisible()
            })


            if (nrow(status_table) > 0) {
                if (should_view) { View(status_table) }
            } else {
                job_ids <- paste(job_ids, collapse = ", ")
                message(paste("No statuses found for job ids:", job_ids))
            }

            invisible(status_table)
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host, submit_dir = "~/stain") {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        view_submission_history = function() {
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                View(history)
                invisible(history)
            }
        },
        view_statuses = function(user = private$user, host = private$host, should_view = TRUE) {
            job_ids <- stain_sub_history(self$dir)$job_id

            tryCatch({
                status_table <- stain_ssh_squeue(user, host, job_ids)
            }, warning = function(w) {
                message(paste("No statuses found for job ids:", job_ids))
                invisible()
            })


            if (nrow(status_table) > 0) {
                if (should_view) { View(status_table) }
            } else {
                job_ids <- paste(job_ids, collapse = ", ")
                message(paste("No statuses found for job ids:", job_ids))
            }

            invisible(status_table)
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
###########################################
# get_cfsv2_ts_ncdc.r
# pulls cfsv2 forecasts from NCDC timeseries archive
# subsets to gbm and africa domains
# pulls out specified forecast variables
###########################################

start_time()
## load libraries 
library(data.table)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(tidyr)
library(doParallel)
library(foreach)

## user inputs
dir_scratch = ''
dir_gbm = ''
dir_africa = ''

lims_lon_gbm = c(73, 98)
lims_lat_gbm = c(22, 32)
lims_lon_africa = c(-20, 55)
lims_lat_africa = c(-40, 40)

fcst_lead_sel = 1440
time_sel_start = as.POSIXct('2011-04-01', tz = 'utc')
time_sel_end = as.POSIXct('2016-09-15 18:00', tz = 'utc')

var_sel = 'prate'

ncores_sel = 6

## setup
setwd(dir_scratch)

time_list = seq(from = time_sel_start, to = time_sel_end, by = '6 hour')
ntimes = length(time_list)

tempvar_list = rep(letters, ceiling(ntimes / 26))

## download function
get_cfs_ts_grb = function(var, time_init_sel, fcst_lead = 1440, tempvar){
	require(data.table)
	require(dplyr)
	require(lubridate)
	require(stringr)
	require(tidyr)
	
	urlhead = 'http://nomads.ncdc.noaa.gov/modeldata/cfsv2_forecast_ts_9mon/'
	
	yearinit = year(time_init_sel)
	monthinit = str_pad(month(time_init_sel), 2, pad = "0")
	dayinit = str_pad(day(time_init_sel), 2, pad = "0")
	hourinit = str_pad(hour(time_init_sel), 2, pad = "0")

	initdatefilestr = paste0(yearinit, monthinit, dayinit)
	initdatestr = paste0(yearinit, monthinit, dayinit, hourinit)
	inityrmon = paste0(yearinit, monthinit)
	
	fcst_lead_list = seq(from = 6, to = fcst_lead, by = 6)
	fcst_match_list = paste(paste0(':', fcst_lead_list, ' hour fcst:'), collapse = '|')
	
	url = paste0(urlhead, yearinit, '/', inityrmon, '/', initdatefilestr, '/', initdatestr, '/', var, '.', '01', '.', initdatestr, '.daily.grb2') 
	
	destfile_gbm = paste0(dir_gbm, var, '.', initdatestr, '.', '01', '.grb2') 
	destfile_africa = paste0(dir_africa, var, '.', initdatestr, '.', '01', '.grb2') 
	
	#checks forecast lead against selected and removes file if too small
	if(file.exists(destfile_gbm) == T){
		file_meta = data.table(raw = system(paste('wgrib2', destfile_gbm, '-ftime'), intern = T)) %>% separate(raw, sep = c(':'), into = c('id', 'ref', 'hour')) %>% separate(hour, sep = ' ', into = c('hour', 'lab1', 'lab2'))
		file_max_hour = max(as.numeric(file_meta$hour))
		if(file_max_hour < fcst_lead){
			system(paste("rm", destfile_gbm))
		}
	}
	if(file.exists(destfile_africa) == T){
		file_meta = data.table(raw = system(paste('wgrib2', destfile_africa, '-ftime'), intern = T)) %>% separate(raw, sep = c(':'), into = c('id', 'ref', 'hour')) %>% separate(hour, sep = ' ', into = c('hour', 'lab1', 'lab2'))
		file_max_hour = max(as.numeric(file_meta$hour))
		if(file_max_hour < fcst_lead){
			system(paste("rm", destfile_africa))
		}
	}

	#downloads and subsets (if needed)
	if(file.exists(destfile_gbm) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match '", fcst_match_list, "' -g2clib 0 -small_grib ", paste(lims_lon_gbm, collapse = ':'), " ", paste(lims_lat_gbm, collapse = ':'), " ", destfile_gbm), ignore.stdout = T, ignore.stderr = T)
		if(file.exists(destfile_africa) == F){
			system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match '", fcst_match_list, "' -g2clib 0 -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
		}
	}
	if(file.exists(destfile_africa) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match '", fcst_match_list, "' -g2clib 0 -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
	}
}

## call function 
cl = makeCluster(ncores_sel)
registerDoParallel(cl)
foreach (i = 1:ntimes) %dopar% {
	time_init_sel = time_list[i]
	tempvar_sel = tempvar_list[i]
	try(get_cfs_ts_grb(var_sel, time_init_sel, fcst_lead_sel, tempvar_sel))
}
stopCluster(cl)
Sys.time() - start_time
###########################################
# get_cfsv2_ncdc.r
# pulls cfsv2 forecasts from NCDC archive
# subsets to gbm and africa domains
# pulls out precip. surface temp, winds, and latent
# heat flux
###########################################

start_time = Sys.time()

## load libraries
library(stringr)
library(dplyr)
library(data.table)
library(lubridate)

date2str = function(dte){
	#dte - POSIXct date 
	year_str = year(dte)
	month_str = str_pad(month(dte), 2, pad = '0')
	day_str = str_pad(day(dte), 2, pad = '0')
	hour_str = str_pad(hour(dte), 2, pad = '0')

	paste0(year_str, month_str, day_str, hour_str)
}

## user inputs
dir_scratch = ''
dir_gbm = ''
dir_africa = ''

lims_lon_gbm = c(73, 98)
lims_lat_gbm = c(22, 32)
lims_lon_africa = c(-20, 55)
lims_lat_africa = c(-40, 40)

fcst_lead_sel = 1440
time_sel_start = as.POSIXct('2011-04-01', tz = 'utc')
time_sel_end = as.POSIXct('2011-12-31 18:00', tz = 'utc')

ncores_sel = 6

## setup
setwd(dir_scratch)

time_init_list = seq(from = time_sel_start, to = time_sel_end, by = '6 hour')
fcst_lead_list = seq(from = 6, to = fcst_lead_sel, by = 6)
nfcstlead = length(fcst_lead_list)
time_dt = data.table(time_init = rep(time_init_list, each = nfcstlead), fcst_lead = fcst_lead_list) %>% mutate(time_fcst = time_init + hours(fcst_lead))
ntimes = nrow(time_dt)

tempvar_list = rep(letters, ceiling(ntimes / 26))

## download function
get_cfs_grb = function(time_init_sel, time_fcst_sel, tempvar){
	require(data.table)
	require(dplyr)
	require(lubridate)
	require(stringr)
	require(tidyr)
	
	urlhead = 'http://nomads.ncdc.noaa.gov/modeldata/cfsv2_forecast_6-hourly_9mon_flxf/'
	
	yearinit = year(time_init_sel)
	monthinit = str_pad(month(time_init_sel), 2, pad = "0")
	dayinit = str_pad(day(time_init_sel), 2, pad = "0")
	hourinit = str_pad(hour(time_init_sel), 2, pad = "0")

	initdatefilestr = paste0(yearinit, monthinit, dayinit)
	initdatestr = paste0(yearinit, monthinit, dayinit, hourinit)
	inityrmon = paste0(yearinit, monthinit)
	
	yearfcst = year(time_fcst_sel)
	monthfcst = str_pad(month(time_fcst_sel), 2, pad = "0")
	dayfcst = str_pad(day(time_fcst_sel), 2, pad = "0")
	hourfcst = str_pad(hour(time_fcst_sel), 2, pad = "0")
	
	fcstdatestr = paste0(yearfcst, monthfcst, dayfcst, hourfcst)

	url = paste0(urlhead, yearinit, '/', inityrmon, '/', initdatefilestr, '/', initdatestr, '/flxf', fcstdatestr, '.01.', initdatestr, '.grb2')
	
	destfile_gbm = paste0(dir_gbm, initdatestr, '.', '01', '.', fcstdatestr, '.grb2') 
	destfile_africa = paste0(dir_africa, initdatestr, '.', '01', '.', fcstdatestr, '.grb2') 
	
	#downloads and subsets (if needed)
	if(file.exists(destfile_gbm) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		
		system(paste0("wgrib2 ", "temp_", tempvar, ".grb2", " -g2clib 0 -match ':(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):' -small_grib ", paste(lims_lon_gbm, collapse = ':'), " ", paste(lims_lat_gbm, collapse = ':'), " ", destfile_gbm), ignore.stdout = T, ignore.stderr = T)
		
		if(file.exists(destfile_africa) == F){
			system(paste0("wgrib2 ", "temp_", tempvar, ".grb2", " -g2clib 0 -match ':(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):' -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
		}
	}
	if(file.exists(destfile_africa) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		system(paste0("wgrib2 ", "temp_", tempvar, ".grb2", " -g2clib 0 -match ':(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):' -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
	}
}

## call function
cl = makeCluster(ncores_sel)
registerDoParallel(cl)
foreach (i = 1:ntimes) %dopar% {
	time_init_sel = time_dt$time_init[i]
	time_fcst_sel = time_dt$time_fcst[i]
	tempvar_sel = tempvar_list[i]
	try(get_cfs_grb(time_init_sel, time_fcst_sel, tempvar_sel))
}
stopCluster(cl)
Sys.time() - start_time
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user = private$user, host = private$host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user = private$user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        set_remote_host = function(user = private$user, host = private$host) {
            private$user <- user
            private$host <- host
        },
        view_submission_history = function() {
            history <- stain_sub_history(self$dir)

            if (is.data.frame(history)) {
                View(history)
                invisible(history)
            }
        },
        view_statuses = function(user = private$user, host = private$host, should_view = TRUE) {
            job_ids <- stain_sub_history(self$dir)$job_id

            tryCatch({
                status_table <- stain_ssh_squeue(user, host, job_ids)
            }, warning = function(w) {
                message(paste("No statuses found for job ids:", job_ids))
                invisible()
            })


            if (nrow(status_table) > 0) {
                if (should_view) { View(status_table) }
            } else {
                job_ids <- paste(job_ids, collapse = ", ")
                message(paste("No statuses found for job ids:", job_ids))
            }

            invisible(status_table)
        }
    ),
    private = list(
        user = NULL,
        host = NULL,
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        view_statuses = function(user, host, should_view = TRUE) {
            job_ids <- stain_sub_history(self$dir)$job_id

            tryCatch({
                status_table <- stain_ssh_squeue(user, host, job_ids)
            }, warning = function(w) {
                message(paste("No statuses found for job ids:", job_ids))
                invisible()
            })


            if (nrow(status_table) > 0) {
                if (should_view) { View(status_table) }
            } else {
                job_ids <- paste(job_ids, collapse = ", ")
                message(paste("No statuses found for job ids:", job_ids))
            }

            invisible(status_table)
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        },
        view_statuses = function(user, host, should_view = TRUE) {
            job_ids <- stain_sub_history(self$dir)$job_id
            status_table <- stain_ssh_squeue(user, host, job_ids)

            if (nrow(status_table) > 0) {
                if (should_view) { View(status_table) }
            } else {
                job_ids <- paste(job_ids, collapse = ", ")
                message(paste("No statuses found for job ids:", job_ids))
            }

            invisible(status_table)
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)

                # Add the job id to submission history
                output <- strsplit(output, " ")[[1]]
                job_id <- as.numeric(output[length(output)])
                stain_sub_history_append(self$dir, job_id)

                message(paste("Submitted job", job_id, "to", remote_host))
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))

                for (obj_name in ls(envir = .GlobalEnv)) {
                    obj <- .GlobalEnv[[obj_name]]

                    if(class(obj)[1] == "SlurmContainer") {
                        if (self$dir == obj$dir) {
                            rm(list = obj_name, envir = .GlobalEnv)
                        }
                    }

                }
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                message("Saving globals...")
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                message("Uploading components...")
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                message("Submitting job...")
                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                output <- stain_ssh(user, host, submit_cmd, intern = TRUE)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
######################################################################
######################################################################
## ROUTINE ZUM EINLESEN UND VERARBEITEN DER ZEITLICHEN MITTELWERTE
## DES U- ,V- ,W-WINDFELDES AUS ERA-DATEN IM NCDF-FORMAT
## source('~/Master_Thesis/r-code-git/process_mean_uvw.r')
######################################################################
######################################################################


######################################################################
## AUFRUF WICHTIGER BIBLIOTHEKEN UND PAKETE
######################################################################
##

library(ncdf4)
library(parallel)
library(chron)

library(fields)
library(clim.pact)

setwd("~/Master_Thesis/02-r-code-git/")
path <- "data/"
# path <- "/home/skiefer/era/raw/"
file <- "era-t63-mean_uvw_13z.nh-trop-inv.nc"  # Nordhemisphäre + Südhemisphäre



######################################################################
## EINLESEN DER DATEN
## ERA40 / ERA-INTERIM
## T63 - GRID - GAUSSIAN
## NORDHEMISPHÄRE & TROPEN
## 192 (lat) * 64 (lon)
######################################################################
##

nc <- nc_open(paste(path, file, sep = ""))
# print(nc)
u.mean <- ncvar_get(nc, "var131") # U-Wind-Komponente
v.mean <- ncvar_get(nc, "var132") # V-Wind-Komponente
w.mean <- ncvar_get(nc, "var135") # W-Wind-Komponente

lon <- ncvar_get(nc, "lon") # Längengrad
lat <- ncvar_get(nc, "lat") # Breitengrad
lev <- ncvar_get(nc, "lev") # Drucklevel
date.help <- ncvar_get(nc, "time")

nc_close(nc)
rm(nc)

uvw.mean <- sqrt( u.mean ** 2 + v.mean **2 + w.mean ** 2 )
##
## ZONAL MEAN
u.zon.mean <- apply(u.mean[,,], c(2,3), mean)
v.zon.mean <- apply(v.mean[,,], c(2,3), mean)
uvw.zon.mean <- apply(uvw.mean[,,], c(2,3), mean)

## ZONAL-WIND U
contour(lat, 1:13, u.zon.mean, xlab = "Breitengrad in (deg)", ylab = "Druckniveaus in (hPa)", axes = FALSE)
title("Zonal gemittelter Zonal-Wind in (m/s)")
axis(1, at = seq(-90,90,10), labels = TRUE)
axis(2, at = seq(1,13,2), labels = c('1000', '850', '700', '500',  '300',  '200', '100'))

## MERIDIONAL-WIND V
image.plot(lat, 1:13, v.zon.mean, xlab = "Breitengrad in (deg)", ylab = "Druckniveaus in (hPa)", axes = FALSE)
title("Zonal gemittelter Meridional-Wind in (m/s)")
axis(1, at = seq(-90,90,10), labels = TRUE)
axis(2, at = seq(1,13,2), labels = c('1000', '850', '700', '500',  '300',  '200', '100'))

## BETRAG DES WINDFELDES
image.plot(lat, 1:13, uvw.zon.mean, xlab = "Breitengrad in (deg)", ylab = "Druckniveaus in (hPa)", axes = FALSE)
title("Zonal gemittelter Wind in (m/s)")
axis(1, at = seq(-90,90,10), labels = TRUE)
axis(2, at = seq(1,13,2), labels = c('1000', '850', '700', '500',  '300',  '200', '100'))

##
## MERIDIONAL MEAN
u.mer.mean <- apply(u.mean[,,], c(1,3), mean)
v.mer.mean <- apply(v.mean[,,], c(1,3), mean)
uvw.mer.mean <- apply(uvw.mean[,,], c(1,3), mean)

## ZONAL-WIND U
image.plot(lon, 1:13, u.mer.mean, xlab = "Längengrad in (deg)", ylab = "Druckniveaus in (hPa)", axes = FALSE)
title("Meridional gemittelter Zonal-Wind in (m/s)")
axis(1, at = seq(0,360,40), labels = TRUE)
axis(2, at = seq(1,13,2), labels = c('1000', '850', '700', '500',  '300',  '200', '100'))

## MERIDIONAL-WIND V
contour(lon, 1:13, v.mer.mean, xlab = "Längengrad in (deg)", ylab = "Druckniveaus in (hPa)", axes = FALSE)
title("Meridional gemittelter Meridional-Wind in (m/s)")
axis(1, at = seq(0,360,40), labels = TRUE)
axis(2, at = seq(1,13,2), labels = c('1000', '850', '700', '500',  '300',  '200', '100'))

## BETRAG DES WINDFELDES
image.plot(lon, 1:13, uvw.mer.mean, xlab = "Längengrad in (deg)", ylab = "Druckniveaus in (hPa)", axes = FALSE)
title("Meridional gemittelter Wind in (m/s)")
axis(1, at = seq(0,360,40), labels = TRUE)
axis(2, at = seq(1,13,2), labels = c('1000', '850', '700', '500',  '300',  '200', '100'))
###########################################
# process_cfsv2_ts_ncdc.r
# processes grib2 files from ncdc cfsv2 archive
# aggregates 6-hrly forecasts to 24hr accumulations
# saves data in csv format
###########################################

## load libraries
library(data.table)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(tidyr)
library(tools)

## user inputs
dir_scratch = ''
dir_dom = ''
dir_dom_proc = '/d1/dbroman/projects/cfsv2/rdata/africa/'

# define domain
lat_dom = c(2, 16)
lon_dom = c(31, 49)
fileout_dom = '_ethiopia_24hraccum.csv'

## setup
setwd(dir_scratch)

dom_file_list = list.files(dir_dom, pattern = '*.grb2')
nfiles_dom = length(dom_file_list)
# 21600 sec / 6hr
weight_tbl = data.table(fcst_hour = c(0, 6, 12, 18, 24), weight = c(0.5, 1, 1, 1, 0.5))

## process files
for(i in 1:nfiles_dom){
	dom_file_sel = paste0(dir_dom, dom_file_list[i])
	file_out = paste0(dir_dom_proc, file_path_sans_ext(dom_file_list[i]), fileout_dom)
	if(file.exists(file_out) == F){
		system(paste0("wgrib2 ", dom_file_sel, " -csv temp.csv"))
		tryCatch({
			fcst_dat = fread('temp.csv') %>% setnames(c('date_init', 'date_fcst', 'var', 'level', 'lon', 'lat', 'value')) %>% select(-var, -level)
			fcst_dat = fcst_dat %>% filter(lon >= lon_dom[1], lon <= lon_dom[2], lat >= lat_dom[1], lat <= lat_dom[2]) %>% mutate(date_init = as.POSIXct(date_init), date_fcst = as.POSIXct(date_fcst), value = value * 21600) %>% mutate(fcst_hour = hour(date_fcst)) %>% mutate(date_init = as.Date(date_init), date_fcst = as.Date(date_fcst))

			fcst_dat_24z = fcst_dat %>% filter(fcst_hour == 0) %>% mutate(date_fcst = date_fcst - days(1), fcst_hour = 24)

			fcst_dat = bind_rows(fcst_dat, fcst_dat_24z)
			fcst_dat_24hraccum = fcst_dat %>% left_join(weight_tbl) %>% mutate(value = value * weight, date_fcst = date_fcst + days(1)) %>% group_by(date_init, date_fcst, lon, lat) %>% dplyr::summarise(value = sum(value)) 
			write.csv(fcst_dat_24hraccum, file_out)
		})
	}
}
###########################################
# process_cfsv2_ts_ncdc.r
# processes grib2 files from ncdc cfsv2 archive
# aggregates 6-hrly forecasts to 24hr and 5-day accumulations
# saves data in rdata format
###########################################

library(data.table)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(tidyr)

dir_scratch = '/d1/dbroman/projects/cfsv2/scratch/'
dir_gbm = '/d1/dbroman/projects/cfsv2/grib2/gbm/'
dir_africa = '/d1/dbroman/projects/cfsv2/grib2/africa/'

dir_gbm_proc = '/d1/dbroman/projects/cfsv2/rdata/gbm/'
dir_africa_proc = '/d1/dbroman/projectscfsv2/rdata/africa/'

rdata_file_gbm = 'prate_fcst_gbm_24hraccum.rda'
rdata_file_africa = 'prate_fcst_africa_24hraccum.rda'

setwd(dir_scratch)

gbm_file_list = list.files(dir_gbm, pattern = '*.grb2')
nfiles_gbm = length(gbm_file_list)
# 21600 sec / 6hr
weight_tbl = data.table(fcst_hour = c(0, 6, 12, 18, 24), weight = c(0.5, 1, 1, 1, 0.5))
for(i in 1:nfiles_gbm){
	gbm_file_sel = paste0(dir_gbm, gbm_file_list[i])
	system(paste0("wgrib2 ", gbm_file_sel, " -csv temp.csv"))
	fcst_dat = fread('temp.csv') %>% setnames(c('date_init', 'date_fcst', 'var', 'level', 'lon', 'lat', 'value')) %>% select(-var, -level)
	fcst_dat = fcst_dat  %>% mutate(date_init = as.POSIXct(date_init), date_fcst = as.POSIXct(date_fcst), value = value * 21600) %>% mutate(fcst_hour = hour(date_fcst)) %>% mutate(date_init = as.Date(date_init), date_fcst = as.Date(date_fcst))

	fcst_dat_24z = fcst_dat %>% filter(fcst_hour == 0) %>% mutate(date_fcst = date_fcst - days(1), fcst_hour = 24)

	fcst_dat = bind_rows(fcst_dat, fcst_dat_24z)
	fcst_dat_24hraccum = fcst_dat %>% left_join(weight_tbl) %>% mutate(value = value * weight, date_fcst = date_fcst + days(1)) %>% group_by(date_init, date_fcst, lon, lat) %>% dplyr::summarise(value = sum(value)) 

	if(file.exists(paste0(dir_gbm_proc, rdata_file_gbm)) == T){
		data_proc_temp = readRDS(paste0(dir_gbm_proc, rdata_file_gbm))
		data_proc_temp = bind_rows(data_proc_temp, fcst_dat)
		saveRDS(data_proc_temp, paste0(dir_gbm_proc, rdata_file_gbm))
	}
	if(file.exists(paste0(dir_gbm_proc, rdata_file_gbm)) == F){
		saveRDS(fcst_dat, paste0(dir_gbm_proc, rdata_file_gbm))
	}
}

for(i in 1:nfiles_africa){
	africa_file_sel = paste0(dir_africa, africa_file_list[i])
	system(paste0("wgrib2 ", africa_file_sel, " -csv temp.csv"))
	fcst_dat = fread('temp.csv') %>% setnames(c('date_init', 'date_fcst', 'var', 'level', 'lon', 'lat', 'value')) %>% select(-var, -level)
	fcst_dat = fcst_dat  %>% mutate(date_init = as.POSIXct(date_init), date_fcst = as.POSIXct(date_fcst), value = value * 21600) %>% mutate(fcst_hour = hour(date_fcst)) %>% mutate(date_init = as.Date(date_init), date_fcst = as.Date(date_fcst))

	fcst_dat_24z = fcst_dat %>% filter(fcst_hour == 0) %>% mutate(date_fcst = date_fcst - days(1), fcst_hour = 24)

	fcst_dat = bind_rows(fcst_dat, fcst_dat_24z)
	fcst_dat_24hraccum = fcst_dat %>% left_join(weight_tbl) %>% mutate(value = value * weight, date_fcst = date_fcst + days(1)) %>% group_by(date_init, date_fcst, lon, lat) %>% dplyr::summarise(value = sum(value)) 

	if(file.exists(paste0(dir_africa_proc, rdata_file_africa)) == T){
		data_proc_temp = readRDS(paste0(dir_africa_proc, rdata_file_africa))
		data_proc_temp = bind_rows(data_proc_temp, fcst_dat)
		saveRDS(data_proc_temp, paste0(dir_africa_proc, rdata_file_africa))
	}
	if(file.exists(paste0(dir_africa_proc, rdata_file_africa)) == F){
		saveRDS(fcst_dat, paste0(dir_africa_proc, rdata_file_africa))
	}
}
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$list_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        list_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$list_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                stain_ssh(user, host, submit_cmd)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' Number of control matrix principal components
#'
#' Fits probe intensities to principal components of the microarray control matrix
#' and calculates the resulting mean squared residuals for different
#' numbers of principal components.
#' 
#' @param qc.objects A list of outputs from \code{\link{meffil.create.qc.object}()}.
#' @param number.pcs Number of principal components to include in the design matrix (Default: all).
#' @param fixed.effects Names of columns in samplesheet that should be included as fixed effects
#' along with control matrix principal components (Default: NULL).
#' @param random.effects Names of columns in samplesheet that should be included as random effects
#' (Default: NULL).
#' @return A list containing a data frame with the mean squared residuals for different numbers of principal components
#' and a plot of these residuals.
#'
#' @export
meffil.plot.pc.fit <- function(qc.objects, fixed.effects=NULL, random.effects=NULL, n.cross=10, name="autosomal.ii") {
    stopifnot(is.valid.site.subset(name))    
    stopifnot(all(sapply(qc.objects, is.qc.object)))
    stopifnot(2*n.cross <= length(qc.objects))
    
    n.quantiles <- length(qc.objects[[1]]$quantiles[[1]]$M)
    max.pcs <- min(ncol(meffil.control.matrix(qc.objects)),
                   length(qc.objects) - ceiling(length(qc.objects)/n.cross))
    
    stats <- mclapply(1:max.pcs, function(number.pcs) {
        residuals <- list(M=matrix(NA,nrow=n.quantiles,ncol=length(qc.objects)),
                          U=matrix(NA,nrow=n.quantiles,ncol=length(qc.objects)))
        group <- sample(rep(1:n.cross, length.out=length(qc.objects)), length(qc.objects), replace=F)
        
        for (test.group in unique(group)) {
            msg("pcs", number.pcs, "group", test.group)
            test.idx <- which(group == test.group)
            design.matrix <- predict.design.matrix(qc.objects, number.pcs, test.idx,
                                                   fixed.effects=fixed.effects,
                                                   random.effects=random.effects)

            intensity.R <- sapply(qc.objects, function(object) object$intensity.R)
            intensity.G <- sapply(qc.objects, function(object) object$intensity.G)
            valid.idx <- which(intensity.R + intensity.G > 200)
            if(length(valid.idx) == 0) {
                valid.idx <- 1:length(intensity.R)
                warning("Most or all of the microarrays have very low intensity.")
            }
            reference.idx <- valid.idx[which.min(abs(intensity.R/intensity.G-1)[valid.idx])]
            dye.intensity <- (intensity.R + intensity.G)[reference.idx]/2
            for (target in c("M","U")) {
                original <- sapply(qc.objects[test.idx], function(object) {
                    object$quantiles[[name]][[target]] * dye.intensity/object$dye.intensity
                })
                residuals[[target]][,test.idx] <- (normalize.quantiles(original, design.matrix)
                                                   - rowMeans(original))
            }
        }
        
        c(n=number.pcs,M=mean((residuals$M[,-1])^2), U=mean((residuals$U[,-1])^2))
    })

    stats <- as.data.frame(do.call(rbind, stats))

    list(data=stats,
         plot=(ggplot(stats, aes(x=n)) +
               geom_line(aes(y=M, colour="M")) +
               geom_line(aes(y=U, colour="U")) +
               ggtitle("Fit residuals for different numbers of PCs") +
               labs(x="number of PCs", y="Mean squared residuals") +
               scale_x_continuous(breaks=seq(0,max(stats$n),by=5 )) +
               theme(legend.title=element_blank())))
}
#coverage/inst/shiny/covmob1/ui.r
#* deprecated version, replaced by coverage1
#andy south 12/5/16

library(shiny)


shinyUI(fluidPage(

  #can add CSS controls in here
  #http://shiny.rstudio.com/articles/css.html
  #http://www.w3schools.com/css/css_rwd_mediaqueries.asp

  #trying to put the @media bit in to make it responsive
  #i think i must have made another change later when i modified from pc to mobile

  tags$head(
    tags$style(HTML("

                    @media only screen and (max-width: 768px) {

                      /* For mobile phones: */

                      [class*='col-'] {
                      padding: 10px;
                      border: 1px;
                      position: relative;
                      min-height: 1px;
                      }

                      .container {
                      margin-right: 0;
                      margin-left: 0;
                      float: left;
                      }
                      .col-sm-1 {width: 8.33%; float: left;}
                      .col-sm-2 {width: 16.66%; float: left;}
                      .col-sm-3 {width: 25%; float: left;}
                      .col-sm-4 {width: 33.33%; float: left;}
                      .col-sm-5 {width: 41.66%; float: left;}
                      .col-sm-6 {width: 50%;  float: left;}
                      .col-sm-7 {width: 58.33%; float: left;}
                      .col-sm-8 {width: 66.66%; float: left; padding: 5px;} !to make more space for plots
                      .col-sm-9 {width: 75%; float: left;}
                      .col-sm-10 {width: 83.33%; float: left;}
                      .col-sm-11 {width: 91.66%; float: left;}
                      .col-sm-12 {width: 100%; float: left;}
                    }
                    "))
    ),

  title = "coverage of vector control interventions",

  h5("Vector control demonstrator prototype. Gerry Killeen & Andy South."),
  h5("Vectors feed indoors and outdoors, on humans and cattle. Interventions target a subset of these behaviours."),
  h5("Change inputs below to see implications."),

  # fluidRow(
  #   column(8, plotOutput('plot_feed')),
  #   # column(2, h5("Vector feeding"), plotOutput('plot_pie_feed') ),
  #   # column(2, h5("Human exposure"), plotOutput('plot_pie_expose') )
  #   column(2, plotOutput('plot_pie_feed') ),
  #   column(2, plotOutput('plot_pie_expose') )
  # ), #end fluid row

  fluidRow(

    #column(12, plotOutput('plot_feed'))

    column(12, HTML("<div style='height: 320px;'>"), plotOutput('plot_feed'), HTML("</div>"))

  ), #end fluid row

  fluidRow(
    #column(2,NULL),

    #column(4, plotOutput('plot_pie_feed') ),
    #column(4, plotOutput('plot_pie_expose') )

    column(6, HTML("<div style='height: 150px;'>"), plotOutput('plot_pie_feed'), HTML("</div>")),
    column(6, HTML("<div style='height: 150px;'>"), plotOutput('plot_pie_expose'), HTML("</div>"))

    #column(4, plotOutput('plot_pie_expose') )
  ), #end fluid row

  #hr(),

  fluidRow(
    column(3,
           #h4("Vector feeding"),
           sliderInput("feed_man", "vectors feeding on man", 0.7, min = 0, max = 1, step = 0.1, ticks=FALSE)
           #numericInput("feed_cow", "cattle", 0.3, min = 0, max = 1, step = 0.1),
           #sliderInput("feed_in","indoor", 0.6, min = 0, max = 1, step = 0.1)
           #numericInput("feed_out","outdoor", 0.4, min = 0, max = 1, step = 0.1)
    ),
    column(3,
           sliderInput("feed_in","vectors feeding indoors", 0.6, min = 0, max = 1, step = 0.1, ticks=FALSE)
    ),
    column(3, offset = 0,
           #h4("Intervention"),
           radioButtons("intervention","intervention",choices=c("bed nets","vet insecticide"))
           #sliderInput("target_coverage", "coverage", 0.7, min = 0, max = 1, step = 0.1)
    ),
    column(3, offset = 0,
           sliderInput("target_coverage", "intervention coverage", 0, min = 0, max = 1, step = 0.1, ticks=FALSE)
    )
           # h4("Intervention target"),
           # numericInput("target_man", "human", 0.7, min = 0, max = 1, step = 0.1),
           # numericInput("target_cow", "cattle", 0.3, min = 0, max = 1, step = 0.1),
           # numericInput("target_in","indoor", 0.6, min = 0, max = 1, step = 0.1),
           # numericInput("target_out","outdoor", 0.4, min = 0, max = 1, step = 0.1)


  ) #end fluid row

))
#' Function to batch download gridded DAYMET data
#'
#' This function downloads DAYMET data 
#' @param lat1 : top left latitude (decimal degrees)
#' @param lon1 : top left longitude (decimal degrees)
#' @param lat2 : bottom right latitude (decimal degrees)
#' @param lon2 : bottom right longitude(decimal degrees)
#' @param start_yr : start of the range of years over which to download data
#' @param end_yr : end of the range of years over which to download data
#' @param param : climate variable you want to download vapour pressure (vp), 
#' minimum and maximum temperature (tmin,tmax), snow water equivalent (swe), 
#' solar radiation (srad), precipitation (prcp) , day length (dayl).
#' The default setting is ALL, this will download all the previously mentioned
#' climate variables.
#' @keywords DAYMET, climate data
#' @export
#' @examples
#' download.daymet.tiles(lat1=36.0133,
#'                       lon1=-84.2625,
#'                       start_yr=1980,
#'                       end_yr=2000,
#'                       param="ALL")

download.daymet.tiles = function(lat1=36.0133,
                                 lon1=-84.2625,
                                 lat2=NA,
                                 lon2=NA,
                                 start_yr=1980,
                                 end_yr=1980,
                                 param="ALL"){
  
  # determine system
  OS = Sys.info()[['sysname']]
  
  # load DAYMET grid associated with the package
  # (this is an imported shapefile)
  # I do not store any additional data in the .rdata
  # file to keep the code transparent.
  data("DAYMET_grid")
  
  # grab the projection string. This is a LCC projection.
  projection = sp::CRS(sp::proj4string(tile_outlines))
  
  # extract tile IDs (vector shape) and the DAYMET IDs associated
  # with them
  tile_nrs = tile_outlines@data[,1]
  
  # if argument 3 or 4 are the default grab only the tile
  # of the first coordinate set, if 4 arguments are given
  # extract all tile numbers within this region of interest
  if ( is.na(lat2) | is.na(lon2)){
    
        # create coordinate pairs, with original coordinate  system
        location = sp::SpatialPoints(cbind(lon1,lat1), projection)
        
        # extract tile for this location
        tiles = sp::over(location,tile_outlines)$TileID
        
        # do not continue if outside range
        if (is.na(tiles)){
          stop("Your defined range is outside DAYMET coverage,
               check your coordinate values!")
        }

      }else{
      
        # create coordinate pairs, with original coordinate system
        topleft = sp::SpatialPoints(cbind(lon1,lat1), projection)
        bottomright = sp::SpatialPoints(cbind(lon2,lat2), projection)

        # this is some juggling to define a polygon (vector format)
        # which I will convert to LCC and use as a mask to extract
        # tile numbers. As such I avoid artefacts due to resampling.
        poly_corners = matrix(NA,5,2)
        poly_corners[1,] = c(lon1,lat2)
        poly_corners[2,] = c(lon2,lat2)
        poly_corners[3,] = c(lon2,lat1)
        poly_corners[4,] = c(lon1,lat1)
        poly_corners[5,] = c(lon1,lat2)
        
        # make into a polygon object
        ROI = sp::SpatialPolygons(list(sp::Polygons(list(sp::Polygon(poly_corners)),1)))
        
        # set original projection
        sp::proj4string(ROI) = projection
        
        # extract pixels within the ROI
        r = rgeos::gIntersection(ROI,tile_outlines,byid=TRUE)
        
        if (is.null(r)){
          stop("Your defined range is outside DAYMET coverage,
               check your coordinate values!")
        }
        
        # extract tile IDs and match to DAYMET grid IDs
        polygon_nr = as.numeric(sapply(r@polygons,function(x)unlist(strsplit(x@ID,split=' '))[2])) + 1
        tiles = tile_nrs[polygon_nr]
  }
  
  # calculate the end of the range of years to download
  # conservative setting based upon the current date
  # -1 year
  max_year = as.numeric(format(Sys.time(), "%Y"))-1
  
  # check validaty of the range of years to download
  # I'm not sure when new data is released so this might be a
  # very conservative setting, remove it if you see more recent data
  # on the website
  
  if (start_yr < 1980){
    stop("Start year preceeds valid data range!")
  }
  
  if (end_yr > max_year){
    stop("End year exceeds valid data range!")
  }
  
  # if the year range is valid, create a string of valid years
  year_range = seq(start_yr,end_yr,by=1)

  # check the parameters we want to download
  if (param == "ALL"){
    param = c('vp','tmin','tmax','swe','srad','prcp','dayl')
  }

  for ( i in year_range ){
    for ( j in tiles ){
      for ( k in param ){
        
        # create download string / url  
        download_string = sprintf("https://daymet.ornl.gov/thredds/fileServer/ornldaac/1219/tiles/%s/%s_%s/%s.nc",i,j,i,k)
                
        # create filename for the output file
        daymet_file = paste(k,"_",i,"_",j,".nc",sep='')
        
        # provide some feedback
        cat(paste('Downloading DAYMET data for tile: ',j,
                  '; year: ',i,
                  '; product: ',k,
                  '\n',sep=''))
        
        # download data, force binary data mode
        try(downloader::download(download_string,
                                 daymet_file,
                                 quiet=TRUE,
                                 mode="wb"),silent=FALSE)  
      }
    }
  }
}
###########################################
# cfsv2_ts_ncdc_sqlite.r
# processes grib2 files from ncdc cfsv2 archive
# saves data to sqlite database
# saves data in rdata format
###########################################

library(data.table)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(tidyr)
library(RSQLite)
library(sqldf)

dir_scratch = '/d1/dbroman/projects/cfsv2/scratch/'
dir_gbm = '/d1/dbroman/projects/cfsv2/grib2/gbm/'
dir_gbm_proc = '/d1/dbroman/projects/cfsv2/rdata/gbm/'

setwd(dir_gbm_proc)
db = dbConnect(SQLite(), dbname = 'gbm_cfsv2.sqlite')

gbm_file_list = list.files(dir_gbm, pattern = '*.grb2')
nfiles_gbm = length(gbm_file_list)

for(i in 1:nfiles_gbm){
  gbm_file_sel = paste0(dir_gbm, gbm_file_list[i])
	system(paste0("wgrib2 ", gbm_file_sel, " -csv temp.csv"))
	tryCatch({
	fcst_dt_temp = fread('temp.csv') %>% setnames(c('date_init', 'date_fcst', 'var', 'level', 'lon', 'lat', 'value'))
	})
	var_temp = unique(fcst_dt_temp$var)
  dbWriteTable(conn = db, name = var_temp, value = fcst_dt_temp, row.names = F, append = T)
}


dir_scratch = '/d1/dbroman/projects/cfsv2/scratch/'
dir_africa = '/d1/dbroman/projects/cfsv2/grib2/africa/'
dir_africa_proc = '/d1/dbroman/projects/cfsv2/rdata/africa/'

setwd(dir_africa_proc)
db = dbConnect(SQLite(), dbname = 'africa_cfsv2.sqlite')

africa_file_list = list.files(dir_africa, pattern = '*.grb2')
nfiles_africa = length(africa_file_list)

for(i in 1:nfiles_africa){
  africa_file_sel = paste0(dir_africa, africa_file_list[i])
	system(paste0("wgrib2 ", africa_file_sel, " -csv temp.csv"))
	tryCatch({
	fcst_dt_temp = fread('temp.csv') %>% setnames(c('date_init', 'date_fcst', 'var', 'level', 'lon', 'lat', 'value'))
	})
	var_temp = unique(fcst_dt_temp$var)
  dbWriteTable(conn = db, name = var_temp, value = fcst_dt_temp, row.names = F, append = T)
}
###########################################
# cfsv2_ts_ncdc_sqlite.r
# processes grib2 files from ncdc cfsv2 archive
# saves data to sqlite database
# saves data in rdata format
###########################################

library(data.table)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(tidyr)
library(RSQLite)
library(sqldf)

dir_scratch = '/d1/dbroman/projects/cfsv2/scratch/'
dir_gbm = '/d1/dbroman/projects/cfsv2/grib2/gbm/'
dir_africa = '/d1/dbroman/projects/cfsv2/grib2/africa/'

dir_gbm_proc = '/d1/dbroman/projects/cfsv2/rdata/gbm/'
dir_africa_proc = '/d1/dbroman/projectscfsv2/rdata/africa/'

setwd(dir_gbm_proc)
db = dbConnect(SQLite(), dbname = 'gbm_cfsv2.sqlite')

gbm_file_list = list.files(dir_gbm, pattern = '*.grb2')
nfiles_gbm = length(gbm_file_list)

for(i in 1:nfiles_gbm){
  gbm_file_sel = paste0(dir_gbm, gbm_file_list[i])
	system(paste0("wgrib2 ", gbm_file_sel, " -csv temp.csv"))
	tryCatch({
	fcst_dt_temp = fread('temp.csv') %>% setnames(c('date_init', 'date_fcst', 'var', 'level', 'lon', 'lat', 'value'))
	})
	var_temp = unique(fcst_dt_temp$var)
  dbWriteTable(conn = db, name = var_temp, value = fcst_dt_temp, row.names = F, append = T)
}
# download:
https://yale.box.com/s/icu69vs2m7ygww38lor7d3laoibpfk6x

#Create a new project in the folder that has the JSTOR data.

install.packages("devtools")
install_github("agoldst/dfrtopics")
install.packages("dplyr")
install.packages("ggplot2")
install.packages("lubridate")
install.packages("stringr")
install.packages("rJava")
install.packages("mallet")



library(devtools)
options(java.parameters="-Xmx4g")
library(dfrtopics)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(rJava)
library(mallet)


data_dir <- file.path("/Users/[YOUR USERNAME HERE]/Desktop/slavic")

# First we load metadata: 

metadata_file <- file.path(data_dir, "citations.tsv")
meta <- read_dfr_metadata(metadata_file)
# 
# "The word counts can be loaded into memory all at once with read_wordcounts, 
# which takes a vector of file names."
counts <- read_wordcounts(list.files(file.path(data_dir, "wordcounts"), full.names=T))


# "Here’s how we might tabulate how many words stoplisting will remove from each document:"
stoplist_file <- file.path("stoplist-russian.txt")
stoplist <- readLines(stoplist_file)
counts <- counts %>% wordcounts_remove_stopwords(stoplist)




# "Filter infrequent words. OCR’d text in particular is littered with hapax legomena.
# The long tail of one-off features means a lot of noise for the modeling process, 
# and you’ll likely want to get rid of these.
# For example, to eliminate all but roughly the 20,000 most frequent features:"
counts <- counts %>%
  wordcounts_remove_rare(20000)
  
  
  
  
  
# "MALLET cannot accept our counts data frame from R as is. 
# Instead, it wants a data frame with one row per document, 
# which it will then tokenize once again. This is silly, but easily handled:"
docs <- wordcounts_texts(counts)



# "To create the MALLET-ready input, which is called an InstanceList, we use:"
ilist <- make_instances(docs)



#
# "Now we launch the LDA algorithm"
#
# we ran 20, 50, 100, and 150, and agreed on 100
topic_model <- train_model(ilist, n_topics=50,
                 n_iters=300,
                 seed=1,
                 threads=4,
                 metadata=meta
)
#this can take quite a long time...
write_mallet_model(topic_model, "modeling_results")




# create folder for topic browsing. note that folder name is 'browser-'+number of topics+formatted datetime
dfr_browser(topic_model, "slavic-review-browser", internalize=F)

# Type this in a terminal, not rStudio:
cd slavic-review-browser
bin/server


# to get a readout of the top N words by weight and first N topic labels, use these
# top_words(topic_model, n=10)
# topic_labels(topic_model, n=8)
#Create a new project in the folder that has the JSTOR data.

install.packages("devtools")
install_github("agoldst/dfrtopics")
install.packages("dplyr")
install.packages("ggplot2")
install.packages("lubridate")
install.packages("stringr")
install.packages("rJava")
install.packages("mallet")



library(devtools)
options(java.parameters="-Xmx4g")
library(dfrtopics)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(rJava)
library(mallet)


data_dir <- file.path("/Users/[YOUR USERNAME HERE]/Desktop/slavic")

# First we load metadata: 

metadata_file <- file.path(data_dir, "citations.tsv")
meta <- read_dfr_metadata(metadata_file)
# 
# "The word counts can be loaded into memory all at once with read_wordcounts, 
# which takes a vector of file names."
counts <- read_wordcounts(list.files(file.path(data_dir, "wordcounts"), full.names=T))


# "Here’s how we might tabulate how many words stoplisting will remove from each document:"
stoplist_file <- file.path("stoplist-russian.txt")
stoplist <- readLines(stoplist_file)
counts <- counts %>% wordcounts_remove_stopwords(stoplist)




# "Filter infrequent words. OCR’d text in particular is littered with hapax legomena.
# The long tail of one-off features means a lot of noise for the modeling process, 
# and you’ll likely want to get rid of these.
# For example, to eliminate all but roughly the 20,000 most frequent features:"
counts <- counts %>%
  wordcounts_remove_rare(20000)
  
  
  
  
  
# "MALLET cannot accept our counts data frame from R as is. 
# Instead, it wants a data frame with one row per document, 
# which it will then tokenize once again. This is silly, but easily handled:"
docs <- wordcounts_texts(counts)



# "To create the MALLET-ready input, which is called an InstanceList, we use:"
ilist <- make_instances(docs)



#
# "Now we launch the LDA algorithm"
#
# we ran 20, 50, 100, and 150, and agreed on 100
topic_model <- train_model(ilist, n_topics=50,
                 n_iters=300,
                 seed=1,
                 threads=4,
                 metadata=meta
)
#this can take quite a long time...
write_mallet_model(topic_model, "modeling_results")




# create folder for topic browsing. note that folder name is 'browser-'+number of topics+formatted datetime
dfr_browser(topic_model, "slavic-review-browser", internalize=F)

# Type this in a terminal, not rStudio:
cd slavic-review-browser
bin/server


# to get a readout of the top N words by weight and first N topic labels, use these
# top_words(topic_model, n=10)
# topic_labels(topic_model, n=8)
#Create a new project in the folder that has the JSTOR data.

install.packages("devtools")
install_github("agoldst/dfrtopics")
install.packages("dplyr")
install.packages("ggplot2")
install.packages("lubridate")
install.packages("stringr")
install.packages("rJava")
install.packages("mallet")



library(devtools)
options(java.parameters="-Xmx4g")
library(dfrtopics)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(rJava)
library(mallet)


data_dir <- file.path("/Users/[YOUR USERNAME HERE]/Desktop/slavic")

# First we load metadata: 

metadata_file <- file.path(data_dir, "citations.tsv")
meta <- read_dfr_metadata(metadata_file)
# 
# "The word counts can be loaded into memory all at once with read_wordcounts, 
# which takes a vector of file names."
counts <- read_wordcounts(list.files(file.path(data_dir, "wordcounts"), full.names=T))


# "Here’s how we might tabulate how many words stoplisting will remove from each document:"
stoplist_file <- file.path("stoplist-russian.txt")
stoplist <- readLines(stoplist_file)
counts <- counts %>% wordcounts_remove_stopwords(stoplist)




# "Filter infrequent words. OCR’d text in particular is littered with hapax legomena.
# The long tail of one-off features means a lot of noise for the modeling process, 
# and you’ll likely want to get rid of these.
# For example, to eliminate all but roughly the 20,000 most frequent features:"
counts <- counts %>%
  wordcounts_remove_rare(20000)
  
  
  
  
  
# "MALLET cannot accept our counts data frame from R as is. 
# Instead, it wants a data frame with one row per document, 
# which it will then tokenize once again. This is silly, but easily handled:"
docs <- wordcounts_texts(counts)



# "To create the MALLET-ready input, which is called an InstanceList, we use:"
ilist <- make_instances(docs)



#
# "Now we launch the LDA algorithm"
#
# we ran 20, 50, 100, and 150, and agreed on 100
topic_model <- train_model(ilist, n_topics=50,
                 n_iters=300,
                 seed=1,
                 threads=4,
                 metadata=meta
)
#this can take quite a long time...
write_mallet_model(topic_model, "modeling_results")




summary(topic_model)
# create folder for topic browsing. note that folder name is 'browser-'+number of topics+formatted datetime
dfr_browser(topic_model, "slavic-review-browser", internalize=F)

# Type this in a terminal, not rStudio:
cd slavic-review-browser
bin/server


# to get a readout of the top N words by weight and first N topic labels, use these
# top_words(topic_model, n=10)
# topic_labels(topic_model, n=8)
#Create a new project in the folder that has the JSTOR data.

install.packages("devtools")
install_github("agoldst/dfrtopics")
install.packages("dplyr")
install.packages("ggplot2")
install.packages("lubridate")
install.packages("stringr")
install.packages("rJava")
install.packages("mallet")



library(devtools)
options(java.parameters="-Xmx4g")
library(dfrtopics)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(rJava)
library(mallet)


data_dir <- file.path("/Users/[YOUR USERNAME HERE]/Desktop/slavic")

# First we load metadata: 

metadata_file <- file.path(data_dir, "citations.tsv")
meta <- read_dfr_metadata(metadata_file)
# 
# "The word counts can be loaded into memory all at once with read_wordcounts, 
# which takes a vector of file names."
counts <- read_wordcounts(list.files(file.path(data_dir, "wordcounts"), full.names=T))


# "Here’s how we might tabulate how many words stoplisting will remove from each document:"
stoplist_file <- file.path("stoplist-russian.txt")
stoplist <- readLines(stoplist_file)
counts <- counts %>% wordcounts_remove_stopwords(stoplist)




# "Filter infrequent words. OCR’d text in particular is littered with hapax legomena.
# The long tail of one-off features means a lot of noise for the modeling process, 
# and you’ll likely want to get rid of these.
# For example, to eliminate all but roughly the 20,000 most frequent features:"
counts <- counts %>%
  wordcounts_remove_rare(20000)
  
  
  
  
  
# "MALLET cannot accept our counts data frame from R as is. 
# Instead, it wants a data frame with one row per document, 
# which it will then tokenize once again. This is silly, but easily handled:"
docs <- wordcounts_texts(counts)



# "To create the MALLET-ready input, which is called an InstanceList, we use:"
ilist <- make_instances(docs)



#
# "Now we launch the LDA algorithm"
#
# we ran 20, 50, 100, and 150, and agreed on 100
topic_model <- train_model(ilist, n_topics=50,
                 n_iters=300,
                 seed=1,
                 threads=4,
                 metadata=meta
)
write_mallet_model(topic_model, "modeling_results")
summary(topic_model)
# create folder for topic browsing. note that folder name is 'browser-'+number of topics+formatted datetime
dfr_browser(topic_model, "slavic-review-browser", internalize=F)

# Type this in a terminal, not rStudio:
cd slavic-review-browser
bin/server


# to get a readout of the top N words by weight and first N topic labels, use these
# top_words(topic_model, n=10)
# topic_labels(topic_model, n=8)
Create a new project in the folder that has the JSTOR data.

install.packages("devtools")
install_github("agoldst/dfrtopics")
install.packages("dplyr")
install.packages("ggplot2")
install.packages("lubridate")
install.packages("stringr")
install.packages("rJava")
install.packages("mallet")



library(devtools)
options(java.parameters="-Xmx4g")
library(dfrtopics)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(rJava)
library(mallet)




data_dir <- file.path("/Users/trip/Coding/TextMining/Bozovic-Rosenkranz-S15/slavic-review-all-names")
# First we load metadata: it won’t be used in “vanilla” LDA modeling, 
# but it is useful to have at this stage in case we want to filter the corpus.
#
# (Using the altered metadata file where we invented the title field for the book reviews)
#
metadata_file <- file.path(data_dir, "citations.tsv")
meta <- read_dfr_metadata(metadata_file)
# 
# "The word counts can be loaded into memory all at once with read_wordcounts, 
# which takes a vector of file names."
counts <- read_wordcounts(list.files(file.path(data_dir, "wordcounts"), full.names=T))


# "Here’s how we might tabulate how many words stoplisting will remove from each document:"
stoplist_file <- file.path("stoplist-russian.txt")
stoplist <- readLines(stoplist_file)
counts <- counts %>% wordcounts_remove_stopwords(stoplist)




# "Filter infrequent words. OCR’d text in particular is littered with hapax legomena.
# The long tail of one-off features means a lot of noise for the modeling process, 
# and you’ll likely want to get rid of these.
# For example, to eliminate all but roughly the 20,000 most frequent features:"
counts <- counts %>%
  wordcounts_remove_rare(20000)
  
  
  
  
  
# "MALLET cannot accept our counts data frame from R as is. 
# Instead, it wants a data frame with one row per document, 
# which it will then tokenize once again. This is silly, but easily handled:"
docs <- wordcounts_texts(counts)



# "To create the MALLET-ready input, which is called an InstanceList, we use:"
ilist <- make_instances(docs)



#
# "Now we launch the LDA algorithm"
#
# we ran 20, 50, 100, and 150, and agreed on 100
topic_model <- train_model(ilist, n_topics=50,
                 n_iters=300,
                 seed=1,
                 threads=4,
                 metadata=meta
)
write_mallet_model(topic_model, "modeling_results")
summary(topic_model)
# create folder for topic browsing. note that folder name is 'browser-'+number of topics+formatted datetime
dfr_browser(topic_model, "slavic-review-browser", internalize=F)

# Type this in a terminal, not rStudio:
cd slavic-review-browser
bin/server


# to get a readout of the top N words by weight and first N topic labels, use these
# top_words(topic_model, n=10)
# topic_labels(topic_model, n=8)
#' Message for globals.
#'
#' Prompt the user to set globals if they have not already been
#' specified.
#'
#' @param globals The list of globals for a stain.
#'
#' @param is_submitting Is a slurm job being submitted? Default
#' value is FALSE to avoid any fatal errors.
stain_message_globals <- function(globals, is_submitting = FALSE) {
    na_globals <- globals[sapply(globals, is.na)]
    n_globals <- length(na_globals)

    if (n_globals > 0) {
        if (n_globals == 1) {
            plurality <- "global"
            demonstrative <- paste("this", plurality)
        } else {
            plurality <- "globals"
            demonstrative <- paste("these", plurality)
        }

        message(paste(length(na_globals), plurality, "to specify:"))

        for (global in names(na_globals)) {
            message(paste("\n    -", global), appendLF = FALSE)
        }

        message(paste("\n\nSet", demonstrative, "in the `globals` property of your `Stain` instance.\n"))

        if (is_submitting) {
            stop("Aborting submission.")
        }
    }
}


#' Message for source files.
#'
#' One of the source files must contain a \code{main} function and this
#' message will notify the user if none of his or her source files
#' contain a \code{main} function.
#'
#' @param source_files The list of R source files.
#'
#' @param is_submitting Is a slurm job being submitted? Default
#' value is FALSE to avoid any fatal errors.
stain_message_source_files <- function(source_files, is_submitting = FALSE) {
    file_count <- length(source_files)

    if (file_count > 0) {
        e <- new.env()

        for (file in source_files) {
            testthat::source_file(file, e)
        }

        if (is.null(e$main)) {
            if (file_count == 1) {
                plurality = paste("Your R source file doesn't")
            } else {
                plurality = paste("None of your", file_count, "R source files")
            }

            m <- paste(plurality, "contain a `main()` function.")

            if (is_submitting) {
                stop(paste(m, "Aborting submission."), call. = FALSE)
            } else {
                message(m)
            }
        }
    } else {
        message("A `Stain` object must contain at least one source file.")

        if (is_submitting) {
            stop(paste(m, "Aborting submission."), call. = FALSE)
        } else {
            message(m)
        }
    }
}


#' Message for ssh.
#'
#' Notify the user about remote host ssh requirements.
stain_message_ssh <- function() {
    cat("If your cluster is remote, add the .ssh/stain_rsa.pub key to your remote host. ")
    cat("To autogenerate the bash code, see ?stain_ssh_setup.")
}
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        get_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/"),
                                     full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$get_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                stain_ssh(user, host, submit_cmd)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        get_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/"),
                                     full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$get_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                stain_ssh(user, host, submit_cmd)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        },
        fetch_output = function(user, host, submit_dir) {
            output_dir <- paste0(basename(self$dir), "/output")
            remote_output_dir <- paste0(user, "@", host, ":", submit_dir, "/", output_dir)
            stain_scp(from = remote_output_dir,  to = self$dir)
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources,
                                       private$is_submitting)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources,
                                       private$is_submitting)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        get_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/"),
                                     full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            private$is_submitting = TRUE

            tryCatch({
                stain_message_source_files(self$get_files(TRUE)$sources,
                                           private$is_submitting)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            tryCatch({
                private$save_globals()
            }, error = function(e) {
                private$is_submitting = FALSE
                stop("A global may not have an NA value. Aborting submission.", call. = FALSE)
            })

            tryCatch({
                remote_host <- paste0(user, "@", host, ":", submit_dir)
                stain_scp(from = self$dir, to = remote_host)

                job_dir <- paste(submit_dir, basename(self$dir), sep = "/")
                submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
                stain_ssh(user, host, submit_cmd)
            }, error = function(e) {
                private$is_submitting = FALSE
                stop(e)
            })

            private$is_submitting = FALSE
        }
    ),
    private = list(
        options = NULL,
        is_submitting = FALSE,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            if (length(globals) > 0) {
                stain_message_globals(globals, private$is_submitting)
            }

            self$globals <- globals
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' Reciprocal function of base::log10
#' 
#' @param x numeric vector
#' @export
#' @keywords internal light
exp10 <- function(x) exp(x * log(10))

#' Convert Wildlife Computers light values from/to linear W/cm^2 units
#' 
#' Use the equation provided by the manufacturer, Wildlife Computers.
#' 
#' @param x raw sensor readings
#' @export
#' @keywords light
SI_light <- function(x) {
  10^((x - 250) / 20)
}

#' @rdname SI_light
#' @param x transformed sensor readings
#' @export
#' @keywords light
WC_light <- function(x) {
  20 * log10(x) + 250
}

#' BioPIC QR decomposition on a TDR sample
#' @param x A data subset of fixed width of 11 seconds/lines.
#' @param lightSI.nm The name of the TDR column with light values in W/cm^2.
#' @references 
#' Vacquié-Garcia, J., Royer, F., Dragon, A.-C., Viviant, M., Bailleul, F. 
#' & Guinet, C. (2012) Foraging in the Darkness of the Southern Ocean: 
#' Influence of Bioluminescence on a Deep Diving Predator. PLoS ONE, 7, e43565.
#' @keywords internal
#' @export
biopic.qr <- function(x, lightSI.nm = "light_si") {
  # A = QR. We use qr.solve() to find R given A and Q.
  Amat <- log10(x[ , lightSI.nm])
  # Build the Q matrix (w rows X length(R) columns)
  Qmat <- matrix(c(
    0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1,  # log(It) = log(Ia)
    1, 0, 1,                                      # log(It) = log(alpha) + log(Ia)
    1, 1, 1, 1, 2, 1, 1, 3, 1, 1, 4, 1, 1, 5, 1), # log(It) = log(alpha) -K*t + log(Ia)
    nrow = 11, byrow = TRUE)
  Rmat <- try(qr.solve(Qmat, Amat), silent = TRUE)
  if (is.error(Rmat)) {
    Rmat <-rep(NA, 3)
  } else {
    Rmat[c(1, 3)] <- exp10(Rmat[c(1, 3)])
  }
  Rmat # alpha, lessK & Ia
}

#' BioPIC: bioluminescent event detection tool
#' 
#' Adaptation of BioPIC method with 1 Hz sampling frequency datasets and 
#' of post-peak attenuation (related to sensor and not depth)
#' 
#' @param x a TDR data sample
#' @param nms The names of the output variables.
#' @inheritParams biopic.qr
#' @export
#' @keywords light
#' @references 
#' Vacquié-Garcia, J., Royer, F., Dragon, A.-C., Viviant, M., Bailleul, F. 
#' & Guinet, C. (2012) Foraging in the Darkness of the Southern Ocean: 
#' Influence of Bioluminescence on a Deep Diving Predator. PLoS ONE, 7, e43565.
#' @examples 
#' data(exses)
#' dv <- tdrply(identity, no = 100, obj = exses)[[1]]
#' dv$light_si <- SI_light(dv$light)
#' biolum_tbl <- BioPIC(dv)
BioPIC <- function(x, lightSI.nm = "light_si", nms = c("alpha", "lessK", "Ia")) {
  x[ , nms] <-  NA
  nr <- nrow(x)
  for (ii in seq(6, nr - 5)) {
    x[ii, nms] <- biopic.qr(x[seq(ii - 5, ii + 5), ], lightSI.nm)
  }
  attr(x, "biopic") <- list("lightSI.nm" = lightSI.nm, "bioPIC.nms" = nms)
  x
}

#' Identify potential bioluminescence emission events
#' 
#' @param x a data.frame such as returned by \code{\link{BioPIC}} output
#' @param sensitivity A threshold to decide if a signal peak is high enought. See 
#' details.
#' @param max_light Max light level (W/cm^2) where a event can be detected. Set to 
#' NULL to disable.
#' @details Sensor sensitivity threshold: The minimum ratio between two measures 
#' to be considered significantly different. In laboratory experiments, the 
#' sensors measured light intensity +- 2 units while submitted to a constant 
#' light intensity. Translating the sensor log-scale units to SI linear scale 
#' units this accuracy measure translates into a minimum ratio of 1.26
#' @export
#' @keywords light
#' @examples 
#' \dontrun{
#' data(exses)
#' exses$tdr$light_si <- SI_light(exses$tdr$light)
#' biolum_tbl <- tdrply(BioPIC, obj = exses)
#' ble_tbl <- Reduce(rbind, lapply(biolum_tbl, biolum_events))
#' }
biolum_events <- function(x, sensitivity = 1.26, max_light = exp(-20)) {
  # Retrieve info
  alpha <- attr(x, "biopic")$bioPIC.nms[1]
  light <- attr(x, "biopic")$lightSI.nm[1]
  
  # Increasing light periods
  is_potble <- is.finite(x[ , alpha]) & x[ , alpha] > 1 # Alpha is valid and > 1
  potble <- per(is_potble)
  potble <- potble[potble$value %in% TRUE, ]
  
  # Compute peak light ratio
  potble$st_idx <- potble$st_idx - 1
  potble$start_time  <- x[potble$st_idx, 1]
  potble$end_time    <- x[potble$ed_idx, 1]
  potble$start_light <- x[potble$st_idx, light]
  peakmax_idx <- mapply(function(st, ed) which.max(x[st:ed, light]), potble$st_idx, potble$ed_idx)
  peakmax_idx <- peakmax_idx + potble$st_idx - 1
  potble$peakmax_time  <- x[peakmax_idx, 1]
  potble$peakmax_light <- x[peakmax_idx, light]
  potble$peak_ratio <- potble$peakmax_light / potble$start_light
  
  # Filter
  cnd <- potble$peak_ratio >= sensitivity
  cnd <- "if"(is.null(max_light), cnd, cnd  & potble$peakmax_light <= max_light)
  potble[cnd, -(1:4)]
}
#SNOPSIS
#calculates genomic estimated breeding values (GEBVs) using rrBLUP,
#GBLUP method

#AUTHOR
# Isaak Y Tecle (iyt2@cornell.edu)

options(echo = FALSE)

library(rrBLUP)
library(plyr)
library(stringr)
library(lme4)
library(randomForest)
library(data.table)
#library(genetics)

allArgs <- commandArgs()

inputFiles  <- scan(grep("input_files", allArgs, ignore.case = TRUE, perl = TRUE, value = TRUE),
                   what = "character")

outputFiles <- scan(grep("output_files", allArgs, ignore.case = TRUE,perl = TRUE, value = TRUE),
                    what = "character")

traitsFile <- grep("traits", inputFiles, ignore.case = TRUE, value = TRUE)
traitFile  <- grep("trait_info", inputFiles, ignore.case = TRUE, value = TRUE)
traitInfo  <- scan(traitFile, what = "character",)
traitInfo  <- strsplit(traitInfo, "\t");
traitId    <- traitInfo[[1]]
trait      <- traitInfo[[2]]

datasetInfoFile <- grep("dataset_info", inputFiles, ignore.case = TRUE, value = TRUE)
datasetInfo     <- c()

if (length(datasetInfoFile) != 0 ) { 
    datasetInfo <- scan(datasetInfoFile, what = "character")    
    datasetInfo <- paste(datasetInfo, collapse = " ")   
  } else {   
    datasetInfo <- c('single population')  
  }

validationTrait <- paste("validation", trait, sep = "_")
validationFile  <- grep(validationTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(validationFile)) {
  stop("Validation output file is missing.")
}

kinshipTrait <- paste("kinship", trait, sep = "_")
blupFile     <- grep(kinshipTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(blupFile)) {
  stop("GEBVs file is missing.")
}
markerTrait <- paste("marker", trait, sep = "_")
markerFile  <- grep(markerTrait, outputFiles, ignore.case = TRUE, value = TRUE)

traitPhenoFile <- paste("phenotype_trait", trait, sep = "_")
traitPhenoFile <- grep(traitPhenoFile, outputFiles,ignore.case = TRUE, value = TRUE)

varianceComponentsFile <- grep("variance_components", outputFiles, ignore.case = TRUE, value = TRUE)

formattedPhenoFile <- grep("formatted_phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE)

formattedPhenoData <- c()
phenoData          <- c()

genoFile <- grep("genotype_data", inputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(genoFile)) {
  stop("genotype data file is missing.")
}

if (file.info(genoFile)$size == 0) {
  stop("genotype data file is empty.")
}

genoData <- fread(genoFile, na.strings = c("NA", " ", "--", "-"),  header = TRUE)

if (length(formattedPhenoFile) != 0 && file.info(formattedPhenoFile)$size != 0) {
  formattedPhenoData <- as.data.frame(fread(formattedPhenoFile,
                                            na.strings = c("NA", " ", "--", "-", ".")
                                            ))
      
  row.names(formattedPhenoData) <- formattedPhenoData[, 1]
  formattedPhenoData[, 1]       <- NULL    
} else {
  phenoFile <- grep("\\/phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE, perl = TRUE)

  if (is.null(phenoFile)) {
    stop("phenotype data file is missing.")
  }

  if (file.info(phenoFile)$size == 0) {
    stop("phenotype data file is empty.")
  }
  
  phenoData <- fread(phenoFile, na.strings = c("NA", " ", "--", "-", "."), header = TRUE) 
}

phenoData  <- as.data.frame(phenoData)
phenoTrait <- c()

if (datasetInfo == 'combined populations') {
  
   if (!is.null(formattedPhenoData)) {
      phenoTrait <- subset(formattedPhenoData, select = trait)
      phenoTrait <- na.omit(phenoTrait)
   
    } else {
      dropColumns <- grep(trait, names(phenoData), ignore.case = TRUE, value = TRUE)
      phenoTrait  <- phenoData[, !(names(phenoData) %in% dropColumns)]
   
      phenoTrait            <- as.data.frame(phenoTrait)
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1]       <- NULL
      colnames(phenoTrait)  <- trait
    }
   
} else {

  if (!is.null(formattedPhenoData)) {
    phenoTrait <- subset(formattedPhenoData, select = trait)
    phenoTrait <- na.omit(phenoTrait)
   
  } else {
    dropColumns <- c("uniquename", "stock_name")
    phenoData   <- phenoData[, !(names(phenoData) %in% dropColumns)]
    
    phenoTrait <- subset(phenoData, select = c("object_name", "object_id", "design", "block", "replicate", trait))
   
    experimentalDesign <- phenoTrait[2, 'design']
  
    if (class(phenoTrait[, trait]) != 'numeric') {
      phenoTrait[, trait] <- as.numeric(as.character(phenoTrait[, trait]))
    }
      
    if (is.na(experimentalDesign) == TRUE) {experimentalDesign <- c('No Design')}
    
    if ((experimentalDesign == 'Augmented' || experimentalDesign == 'RCBD')  &&  unique(phenoTrait$block) > 1) {

      message("GS experimental design: ", experimentalDesign)

      augData <- subset(phenoTrait, select = c("object_name", "object_id",  "block",  trait))

      colnames(augData)[1] <- "genotypes"
      colnames(augData)[4] <- "trait"

      model <- try(lmer(trait ~ 0 + genotypes + (1|block),
                        augData,
                        na.action = na.omit))

      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
        
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))  
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
      }
            
    } else if (experimentalDesign == 'Alpha') {
   
      message("Experimental desgin: ", experimentalDesign)
      
      alphaData <- subset(phenoData,
                            select = c("object_name", "object_id","block", "replicate", trait)
                            )
      
      colnames(alphaData)[1] <- "genotypes"
      colnames(alphaData)[5] <- "trait"
         
      model <- try(lmer(trait ~ 0 + genotypes + (1|replicate/block),
                        alphaData,
                        na.action = na.omit))
        
      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
      
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))     
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
        
      }
      
    } else {

      phenoTrait <- subset(phenoData,
                           select = c("object_name", "object_id",  trait))
       
      if (sum(is.na(phenoTrait)) > 0) {
        message("No. of pheno missing values: ", sum(is.na(phenoTrait)))      
        phenoTrait <- na.omit(phenoTrait)
      }

        #calculate mean of reps/plots of the same accession and
        #create new df with the accession means    
     
      phenoTrait   <- phenoTrait[order(row.names(phenoTrait)), ]
      phenoTrait   <- data.frame(phenoTrait)
      message('phenotyped lines before averaging: ', length(row.names(phenoTrait)))
   
      phenoTrait<-ddply(phenoTrait, "object_name", colwise(mean))
      message('phenotyped lines after averaging: ', length(row.names(phenoTrait)))
        
      phenoTrait <- subset(phenoTrait, select = c("object_name", trait))
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1] <- NULL
       
        #format all-traits population phenotype dataset
        ## formattedPhenoData <- phenoData
        ## dropColumns <- c("object_id", "stock_id", "design", "block", "replicate" )

        ## formattedPhenoData <- formattedPhenoData[, !(names(formattedPhenoData) %in% dropColumns)]
        ## formattedPhenoData <- ddply(formattedPhenoData,
        ##                             "object_name",
        ##                             colwise(mean)
        ##                             )

        ## row.names(formattedPhenoData) <- formattedPhenoData[, 1]
        ## formattedPhenoData[, 1] <- NULL

        ## formattedPhenoData <- round(formattedPhenoData,
        ##                             digits=3
        ##                             )     
    }
  }
}



#remove markers with > 60% missing marker data
message('no of markers before filtering out: ', ncol(genoData))
genoData[, which(colSums(is.na(genoData)) >= nrow(genoData) * 0.6) := NULL]
message('no of markers after filtering out 60% missing: ', ncol(genoData))

#remove indls with > 80% missing marker data
genoData[, noMissing := apply(.SD, 1, function(x) sum(is.na(x)))]
genoData <- genoData[noMissing <= ncol(genoData) * 0.8]
genoData[, noMissing := NULL]
message('no of indls after filtering out ones with 80% missing: ', nrow(genoData))

### MAF calculation ###
calculateMAF <- function(x) {
  mafThreshold <- c(0.05)
 
  a0 <-  length(x[x==0])
  a1 <-  length(x[x==1])
  a2 <-  length(x[x==2])
  aT <- a0 + a1 + a2

  message('a0: ', a0, ' a1: ', a1, ' a2:', a2, ' aT: ', aT)
  p   <- ((2*a0)+a1)/(2*aT)
  q   <- 1- p
  maf <- min(p, q)
  
  return (maf)

}

#remove monomorphic markers
#genoData[, which(apply(.SD, 2,  function(x) length(unique(x)) == 1 )) ]

#remove markers with MAF < 5%
genoData[, which(apply(genoData, 2,  calculateMAF) < 0.05) := NULL ]
message('marker no after MAF cleaning ', ncol(genoData))

genoData           <- as.data.frame(genoData)
rownames(genoData) <- genoData[, 1]
genoData[, 1]      <- NULL

predictionTempFile <- grep("prediction_population", inputFiles, ignore.case = TRUE, value = TRUE)
predictionFile     <- c()

message('prediction temp genotype file: ', predictionTempFile)

if (length(predictionTempFile) !=0 ) {
  predictionFile <- scan(predictionTempFile, what = "character")
}

message('prediction genotype file: ', predictionFile)

predictionPopGEBVsFile <- grep("prediction_pop_gebvs", outputFiles, ignore.case = TRUE, value = TRUE)
message("prediction gebv file: ",  predictionPopGEBVsFile)

predictionData <- c()

if (length(predictionFile) !=0 ) {

  predictionData <- fread(predictionFile, na.strings = c("NA", " ", "--", "-"),)
  message('selection population: no of markers before filtering out: ', ncol(genoData))
  predictionData[, which(colSums(is.na(predictionData)) >= nrow(predictionData) * 0.6) := NULL]

  #remove indls with > 80% missing marker data
  predictionData[, noMissing := apply(.SD, 1, function(x) sum(is.na(x)))]
  predictionData <- predictionData[noMissing <= ncol(predictionData) * 0.8]
  predictionData[, noMissing := NULL]
  
  predictionData[, which(apply(predictionData, 2,  calculateMAF) < 0.05) := NULL ]
  message('selection pop marker no after MAF cleaning ', ncol(preditionData))
  predictionData           <- as.data.frame(predictionData)
  rownames(predictionData) <- predictionData[, 1]
  predictionData[, 1]      <- NULL
 
}

#impute genotype values for obs with missing values,
#based on mean of neighbouring 10 (arbitrary) obs
genoDataMissing <- c()

if (sum(is.na(genoData)) > 0) {
  genoDataMissing<- c('yes')

  message("sum of geno missing values, ", sum(is.na(genoData)) )  
  genoData <- na.roughfix(genoData)
  genoData <- data.matrix(genoData)
}

genoData <- genoData[order(row.names(genoData)), ]

#create phenotype and genotype datasets with
#common stocks only
message('phenotyped lines: ', length(row.names(phenoTrait)))
message('genotyped lines: ', length(row.names(genoData)))

#extract observation lines with both
#phenotype and genotype data only.
commonObs <- intersect(row.names(phenoTrait), row.names(genoData))
commonObs <- data.frame(commonObs)
rownames(commonObs)<-commonObs[, 1]

message('lines with both genotype and phenotype data: ', length(row.names(commonObs)))

#include in the genotype dataset only observation lines
#with phenotype data
message("genotype lines before filtering for phenotyped only: ", length(row.names(genoData)))        
genoDataFiltered <- genoData[(rownames(genoData) %in% rownames(commonObs)), ]
message("genotype lines after filtering for phenotyped only: ", length(row.names(genoDataFiltered)))

#drop observation lines without genotype data
message("phenotype lines before filtering for genotyped only: ", length(row.names(phenoTrait)))        
phenoTrait <- merge(data.frame(phenoTrait), commonObs, by=0, all=FALSE)
rownames(phenoTrait) <- phenoTrait[, 1]
phenoTrait <- subset(phenoTrait, select=trait)

message("phenotype lines after filtering for genotyped only: ", length(row.names(phenoTrait)))
#a set of only observation lines with genotype data

traitPhenoData   <- data.frame(round(phenoTrait, digits = 2))           
phenoTrait       <- data.matrix(phenoTrait)
genoDataFiltered <- data.matrix(genoDataFiltered)

#impute missing data in prediction data
predictionDataMissing <- c()
if (length(predictionData) != 0) {
  #purge markers unique to both populations
  commonMarkers    <- intersect(names(data.frame(genoDataFiltered)), names(predictionData))
  predictionData   <- subset(predictionData, select = commonMarkers)
  genoDataFiltered <- subset(genoDataFiltered, select= commonMarkers)
  
 # predictionData <- data.matrix(predictionData)
 
  if (sum(is.na(predictionData)) > 0) {
    predictionDataMissing <- c('yes')
    message("sum of geno missing values, ", sum(is.na(predictionData)) )  
    predictionData <- data.matrix(na.roughfix(predictionData))
    
  }
}

relationshipMatrixFile <- grep("relationship_matrix", outputFiles, ignore.case = TRUE, value = TRUE)

message("relationship matrix file: ", relationshipMatrixFile)

relationshipMatrix <- c()
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size > 0 ) {
    relationshipDf <- as.data.frame(fread(relationshipMatrixFile))

    rownames(relationshipDf) <- relationshipDf[, 1]
    relationshipDf[, 1]      <- NULL
    relationshipMatrix       <- data.matrix(relationshipDf)
  }
}


#change genotype coding to [-1, 0, 1], to use the A.mat ) if  [0, 1, 2]
genoTrCode <- grep("2", genoDataFiltered[1, ], value = TRUE)
if(length(genoTrCode) != 0) {
  genoDataFiltered <- genoDataFiltered - 1
}

if (length(predictionData) != 0 ) {
  genoSlCode <- grep("2", predictionData[1, ], value = TRUE)
  if (length(genoSlCode) != 0 ) {
    predictionData <- predictionData - 1
  }
}

ordered.markerEffects <- c()
if ( length(predictionData) == 0 ) {
  markerEffects <- mixed.solve(y = phenoTrait,
                               Z = genoDataFiltered
                               )

  ordered.markerEffects <- data.matrix(markerEffects$u)
  ordered.markerEffects <- data.matrix(ordered.markerEffects [order (-ordered.markerEffects[, 1]), ])
  ordered.markerEffects <- round(ordered.markerEffects, digits=5)

  colnames(ordered.markerEffects) <- c("Marker Effects")

}

#additive relationship model
#calculate the inner products for
#genotypes (realized relationship matrix)
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size == 0) {
    relationshipMatrix <- tcrossprod(data.matrix(genoData))
  }
}
relationshipMatrixFiltered <- relationshipMatrix[(rownames(relationshipMatrix) %in% rownames(commonObs)),]
relationshipMatrixFiltered <- relationshipMatrixFiltered[, (colnames(relationshipMatrixFiltered) %in% rownames(commonObs))]

#construct an identity matrix for genotypes
identityMatrix <- diag(nrow(phenoTrait))

relationshipMatrixFiltered <- data.matrix(relationshipMatrixFiltered)

iGEBV  <- mixed.solve(y = phenoTrait, Z = identityMatrix, K = relationshipMatrixFiltered) 
iGEBVu <- iGEBV$u

heritability  <- c()

if ( is.null(predictionFile) == TRUE ) {
  additiveEffects <- data.frame(iGEBVu)
 
  pN <- nrow(phenoTrait)
  aN <- nrow(additiveEffects)

  if (pN <= 1 || pN != aN) {
    stop("phenoTrait and additiveEffects have different lengths: ",
         pN, " and ", aN, ".")
  }
      
  if (TRUE %in% is.na(phenoTrait) || TRUE %in% is.na(additiveEffects)) {
    stop(" Arguments phenoTrait and additiveEffects have missing values.")
  }
  
  phenoVariance <- var(phenoTrait)
  gebvVariance  <- var(additiveEffects)
  heritability  <- round((gebvVariance / phenoVariance), digits = 2)
      
  cat("\n", file = varianceComponentsFile,  append = FALSE)
  cat('Error variance', iGEBV$Ve, file = varianceComponentsFile, sep = "\t", append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Additive genetic variance',  iGEBV$Vu, file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Phenotype mean', iGEBV$beta,file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Heritability (h)', heritability, file = varianceComponentsFile, sep = '\t', append = TRUE)
}

iGEBV         <- data.matrix(iGEBVu)
ordered.iGEBV <- as.data.frame(iGEBV[order(-iGEBV[, 1]), ])
ordered.iGEBV <- round(ordered.iGEBV, digits = 3)

combinedGebvsFile <- grep('selected_traits_gebv', outputFiles, ignore.case = TRUE,value = TRUE)

allGebvs<-c()
if (length(combinedGebvsFile) != 0) {
    fileSize <- file.info(combinedGebvsFile)$size
    if (fileSize != 0 ) {
        combinedGebvs <- as.data.frame(fread(combinedGebvsFile))

        rownames(combinedGebvs) <- combinedGebvs[,1]
        combinedGebvs[,1]       <- NULL

        colnames(ordered.iGEBV) <- c(trait)
      
        traitGEBV <- as.data.frame(ordered.iGEBV)
        allGebvs <- merge(combinedGebvs, traitGEBV,
                          by = 0,
                          all = TRUE                     
                          )

        rownames(allGebvs) <- allGebvs[,1]
        allGebvs[,1] <- NULL
     }
  }

colnames(ordered.iGEBV) <- c(trait)
                  
#cross-validation
validationAll <- c()

if(is.null(predictionFile)) {
  genoNum <- nrow(phenoTrait)
if(genoNum < 20 ) {
  warning(genoNum, " is too small number of genotypes.")
}
  
reps <- round_any(genoNum, 10, f = ceiling) %/% 10

genotypeGroups <-c()

if (genoNum %% 10 == 0) {
    genotypeGroups <- rep(1:10, reps)
  } else {
    genotypeGroups <- rep(1:10, reps) [- (genoNum %% 10) ]
  }

set.seed(4567)                                   
genotypeGroups <- genotypeGroups[ order (runif(genoNum)) ]

for (i in 1:10) {
  tr <- paste("trPop", i, sep = ".")
  sl <- paste("slPop", i, sep = ".")
 
  trG <- which(genotypeGroups != i)
  slG <- which(genotypeGroups == i)
  
  assign(tr, trG)
  assign(sl, slG)

  kblup <- paste("rKblup", i, sep = ".")
  
  result <- kinship.BLUP(y = phenoTrait[trG, ],
                         G.train = genoDataFiltered[trG, ],
                         G.pred = genoDataFiltered[slG, ],                      
                         mixed.method = "REML",
                         K.method = "RR",
                         )
 
  assign(kblup, result)

#calculate cross-validation accuracy  
  valCorData <- merge(phenoTrait[slG, ], result$g.pred, by=0, all=FALSE)
  rownames(valCorData) <- valCorData[, 1]
  valCorData[, 1]      <- NULL
 
  accuracy <- try(cor(valCorData))
  validation <- paste("validation", i, sep = ".")

  cvTest <- paste("Validation test", i, sep = " ")

  if ( class(accuracy) != "try-error")
    {
      accuracy <- round(accuracy[1,2], digits = 3)
      accuracy <- data.matrix(accuracy)
    
      colnames(accuracy) <- c("correlation")
      rownames(accuracy) <- cvTest

      assign(validation, accuracy)
      
      if (!is.na(accuracy[1,1])) {
        validationAll <- rbind(validationAll, accuracy)
      }    
    }
}

validationAll <- data.matrix(validationAll[order(-validationAll[, 1]), ])
     
if (!is.null(validationAll)) {
    validationMean <- data.matrix(round(colMeans(validationAll), digits = 2))
   
    rownames(validationMean) <- c("Average")
     
    validationAll <- rbind(validationAll, validationMean)
    colnames(validationAll) <- c("Correlation")
  }
}

predictionPopResult <- c()
predictionPopGEBVs  <- c()

if (length(predictionData) != 0) {
    message("running prediction for selection candidates...marker data", ncol(predictionData), " vs. ", ncol(genoDataFiltered))

    predictionPopResult <- kinship.BLUP(y = phenoTrait,
                                        G.train = genoDataFiltered,
                                        G.pred = predictionData,
                                        mixed.method = "REML",
                                        K.method = "RR"
                                        )
 message("running prediction for selection candidates...DONE!!")

    predictionPopGEBVs <- round(data.matrix(predictionPopResult$g.pred), digits = 3)
    predictionPopGEBVs <- data.matrix(predictionPopGEBVs[order(-predictionPopGEBVs[, 1]), ])
   
    colnames(predictionPopGEBVs) <- c(trait)
  
}

if (!is.null(predictionPopGEBVs) & length(predictionPopGEBVsFile) != 0)  {
    write.table(predictionPopGEBVs,
                file = predictionPopGEBVsFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if(!is.null(validationAll)) {
    write.table(validationAll,
                file = validationFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.markerEffects)) {
    write.table(ordered.markerEffects,
                file = markerFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.iGEBV)) {
    write.table(ordered.iGEBV,
                file = blupFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (length(combinedGebvsFile) != 0 ) {
    if(file.info(combinedGebvsFile)$size == 0) {
        write.table(ordered.iGEBV,
                    file = combinedGebvsFile,
                    sep = "\t",
                    col.names = NA,
                    quote = FALSE,
                    )
      } else {
      write.table(allGebvs,
                  file = combinedGebvsFile,
                  sep = "\t",
                  quote = FALSE,
                  col.names = NA,
                  )
    }
}

if (!is.null(traitPhenoData) & length(traitPhenoFile) != 0) {
    write.table(traitPhenoData,
                file = traitPhenoFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                )
}



## if (!is.null(genoDataMissing)) {
##   write.table(genoData,
##               file = genoFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##             )

## }

## if (!is.null(predictionDataMissing)) {
##   write.table(predictionData,
##               file = predictionFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##               )
## }


if (file.info(relationshipMatrixFile)$size == 0) {
  write.table(relationshipMatrix,
              file = relationshipMatrixFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}


if (file.info(formattedPhenoFile)$size == 0 && !is.null(formattedPhenoData) ) {
  write.table(formattedPhenoData,
              file = formattedPhenoFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}

message("Done.")

q(save = "no", runLast = FALSE)
###########################################
# get_cfsv2_ncdc.r
# pulls cfsv2 forecasts from NCDC archive
# subsets to gbm and africa domains
# pulls out precip. surface temp, winds, and latent
# heat flux
###########################################

start_time = Sys.time()

## load libraries
library(stringr)
library(dplyr)
library(data.table)
library(lubridate)

date2str = function(dte){
	#dte - POSIXct date 
	year_str = year(dte)
	month_str = str_pad(month(dte), 2, pad = '0')
	day_str = str_pad(day(dte), 2, pad = '0')
	hour_str = str_pad(hour(dte), 2, pad = '0')

	paste0(year_str, month_str, day_str, hour_str)
}

## user inputs
dir_scratch = ''
dir_gbm = ''
dir_africa = ''

lims_lon_gbm = c(73, 98)
lims_lat_gbm = c(22, 32)
lims_lon_africa = c(-20, 55)
lims_lat_africa = c(-40, 40)

fcst_lead_sel = 1440
time_sel_start = as.POSIXct('2011-04-01', tz = 'utc')
time_sel_end = as.POSIXct('2011-12-31 18:00', tz = 'utc')

ncores_sel = 6

## setup
setwd(dir_scratch)

time_init_list = seq(from = time_sel_start, to = time_sel_end, by = '6 hour')
fcst_lead_list = seq(from = 6, to = fcst_lead_sel, by = 6)
nfcstlead = length(fcst_lead_list)
time_dt = data.table(time_init = rep(time_init_list, each = nfcstlead), fcst_lead = fcst_lead_list) %>% mutate(time_fcst = time_init + hours(fcst_lead))
ntimes = nrow(time_dt)

tempvar_list = rep(letters, ceiling(ntimes / 26))

## download function
get_cfs_grb = function(time_init_sel, time_fcst_sel, tempvar){
	require(data.table)
	require(dplyr)
	require(lubridate)
	require(stringr)
	require(tidyr)
	
	urlhead = 'http://nomads.ncdc.noaa.gov/modeldata/cfsv2_forecast_6-hourly_9mon_flxf/'
	
	yearinit = year(time_init_sel)
	monthinit = str_pad(month(time_init_sel), 2, pad = "0")
	dayinit = str_pad(day(time_init_sel), 2, pad = "0")
	hourinit = str_pad(hour(time_init_sel), 2, pad = "0")

	initdatefilestr = paste0(yearinit, monthinit, dayinit)
	initdatestr = paste0(yearinit, monthinit, dayinit, hourinit)
	inityrmon = paste0(yearinit, monthinit)
	
	yearfcst = year(time_fcst_sel)
	monthfcst = str_pad(month(time_fcst_sel), 2, pad = "0")
	dayfcst = str_pad(day(time_fcst_sel), 2, pad = "0")
	hourfcst = str_pad(hour(time_fcst_sel), 2, pad = "0")
	
	fcstdatestr = paste0(yearfcst, monthfcst, dayfcst, hourfcst)

	url = paste0(urlhead, yearinit, '/', inityrmon, '/', initdatefilestr, '/', initdatestr, '/flxf', fcstdatestr, '.01.', initdatestr, '.grb2')
	
	destfile_gbm = paste0(dir_gbm, fcstdatestr, '_', '01', '_', initdatestr ,'.grb2') 
	destfile_africa = paste0(dir_africa, fcstdatestr, '_', '01', '_', initdatestr ,'.grb2') 
	
	#downloads and subsets (if needed)
	if(file.exists(destfile_gbm) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		
		system(paste0("wgrib2 ", "temp_", tempvar, ".grb2", " -g2clib 0 -match ':(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):' -small_grib ", paste(lims_lon_gbm, collapse = ':'), " ", paste(lims_lat_gbm, collapse = ':'), " ", destfile_gbm), ignore.stdout = T, ignore.stderr = T)
		
		if(file.exists(destfile_africa) == F){
			system(paste0("wgrib2 ", "temp_", tempvar, ".grb2", " -g2clib 0 -match ':(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):' -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
		}
	}
	if(file.exists(destfile_africa) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		system(paste0("wgrib2 ", "temp_", tempvar, ".grb2", " -g2clib 0 -match ':(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):' -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
	}
}

## call function
cl = makeCluster(ncores_sel)
registerDoParallel(cl)
foreach (i = 1:ntimes) %dopar% {
	time_init_sel = time_dt$time_init[i]
	time_fcst_sel = time_dt$time_fcst[i]
	tempvar_sel = tempvar_list[i]
	try(get_cfs_grb(time_init_sel, time_fcst_sel, tempvar_sel))
}
stopCluster(cl)
Sys.time() - start_time
###########################################
# get_cfsv2_ts_ncdc.r
# pulls cfsv2 forecasts from NCDC timeseries archive
# subsets to gbm and africa domains
# pulls out specified forecast variables
###########################################

start_time()
## load libraries 
library(data.table)
library(dplyr)
library(ggplot2)
library(lubridate)
library(stringr)
library(tidyr)
library(doParallel)
library(foreach)

## user inputs
dir_scratch = ''
dir_gbm = ''
dir_africa = ''

lims_lon_gbm = c(73, 98)
lims_lat_gbm = c(22, 32)
lims_lon_africa = c(-20, 55)
lims_lat_africa = c(-40, 40)

fcst_lead_sel = 1440
time_sel_start = as.POSIXct('2011-04-01', tz = 'utc')
time_sel_end = as.POSIXct('2016-09-15 18:00', tz = 'utc')

var_sel = 'prate'

ncores_sel = 6

## setup
setwd(dir_scratch)

time_list = seq(from = time_sel_start, to = time_sel_end, by = '6 hour')
ntimes = length(time_list)

tempvar_list = rep(letters, ceiling(ntimes / 26))

## download function
get_cfs_ts_grb = function(var, time_init_sel, fcst_lead = 1440, tempvar){
	require(data.table)
	require(dplyr)
	require(lubridate)
	require(stringr)
	require(tidyr)
	
	urlhead = 'http://nomads.ncdc.noaa.gov/modeldata/cfsv2_forecast_ts_9mon/'
	
	yearinit = year(time_init_sel)
	monthinit = str_pad(month(time_init_sel), 2, pad = "0")
	dayinit = str_pad(day(time_init_sel), 2, pad = "0")
	hourinit = str_pad(hour(time_init_sel), 2, pad = "0")

	initdatefilestr = paste0(yearinit, monthinit, dayinit)
	initdatestr = paste0(yearinit, monthinit, daynow, hourinit)
	
	fcst_lead_list = seq(from = 6, to = fcst_lead, by = 6)
	fcst_match_list = paste(paste0(':', fcst_lead_list, ' hour fcst:'), collapse = '|')
	
	url = paste0(urlhead, yearnow, '/', paste0(yearnow, monthnow), '/', initdatefilestr, '/', initdatestr, '/', var, '.', '01', '.', initdatestr, '.daily.grb2') 
	
	destfile_gbm = paste0(dir_gbm, var, '.', initdatestr, '.', '01', '.grb2') 
	destfile_africa = paste0(dir_africa, var, '.', initdatestr, '.', '01', '.grb2') 
	
	#checks forecast lead against selected and removes file if too small
	if(file.exists(destfile_gbm) == T){
		file_meta = data.table(raw = system(paste('wgrib2', destfile_gbm, '-ftime'), intern = T)) %>% separate(raw, sep = c(':'), into = c('id', 'ref', 'hour')) %>% separate(hour, sep = ' ', into = c('hour', 'lab1', 'lab2'))
		file_max_hour = max(as.numeric(file_meta$hour))
		if(file_max_hour < fcst_lead){
			system(paste("rm", destfile_gbm))
		}
	}
	if(file.exists(destfile_africa) == T){
		file_meta = data.table(raw = system(paste('wgrib2', destfile_africa, '-ftime'), intern = T)) %>% separate(raw, sep = c(':'), into = c('id', 'ref', 'hour')) %>% separate(hour, sep = ' ', into = c('hour', 'lab1', 'lab2'))
		file_max_hour = max(as.numeric(file_meta$hour))
		if(file_max_hour < fcst_lead){
			system(paste("rm", destfile_africa))
		}
	}

	#downloads and subsets (if needed)
	if(file.exists(destfile_gbm) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match '", fcst_match_list, "' -g2clib 0 -small_grib ", paste(lims_lon_gbm, collapse = ':'), " ", paste(lims_lat_gbm, collapse = ':'), " ", destfile_gbm), ignore.stdout = T, ignore.stderr = T)
		if(file.exists(destfile_africa) == F){
			system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match '", fcst_match_list, "' -g2clib 0 -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
		}
	}
	if(file.exists(destfile_africa) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match '", fcst_match_list, "' -g2clib 0 -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
	}
}

## call function 
cl = makeCluster(ncores_sel)
registerDoParallel(cl)
foreach (i = 1:ntimes) %dopar% {
	time_init_sel = time_list[i]
	tempvar_sel = tempvar_list[i]
	try(get_cfs_ts_grb(var_sel, time_init_sel, fcst_lead_sel, tempvar_sel))
}
stopCluster(cl)
Sys.time() - start_time
###########################################
# get_cfsv2_ncdc.r
# pulls cfsv2 forecasts from NCDC archive
# subsets to gbm and africa domains
# pulls out precip. surface temp, winds, and latent
# heat flux
###########################################

start_time = Sys.time()

## load libraries
library(stringr)
library(dplyr)
library(data.table)
library(lubridate)

date2str = function(dte){
	#dte - POSIXct date 
	year_str = year(dte)
	month_str = str_pad(month(dte), 2, pad = '0')
	day_str = str_pad(day(dte), 2, pad = '0')
	hour_str = str_pad(hour(dte), 2, pad = '0')

	paste0(year_str, month_str, day_str, hour_str)
}

## user inputs
savdir_scratch = ''
savdir_gbm = ''
savdir_africa = ''

dir_scratch = ''
dir_gbm = ''
dir_africa = ''

lims_lon_gbm = c(73, 98)
lims_lat_gbm = c(22, 32)
lims_lon_africa = c(-20, 55)
lims_lat_africa = c(-40, 40)

fcst_lead_sel = 1440
time_sel_start = as.POSIXct('2011-04-01', tz = 'utc')
time_sel_end = as.POSIXct('2011-12-31 18:00', tz = 'utc')

ncores_sel = 6

## setup
setwd(dir_scratch)

time_init_list = seq(from = time_sel_start, to = time_sel_end, by = '6 hour')
fcst_lead_list = seq(from = 6, to = fcst_lead_sel, by = 6)
nfcstlead = length(fcst_lead_list)
time_dt = data.table(time_init = rep(time_init_list, each = nfcstlead), fcst_lead = fcst_lead_list) %>% mutate(time_fcst = time_init + hours(fcst_lead))
ntimes = nrow(time_dt)

tempvar_list = rep(letters, ceiling(ntimes / 26))

## download function
get_cfs_grb = function(time_init_sel, time_fcst_sel, tempvar){
	require(data.table)
	require(dplyr)
	require(lubridate)
	require(stringr)
	require(tidyr)
	
	urlhead = 'http://nomads.ncdc.noaa.gov/modeldata/cfsv2_forecast_6-hourly_9mon_flxf/'
	
	yearinit = year(time_init_sel)
	monthinit = str_pad(month(time_init_sel), 2, pad = "0")
	dayinit = str_pad(day(time_init_sel), 2, pad = "0")
	hourinit = str_pad(hour(time_init_sel), 2, pad = "0")

	initdatefilestr = paste0(yearinit, monthinit, dayinit)
	initdatestr = paste0(yearinit, monthinit, daynow, hourinit)
	
	yeafcstr = year(time_fcst_sel)
	monthfcst = str_pad(month(time_fcst_sel), 2, pad = "0")
	dayfcst = str_pad(day(time_fcst_sel), 2, pad = "0")
	hourfcst = str_pad(hour(time_fcst_sel), 2, pad = "0")

	fcstdatestr = date2str(check_tbl[i, ]$fcst_date)

	url = paste0(urlhead, inityr, '/', inityrmon, '/', initdatefilestr, '/', initdatestr, '/flxf', fcstdatestr, '.01.', initdatestr, '.grb2')
	
	destfile_gbm = paste0(dir_gbm, fcstdatestr, '_', '01', '_', initdatestr ,'.grb2') 
	destfile_africa = paste0(dir_africa, fcstdatestr, '_', '01', '_', initdatestr ,'.grb2') 
	
	#downloads and subsets (if needed)
	if(file.exists(destfile_gbm) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		
		system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match ":(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):" -small_grib ", paste(lims_lon_gbm, collapse = ':'), " ", paste(lims_lat_gbm, collapse = ':'), " ", destfile_gbm), ignore.stdout = T, ignore.stderr = T)
		
		system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match '", fcst_match_list, "' -g2clib 0 -small_grib ", paste(lims_lon_gbm, collapse = ':'), " ", paste(lims_lat_gbm, collapse = ':'), " ", destfile_gbm), ignore.stdout = T, ignore.stderr = T)
		if(file.exists(destfile_africa) == F){
			system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match ":(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):" -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
		}
	}
	if(file.exists(destfile_africa) == F){
		download.file(url, paste0('temp_', tempvar, '.grb2'), mode = 'wb')
		system(paste0('wgrib2 ', 'temp_', tempvar, '.grb2'," -match ":(TMP:2 m above ground|PRATE|CPRAT|LHTFL|UGRD:10 m above ground|VGRD:10 m above ground):" -small_grib ", paste(lims_lon_africa, collapse = ':'), " ", paste(lims_lat_africa, collapse = ':'), " ", destfile_africa), ignore.stdout = T, ignore.stderr = T)
	}
}

## call function
cl = makeCluster(ncores_sel)
registerDoParallel(cl)
foreach (i = 1:ntimes) %dopar% {
	time_init_sel = time_dt$time_init[i]
	time_fcst_sel = time_dt$time_fcst[i]
	tempvar_sel = tempvar_list[i]
	try(get_cfs_grb(time_init_sel, fcst_lead_sel, tempvar_sel))
}
stopCluster(cl)
Sys.time() - start_time
#' Message for globals.
#'
#' Prompt the user to set globals if they have not already been
#' specified.
#'
#' @param globals The list of globals for a stain.
#'
#' @param is_submitting Is a slurm job being submitted? Default
#' value is FALSE to avoid any fatal errors.
stain_message_globals <- function(globals, is_submitting = FALSE) {
    na_globals <- globals[sapply(globals, is.na)]
    n_globals <- length(na_globals)

    if (n_globals > 0) {
        if (n_globals == 1) {
            plurality <- "global"
            demonstrative <- paste("this", plurality)
        } else {
            plurality <- "globals"
            demonstrative <- paste("these", plurality)
        }

        message(paste(length(na_globals), plurality, "to specify:"))

        for (global in names(na_globals)) {
            message(paste("\n    -", global))
        }

        message(paste("\nSet", demonstrative, "in the `globals` property of your `Stain` instance.\n"))

        if (is_submitting) {
            stop("Aborting submission.")
        }
    }
}


#' Message for source files.
#'
#' One of the source files must contain a \code{main} function and this
#' message will notify the user if none of his or her source files
#' contain a \code{main} function.
#'
#' @param source_files The list of R source files.
#'
#' @param is_submitting Is a slurm job being submitted? Default
#' value is FALSE to avoid any fatal errors.
stain_message_source_files <- function(source_files, is_submitting = FALSE) {
    file_count <- length(source_files)

    if (file_count > 0) {
        e <- new.env()

        for (file in source_files) {
            testthat::source_file(file, e)
        }

        if (is.null(e$main)) {
            if (file_count == 1) {
                plurality = paste("Your R source file doesn't")
            } else {
                plurality = paste("None of your", file_count, "R source files")
            }

            m <- paste(plurality, "contain a `main()` function.")

            if (is_submitting) {
                stop(paste(m, "Aborting submission."), call. = FALSE)
            } else {
                message(m)
            }
        }
    } else {
        message("A `Stain` object must contain at least one source file.")

        if (is_submitting) {
            stop(paste(m, "Aborting submission."), call. = FALSE)
        } else {
            message(m)
        }
    }
}


#' Message for ssh.
#'
#' Notify the user about remote host ssh requirements.
stain_message_ssh <- function() {
    cat("If your cluster is remote, add the .ssh/stain_rsa.pub key to your remote host. ")
    cat("To autogenerate the bash code, see ?stain_ssh_setup.")
}
#' Message for globals.
#'
#' Prompt the user to set globals if they have not already been
#' specified.
#'
#' @param globals The list of globals for a stain.
#'
#' @param is_submitting Is a slurm job being submitted? Default
#' value is FALSE to avoid any fatal errors.
stain_message_globals <- function(globals, is_submitting = FALSE) {
    na_globals <- globals[sapply(globals, is.na)]
    n_globals <- length(na_globals)

    if (n_globals > 0) {
        if (n_globals == 1) {
            plurality <- "global"
            demonstrative <- paste("this", plurality)
        } else {
            plurality <- "globals"
            demonstrative <- paste("these", plurality)
        }

        cat(paste(length(na_globals), plurality, "to specify:"))

        for (global in names(na_globals)) {
            cat(paste("\n    -", global))
        }

        cat(paste("\n\nSet", demonstrative, "in the `globals` property of your `Stain` instance.\n"))

        if (is_submitting) {
            stop("Aborting submission.")
        }
    }
}


#' Message for source files.
#'
#' One of the source files must contain a \code{main} function and this
#' message will notify the user if none of his or her source files
#' contain a \code{main} function.
#'
#' @param source_files The list of R source files.
#'
#' @param is_submitting Is a slurm job being submitted? Default
#' value is FALSE to avoid any fatal errors.
stain_message_source_files <- function(source_files, is_submitting = FALSE) {
    file_count <- length(source_files)

    if (file_count > 0) {
        e <- new.env()

        for (file in source_files) {
            testthat::source_file(file, e)
        }

        if (is.null(e$main)) {
            if (file_count == 1) {
                plurality = paste("Your R source file doesn't")
            } else {
                plurality = paste("None of your", file_count, "R source files")
            }

            cat(paste(plurality, "contain a `main()` function."))

            if (is_submitting) {
                stop("Aborting submission.")
            }
        }
    } else {
        cat("A `Stain` object must contain at least one source file.")

        if (is_submitting) {
            stop("Aborting submission.")
        }
    }
}


#' Message for ssh.
#'
#' Notify the user about remote host ssh requirements.
stain_message_ssh <- function() {
    cat("If your cluster is remote, add the .ssh/stain_rsa.pub key to your remote host. ")
    cat("To autogenerate the bash code, see ?stain_ssh_setup.")
}
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted because TRUE must be passed to `delete`.")
            }
        },
        get_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/"),
                                     full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        },
        submit = function(user, host, submit_dir) {
            stain_scp(user, host, self$dir, submit_dir)

            job_dir <- paste(submit_dir, self$dir, sep = "/")
            submit_cmd <- paste("cd", job_dir, "&& sbatch submit.slurm")
            stain_ssh(user, host, submit_cmd)
        }
    ),
    private = list(
        options = NULL,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            stain_message_globals(globals)

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' Message for globals.
#'
#' Prompt the user to set globals if they have not already been
#' specified.
#'
#' @param globals The list of globals for a stain.
stain_message_globals <- function(globals) {
    na_globals <- sapply(globals, is.na)
    n_globals <- length(na_globals)

    if (n_globals != 0) {
        na <- globals[na_globals]

        if (n_globals == 1) {
            plurality <- "global"
            demonstrative <- paste("this", plurality)
        } else {
            plurality <- "globals"
            demonstrative <- paste("these", plurality)
        }

        cat(paste(length(na_globals), plurality, "to specify:"))

        for (global in names(na_globals)) {
            cat(paste("\n    -", global))
        }

        cat(paste("\n\nSet", demonstrative, "in the `globals` property of your `Stain` instance."))
    }
}


#' Message for source files.
#'
#' One of the source files must contain a \code{main} function and this
#' message will notify the user if none of his or her source files
#' contain a \code{main} function.
#'
#' @param source_files The list of R source files.
stain_message_source_files <- function(source_files) {
    file_count <- length(source_files)

    if (file_count > 0) {
        e <- new.env()

        for (file in source_files) {
            testthat::source_file(file, e)
        }

        if (is.null(e$main)) {
            if (file_count == 1) {
                plurality = paste("Your R source file doesn't")
            } else {
                plurality = paste("None of your", file_count, "R source files")
            }

            cat(paste(plurality, "contain a `main()` function."))
        }
    } else {
        cat("A `Stain` object must contain at least one source file.")
    }
}


#' Message for ssh.
#'
#' Notify the user about remote host ssh requirements.
stain_message_ssh <- function() {
    cat("If your cluster is remote, add the .ssh/stain_rsa.pub key to your remote host. ")
    cat("To autogenerate the bash code, see ?stain_ssh_setup.")
}
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename1 = 'catalog_predictions2'
filename2 = 'catalog_predictions3'
filename3 = 'catalog_predictions4'


catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions2 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename1)

catalog_predictions3 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(30,50,70),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename2)

catalog_predictions4 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(60,80,90),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename3)



# Catalog vs predictions
load("./Analyses/catalog_predictions0.RData")
catalog_predictions0 <- Tanimoto_analysis
load("./Analyses/catalog_predictions1.RData")
catalog_predictions1 <- Tanimoto_analysis
load("./Analyses/catalog_predictions2.RData")
catalog_predictions2 <- Tanimoto_analysis
load("./Analyses/catalog_predictions3.RData")
catalog_predictions3 <- Tanimoto_analysis
load("./Analyses/catalog_predictions4.RData")
catalog_predictions4 <- Tanimoto_analysis

accuracy <- accuracy0 <- accuracy1 <- accuracy2 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) <- names(accuracy2) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy2[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, empirical.only = TRUE)
accuracy2[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, predict.only = TRUE)
accuracy2[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3)

accuracy3[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions4, empirical.only = TRUE)
accuracy3[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions4, predict.only = TRUE)
accuracy3[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions4)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]], accuracy2[[1]], accuracy3[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]], accuracy2[[2]], accuracy3[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]], accuracy2[[3]], accuracy3[[3]])

percent_remove = c(0,10,20,30,40,50,60,70,80,90,100)
nb_iter = 50
K.values = 8
MW = 1
WT =  c(0.5,1)
minimum_threshold = 0.3

nb.pts <- length(percent_remove)

#Figure version 1
pdf(paste('./Article/','catalog_predictions','.pdf',sep=''),width=6,height=8)
j = 14 #'Score'[y]
        eplot(xmin = -1, xmax = 100 + 1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        col <- c("#FF8822",'#5ED275','#9CCBFF')
        col2 <- c("#FF8822",'#275A31','#0077FF')
        col3 <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.05)
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.05 + 2.5)
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)
            mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            mtext(text = expression(paste("Percent of taxa removed from ", italic(S0), ' (%)')), side = 1, line = 2, at = 50, font = 2, cex = 1)
            mtext(text = seq(0, 100, by = 10), side = 1, line = 0, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            mtext(text = seq(0, 100, by = 10), side = 3, line = -0.5, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            text(x = 5, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col3[1], adj = 0)
            text(x = 5, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col3[2], adj = 0)
            text(x = 5, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col3[3], adj = 0)


        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            points(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it, cex = 0.5, pch = 1, col = col[i])
            points(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it, cex = 0.5, pch = 1, col = col2[i])

            lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it), col = col[i])
            lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it), col = col2[i])

            if(i == 2 || i == 3) {
                text(x = 90, y = 0.9 + it, labels = expression(paste(italic('w'[t]), ' = 0.5')), col = col[i], font = 1, cex = 0.75)
                text(x = 90, y = 0.8 + it, labels = expression(paste(italic('w'[t]), ' = 1')), col = col2[i], font = 1, cex = 0.75)
            }

            it <- it + 1.25
        } #i
dev.off()

#Figure version 2
pdf(paste('./Article/','catalog_predictions2','.pdf',sep=''),width=6,height=8)
j = 14 #'Score'[y]
        eplot(xmin = -1, xmax = 100 + 1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        col <- c("#FF8822",'#5ED275','#9CCBFF')
        col2 <- c("#FF8822",'#275A31','#0077FF')
        col3 <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.05)
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.05 + 2.5)
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)
            mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            mtext(text = expression(paste("Percent of taxa removed from ", italic(S0), ' (%)')), side = 1, line = 2, at = 50, font = 2, cex = 1)
            mtext(text = expression(paste("Percent of ",italic(S1)," taxa in ", italic(S0), ' (%)')), side = 3, line = 1, at = 50, font = 2, cex = 1)
            mtext(text = seq(0, 100, by = 10), side = 1, line = 0, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            mtext(text = seq(100, 0, by = -10), side = 3, line = -0.5, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            text(x = 5, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col3[1], adj = 0)
            text(x = 5, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col3[2], adj = 0)
            text(x = 5, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col3[3], adj = 0)


        it <- 0
        for(i in 1:length(accuracy)) {
            if(i == 2 || i == 3) {
                accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'pc_rm']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
                # hack: we draw arrows but with very special "arrowheads" for error bars

                arrows(seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][,1] - accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 2]+it, seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 1] + accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
                points(x = seq(0,100,by=10), y = accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])

                arrows(seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][,1] - accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 2]+it, seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 1] + accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 2]+it, length=0.025, angle=90, code=3, col = col2[i])
                points(x = seq(0,100,by=10), y = accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 1]+it, cex = 0.75, pch = 22, col = col2[i])

                lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it), col = col[i])
                lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it), col = col2[i])

                text(x = 90, y = 0.9 + it, labels = expression(paste(italic('w'[t]), ' = 0.5')), col = col[i], font = 1, cex = 0.75)
                text(x = 90, y = 0.8 + it, labels = expression(paste(italic('w'[t]), ' = 1')), col = col2[i], font = 1, cex = 0.75)
                } else {
                    accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'pc_rm']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                    accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
                    # hack: we draw arrows but with very special "arrowheads" for error bars

                    arrows(seq(0,100,by=10), accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2]+it, seq(0,100,by=10), accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2]+it, length=0.025, angle=90, code=3, col = col3[i])
                    points(x = seq(0,100,by=10), y = accuracy_mean[, 2][, 1]+it, cex = 0.75, pch = 22, col = col3[i])

                    lines(lowess(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it), col = col3[i])
                }

            it <- it + 1.25
        } #i
dev.off()
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename1 = 'catalog_predictions2'
filename2 = 'catalog_predictions3'


catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions2 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40,60,80),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename1)

catalog_predictions3 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(30,50,70,90),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename2)


# Catalog vs predictions

accuracy <- accuracy0 <- accuracy1 <- accuracy2 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) <- names(accuracy2) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy2[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, empirical.only = TRUE)
accuracy2[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, predict.only = TRUE)
accuracy2[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]], accuracy2[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]], accuracy2[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]], accuracy2[[3]])

percent_remove = c(0,10,20,30,40,50,60,70,80,90,100)
nb_iter = 50
K.values = 8
MW = 1
WT =  c(0.5,1)
minimum_threshold = 0.3

nb.pts <- length(percent_remove)

#Figure version 1
pdf(paste('./Article/','catalog_predictions','.pdf',sep=''),width=6,height=8)
j = 14 #'Score'[y]
        eplot(xmin = -1, xmax = 100 + 1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        col <- c("#FF8822",'#5ED275','#9CCBFF')
        col2 <- c("#FF8822",'#275A31','#0077FF')
        col3 <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.05)
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.05 + 2.5)
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)
            mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            mtext(text = expression(paste("Percent of taxa removed from ", italic(S0), ' (%)')), side = 1, line = 2, at = 50, font = 2, cex = 1)
            mtext(text = seq(0, 100, by = 10), side = 1, line = 0, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            mtext(text = seq(0, 100, by = 10), side = 3, line = -0.5, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            text(x = 5, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col3[1], adj = 0)
            text(x = 5, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col3[2], adj = 0)
            text(x = 5, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col3[3], adj = 0)


        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            points(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it, cex = 0.5, pch = 1, col = col[i])
            points(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it, cex = 0.5, pch = 1, col = col2[i])

            lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it), col = col[i])
            lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it), col = col2[i])

            if(i == 2 || i == 3) {
                text(x = 90, y = 0.9 + it, labels = expression(paste(italic('w'[t]), ' = 0.5')), col = col[i], font = 1, cex = 0.75)
                text(x = 90, y = 0.8 + it, labels = expression(paste(italic('w'[t]), ' = 1')), col = col2[i], font = 1, cex = 0.75)
            }

            it <- it + 1.25
        } #i
dev.off()

#Figure version 2
pdf(paste('./Article/','catalog_predictions2','.pdf',sep=''),width=6,height=8)
j = 14 #'Score'[y]
        eplot(xmin = -1, xmax = 100 + 1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        col <- c("#FF8822",'#5ED275','#9CCBFF')
        col2 <- c("#FF8822",'#275A31','#0077FF')
        col3 <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.05)
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.05 + 2.5)
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)
            mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            mtext(text = expression(paste("Percent of taxa removed from ", italic(S0), ' (%)')), side = 1, line = 2, at = 50, font = 2, cex = 1)
            mtext(text = expression(paste("Percent of ",italic(S1)," taxa in ", italic(S0), ' (%)')), side = 3, line = 1, at = 50, font = 2, cex = 1)
            mtext(text = seq(0, 100, by = 10), side = 1, line = 0, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            mtext(text = seq(100, 0, by = -10), side = 3, line = -0.5, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            text(x = 5, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col3[1], adj = 0)
            text(x = 5, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col3[2], adj = 0)
            text(x = 5, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col3[3], adj = 0)


        it <- 0
        for(i in 1:length(accuracy)) {
            if(i == 2 || i == 3) {
                accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'pc_rm']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
                # hack: we draw arrows but with very special "arrowheads" for error bars

                arrows(seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][,1] - accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 2]+it, seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 1] + accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
                points(x = seq(0,100,by=10), y = accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])

                arrows(seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][,1] - accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 2]+it, seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 1] + accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 2]+it, length=0.025, angle=90, code=3, col = col2[i])
                points(x = seq(0,100,by=10), y = accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 1]+it, cex = 0.75, pch = 22, col = col2[i])

                lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it), col = col[i])
                lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it), col = col2[i])

                text(x = 90, y = 0.9 + it, labels = expression(paste(italic('w'[t]), ' = 0.5')), col = col[i], font = 1, cex = 0.75)
                text(x = 90, y = 0.8 + it, labels = expression(paste(italic('w'[t]), ' = 1')), col = col2[i], font = 1, cex = 0.75)
                } else {
                    accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'pc_rm']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                    accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
                    # hack: we draw arrows but with very special "arrowheads" for error bars

                    arrows(seq(0,100,by=10), accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2]+it, seq(0,100,by=10), accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2]+it, length=0.025, angle=90, code=3, col = col3[i])
                    points(x = seq(0,100,by=10), y = accuracy_mean[, 2][, 1]+it, cex = 0.75, pch = 22, col = col3[i])

                    lines(lowess(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it), col = col3[i])
                }

            it <- it + 1.25
        } #i
dev.off()
#Solve for optimal lobby effort under DGH97-style model with obj fcn W + e

#reserve space for loop output
tau = seq(0.001,.166,0.001) #this will be counter variable in loop
PSx = matrix(NA,length(tau),1)
CSx = matrix(NA,length(tau),1)
TR = matrix(NA,length(tau),1)
PSy = matrix(NA,length(tau),1)
CSy = matrix(NA,length(tau),1)

#calculate producer surplus, consumer surplus, tariff revenue for each possible
#value of the tariff on the grid (just above zero to prohibitive tariff 1/6)
for (j in 1:length(tau)) {
  t = tau[j]

  PSx[j] = ((2 +2*t)^2)/49
  CSx[j] = .5*((3 -4*t)^2)/49
  TR[j] = (t - 6*t^2)/7
  CSy[j] = ((3 +3*t)^2)/98
  PSy[j] = ((4 -3*t)^2)/98
}

#Calculations for when lobby has all the bargaining power

#calculate government welfare when tau = 0 (baseline)
b = ((2 +2*0)^2)/49 + .5*((3 -4*0)^2)/49 + (0 - 6*0^2)/7 + ((3 +3*0)^2)/98 + ((4 -3*0)^2)/98
W = PSx + CSx + TR + CSy + PSy  #social welfare
e = ((b - W)/PSx)^5             #gov't indifference condition when WG = W + e
pi = PSx - e                    #net profits

value = max(pi) #the value at which profits are maximized (over non-negative values)
ind = which.max(pi) #the location at which profits are maximized
RC = arrayInd(ind,c(dim(pi),dim(pi))) #row/column version of maximand location


#Calculations for when government has all the bargaining power
bl = ((2 +2*0)^2)/49           #baseline for lobby: profits when tau = 0
e = PSx - bl                   #effort level giving all excess profits over tau=0 to gov't

g = e^.9*PSx                   #little g(e) function to add to social welfare
G = W + e^.9*PSx               #gov't welfare a la DGH97
plot(G)

value = max(G) #the value at which profits are maximized (over non-negative values)
ind = which.max(G) #the location at which profits are maximized
RC = arrayInd(ind,c(dim(G),dim(G))) #row/column version of maximand locationlibrary(DiagrammeR)
grViz("

digraph boxes_and_circles{

    node [shape = box
            # fixedsize = TRUE
            # width = 2.5
            ]
            1 [label = <<B>S1) </B>I(<I>T<sub><font point-size='8'>C</font></sub>,T<sub><font point-size='8'>R</font></sub></I>) in <I>S0</I>?>]
            2 [label = <<B>S2) </B><I>T<sub><font point-size='8'>R </font></sub></I> in <I>S1</I>?>]
            3 [label = <<B>S3) </B>Add <I>T<sub><font point-size='8'>R </font></sub></I> to<br/>predictions>]
            4 [label = <<B>S4) </B><I>K </I> most similar<br/>resource <I>T<sub><font point-size='8'>R&apos;</font></sub></I> in <I>S1</I>>]
            5 [label = <<B>S5) </B><I>T<sub><font point-size='8'>R&apos; </font></sub></I> in <I>C<SUB><font point-size='8'>R</font></SUB></I>?>]
            6 [label = <<B>S6) </B>Add weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I><br/>to <I>T<sub><font point-size='8'>R&apos; </font></sub></I>in <I>C<SUB><font point-size='8'>R </font></SUB></I> if<br/><I>t </I> &gt; minimum threshold>]
            7 [label = <<B>S7) </B>Add <I>T<sub><font point-size='8'>R&apos; </font></sub></I>to <I>C<SUB><font point-size='8'>R </font></SUB></I> with<br/>weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I> if<br/><I>t </I> &gt; minimum threshold>]
            8 [label = <<B>S8) </B><I>K </I> most similar<br/>consumer <I>T<sub><font point-size='8'>C&apos;</font></sub></I>>]
            9 [label = <<B>S9) </B><I>T<sub><font point-size='8'>R </font></sub></I>in <I>S1</I>?>]
            10 [label = <<B>S10) </B><I>T<sub><font point-size='8'>R </font></sub></I>in <I>C<SUB><font point-size='8'>R</font></SUB></I>?>]
            11 [label = <<B>S11) </B>Add 1 to <I>T<sub><font point-size='8'>R </font></sub></I><br/>weight in <I>C<SUB><font point-size='8'>R</font></SUB></I>>]
            12 [label = <<B>S12) </B>Add <I>T<sub><font point-size='8'>R </font></sub></I>to <I>C<SUB><font point-size='8'>R </font></SUB></I><br/>with weight = 1>]
            13 [label = <<B>S13) </B><I>K </I> most similar<br/>resource <I>T<sub><font point-size='8'>R&apos; </font></sub></I>in <I>S1</I>>]
            14 [label = <<B>S14) </B><I>T<sub><font point-size='8'>R&apos; </font></sub></I>in <I>C<SUB><font point-size='8'>R</font></SUB></I>?>]
            15 [label = <<B>S15) </B>Add weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I><br/>to <I>T<sub><font point-size='8'>R&apos; </font></sub></I>in <I>C<SUB><font point-size='8'>R </font></SUB></I>if<br/><I>t </I> &gt; minimum threshold>]
            16 [label = <<B>S16) </B>Add <I>T<sub><font point-size='8'>R&apos; </font></sub></I>to <I>C<SUB><font point-size='8'>R </font></SUB></I>with<br/> weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I> if<br/><I>t </I> &gt; minimum threshold>]
            17 [label = <<B>S17) </B>Add <I>T<sub><font point-size='8'>R </font></sub></I>or <I>T<sub><font point-size='8'>R&apos; </font></sub></I>to predictions if weight &gt; minimum weight>]

1 -> 2 [label = 'Yes', headport = 'n', tailport = 'w']
1 -> 3 [color = 'transparent']
1 -> 4 [color = 'transparent']
1 -> 5 [color = 'transparent']
1 -> 6 [color = 'transparent']
1 -> 7 [color = 'transparent']
1 -> 8 [color = 'transparent']
2 -> 3 [label = 'Yes']
2 -> 4 [label = 'No']
4 -> 5
5 -> 6 [label = 'Yes']
5 -> 7 [label = 'No']
6 -> 17
7 -> 17
1 -> 8 [tailport = 'e']
8 -> 9
9 -> 10 [label = 'Yes']
10 -> 11 [label = 'Yes']
10 -> 12 [label = 'No']
11 -> 17
12 -> 17
9 -> 13 [label = 'No']
13 -> 14
14 -> 15 [label = 'Yes']
14 -> 16 [label = 'No']
15 -> 17
16 -> 17

graph [ranksep = 0.15
        rank = sink
        # rankdir = LR
        # splines = ortho
        ]


}
")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2.8 Example with southern St. Lawrence EwE model for mid-1980s
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "./RawData/South_St_Lawrence_EwE.RData"
#   Script  <- file = "Script/2-8_St_Lawrence_ex.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REFERENCE:
#   Savenkoff, to add
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
library(stringr)
load("./RawData/South_St_Lawrence_EwE.RData")
SSL <- South_St_Lawrence

SSL[[2]][which(SSL[[2]] > 0)] <- 1
rownames(SSL[[2]]) <- colnames(SSL[[2]]) <- SSL[[3]]

sp_SSL <- matrix(ncol = 3, nrow = 29, data = NA, dimnames = list(c(), c('ACCR','SP','FG')))

sp_SSL[,1] <- c('WHA','HAS','HOS','GRS','HSE','SEA','LCO','SCO','LGH','SAP','LAP','FLO','SKA','RED','LDF','SDF','CAP','LPF','PISF','PLSF','SHR','LCRU','ECH','MOL','POL','OBI','LZOO','SZOO','PHY')

sp_SSL[,3] <- c('Cetaceans',
'Harp seals',
'Hooded seals',
'Grey seals',
'Harbour seals',
'Seabirds',
'Atlantic cod',
'Atlantic cod',
'Greenland halibut',
'American plaice',
'American plaice',
'Flounders',
'Skates',
'Redfish',
'Large demersal feeders',
'Small demersal feeders',
'Capelin',
'Large pelagic feeders',
'Piscivorous small pelagic feeders',
'Planktivorous small pelagic feeders',
'Shrimp',
'Large crustaceans',
'Echinoderms',
'Molluscs',
'Polychates',
'Other benthic invertebrates',
'Large zooplankton',
'Small zooplankton',
'Phytoplankton')



sp_SSL[,2] <- c('Balaenoptera physalus - Balaenoptera acutorostrata - Megaptera novaeangliae - Phocoena phocoena - Lagenorhynchus acutus - Lagenorhynchus albirostris',
'Pagophilus groenlandicus',
'Cystophora cristata',
'Halichoerus grypus',
'Phoca vitulina',
'Phalacrocorax carbo - Phalacrocorax auritus - Larus delawarensis - Larus argentatus - Larus marinus - Sterna hirundo - Sterna paradisaea - Cepphus grylle - Oceanodroma leucorhoa - Morus bassanus - Rissa tridactyla - Uria aalge - Alca torda - Fratercula arctica',
'Gadus morhua',
'Gadus morhua',
'Reinhardtius hippoglossoides',
'Hippoglossoides platessoides',
'Hippoglossoides platessoides',
'Limanda ferruginea - Glyptocephalus cynoglossus - Pseudopleuronectes americanus',
'Amblyraja radiata - Malacoraja senta - Leucoraja ocellata',
'Sebastes mentella - Sebastes fasciatus',
'Urophycis tenuis - Melanogrammus aeglefinus - Centroscyllium fabricii - Anarhichas - Cyclopterus lumpus - Lycodes - Macrouridae - Zoarcidae - Lophius americanus - Hippoglossus hippoglossus',
'Myoxocephalus - Tautogolabrus adspersus - Zoarces americanus',
'Mallotus villosus',
'Squalus acanthias - Pollachius virens - Merluccius bilinearis - Cetorhinus maximus',
'Scomber scombrus - Illex illecebrosus',
'Clupea harengus - Scomberesox saurus - Gonatus',
'Argis dentata - Eualus macilentus - Eualus gaimardi - Pandalus montagui',
'Chionoecetes opilio - Hyas',
'Echinarachnius parma - Stronglyocentrotus pallidus - Ophiura robusta',
'Mesodesma deauratum - Cyrtodaria siliqua',
'Parexogone hebes',
'Miscellaneous crustaceans', #to remove OBI
'Euphausiids - chaetognaths', # to remove LZOO
'Oithona similis - Temora longicornis - Pseudocalanus - Calanus finmarchicus',
'Chaetoceros affinis - Chaetoceros - Leptocylindrus minimus - Thalassiiosira nordenskioldii - Thalassiiosira - Fragilariopsis')

# Removing portions of the web for which there is no taxa usable for the analysis, 'OBI' & 'LZOO'
SSL[[2]] <- SSL[[2]][-which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO'), -which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO')]
sp_SSL <- sp_SSL[-which(sp_SSL[,1] == 'OBI' | sp_SSL[,1] == 'LZOO'), ]

S1 <- unique(unlist(str_split(sp_SSL[,2], ' - ')))

load("./RData/S0_catalog.RData")
S0 <- S0_catalog


# Have to extract taxonomy for speies that are not found in S0
S1_missing <- which(!S1 %in% S0[,1])

S1_add_S0 <- matrix(ncol = 6, nrow = length(S1_missing), data = "", dimnames = list(c(), c("taxon", "taxonomy", "resource", "non-resource", "consumer", "non-consumer")))

S1_add_S0[, 'taxon'] <- S1[S1_missing]

S1_add_S0[, 'taxonomy'] <- c('Animalia | Chordata | Mammalia | Cetartiodactyla | Delphinidae | Lagenorhynchus | Lagenorhynchus acutus',
'Animalia | Chordata | Mammalia | Carnivora | Phocidae | Halichoerus | Halichoerus grypus',
'Animalia | Chordata | Procellariiformes | Hydrobatidae | Oceanodroma | Oceanodroma leucorhoa',
'Animalia | Chordata | Aves | Pelecaniformes | Sulidae | Morus | Morus bassanus',
'Animalia | Chordata | Aves | Charadriiformes | Alcidae | Alca | Alca torda',
'Animalia | Chordata | Elasmobranchii | Rajiformes | Rajidae | Malacoraja | Malacoraja senta',
'Animalia | Chordata | Elasmobranchii | Squaliformes | Etmopteridae | Centroscyllium | Centroscyllium fabricii',
'Animalia | Arthropoda | Malacostraca | Decapoda | Crangonidae | Argis | Argis dentata',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus macilentus',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus gaimardii',
'Animalia | Echinodermata | Echinoidea | Camarodonta | Strongylocentrotidae | Strongylocentrotus | Strongylocentrotus pallidus',
'Animalia | Mollusca | Bivalvia | Imparidentia | Mesodesmatidae | Mesodesma | Mesodesma deauratum',
'Animalia | Mollusca | Bivalvia | Adapedonta | Hiatellidae | Cyrtodaria | Cyrtodaria siliqua',
'Animalia | Annelida | Polychaeta | Phyllodocida | Syllidae | Parexogone | Parexogone hebes',
'Chromista | Ochrophyta | Bacillariophyceae | Chaetocerotanae | Chaetocerotaceae | Chaetoceros | Chaetoceros affinis',
'Chromista | Ochrophyta | Bacillariophyceae | Leptocylindrales | Leptocylindraceae | Leptocylindrus | Leptocylindrus minimus',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | Thalassiosira nordenskioeldii',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | NA')

 S0 <- rbind(S0, S1_add_S0) #binding missing taxonomies
 rownames(S0) <- S0[, 'taxon']


# #Thinning down catalogue
# S02 <- S0[unique(c(which(S0[, 'resource'] != ""), which(S0[, 'consumer'] != ""))), ]
#
# S1_missing2 <- which(!S1 %in% S02[,1]) #after culling
# S1_missing3 <- S1_missing2[which(!S1_missing2 %in% S1_missing)] #taxo to keep
# S1_add_S0 <- rbind(S1_add_S0, S0[which(S0[, 'taxon'] %in% S1[S1_missing3]), ])
# rownames(S1_add_S0) <- NULL
# S0 <- rbind(S02, S1_add_S0)
# remove(S02,S1_missing3,S1_missing2,S1_missing)

# Predicting interactions
SSL_predict <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.3)

# SSL_predict2 <- full_algorithm(Kc = 4,
#                             Kr = 4,
#                             S0 = S0,
#                             S1 = S1,
#                             MW = 1,
#                             wt = 0.5,
#                             minimum_threshold = 0.2)

SSL_predict_mat <- prediction_matrix(S1 = S1, predictions = SSL_predict)
# SSL_predict_mat2 <- prediction_matrix(S1 = S1, predictions = SSL_predict2)
x <- SSL_predict_mat

for(i in 1:nrow(sp_SSL)) {
    Sx <- unique(unlist(str_split(sp_SSL[i,2], ' - ')))
    for(j in 1:length(Sx)){
        for(k in 1:length(S1))
        if(S1[k] %in% Sx == TRUE) {
            colnames(SSL_predict_mat)[k] <- rownames(SSL_predict_mat)[k] <- sp_SSL[i, 2]
            # colnames(SSL_predict_mat2)[k] <- rownames(SSL_predict_mat2)[k] <- sp_SSL[i, 2]
        }
    }
}

SSL_predict_mat_combine <- dupl_sp(SSL_predict_mat)
# SSL_predict_mat_combine2 <- dupl_sp(SSL_predict_mat2)

SSL_emp <- SSL[[2]]
colnames(SSL_emp) <- rownames(SSL_emp) <- sp_SSL[,2]
SSL_emp <-  dupl_sp(SSL_emp)

accuracy_SSL <- prediction_accuracy_id(predicted = SSL_predict_mat_combine, empirical = SSL_emp)
# accuracy_SSL2 <- prediction_accuracy_id(predicted = SSL_predict_mat_combine2, empirical = SSL_emp)
accuracy_SSL
# accuracy_SSL2

# for(i in 2:nrow(accuracy_SSL[[4]])) {
#     print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]))
# }
#
# for(i in 2:nrow(accuracy_SSL[[3]])) {
#     print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]))
# }


SSL_bin_inter <- bin_inter(SSL_predict_mat_combine)
# SSL_bin_inter2 <- bin_inter(SSL_predict_mat_combine2)
SSL_emp_bin <- bin_inter(SSL_emp)
SSL_bin_inter <- SSL_bin_inter[which(SSL_bin_inter[, 'FeedInter'] == '1'), ]
# SSL_bin_inter2 <- SSL_bin_inter2[which(SSL_bin_inter2[, 'FeedInter'] == '1'), ]
SSL_emp_bin <- SSL_emp_bin[which(SSL_emp_bin[, 'FeedInter'] == '1'), ]

# SSL species with interactions noted in catalogue
x <- which(S0[, 'taxon'] %in% S1)
length(which(S0[x,'resource'] != "" | S0[x,'consumer'] != ""))

id_c <- matrix(nrow = nrow(accuracy_SSL[[4]]), ncol = 2, data = NA, dimnames = list(c(), c('consumer','resource')))
for(i in 2:nrow(accuracy_SSL[[4]])) {
    id_c[i,1] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]
    id_c[i,2] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]]
}

id_b <- matrix(nrow = nrow(accuracy_SSL[[3]]), ncol = 2, data = NA, dimnames = list(c(), c('consumer','resource')))
for(i in 2:nrow(accuracy_SSL[[3]])) {
    id_b[i,1] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]
    id_b[i,2] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]]
}


pp <- which(SSL_emp_bin[,'Predator'] == "Scomber scombrus - Illex illecebrosus" | SSL_emp_bin[,'Prey'] == "Scomber scombrus - Illex illecebrosus")
cap <- which(SSL_emp_bin[,'Predator'] == "Mallotus villosus" | SSL_emp_bin[,'Prey'] == "Mallotus villosus")
SSL_emp_part <- SSL_emp_bin[unique(c(pp,cap)), ]


pp <- which(SSL_bin_inter[,'Predator'] == "Scomber scombrus - Illex illecebrosus" | SSL_bin_inter[,'Prey'] == "Scomber scombrus - Illex illecebrosus")

cap <- which(SSL_bin_inter[,'Predator'] == "Mallotus villosus" | SSL_bin_inter[,'Prey'] == "Mallotus villosus")
SSL_pred_part <- SSL_bin_inter[unique(c(pp,cap)), ]

for(i in 1:nrow(sp_SSL)){
    SSL_emp_part[which(SSL_emp_part[, 'Predator'] == sp_SSL[i,2]), 'Predator'] <- sp_SSL[i,3]
    SSL_emp_part[which(SSL_emp_part[, 'Prey'] == sp_SSL[i,2]), 'Prey'] <- sp_SSL[i,3]
    SSL_pred_part[which(SSL_pred_part[, 'Predator'] == sp_SSL[i,2]), 'Predator'] <- sp_SSL[i,3]
    SSL_pred_part[which(SSL_pred_part[, 'Prey'] == sp_SSL[i,2]), 'Prey'] <- sp_SSL[i,3]
}

unique(c(SSL_emp_part,SSL_pred_part))

SSL_pred_part <- gsub("1", "->",SSL_pred_part)
SSL_pred_part <- gsub("Skates", "1",SSL_pred_part)
SSL_pred_part <- gsub("Cetaceans", "2",SSL_pred_part)
SSL_pred_part <- gsub("Hooded seals", "3",SSL_pred_part)
SSL_pred_part <- gsub("Atlantic cod", "4",SSL_pred_part)
SSL_pred_part <- gsub("Grey seals", "5",SSL_pred_part)
SSL_pred_part <- gsub("Harp seals", "6",SSL_pred_part)
SSL_pred_part <- gsub("Seabirds", "7",SSL_pred_part)
SSL_pred_part <- gsub("Harbour seals", "8",SSL_pred_part)
SSL_pred_part <- gsub("Greenland halibut", "9",SSL_pred_part)
SSL_pred_part <- gsub("Piscivorous small pelagic feeders", "10",SSL_pred_part)
SSL_pred_part <- gsub("Redfish", "11",SSL_pred_part)
SSL_pred_part <- gsub("Large pelagic feeders", "12",SSL_pred_part)
SSL_pred_part <- gsub("Large demersal feeders", "13",SSL_pred_part)
SSL_pred_part <- gsub("Capelin", "14",SSL_pred_part)
SSL_pred_part <- gsub("Small demersal feeders","15",SSL_pred_part)
SSL_pred_part <- gsub("Planktivorous small pelagic feeders", "16",SSL_pred_part)
SSL_pred_part <- gsub("Small zooplankton", "17",SSL_pred_part)
SSL_pred_part <- gsub("Flounders", "18",SSL_pred_part)
SSL_pred_part <- gsub("Large crustaceans", "19",SSL_pred_part)
SSL_pred_part <- gsub("American plaice", "20",SSL_pred_part)
SSL_pred_part <- gsub("Shrimp", "21",SSL_pred_part)

SSL_emp_part <- gsub("1", "->",SSL_emp_part)
SSL_emp_part <- gsub("Skates", "1",SSL_emp_part)
SSL_emp_part <- gsub("Cetaceans", "2",SSL_emp_part)
SSL_emp_part <- gsub("Hooded seals", "3",SSL_emp_part)
SSL_emp_part <- gsub("Atlantic cod", "4",SSL_emp_part)
SSL_emp_part <- gsub("Grey seals", "5",SSL_emp_part)
SSL_emp_part <- gsub("Harp seals", "6",SSL_emp_part)
SSL_emp_part <- gsub("Seabirds", "7",SSL_emp_part)
SSL_emp_part <- gsub("Harbour seals", "8",SSL_emp_part)
SSL_emp_part <- gsub("Greenland halibut", "9",SSL_emp_part)
SSL_emp_part <- gsub("Piscivorous small pelagic feeders", "10",SSL_emp_part)
SSL_emp_part <- gsub("Redfish", "11",SSL_emp_part)
SSL_emp_part <- gsub("Large pelagic feeders", "12",SSL_emp_part)
SSL_emp_part <- gsub("Large demersal feeders", "13",SSL_emp_part)
SSL_emp_part <- gsub("Capelin", "14",SSL_emp_part)
SSL_emp_part <- gsub("Small demersal feeders", "15",SSL_emp_part)
SSL_emp_part <- gsub("Planktivorous small pelagic feeders", "16",SSL_emp_part)
SSL_emp_part <- gsub("Small zooplankton", "17",SSL_emp_part)
SSL_emp_part <- gsub("Flounders", "18",SSL_emp_part)
SSL_emp_part <- gsub("Large crustaceans", "19",SSL_emp_part)
SSL_emp_part <- gsub("American plaice", "20",SSL_emp_part)
SSL_emp_part <- gsub("Shrimp", "21",SSL_emp_part)

SSL_emp_part
SSL_pred_part

library(DiagrammeR)
grViz("

digraph boxes_and_circles{

    node [shape = box
            # fixedsize = TRUE
            # width = 2.5
            ]
            1 [label =  <Skates>]
            2 [label =  <Cetaceans>]
            3 [label =  <Hooded seals>]
            4 [label =  <Atlantic cod>]
            5 [label =  <Grey seals>]
            6 [label =  <Harp seals>]
            7 [label =  <Seabirds>]
            8 [label =  <Harbour seals>]
            9 [label =  <Greenland halibut>]
            10 [label =  <Piscivorous small<br/>pelagic feeders>]
            11 [label =  <Redfish>]
            12 [label =  <Large pelagic<br/>feeders>]
            13 [label =  <Large demersal<br/>feeders>]
            14 [label =  <Capelin>]
            15 [label =  <Small demersal<br/>feeders>]
            16 [label =  <Planktivorous small<br/>pelagic feeders>]
            17 [label =  <Small zooplankton>]
            18 [label =  <Flounders>]
            19 [label =  <Large crustaceans>]
            20 [label =  <American plaice>]
            21 [label =  <Shrimp>]

    edge [dir = back]
            7 -> 12 [color = 'transparent']
            7 -> 13 [color = 'transparent']
            7 -> 20 [color = 'transparent']
            7 -> 18 [color = 'transparent']
            7 -> 4 [color = 'transparent']
            8 -> 12 [color = 'transparent']
            8 -> 13 [color = 'transparent']
            8 -> 20 [color = 'transparent']
            8 -> 18 [color = 'transparent']
            8 -> 4 [color = 'transparent']
            12 -> 15 [color = 'transparent']
            12 -> 16 [color = 'transparent']
            13 -> 15 [color = 'transparent']
            13 -> 16 [color = 'transparent']
            20 -> 15 [color = 'transparent']
            20 -> 16 [color = 'transparent']
            18 -> 15 [color = 'transparent']
            18 -> 16 [color = 'transparent']
            4 -> 15 [color = 'transparent']
            4 -> 16 [color = 'transparent']
            15 -> 21 [color = 'transparent']
            15 -> 19 [color = 'transparent']
            16 -> 21 [color = 'transparent']
            16 -> 19 [color = 'transparent']

            2 -> 11 [color = 'transparent']
            2 -> 1 [color = 'transparent']
            2 -> 9 [color = 'transparent']
            3 -> 11 [color = 'transparent']
            3 -> 1 [color = 'transparent']
            3 -> 9 [color = 'transparent']
            5 -> 11 [color = 'transparent']
            5 -> 1 [color = 'transparent']
            5 -> 9 [color = 'transparent']
            6 -> 11 [color = 'transparent']
            6 -> 1 [color = 'transparent']
            6 -> 9 [color = 'transparent']

            #Empirical
            1 -> 10 [color = 'green']
            2 -> 10 [color = 'green']
            3 -> 10 [color = 'black']
            4 -> 10 [color = 'green']
            5 -> 10 [color = 'black']
            6 -> 10 [color = 'black']
            7 -> 10 [color = 'black']
            8 -> 10 [color = 'green']
            9 -> 10 [color = 'black']
            10 -> 16 [color = 'green']
            10 -> 14 [color = 'green']
            10 -> 17 [color = 'green']
            11 -> 10 [color = 'black']
            12 -> 10 [color = 'green']
            13 -> 10 [color = 'green']
            1 -> 14 [color = 'green']
            2 -> 14 [color = 'green']
            3 -> 14 [color = 'green']
            4 -> 14 [color = 'green']
            5 -> 14 [color = 'green']
            14 -> 17 [color = 'green']
            15 -> 14 [color = 'green']
            6 -> 14 [color = 'green']
            7 -> 14 [color = 'green']
            8 -> 14 [color = 'green']
            9 -> 14 [color = 'green']
            11 -> 14 [color = 'green']
            12 -> 14 [color = 'green']
            13 -> 14 [color = 'green']

            # #Predictions

            18 -> 10 [color = 'blue']
            15 -> 10 [color = 'blue']
            10 -> 1 [color = 'blue']
            10 -> 21 [color = 'blue']
            10 -> 4 [color = 'blue']
            10 -> 18 [color = 'blue']
            10 -> 15 [color = 'blue']
            10 -> 7 [color = 'blue']
            10 -> 8 [color = 'blue']
            10 -> 10 [color = 'blue']
            10 -> 12 [color = 'blue']
            10 -> 13 [color = 'blue']
            19 -> 14 [color = 'blue']
            16 -> 14 [color = 'blue']
            20 -> 14 [color = 'blue']
            18 -> 14 [color = 'blue']
            14 -> 14 [color = 'blue']
}
")


# #Empirical
# 1 -> 10 [color = 'blue']
# 2 -> 10 [color = 'blue']
# 3 -> 10 [color = '']
# 4 -> 10 [color = 'blue']
# 5 -> 10 [color = '']
# 6 -> 10 [color = '']
# 7 -> 10 [color = '']
# 8 -> 10 [color = '']
# 9 -> 10 [color = '']
# 10 -> 16 [color = '']
# 10 -> 14 [color = '']
# 10 -> 17 [color = '']
# 11 -> 10 [color = '']
# 12 -> 10 [color = '']
# 13 -> 10 [color = '']
# 1 -> 14 [color = '']
# 2 -> 14 [color = '']
# 3 -> 14 [color = '']
# 4 -> 14 [color = '']
# 5 -> 14 [color = '']
# 14 -> 17 [color = '']
# 15 -> 14 [color = '']
# 6 -> 14 [color = '']
# 7 -> 14 [color = '']
# 8 -> 14 [color = '']
# 9 -> 14 [color = '']
# 11 -> 14 [color = '']
# 12 -> 14 [color = '']
# 13 -> 14 [color = '']

# #Predictions
# 1 -> 10
# 2 -> 10
# 4 -> 10
# 18 -> 10
# 15 -> 10
# 8 -> 10
# 10 -> 1
# 10 -> 21
# 10 -> 16
# 10 -> 4
# 10 -> 18
# 10 -> 14
# 10 -> 15
# 10 -> 17
# 10 -> 7
# 10 -> 8
# 10 -> 10
# 10 -> 12
# 10 -> 13
# 12 -> 10
# 13 -> 10
# 1 -> 14
# 2 -> 14
# 19 -> 14
# 16 -> 14
# 3 -> 14
# 4 -> 14
# 5 -> 14
# 20 -> 14
# 18 -> 14
# 14 -> 14
# 14 -> 17
# 15 -> 14
# 6 -> 14
# 7 -> 14
# 8 -> 14
# 9 -> 14
# 11 -> 14
# 12 -> 14
# 13 -> 14

# Load package
library(networkD3)
# Plot
simpleNetwork(as.data.frame(SSL_bin_inter[, c(1,3)]))
simpleNetwork(as.data.frame(SSL_emp_bin[, c(1,3)]))
create_dtm <- function( path ) {

  library(tm)

  a <- Corpus( DirSource( path, encoding = "UTF-8" ) )

  stop <- scan('stop.txt', what = list(""), sep = '\n' )
  stop <- c( stopwords("finnish") , stop , recursive=T )

  ## bunch of cleanup and transformations
  a <- tm_map(a, removeNumbers, mc.cores=1 )
  a <- tm_map(a, stripWhitespace, mc.cores=1 )
  a <- tm_map(a, removePunctuation, mc.cores=1 )
  a <- tm_map(a, tolower, mc.cores=1 )
  a <- tm_map(a, function(x) iconv(x, to='UTF-8', sub='byte'), mc.cores=1 )
  a <- tm_map(a, removeWords, stop, mc.cores=1 )

  ## compute word frequencies
  dtm <-DocumentTermMatrix(a)

  frequency <- col_sums( dtm , na.rm = T )
  frequency <- sort(frequency, decreasing=TRUE)

  ## choose removal boundaries for further data analysis

  upper = Inf ## floor( length( frequency ) * .005 )
  lower = floor( length( frequency) * .95 )
  ## upper = frequency[ upper ]
  lower = frequency[ lower ]
  ## upper = as.integer( upper )
  lower = as.integer( lower ) + 1

  dtm2 = DocumentTermMatrix( a , control = list( bounds = list( global = c( lower, upper ) ) ) )

  ## throw away columns with 0 indicators
  dtm3 <- dtm2[ row_sums( dtm2 ) > 0, ]

  return( dtm3 )

}

create_model <- function( dtm, k ) {

   library(topicmodels)

   burnin = 1000
   iter = 1000
   keep = 50

   model <- LDA( dtm , k = k, method = "Gibbs", control =  list(burnin = burnin, iter = iter, keep = keep) )

   return( model )

}

check_fitness <- function( dtm , k ) {

  library(topicmodels)
  library(Rmpfr)

  burnin = 1000
  iter = 1000
  keep = 50

  model <- create_model( dtm , k )
  ll <- model@logLiks[ -c(1:(burnin/keep)) ]

  precision = 2000L
  llMed <- median( ll )
  ll = as.double( llMed - log( mean( exp( -mpfr(ll , prec = precision) + llMed ) ) ) )

  return( ll )

}


## from http://www.r-bloggers.com/a-link-between-topicmodels-lda-and-ldavis/

visualize_topicmodel <- function(fitted, corpus, doc_term){
    # Required packages
    library(topicmodels)
    library(dplyr)
    library(stringi)
    library(tm)
    library(LDAvis)

    # Find required quantities
    phi <- posterior(fitted)$terms %>% as.matrix
    theta <- posterior(fitted)$topics %>% as.matrix
    vocab <- colnames(phi)
    doc_length <- vector()
    for (i in 1:length(corpus)) {
        temp <- paste(corpus[[i]]$content, collapse = ' ')
        doc_length <- c(doc_length, stri_count(temp, regex = '\\S+'))
    }
    temp_frequency <- inspect(doc_term)
    freq_matrix <- data.frame(ST = colnames(temp_frequency),
                              Freq = colSums(temp_frequency))
    rm(temp_frequency)

    # Convert to json
    json_lda <- LDAvis::createJSON(phi = phi, theta = theta,
                            vocab = vocab,
                            doc.length = doc_length,
                            term.frequency = freq_matrix$Freq)

    return(json_lda)
}
source('topics.r')

args <- commandArgs(trailingOnly = TRUE)

load( args[1] )
k <- as.integer( args[2] )

model <- create_model( dtm , k )

path <- paste( args[1] , '-', args[2], '.rdata' , sep = '' )
save( model , file = path )
create_dtm <- function( path ) {

  library(tm)

  a <- Corpus( DirSource( path, encoding = "UTF-8" ) )


  stop <- scan('stop.txt', what = list(""), sep = '\n' )
  stop <- c( stopwords("finnish") , stop , recursive=T )

  ## bunch of cleanup and transformations
  a <- tm_map(a, removeNumbers, mc.cores=1 )
  a <- tm_map(a, stripWhitespace, mc.cores=1 )
  a <- tm_map(a, removePunctuation, mc.cores=1 )
  a <- tm_map(a, tolower, mc.cores=1 )
  a <- tm_map(a, function(x) iconv(x, to='UTF-8', sub='byte'), mc.cores=1 )
  a <- tm_map(a, removeWords, stop, mc.cores=1 )

  ## compute word frequencies
  dtm <-DocumentTermMatrix(a) ## , control = list( bounds = list( global = c( minDocFreq, maxDocFreq ) ) ) )

  frequency <- col_sums( dtm , na.rm = T )
  frequency <- sort(frequency, decreasing=TRUE)

  upper = Inf ## floor( length( frequency ) * .005 )
  lower = floor( length( frequency) * .80 )
  ## upper = frequency[ upper ]
  lower = frequency[ lower ]
  ## upper = as.integer( upper )
  lower = as.integer( lower ) + 1

  dtm2 = DocumentTermMatrix( a , control = list( bounds = list( global = c( lower, upper ) ) ) )

  ## throw away columns with 0 indicators
  dtm3 <- dtm2[ row_sums( dtm2 ) > 0, ]

  return( dtm3 )

}

create_model <- function( dtm, k ) {

   library(topicmodels)

   burnin = 1000
   iter = 1000
   keep = 50

   model <- LDA( dtm , k = k, method = "Gibbs", control =  list(burnin = burnin, iter = iter, keep = keep) )

   return( model )

}

check_fitness <- function( dtm , k ) {

  library(topicmodels)
  library(Rmpfr)

  burnin = 1000
  iter = 1000
  keep = 50

  model <- create_model( dtm , k )
  ll <- model@logLiks[ -c(1:(burnin/keep)) ]

  precision = 2000L
  llMed <- median( ll )
  ll = as.double( llMed - log( mean( exp( -mpfr(ll , prec = precision) + llMed ) ) ) )

  return( ll )

}


## from http://www.r-bloggers.com/a-link-between-topicmodels-lda-and-ldavis/

visualize_topicmodel <- function(fitted, corpus, doc_term){
    # Required packages
    library(topicmodels)
    library(dplyr)
    library(stringi)
    library(tm)
    library(LDAvis)

    # Find required quantities
    phi <- posterior(fitted)$terms %>% as.matrix
    theta <- posterior(fitted)$topics %>% as.matrix
    vocab <- colnames(phi)
    doc_length <- vector()
    for (i in 1:length(corpus)) {
        temp <- paste(corpus[[i]]$content, collapse = ' ')
        doc_length <- c(doc_length, stri_count(temp, regex = '\\S+'))
    }
    temp_frequency <- inspect(doc_term)
    freq_matrix <- data.frame(ST = colnames(temp_frequency),
                              Freq = colSums(temp_frequency))
    rm(temp_frequency)

    # Convert to json
    json_lda <- LDAvis::createJSON(phi = phi, theta = theta,
                            vocab = vocab,
                            doc.length = doc_length,
                            term.frequency = freq_matrix$Freq)

    return(json_lda)
}
create_dtm <- function( path ) {

  library(tm)

  a <- Corpus( DirSource( path, encoding = "UTF-8" ) )


  stop <- scan('stop.txt', what = list(""), sep = '\n' )
  stop <- c( stopwords("finnish") , stop , recursive=T )

  ## bunch of cleanup and transformations
  a <- tm_map(a, removeNumbers, mc.cores=1 )
  a <- tm_map(a, stripWhitespace, mc.cores=1 )
  a <- tm_map(a, removePunctuation, mc.cores=1 )
  a <- tm_map(a, tolower, mc.cores=1 )
  a <- tm_map(a, function(x) iconv(x, to='UTF-8', sub='byte'), mc.cores=1 )
  a <- tm_map(a, removeWords, stop, mc.cores=1 )

  ## transform back to plaintext documents
  a <- tm_map(a, PlainTextDocument)

  ## compute word frequencies
  dtm <-DocumentTermMatrix(a) ## , control = list( bounds = list( global = c( minDocFreq, maxDocFreq ) ) ) )

  frequency <- col_sums( dtm , na.rm = T )
  frequency <- sort(frequency, decreasing=TRUE)

  upper = Inf ## floor( length( frequency ) * .005 )
  lower = floor( length( frequency) * .80 )
  ## upper = frequency[ upper ]
  lower = frequency[ lower ]
  ## upper = as.integer( upper )
  lower = as.integer( lower ) + 1

  dtm2 = DocumentTermMatrix( a , control = list( bounds = list( global = c( lower, upper ) ) ) )

  ## throw away columns with 0 indicators
  dtm3 <- dtm2[ row_sums( dtm2 ) > 0, ]

  return( dtm3 )

}

create_model <- function( dtm, k ) {

   library(topicmodels)

   burnin = 1000
   iter = 1000
   keep = 50

   model <- LDA( dtm , k = k, method = "Gibbs", control =  list(burnin = burnin, iter = iter, keep = keep) )

   return( model )

}

check_fitness <- function( dtm , k ) {

  library(topicmodels)
  library(Rmpfr)

  burnin = 1000
  iter = 1000
  keep = 50

  model <- create_model( dtm , k )
  ll <- model@logLiks[ -c(1:(burnin/keep)) ]

  precision = 2000L
  llMed <- median( ll )
  ll = as.double( llMed - log( mean( exp( -mpfr(ll , prec = precision) + llMed ) ) ) )

  return( ll )

}


## from http://www.r-bloggers.com/a-link-between-topicmodels-lda-and-ldavis/

visualize_topicmodel <- function(fitted, corpus, doc_term){
    # Required packages
    library(topicmodels)
    library(dplyr)
    library(stringi)
    library(tm)
    library(LDAvis)

    # Find required quantities
    phi <- posterior(fitted)$terms %>% as.matrix
    theta <- posterior(fitted)$topics %>% as.matrix
    vocab <- colnames(phi)
    doc_length <- vector()
    for (i in 1:length(corpus)) {
        temp <- paste(corpus[[i]]$content, collapse = ' ')
        doc_length <- c(doc_length, stri_count(temp, regex = '\\S+'))
    }
    temp_frequency <- inspect(doc_term)
    freq_matrix <- data.frame(ST = colnames(temp_frequency),
                              Freq = colSums(temp_frequency))
    rm(temp_frequency)

    # Convert to json
    json_lda <- LDAvis::createJSON(phi = phi, theta = theta,
                            vocab = vocab,
                            doc.length = doc_length,
                            term.frequency = freq_matrix$Freq)

    return(json_lda)
}
source('~/digivaalit_public/topics/topics.r')

paths <- c( 'citizen-tweets-lemma' , 'digivaalit-media-lemmas', 'candidate-tweets-lemma' )

for( path in paths ) {

   path = paste( '/homeappl/home/mnelimar/' , path, '/',  sep = '' )

   print( paste( "Working on" , path ) )

   unlink( paste( path , '*.rdata*', sep = '' ) )
   dtm <- create_dtm( path )
   save( dtm , file = paste( path, 'dtm.rdata' , sep = '' ) )

}
# Run init.r before other scripts
rm(list=ls())
 # for use in R console.
 # set own relevant directory if working in R console, otherwise ignore if in terminal
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "./Script/0-1-Tanimoto_data.r
#           RData <- file = './RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "./Script/0-1-Interactions_sources.r
#           RData <- file = "./RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = './Script/1-Similarity_matrix.r'
#       RData <- file = './RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = './Script/2-1-Tanimoto_analysis.r'
#           RData <- file = './RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = './Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = './RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("./Script/tanimoto.r") # basic tanimoto similarity
source("./Script/tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("./Script/similarity_taxon.r") # similarity matrix for set of taxa
source("./Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("./Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("./Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/consumer_set_of_resource.r")
source("./Script/resource_set_of_consumer.r")
source("./Script/prediction_accuracy.r") #
source("./Script/prediction_accuracy_id.r") #
source("./Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("./Script/serialNext.r") # function to avoid overwriting existing files in temporary analyses folder
source("./Script/eplot.r") # empty plot for figure generation
source("./Script/tanimoto_analysis.r")
source("./Script/catalog_predictions.r") # computing prediction accuracy ~ # taxa in catalog
source("./Script/catalog_predictions_accuracy.r") # accuracy of predictions for accuracy ~ # taxa in catalog
source("./Script/full_algorithm.r") # full algorithm with similarity measurements included
source("./Script/similarity_full_algorithm.r") # similarity measurements for full algorithm
source("./Script/duplicate_row_col.r") # function to combine duplicated row and column names
source("./Script/bin_inter.r") # function to extract binary interaction from diet matrix


# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources)
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
            stain_message_source_files(self$get_files(TRUE)$sources)
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function(full.names = FALSE) {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/"),
                                  full.names = full.names),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/"),
                                     full.names = full.names),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"),
                                     full.names = full.names)
            ))
        }
    ),
    private = list(
        options = NULL,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            stain_message_globals(globals)

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' ssh with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param cmds A sting of one or more commands to run on the remote host.
stain_ssh <- function(user, host, cmds = "") {
    if (!stain_ssh_key_exists()) {
        invisible(stain_ssh_key_gen())
    }

    remote_host <- paste(user, host, sep = "@")
    system(paste("ssh -i ~/.ssh/stain_rsa", cmds))
}


#' scp with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param from The local files or directory to copy from.
#'
#' @param to The directory in \code{<user>@<host>} to copy into.
stain_scp <- function(user, host, from, to) {
    if (!dir.exists(from) & !file.exists(from)) {
        stop(paste(from, "is an invalid path."))
    }

    recursive <- ifelse(dir.exists(from), "-r", "")
    to <- paste0(user, "@", host, ":", to)

    system(paste("scp -i ~/.ssh/stain_rsa", recursive, normalizePath(from), to))
}


#' Check for a Stain ssh key.
#'
#' @return If a public/private key pair exists in \code{~/.ssh/} with the name
#' \code{stain_rsa}, return TRUE, otherwise return FALSE.
stain_ssh_key_exists <- function() {
    return("stain_rsa" %in% list.files("~/.ssh/"))
}


#' Generate a Stain ssh key.
#'
#' A 4096 bit key will be generated and stored in \code{~/.ssh/} with the name
#' \code{stain_rsa}.
#'
#' @param overwrite Should an existing Stain ssh key be overwritten. Default
#' value is FALSE.
stain_ssh_key_gen <- function(overwrite = FALSE) {
    if (overwrite | !(overwrite | stain_ssh_key_exists())) {
        system("ssh-keygen -b 4096 -f ~/.ssh/stain_rsa -N ''")
    }
}


#' Create bash code for ssh setup.
#'
#' In order for a remote submission to work, an ssh public key for Stain must
#' be present in the remote host's \code{~/.ssh/authorized_keys} list. This
#' process requires two steps. 1) To \code{scp} the public key and 2) to add
#' the key to \code{~/.ssh/authorized_keys}. This function will autogenerate
#' the necessary bash code to complete these steps.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @return A single bash command to run.
#'
#' @export
stain_ssh_setup <- function(user, host) {
    remote_host <- paste(user, host, sep = "@")
    scp <- paste0("scp ~/.ssh/stain_rsa.pub", remote_host, ":~/.ssh/stain_rsa.pub")
    ssh <- paste0("ssh ", scp, " 'echo `cat ~/.ssh/stain_rsa.pub` >> ~/.ssh/authorized_keys'")
    cmd <- paste0(scp, " && ", ssh)

    if (Sys.info()["sysname"] == "Darwin") {
        cat("The bash command to setup remote submission has been copied to your clipboard. Run it in your terminal.")
        write.table(cmd, file = pipe("pbcopy"), sep = "\t",
                    col.names = F, row.names = F , quote = F)
    } else {
        cat("Run the following bash command in your terminal to setup remote submission:")
        cat(cmd)
    }
}
#' ssh with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param cmds A sting of one or more commands to run on the remote host.
stain_ssh <- function(user, host, cmds = "") {
    if (!stain_ssh_key_exists()) {
        invisible(stain_ssh_key_gen())
    }

    remote_host <- paste(user, host, sep = "@")
    system(paste("ssh -i ~/.ssh/stain_rsa", cmds))
}


#' scp with the Stain RSA key.
#'
#' The stain-specific key must be used to ensure remote login.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @param from The local files or directory to copy from.
#'
#' @param to The directory in \code{<user>@<host>} to copy into.
stain_scp <- function(user, host, from, to) {
    if (!dir.exists(from) & !file.exists(from)) {
        stop(paste(from, "is an invalid path."))
    }

    recursive <- ifelse(dir.exists(from), "-r", "")
    to <- paste0(user, "@", host, ":", to)

    system(paste("scp -i ~/.ssh/stain_rsa", recursive, normalizePath(from), to))
}


#' Check for a Stain ssh key.
#'
#' @return If a public/private key pair exists in \code{~/.ssh/} with the name
#' \code{stain_rsa}, return TRUE, otherwise return FALSE.
stain_ssh_key_exists <- function() {
    return("stain_rsa" %in% list.files("~/.ssh/"))
}


#' Generate a Stain ssh key.
#'
#' A 4096 bit key will be generated and stored in \code{~/.ssh/} with the name
#' \code{stain_rsa}.
#'
#' @param overwrite Should an existing Stain ssh key be overwritten. Default
#' value is FALSE.
stain_ssh_key_gen <- function(overwrite = FALSE) {
    if (overwrite | !(overwrite | stain_ssh_key_exists())) {
        system("ssh-keygen -b 4096 -f ~/.ssh/stain_rsa")
    }
}


#' Create bash code for ssh setup.
#'
#' In order for a remote submission to work, an ssh public key for Stain must
#' be present in the remote host's \code{~/.ssh/authorized_keys} list. This
#' process requires two steps. 1) To \code{scp} the public key and 2) to add
#' the key to \code{~/.ssh/authorized_keys}. This function will autogenerate
#' the necessary bash code to complete these steps.
#'
#' @param user The user on your remote host.
#'
#' @param host The static ip address or url for the remote host.
#'
#' @return A single bash command to run.
#'
#' @export
stain_ssh_setup <- function(user, host) {
    remote_host <- paste(user, host, sep = "@")
    scp <- paste0("scp ~/.ssh/stain_rsa.pub", remote_host, ":~/.ssh/stain_rsa.pub")
    ssh <- paste0("ssh ", scp, " 'echo `cat ~/.ssh/stain_rsa.pub` >> ~/.ssh/authorized_keys'")
    cmd <- paste0(scp, " && ", ssh)

    if (Sys.info()["sysname"] == "Darwin") {
        cat("The bash command to setup remote submission has been copied to your clipboard. Run it in your terminal.")
        write.table(cmd, file = pipe("pbcopy"), sep = "\t",
                    col.names = F, row.names = F , quote = F)
    } else {
        cat("Run the following bash command in your terminal to setup remote submission:")
        cat(cmd)
    }
}
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#    1. Evaluating similarity of consumers and resources
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
# // TODO: Evaluate similarity based on set of consumers for resources
# // TODO: Look into proximity graphs for better performance
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# LIBRARIES:
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/Tanimoto_data.RData")

# Measuring the similarity with multiple weights for all taxa in interaction catalogue
# Will be better once we code for proximity graphs

# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
# Format interaction catalogue to fit this table format
    S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
    S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']

    }

# Weight values for 2-way similarity measurements
    wt <- seq(0, 1, by = 0.1)

# 1st is for similarity measured from set of resources and taxonomy, for consumers
    similarity.consumers <- vector('list',11)
    names(similarity.consumers) <- wt
    for(i in 1:length(wt)) {
        similarity.consumers[[i]] <- similarity_taxon(S0 = S0_catalog, wt = wt[i], taxa = 'consumer')
        save(x = similarity.consumers, file = "./RData/Similarity_consumers.RData")
    }
    save(x = similarity.consumers, file = "./RData/Similarity_consumers.RData")

# 2nd is for similarity measured from set of consumers and taxonomy, for resources
    similarity.resources <- vector('list',11)
    names(similarity.resources) <- wt
    for(i in 1:length(wt)) {
        similarity.resources[[i]] <- similarity_taxon(S0 = S0_catalog, wt = wt[i], taxa = 'resource')
        save(x = similarity.resources, file = "./RData/Similarity_resources.RData")
    }
    save(x = similarity.resources, file = "./RData/Similarity_resources.RData")
###############################################
### COMMONLY USED PACKAGES IN AIM R SCRIPTS ###
###############################################

#### THE CORE ####
install.packages("tidyverse")
## The tidyverse package includes a number of packages also listed below. It's a quick way to bootstrap up a new install of R.
## They include:
## broom, DBI, dplyr, forcats, ggplot2, haven, httr, hms, jsonlite, lubridate, magrittr, modelr, purrr, readr, readxl, stringr,
## tibble, rvest, tidyr, and xml2

#### DATA WRANGLING ####
install.packages(
  c(
    "dplyr", ## Notably useful for data frame manipulation with group_by(), summarize(), and mutate() and the piping operator %>%. Do you have a moment to hear the good news of our savior, piping?
    "tidyr", ## Lots of useful things, but specifically gather() and spread() for converting wide data frames into long ones and vice versa
    "broom", ## Get stats objects into tidy data frames. Not as common
    "stringr", ## All about character strings. Great for str_split() in particular, but the whole str_ family of functions are A+
    "RODBC", ## Allows R to pass SQL queries to Access databases and pull out the results
    "XLSX" ## Read in modern Excel workbooks and spreadsheets
  )
)

#### SPATIAL DATA ####
install.packages(
  c(
    "sp", ## Functions for manipulating spatial objects. If you want a Spatial _____ Data Frame, this is part of the deal
    "spsurvey", ## Contains plenty, but the most important to AIM is the GRTS function
    "rgeos", ## Additional spatial object functions
    "rgdal", ## Contains the mission critical readOGR() function that we read shapefiles in with
    "raster" ## Everything you didn't know you needed for dealing with rasters
  )
)

#### DATA VISUALIZATION ####
install.packages(
  c(
    "ggplot2", ## The go-to for figure generation. Most R-using scientists AND Nate Silver use it, so you should too
    "ggthemes", ## Quick themes to painlessly apply to figures from ggplot
    "ggmap", ## Mapping support for ggplot
    "RColorBrewer" ## All about making beautiful color palettes for maps and figures
  )
)

#### MISCELLANEOUS PACKAGES ####
## These are more ala carte. Pick and choose as you need them
install.packages("markdown") ## Generates documents with figures and everything based on your script, which means that if you change the data, the document changes to reflect it. POWERFUL.
install.packages("rJava") ## Chances are really good that this is already installed as a dependency for another package, but just to be safe, here it is
install.packages("devtools") ## For more granular control of the R environment when you need it, which may not be very often at all
install.packages("git2r") ## If you're going to use Git, this is important because it lets you use git from within R. It's a dependency of devtools though, so it may already be installed
install.packages("arcgisbinding") ## Young and finicky, but once you have it all installed (an ordeal) you should be able to read from and write to file geodatabases from R
install.packages("gridExtra") ## Lets you make grid objects that you can place ggplot figures into. May occasionally be preferable to faceting in ggplot, but rarely
install.packages("shiny") ## Required for working with Shiny tools in any form. Can be maddening
install.packages("purrr") ## Really, really useful for writing functions, particularly those that fail gracefully
install.packages("gstat") ## For spatial and spatio-temporal geostatistical modelling and simulation
install.packages("foreach") ## Parallel looping structures. Sarah McCord's thesis work required this
install.packages("snow") ## If you're doing distributed computing across multiple machines, grab thistanimoto_analysis <- function(min.tx, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, blind = FALSE) {
    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon
                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog

                        if(similarity == 'both') { # For similarity matrices already evaluated
                            similarity.consumer <- similarity.consumers[[i]]
                            similarity.resource <- similarity.resources[[i]]
                        } else if(similarity == 'consumer') {
                            similarity.consumer <- similarity.consumers[[i]]
                        } else if (similarity == 'resource') {
                            similarity.resource <- similarity.resources[[i]]
                        }

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                              S0[S1[k], 'consumer'] <- ""
                              S0[S1[k], 'non-consumer'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                                consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                        resource = interactions[, 'resource'],
                                                                        inter_type = interactions[, 'inter'])


                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                }
                                for(k in 1:nrow(consumer_set)) {
                                  S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                  S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.consumer,
                                                                                taxa = 'consumer')

                            similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.resource,
                                                                                taxa = 'resource')

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.consumer = similarity.consumer,
                                                                                    similarity.resource = similarity.resource,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.consumer, similarity.resource)
                        iteration <- iteration + 1
                        setTxtProgressBar(pb, iteration)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values

        }#m
    }#n
    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
catalog_predictions <- function(min.tx = 45, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, percent_remove = 0, nb_iter = 1, comm_id = FALSE, community) {

    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        if(comm_id == FALSE) {
            to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        } else { # comm_id = TRUE
            to.delete <- which(!Cm %in% community)
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        }

    # Setting up lists to store the results
    # weights
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        #Minimum weight
        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

        #Number of iterations
        iter <- vector('list', nb_iter)
            for(i in 1:nb_iter) {
                iter[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- iter
        names(Tanimoto_analysis) <- seq(1,nb_iter)
        remove(iter)


        # Percent remove in communities
        pc_rm <- vector('list', length(percent_remove))
            for(i in 1:length(percent_remove)) {
                pc_rm[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- pc_rm
        names(Tanimoto_analysis) <- percent_remove
        remove(pc_rm)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(percent_remove) * nb_iter * length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(p in 1:length(percent_remove)){
        percent_rm <- percent_remove[p]
        for(o in 1:nb_iter){
            for(n in 1:length(MW)) {
                mw <- MW[n]
                for(m in 1:length(K.values)) {

                    # Tanimoto analysis with different weights for different communities
                        # Parameters:
                            Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                            Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                            # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                        #   wt  Weight of traits in similarity measurement
                        #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                        #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                        # Output:
                        #   A vector of sets of resources for each taxon
                        for(i in 1:length(WT)){ #1st loop for all types of wt values
                            wt <- WT[i]
                            for(j in 1:length(Cm)) { #2nd loop for all C[i]
                                S1 <- communities[[j]]
                                S0 <- S0_catalog

                                if(similarity == 'both') { # For similarity matrices already evaluated
                                    similarity.consumer <- similarity.consumers[[i]]
                                    similarity.resource <- similarity.resources[[i]]
                                } else if(similarity == 'consumer') {
                                    similarity.consumer <- similarity.consumers[[i]]
                                } else if (similarity == 'resource') {
                                    similarity.resource <- similarity.resources[[i]]
                                }

                                # setting up the iterative process to evaluate the accuracy ~ # taxa in catalog
                                # removing a certain percentage of the # of species for which there are interactions as consumers described in the original food web.

                                # inter_Cm <- unique(subset(interactions_sources[, 'consumer'], interactions_sources[, 'source'] == Cm[j] & interactions_sources[, 'inter'] == "1")) # Species for which there are interactions as consumer in Cm[j]

                                interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3] # interaction catalog without interactions coming from Cm[j]

                                # inter_Cm2 <- unique(interactions[which(interactions[, 'consumer'] %in% inter_Cm), 'consumer']) # consumers in Cm[j] for which information is still available in catalog after deletion of Cm[j] from catalog

                                #Removing a percentage of consumers described in catalog
                                    # sample_iter <- sample(x = inter_Cm2, size = round((percent_rm / 100) * length(inter_Cm2)), replace = FALSE)
                                    sample_iter <- sample(x = S1, size = round((percent_rm / 100) * length(S1)), replace = FALSE) # To use if removing a percent of all taxa in original web

                                    if(length(sample_iter) == 0) {
                                        S1_no_mod <- seq(1,length(S1))
                                    } else {
                                        for(k in 1:length(sample_iter)) {
                                          S0[sample_iter[k], 'resource'] <- ""
                                          S0[sample_iter[k], 'non-resource'] <- ""
                                          S0[sample_iter[k], 'consumer'] <- ""
                                          S0[sample_iter[k], 'non-consumer'] <- ""
                                        }
                                        S1_no_mod <- which(!S1 %in% sample_iter)
                                    }

                                # 2. Preexisting information kept to inform algorithm
                                    if(length(S1_no_mod) == 0) {
                                        NULL
                                    } else {
                                    # Only modifying those that are loosing data from the catalogue, less time
                                        to.change <- numeric()
                                        for(k in 1:length(S1_no_mod)) {
                                            to.change <- c(to.change, which(interactions[, 'consumer'] == S1[S1_no_mod[k]]), which(interactions[, 'resource'] == S1[S1_no_mod[k]]))
                                        }
                                        to.change <- unique(to.change)

                                    # Modifying sets of resources and non-resources for taxa in S1_no_mod
                                        interactions <- interactions[to.change, ]
                                        rownames(interactions) <- seq(1,nrow(interactions))
                                        resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                                  resource = interactions[, 'resource'],
                                                                                  inter_type = interactions[, 'inter'])

                                        consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                                resource = interactions[, 'resource'],
                                                                                inter_type = interactions[, 'inter'])


                                    # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                        for(k in 1:nrow(resource_set)) {
                                          S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                          S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                        }
                                        for(k in 1:nrow(consumer_set)) {
                                          S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                          S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                        }
                                    remove(interactions, resource_set, to.change)
                                    }#if

                                # Recalculate similarity
                                    similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.consumer,
                                                                                        taxa = 'consumer')

                                    similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.resource,
                                                                                        taxa = 'resource')

                                # Predicting interactions
                                    Tanimoto_analysis[[p]][[o]][[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                            Kr = Kr,
                                                                                            S0 = S0,
                                                                                            S1 = S1,
                                                                                            MW = mw,
                                                                                            similarity.consumer = similarity.consumer,
                                                                                            similarity.resource = similarity.resource,
                                                                                            minimum_threshold = minimum_threshold)

                                save(x = Tanimoto_analysis, file = file.to.save)
                                remove(S0, S1, similarity.consumer, similarity.resource)
                                iteration <- iteration + 1
                                setTxtProgressBar(pb, iteration)
                            }#2nd loop for all C[i]

                            save(x = Tanimoto_analysis, file = file.to.save)
                            remove(wt)

                        }#1st loop for all types of wt values
                }#m
            }#n
        }#o
    }#p
    #Saving number of species in original web vs catalog once web removed
    # percent_original <- length(inter_Cm2) / length(inter_Cm)
    # x <- c(percent_original, length(inter_Cm), length(inter_Cm2))
    # file.to.save2 <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis_pc_tx.RData")
    # save(x = x, file = file.to.save2)

    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2.8 Example with southern St. Lawrence EwE model for mid-1980s
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "./RawData/South_St_Lawrence_EwE.RData"
#   Script  <- file = "Script/2-8_St_Lawrence_ex.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REFERENCE:
#   Savenkoff, to add
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
library(stringr)
load("./RawData/South_St_Lawrence_EwE.RData")
SSL <- South_St_Lawrence

SSL[[2]][which(SSL[[2]] > 0)] <- 1
rownames(SSL[[2]]) <- colnames(SSL[[2]]) <- SSL[[3]]

sp_SSL <- matrix(ncol = 3, nrow = 29, data = NA, dimnames = list(c(), c('ACCR','SP','FG')))

sp_SSL[,1] <- c('WHA','HAS','HOS','GRS','HSE','SEA','LCO','SCO','LGH','SAP','LAP','FLO','SKA','RED','LDF','SDF','CAP','LPF','PISF','PLSF','SHR','LCRU','ECH','MOL','POL','OBI','LZOO','SZOO','PHY')

sp_SSL[,3] <- c('Cetaceans',
'Harp seals',
'Hooded seals',
'Grey seals',
'Harbour seals',
'Seabirds',
'Atlantic cod',
'Atlantic cod',
'Greenland halibut',
'American plaice',
'American plaice',
'Flounders',
'Skates',
'Redfish',
'Large demersal feeders',
'Small demersal feeders',
'Capelin',
'Large pelagic feeders',
'Piscivorous small pelagic feeders',
'Planktivorous small pelagic feeders',
'Shrimp',
'Large crustaceans',
'Echinoderms',
'Molluscs',
'Polychates',
'Other benthic invertebrates',
'Large zooplankton',
'Small zooplankton',
'Phytoplankton')



sp_SSL[,2] <- c('Balaenoptera physalus - Balaenoptera acutorostrata - Megaptera novaeangliae - Phocoena phocoena - Lagenorhynchus acutus - Lagenorhynchus albirostris',
'Pagophilus groenlandicus',
'Cystophora cristata',
'Halichoerus grypus',
'Phoca vitulina',
'Phalacrocorax carbo - Phalacrocorax auritus - Larus delawarensis - Larus argentatus - Larus marinus - Sterna hirundo - Sterna paradisaea - Cepphus grylle - Oceanodroma leucorhoa - Morus bassanus - Rissa tridactyla - Uria aalge - Alca torda - Fratercula arctica',
'Gadus morhua',
'Gadus morhua',
'Reinhardtius hippoglossoides',
'Hippoglossoides platessoides',
'Hippoglossoides platessoides',
'Limanda ferruginea - Glyptocephalus cynoglossus - Pseudopleuronectes americanus',
'Amblyraja radiata - Malacoraja senta - Leucoraja ocellata',
'Sebastes mentella - Sebastes fasciatus',
'Urophycis tenuis - Melanogrammus aeglefinus - Centroscyllium fabricii - Anarhichas - Cyclopterus lumpus - Lycodes - Macrouridae - Zoarcidae - Lophius americanus - Hippoglossus hippoglossus',
'Myoxocephalus - Tautogolabrus adspersus - Zoarces americanus',
'Mallotus villosus',
'Squalus acanthias - Pollachius virens - Merluccius bilinearis - Cetorhinus maximus',
'Scomber scombrus - Illex illecebrosus',
'Clupea harengus - Scomberesox saurus - Gonatus',
'Argis dentata - Eualus macilentus - Eualus gaimardi - Pandalus montagui',
'Chionoecetes opilio - Hyas',
'Echinarachnius parma - Stronglyocentrotus pallidus - Ophiura robusta',
'Mesodesma deauratum - Cyrtodaria siliqua',
'Parexogone hebes',
'Miscellaneous crustaceans', #to remove OBI
'Euphausiids - chaetognaths', # to remove LZOO
'Oithona similis - Temora longicornis - Pseudocalanus - Calanus finmarchicus',
'Chaetoceros affinis - Chaetoceros - Leptocylindrus minimus - Thalassiiosira nordenskioldii - Thalassiiosira - Fragilariopsis')

# Removing portions of the web for which there is no taxa usable for the analysis, 'OBI' & 'LZOO'
SSL[[2]] <- SSL[[2]][-which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO'), -which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO')]
sp_SSL <- sp_SSL[-which(sp_SSL[,1] == 'OBI' | sp_SSL[,1] == 'LZOO'), ]

S1 <- unique(unlist(str_split(sp_SSL[,2], ' - ')))

load("./RData/Tanimoto_data.RData")
# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
# Format interaction catalogue to fit this table format
    S0 <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
    S0[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
        S0[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
    }


# Have to extract taxonomy for speies that are not found in S0
S1_missing <- which(!S1 %in% S0[,1])

S1_add_S0 <- matrix(ncol = 6, nrow = length(S1_missing), data = "", dimnames = list(c(), c("taxon", "taxonomy", "resource", "non-resource", "consumer", "non-consumer")))

S1_add_S0[, 'taxon'] <- S1[S1_missing]

S1_add_S0[, 'taxonomy'] <- c('Animalia | Chordata | Mammalia | Cetartiodactyla | Delphinidae | Lagenorhynchus | Lagenorhynchus acutus',
'Animalia | Chordata | Mammalia | Carnivora | Phocidae | Halichoerus | Halichoerus grypus',
'Animalia | Chordata | Procellariiformes | Hydrobatidae | Oceanodroma | Oceanodroma leucorhoa',
'Animalia | Chordata | Aves | Pelecaniformes | Sulidae | Morus | Morus bassanus',
'Animalia | Chordata | Aves | Charadriiformes | Alcidae | Alca | Alca torda',
'Animalia | Chordata | Elasmobranchii | Rajiformes | Rajidae | Malacoraja | Malacoraja senta',
'Animalia | Chordata | Elasmobranchii | Squaliformes | Etmopteridae | Centroscyllium | Centroscyllium fabricii',
'Animalia | Arthropoda | Malacostraca | Decapoda | Crangonidae | Argis | Argis dentata',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus macilentus',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus gaimardii',
'Animalia | Echinodermata | Echinoidea | Camarodonta | Strongylocentrotidae | Strongylocentrotus | Strongylocentrotus pallidus',
'Animalia | Mollusca | Bivalvia | Imparidentia | Mesodesmatidae | Mesodesma | Mesodesma deauratum',
'Animalia | Mollusca | Bivalvia | Adapedonta | Hiatellidae | Cyrtodaria | Cyrtodaria siliqua',
'Animalia | Annelida | Polychaeta | Phyllodocida | Syllidae | Parexogone | Parexogone hebes',
'Chromista | Ochrophyta | Bacillariophyceae | Chaetocerotanae | Chaetocerotaceae | Chaetoceros | Chaetoceros affinis',
'Chromista | Ochrophyta | Bacillariophyceae | Leptocylindrales | Leptocylindraceae | Leptocylindrus | Leptocylindrus minimus',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | Thalassiosira nordenskioeldii',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | NA')

 S0 <- rbind(S0, S1_add_S0) #binding missing taxonomies
 rownames(S0) <- S0[, 'taxon']


# #Thinning down catalogue
# S02 <- S0[unique(c(which(S0[, 'resource'] != ""), which(S0[, 'consumer'] != ""))), ]
#
# S1_missing2 <- which(!S1 %in% S02[,1]) #after culling
# S1_missing3 <- S1_missing2[which(!S1_missing2 %in% S1_missing)] #taxo to keep
# S1_add_S0 <- rbind(S1_add_S0, S0[which(S0[, 'taxon'] %in% S1[S1_missing3]), ])
# rownames(S1_add_S0) <- NULL
# S0 <- rbind(S02, S1_add_S0)
# remove(S02,S1_missing3,S1_missing2,S1_missing)

# Predicting interactions
SSL_predict <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.3)

SSL_predict2 <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.2)

SSL_predict_mat <- prediction_matrix(S1 = S1, predictions = SSL_predict)
SSL_predict_mat2 <- prediction_matrix(S1 = S1, predictions = SSL_predict2)
x <- SSL_predict_mat

for(i in 1:nrow(sp_SSL)) {
    Sx <- unique(unlist(str_split(sp_SSL[i,2], ' - ')))
    for(j in 1:length(Sx)){
        for(k in 1:length(S1))
        if(S1[k] %in% Sx == TRUE) {
            colnames(SSL_predict_mat)[k] <- rownames(SSL_predict_mat)[k] <- sp_SSL[i, 2]
            colnames(SSL_predict_mat2)[k] <- rownames(SSL_predict_mat2)[k] <- sp_SSL[i, 2]
        }
    }
}

SSL_predict_mat_combine <- dupl_sp(SSL_predict_mat)
SSL_predict_mat_combine2 <- dupl_sp(SSL_predict_mat2)

SSL_emp <- SSL[[2]]
colnames(SSL_emp) <- rownames(SSL_emp) <- sp_SSL[,2]
SSL_emp <-  dupl_sp(SSL_emp)

accuracy_SSL <- prediction_accuracy_id(predicted = SSL_predict_mat_combine, empirical = SSL_emp)
accuracy_SSL2 <- prediction_accuracy_id(predicted = SSL_predict_mat_combine2, empirical = SSL_emp)
accuracy_SSL
accuracy_SSL2

# for(i in 2:nrow(accuracy_SSL[[4]])) {
#     print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]))
# }
#
# for(i in 2:nrow(accuracy_SSL[[3]])) {
#     print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]))
# }


SSL_bin_inter <- bin_inter(SSL_predict_mat_combine)
SSL_bin_inter2 <- bin_inter(SSL_predict_mat_combine2)
SSL_emp_bin <- bin_inter(SSL_emp)
SSL_bin_inter <- SSL_bin_inter[which(SSL_bin_inter[, 'FeedInter'] == '1'), ]
SSL_bin_inter2 <- SSL_bin_inter2[which(SSL_bin_inter2[, 'FeedInter'] == '1'), ]
SSL_emp_bin <- SSL_emp_bin[which(SSL_emp_bin[, 'FeedInter'] == '1'), ]

# SSL species with interactions noted in catalogue
x <- which(S0[, 'taxon'] %in% S1)
length(which(S0[x,'resource'] != "" | S0[x,'consumer'] != ""))

id_c <- matrix(nrow = nrow(accuracy_SSL[[4]]), ncol = 2, data = NA, dimnames = list(c(), c('consumer','resource')))
for(i in 2:nrow(accuracy_SSL[[4]])) {
    id_c[i,1] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]
    id_c[i,2] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]]
}

id_b <- matrix(nrow = nrow(accuracy_SSL[[3]]), ncol = 2, data = NA, dimnames = list(c(), c('consumer','resource')))
for(i in 2:nrow(accuracy_SSL[[3]])) {
    id_b[i,1] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]
    id_b[i,2] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]]
}



# Load package
library(networkD3)
# Plot
simpleNetwork(as.data.frame(SSL_bin_inter[, c(1,3)]))
simpleNetwork(as.data.frame(SSL_emp_bin[, c(1,3)]))





# remplace , par ' - '
# remplacer les noms de colonnes et lignes
# combiner duplicatas
# rouler fonction du catalogue pour séparer les lignes et colonnes qui ont plusieurs entrées?
# faire l'analyse en séparant toutes les espèces listées, puis comparer l'analyse divisée, compartimenter les résultats (combiner les interactions des espèces qui sont dans un compartiment), et la réseau présenté dans l'article à partir de la matrice de diète.


pp <- which(SSL_emp_bin[,'Predator'] == "Scomber scombrus - Illex illecebrosus" | SSL_emp_bin[,'Prey'] == "Scomber scombrus - Illex illecebrosus")
cap <- which(SSL_emp_bin[,'Predator'] == "Mallotus villosus" | SSL_emp_bin[,'Prey'] == "Mallotus villosus")
SSL_emp_part <- SSL_emp_bin[unique(c(pp,cap)), ]


pp <- which(SSL_bin_inter[,'Predator'] == "Scomber scombrus - Illex illecebrosus" | SSL_bin_inter[,'Prey'] == "Scomber scombrus - Illex illecebrosus")

cap <- which(SSL_bin_inter[,'Predator'] == "Mallotus villosus" | SSL_bin_inter[,'Prey'] == "Mallotus villosus")
SSL_pred_part <- SSL_bin_inter[unique(c(pp,cap)), ]

for(i in 1:nrow(sp_SSL)){
    SSL_emp_part[which(SSL_emp_part[, 'Predator'] == sp_SSL[i,2]), 'Predator'] <- sp_SSL[i,3]
    SSL_emp_part[which(SSL_emp_part[, 'Prey'] == sp_SSL[i,2]), 'Prey'] <- sp_SSL[i,3]
    SSL_pred_part[which(SSL_pred_part[, 'Predator'] == sp_SSL[i,2]), 'Predator'] <- sp_SSL[i,3]
    SSL_pred_part[which(SSL_pred_part[, 'Prey'] == sp_SSL[i,2]), 'Prey'] <- sp_SSL[i,3]
}

unique(c(SSL_emp_part,SSL_pred_part))

SSL_pred_part <- gsub("1", "->",SSL_pred_part)
SSL_pred_part <- gsub("Skates", "1",SSL_pred_part)
SSL_pred_part <- gsub("Cetaceans", "2",SSL_pred_part)
SSL_pred_part <- gsub("Hooded seals", "3",SSL_pred_part)
SSL_pred_part <- gsub("Atlantic cod", "4",SSL_pred_part)
SSL_pred_part <- gsub("Grey seals", "5",SSL_pred_part)
SSL_pred_part <- gsub("Harp seals", "6",SSL_pred_part)
SSL_pred_part <- gsub("Seabirds", "7",SSL_pred_part)
SSL_pred_part <- gsub("Harbour seals", "8",SSL_pred_part)
SSL_pred_part <- gsub("Greenland halibut", "9",SSL_pred_part)
SSL_pred_part <- gsub("Piscivorous small pelagic feeders", "10",SSL_pred_part)
SSL_pred_part <- gsub("Redfish", "11",SSL_pred_part)
SSL_pred_part <- gsub("Large pelagic feeders", "12",SSL_pred_part)
SSL_pred_part <- gsub("Large demersal feeders", "13",SSL_pred_part)
SSL_pred_part <- gsub("Capelin", "14",SSL_pred_part)
SSL_pred_part <- gsub("Small demersal feeders","15",SSL_pred_part)
SSL_pred_part <- gsub("Planktivorous small pelagic feeders", "16",SSL_pred_part)
SSL_pred_part <- gsub("Small zooplankton", "17",SSL_pred_part)
SSL_pred_part <- gsub("Flounders", "18",SSL_pred_part)
SSL_pred_part <- gsub("Large crustaceans", "19",SSL_pred_part)
SSL_pred_part <- gsub("American plaice", "20",SSL_pred_part)
SSL_pred_part <- gsub("Shrimp", "21",SSL_pred_part)

SSL_emp_part <- gsub("1", "->",SSL_emp_part)
SSL_emp_part <- gsub("Skates", "1",SSL_emp_part)
SSL_emp_part <- gsub("Cetaceans", "2",SSL_emp_part)
SSL_emp_part <- gsub("Hooded seals", "3",SSL_emp_part)
SSL_emp_part <- gsub("Atlantic cod", "4",SSL_emp_part)
SSL_emp_part <- gsub("Grey seals", "5",SSL_emp_part)
SSL_emp_part <- gsub("Harp seals", "6",SSL_emp_part)
SSL_emp_part <- gsub("Seabirds", "7",SSL_emp_part)
SSL_emp_part <- gsub("Harbour seals", "8",SSL_emp_part)
SSL_emp_part <- gsub("Greenland halibut", "9",SSL_emp_part)
SSL_emp_part <- gsub("Piscivorous small pelagic feeders", "10",SSL_emp_part)
SSL_emp_part <- gsub("Redfish", "11",SSL_emp_part)
SSL_emp_part <- gsub("Large pelagic feeders", "12",SSL_emp_part)
SSL_emp_part <- gsub("Large demersal feeders", "13",SSL_emp_part)
SSL_emp_part <- gsub("Capelin", "14",SSL_emp_part)
SSL_emp_part <- gsub("Small demersal feeders", "15",SSL_emp_part)
SSL_emp_part <- gsub("Planktivorous small pelagic feeders", "16",SSL_emp_part)
SSL_emp_part <- gsub("Small zooplankton", "17",SSL_emp_part)
SSL_emp_part <- gsub("Flounders", "18",SSL_emp_part)
SSL_emp_part <- gsub("Large crustaceans", "19",SSL_emp_part)
SSL_emp_part <- gsub("American plaice", "20",SSL_emp_part)
SSL_emp_part <- gsub("Shrimp", "21",SSL_emp_part)

SSL_emp_part
SSL_pred_part

library(DiagrammeR)
grViz("

digraph boxes_and_circles{

    node [shape = box
            # fixedsize = TRUE
            # width = 2.5
            ]
            1 [label =  <Skates>]
            2 [label =  <Cetaceans>]
            3 [label =  <Hooded seals>]
            4 [label =  <Atlantic cod>]
            5 [label =  <Grey seals>]
            6 [label =  <Harp seals>]
            7 [label =  <Seabirds>]
            8 [label =  <Harbour seals>]
            9 [label =  <Greenland halibut>]
            10 [label =  <Piscivorous small<br/>pelagic feeders>]
            11 [label =  <Redfish>]
            12 [label =  <Large pelagic<br/>feeders>]
            13 [label =  <Large demersal<br/>feeders>]
            14 [label =  <Capelin>]
            15 [label =  <Small demersal<br/>feeders>]
            16 [label =  <Planktivorous small<br/>pelagic feeders>]
            17 [label =  <Small zooplankton>]
            18 [label =  <Flounders>]
            19 [label =  <Large crustaceans>]
            20 [label =  <American plaice>]
            21 [label =  <Shrimp>]

    edge [dir = back]
            7 -> 12 [color = 'transparent']
            7 -> 13 [color = 'transparent']
            7 -> 20 [color = 'transparent']
            7 -> 18 [color = 'transparent']
            7 -> 4 [color = 'transparent']
            8 -> 12 [color = 'transparent']
            8 -> 13 [color = 'transparent']
            8 -> 20 [color = 'transparent']
            8 -> 18 [color = 'transparent']
            8 -> 4 [color = 'transparent']
            12 -> 15 [color = 'transparent']
            12 -> 16 [color = 'transparent']
            13 -> 15 [color = 'transparent']
            13 -> 16 [color = 'transparent']
            20 -> 15 [color = 'transparent']
            20 -> 16 [color = 'transparent']
            18 -> 15 [color = 'transparent']
            18 -> 16 [color = 'transparent']
            4 -> 15 [color = 'transparent']
            4 -> 16 [color = 'transparent']
            15 -> 21 [color = 'transparent']
            15 -> 19 [color = 'transparent']
            16 -> 21 [color = 'transparent']
            16 -> 19 [color = 'transparent']

            2 -> 11 [color = 'transparent']
            2 -> 1 [color = 'transparent']
            2 -> 9 [color = 'transparent']
            3 -> 11 [color = 'transparent']
            3 -> 1 [color = 'transparent']
            3 -> 9 [color = 'transparent']
            5 -> 11 [color = 'transparent']
            5 -> 1 [color = 'transparent']
            5 -> 9 [color = 'transparent']
            6 -> 11 [color = 'transparent']
            6 -> 1 [color = 'transparent']
            6 -> 9 [color = 'transparent']

            #Empirical
            1 -> 10 [color = 'green']
            2 -> 10 [color = 'green']
            3 -> 10 [color = 'black']
            4 -> 10 [color = 'green']
            5 -> 10 [color = 'black']
            6 -> 10 [color = 'black']
            7 -> 10 [color = 'black']
            8 -> 10 [color = 'green']
            9 -> 10 [color = 'black']
            10 -> 16 [color = 'green']
            10 -> 14 [color = 'green']
            10 -> 17 [color = 'green']
            11 -> 10 [color = 'black']
            12 -> 10 [color = 'green']
            13 -> 10 [color = 'green']
            1 -> 14 [color = 'green']
            2 -> 14 [color = 'green']
            3 -> 14 [color = 'green']
            4 -> 14 [color = 'green']
            5 -> 14 [color = 'green']
            14 -> 17 [color = 'green']
            15 -> 14 [color = 'green']
            6 -> 14 [color = 'green']
            7 -> 14 [color = 'green']
            8 -> 14 [color = 'green']
            9 -> 14 [color = 'green']
            11 -> 14 [color = 'green']
            12 -> 14 [color = 'green']
            13 -> 14 [color = 'green']

            # #Predictions

            18 -> 10 [color = 'blue']
            15 -> 10 [color = 'blue']
            10 -> 1 [color = 'blue']
            10 -> 21 [color = 'blue']
            10 -> 4 [color = 'blue']
            10 -> 18 [color = 'blue']
            10 -> 15 [color = 'blue']
            10 -> 7 [color = 'blue']
            10 -> 8 [color = 'blue']
            10 -> 10 [color = 'blue']
            10 -> 12 [color = 'blue']
            10 -> 13 [color = 'blue']
            19 -> 14 [color = 'blue']
            16 -> 14 [color = 'blue']
            20 -> 14 [color = 'blue']
            18 -> 14 [color = 'blue']
            14 -> 14 [color = 'blue']
}
")


# #Empirical
# 1 -> 10 [color = 'blue']
# 2 -> 10 [color = 'blue']
# 3 -> 10 [color = '']
# 4 -> 10 [color = 'blue']
# 5 -> 10 [color = '']
# 6 -> 10 [color = '']
# 7 -> 10 [color = '']
# 8 -> 10 [color = '']
# 9 -> 10 [color = '']
# 10 -> 16 [color = '']
# 10 -> 14 [color = '']
# 10 -> 17 [color = '']
# 11 -> 10 [color = '']
# 12 -> 10 [color = '']
# 13 -> 10 [color = '']
# 1 -> 14 [color = '']
# 2 -> 14 [color = '']
# 3 -> 14 [color = '']
# 4 -> 14 [color = '']
# 5 -> 14 [color = '']
# 14 -> 17 [color = '']
# 15 -> 14 [color = '']
# 6 -> 14 [color = '']
# 7 -> 14 [color = '']
# 8 -> 14 [color = '']
# 9 -> 14 [color = '']
# 11 -> 14 [color = '']
# 12 -> 14 [color = '']
# 13 -> 14 [color = '']

# #Predictions
# 1 -> 10
# 2 -> 10
# 4 -> 10
# 18 -> 10
# 15 -> 10
# 8 -> 10
# 10 -> 1
# 10 -> 21
# 10 -> 16
# 10 -> 4
# 10 -> 18
# 10 -> 14
# 10 -> 15
# 10 -> 17
# 10 -> 7
# 10 -> 8
# 10 -> 10
# 10 -> 12
# 10 -> 13
# 12 -> 10
# 13 -> 10
# 1 -> 14
# 2 -> 14
# 19 -> 14
# 16 -> 14
# 3 -> 14
# 4 -> 14
# 5 -> 14
# 20 -> 14
# 18 -> 14
# 14 -> 14
# 14 -> 17
# 15 -> 14
# 6 -> 14
# 7 -> 14
# 8 -> 14
# 9 -> 14
# 11 -> 14
# 12 -> 14
# 13 -> 14
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:
    filename <- 'Multiple_parameters'
    min.tx = 45
    K.values = c(2,4,6,8)
    MW = c(1,3,5)
    WT = c(0,0.3,0.6,1)
    blind = FALSE
    minimum_threshold = 0.3
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/Tanimoto_data.RData")
load("./RData/interactions_source.RData")
suppressMessages(load("./RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
# Format interaction catalogue to fit this table format
    S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
    S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
    }

# setting up the analyses for multiple communities
# Data for communities on which to test the algorithm
    Cm <- unique(interactions_sources[, 'source'])
    communities <- vector("list", length(Cm))
    names(communities) <- Cm

    # Taxa list per community to predict
        for(i in 1:length(communities)) {
            Ci <- which(interactions_sources[, 'source'] == Cm[i])
            S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

            if(length(which(!S1 %in% S0_catalog)) > 0) {
                print('Taxa in C[i] are not all included in taxa list S0')
                break
            }

            communities[[i]] <- S1
        }

# Substracting GloBI interactions for this portion
    Cm.lg <- numeric()
    for(i in 1:length(communities)) {
        Cm.lg <- c(Cm.lg,length(communities[[i]]))
    }

    to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

    Cm <- Cm[-to.delete]
    for(i in rev(to.delete)) {
        communities[[i]] <- NULL
    }
    names(communities) <- Cm

# Setting up lists to store the results
    wt.init <- wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
    wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
    for(i in rev(wt.remove)) {
        similarity.matrices[[i]] <- NULL
    }

    sim.wt <- names(similarity.matrices)
    Tanimoto_analysis <- vector("list",length(sim.wt))
    names(Tanimoto_analysis) <- sim.wt
    for(i in 1:length(sim.wt)) {
        Tanimoto_analysis[[i]] <- vector("list", length(Cm))
        names(Tanimoto_analysis[[i]]) <- Cm
    }

# List to store results of multiple K values
K <- vector("list", length(K.values))
for(i in 1:length(K.values)) {
    K[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- K
names(Tanimoto_analysis) <- K.values
remove(K)

min.wt <- vector("list", length(MW))
for(i in 1:length(MW)) {
    min.wt[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- min.wt
names(Tanimoto_analysis) <- MW
remove(min.wt)

file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
save(x = Tanimoto_analysis, file = file.to.save)

init.time <- Sys.time()
for(n in 1:length(MW)) {
    mw <- MW[n]
    for(m in 1:length(K.values)) {

        # Tanimoto analysis with different weights for different communities
            # Parameters:
                Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
            #   wt  Weight of traits in similarity measurement
            #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
            #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

            # Output:
            #   A vector of sets of resources for each taxon

            for(i in 1:length(WT)){ #1st loop for all types of wt values
                wt <- WT[i]
                pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                for(j in 1:length(Cm)) { #2nd loop for all C[i]
                    S1 <- communities[[j]]
                    S0 <- S0_catalog
                    similarity.matrix <- similarity.matrices[[i]]

                    # Two choices here:
                    #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                    #   2. The analysis takes into account preexisting information already contained in the catalogue

                    # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                    if(blind == TRUE) {
                        for(k in 1:length(S1)) {
                          S0[S1[k], 'resource'] <- ""
                          S0[S1[k], 'non-resource'] <- ""
                        }

                    # 2. Preexisting information kept to inform algorithm
                    } else { # blind == FALSE

                        interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                        # Only modifying those that are loosing data from the catalogue, less time
                            to.change <- numeric()
                            for(k in 1:length(S1)) {
                                to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                            }
                            to.change <- unique(to.change)

                        # Modifying sets of resources and non-resources for taxa in S1
                            interactions <- interactions[to.change, ]
                            rownames(interactions) <- seq(1,nrow(interactions))
                            resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                      resource = interactions[, 'resource'],
                                                                      inter_type = interactions[, 'inter'])

                        # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                            for(k in 1:nrow(resource_set)) {
                              S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                              S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                            }
                        remove(interactions, resource_set, to.change)
                    } #if blind or not blind

                    # Recalculate similarity
                        similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                            S1 = S1,
                                                                            wt = wt,
                                                                            similarity.matrix = similarity.matrix)

                    # Predicting interactions
                        Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                Kr = Kr,
                                                                                S0 = S0,
                                                                                S1 = S1,
                                                                                MW = mw,
                                                                                similarity.matrix = similarity.matrix,
                                                                                minimum_threshold = minimum_threshold)

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(S0, S1, similarity.matrix)
                    setTxtProgressBar(pb, j)
                }#2nd loop for all C[i]

                save(x = Tanimoto_analysis, file = file.to.save)
                remove(wt)

            }#1st loop for all types of wt values
            close(pb)
    }#m
}#n
print(Sys.time() - init.time)
save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))


# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 50, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(WT) * length(K.values)) + 0.5, labels = FALSE, las = 1, pos = -0.02) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, nb.pts, by = length(WT)) + 0.5, labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)

            abline(v = seq(length(WT)+0.5,nb.pts-length(WT)+0.5,by = length(WT)), col = "grey", lty = 2)
            abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
            abline(h = c(1.125,2.375), col = "black", lty = 2)


            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'MW']) + as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,48), accuracy_mean[, 4][,1] - accuracy_mean[, 4][, 2]+it, seq(1,48), accuracy_mean[, 4][, 1] + accuracy_mean[, 4][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,48), y = accuracy_mean[, 4][, 1]+it, cex = 0.75, pch = 22, col = col[i])
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
#Solve for optimal lobby effort under DGH97-style model with obj fcn W + e

#reserve space for loop output
tau = seq(0.001,.166,0.001) #this will be counter variable in loop
PSx = matrix(NA,length(tau),1)
CSx = matrix(NA,length(tau),1)
TR = matrix(NA,length(tau),1)
PSy = matrix(NA,length(tau),1)
CSy = matrix(NA,length(tau),1)

#calculate government welfare when tau = 0 (baseline)
b = ((2 +2*0)^2)/49 + .5*((3 -4*0)^2)/49 + (0 - 6*0^2)/7 + ((3 +3*0)^2)/98 + ((4 -3*0)^2)/98

#calculate producer surplus, consumer surplus, tariff revenue for each possible
#value of the tariff on the grid (just above zero to prohibitive tariff 1/6)
for (j in 1:length(tau)) {
  t = tau[j]

  PSx[j] = ((2 +2*t)^2)/49
  CSx[j] = .5*((3 -4*t)^2)/49
  TR[j] = (t - 6*t^2)/7
  CSy[j] = ((3 +3*t)^2)/98
  PSy[j] = ((4 -3*t)^2)/98
}

W = PSx + CSx + TR + CSy + PSy  #social welfare
e = b - W                       #gov't indifference condition when WG = W + e
pi = PSx - e                    #net profits

value = max(pi) #the value at which profits are maximized (over non-negative values)
ind = which.max(pi) #the location at which profits are maximized
RC = arrayInd(ind,c(dim(pi),dim(pi))) #row/column version of maximand location


# now solve for optimal effort under my model with gamma ismorphic to W + e model

#I've just copied this from 'solve_leg_constraint.R', not made any adjustments yet
etw <- uniroot(function(cn) (8/49*(1+(8*(1 + cn^E)-5)/(68-8*(1 + cn^E)))*(8*63*.2*(cn^(-.8)))/((68-8*(1 + cn^E))^2))-1, lower=0, upper = 1, tol = 0.00001, maxiter = 1000)full_algorithm <- function(Kc, Kr, S0, S1, MW, wt, minimum_threshold) {
    # Two-way Tanimoto Algorithm
    # ===========================

    # Parameters:
    #   Kc  Integer, how many neighbors to select for consumers
    #   Kr  Integer, how many neighbors to select for resources
    #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
    #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name
    #   MW  Mimimum weight to accept a candidate as a prey

    # Output
    #   A vector of sets (the preys for each species)

    predictions <- matrix(nrow = length(S1), ncol = 3, data = "", dimnames = list(c(S1), c('consumer','resource_empirical','resource_predictions'))) # empty object for resource predictions
    predictions[, 'consumer'] <- S1

    pb <- txtProgressBar(min = 0,max = length(S1), style = 3)
    for(i in 1:length(S1)) { # loop through each taxon in S1
        candidates <- matrix(nrow = 0, ncol = 2, dimnames = list(c(), c('resource', 'weight')), data = NA) # empty matrix for resource candidate list for S1[i], with taxon name and weight
        resources.S1 <- unlist(strsplit(S0[S1[i], 'resource'], " \\|\\ ")) # resources of S1[i]

        # Add resources that are already listed as resources for S1[i] in predictions[, 'resource_empirical'] or
        # Find similar resources to resources for S1[i] in S1
        if(length(resources.S1) > 0) {
            empirical <- character()
            for(j in 1:length(resources.S1)) { #loop through empirical resources for S1
                if(resources.S1[j] %in% S1) {
                    empirical <- c(empirical, resources.S1[j]) # observed resource found in S1 are automatically added to the column resource_empirical
                } else { # selecting Kr most similar resources in S1
                    # Let's assume for this part that we are not compiling a different similarity measure for predators and preys.

                    similarity.resources <- similarity_full_algorithm(S0 = unique(S0[which(S0[, 'taxon'] %in% S1 | S0[, 'taxon'] == resources.S1[j]), ]), # S1 in S0 + resource for which similarity has to be measured
                                                                    S1 = resources.S1[j], # resource for which similarity has to be measured
                                                                    wt = wt,
                                                                    taxa = 'resource')

                    similar.resource <- matrix(nrow = nrow(similarity.resources), ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources
                    similar.resource[, 'resource'] <- names(similarity.resources[order(similarity.resources, decreasing = TRUE), ])
                    similar.resource[, 'similarity'] <- similarity.resources[order(similarity.resources, decreasing = TRUE)]
                    to.remove <- which(similar.resource[,'resource'] == resources.S1[j])
                    if(length(to.remove) > 0){ #remove resoures.S1[j] in case it gets through (just keeping it consistant with other similarity evaluation further down in the catalogue, even though it is not necessary in this portion)
                        similar.resource <- similar.resource[-which(similar.resource[,'resource'] == resources.S1[j]), ]
                    }

                    # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
                    if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {
                        same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])
                        similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]
                        similar.resource <- similar.resource[1:Kr, ]
                    } else {
                        similar.resource <- similar.resource[1:Kr, ]
                    }# if for random draw

                    for(l in 1:Kr) { # extracting resource candidates
                        if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break
                            break
                        } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                            NULL
                            # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed
                        } else if(similar.resource[l, 'similarity'] < minimum_threshold) {
                            NULL
                        } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add resource' with wt to its weight
                          candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])
                        } else {
                              candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it resource' with wt to its weight
                        }#if3
                    }#l
                }#if
            }#j
            predictions[S1[i], 'resource_empirical'] <- paste(empirical, collapse = ' | ')
        }#if1

        # Identify similar consumers to S1[i]

        similarity.consumers <- similarity_full_algorithm(S0 = S0,
                                                        S1 = S1[i],
                                                        wt = wt,
                                                        taxa = 'consumer')

        similar.consumer <- matrix(nrow = nrow(similarity.consumers), ncol = 2, dimnames = list(c(), c('consumer','similarity')), data = NA) # importing K nearest neighbors consumers
        similar.consumer[, 'consumer'] <- names(similarity.consumers[order(similarity.consumers, decreasing = TRUE), ])
        similar.consumer[, 'similarity'] <- similarity.consumers[order(similarity.consumers, decreasing = TRUE)]
        to.remove <- which(similar.consumer[,'consumer'] == S1[i])
        if(length(to.remove) > 0){ #remove resoures.S1[j] in case it gets through (just keeping it consistant with other similarity evaluation further down in the catalogue, even though it is not necessary in this portion)
            similar.consumer <- similar.consumer[-which(similar.consumer[,'consumer'] == S1[i]), ]
        }

        # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
        if(similar.consumer[Kc+1, 'similarity'] == similar.consumer[Kc, 'similarity']) {
            same.similarity <- which(similar.consumer[, 'similarity'] == similar.consumer[Kc, 'similarity'])
            similar.consumer[same.similarity, ] <- similar.consumer[sample(same.similarity), ]
            similar.consumer <- similar.consumer[1:Kc, ]
        } else {
            similar.consumer <- similar.consumer[1:Kc, ]
        }# if for random draw


        # Est-ce que la valeur de similarité a de l'importance pour l'attribution des proies?
        # If yes, we could add an argument call wt_predator.
          # if(wt_predator == FALSE) {
          #   resources <- unique of all prey species of all similar predators
          # } else {}

        for(j in 1:Kc) { #loop through consumers

            if(all.equal(similar.consumer[, 'similarity'], rep('0',Kc)) == TRUE) { # if similarities all == 0, break
                break
            } else if(similar.consumer[j, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                NULL
            } else {

                # It's possible that consumers in the list have high taxonomic similarity, but no recorded resource
                candidate.resource <- unlist(strsplit(S0[similar.consumer[j, 'consumer'], 'resource'], " \\|\\ ")) # list of resources for consumer j
                # candidate.resource <- candidate.resource[(candidate.resource %in% resources.S1) == FALSE] # substracting candidate resources that are already listed as resources for S1[i] and hence considered in the preceding code segment

                for(k in 1:length(candidate.resource)) { # loop through resources of consumer j
                    if(length(candidate.resource) == 0) { # if candidate resource list is empty, break
                        break
                    } else if(candidate.resource[1] == "") { # if candidate list is an empty vector "", break
                        break
                    } else if(candidate.resource[k] == S1[i]) {
                    #   #// FIXME: if candidate resource is taxon for which predictions are being made, break (unless we want to allow CANIBALISM). Add argument for cannibalism allowed or not
                         NULL
                    } else if((candidate.resource[k] %in% S1) == TRUE) {
                        if((candidate.resource[k] %in% candidates[, 'resource']) == TRUE) {# if candidate is already in candidate list, add 1 to its weight
                            candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight']) + 1
                        } else {
                            candidates <- rbind(candidates, c(candidate.resource[k], 1)) # if candidate is not in the list, add it with 1 to its weight
                        }#if2

                    } else {
                        similarity.resources <- similarity_full_algorithm(S0 = unique(S0[which(S0[, 'taxon'] %in% S1 | S0[, 'taxon'] == candidate.resource[k]), ]), # S1 in S0 + resource for which similarity has to be measured
                                                                        S1 = candidate.resource[k], # resource for which similarity has to be measured
                                                                        wt = wt,
                                                                        taxa = 'resource')

                        similar.resource <- matrix(nrow = nrow(similarity.resources), ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources
                        similar.resource[, 'resource'] <- names(similarity.resources[order(similarity.resources, decreasing = TRUE), ])
                        similar.resource[, 'similarity'] <- similarity.resources[order(similarity.resources, decreasing = TRUE)]
                        to.remove <- which(similar.resource[,'resource'] == candidate.resource[k])
                        if(length(to.remove) > 0){ #remove resoures.S1[j] in case it gets through (just keeping it consistant with other similarity evaluation further down in the catalogue, even though it is not necessary in this portion)
                            similar.resource <- similar.resource[-which(similar.resource[,'resource'] == candidate.resource[k]), ]
                        }

                        # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
                        if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {
                            same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])
                            similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]
                            similar.resource <- similar.resource[1:Kr, ]
                        } else {
                            similar.resource <- similar.resource[1:Kr, ]
                        }# if for random draw

                        for(l in 1:Kr) { # extracting resource candidates
                            if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break
                                break
                            } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                                NULL
                                # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed
                            } else if(similar.resource[l, 'similarity'] < minimum_threshold) {
                                NULL
                            } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add 1 to its weight
                              candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])
                            } else {
                                  candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it with its weight = similarity
                            }#if3
                        }#l
                    } #if1
                }#k
            }#if
        }#j

        candidates <- candidates[which(candidates[, 'weight'] >= MW), ] # remove candidates with a weight below MW
        if(is.matrix(candidates) == TRUE) { #if it's a vector, there's only one predicted resource, no need to order
            candidates[order(candidates[, 'weight']), ] # sorts candidates according to their weight
            predictions[S1[i], 'resource_predictions'] <- paste(candidates[, 'resource'], collapse = ' | ')
        } else {
          predictions[S1[i], 'resource_predictions'] <- paste(candidates['resource'], collapse = ' | ')
        }#if
    setTxtProgressBar(pb, i)
    }#i
    close(pb)
    return(predictions)
}#full algorithm function
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2.8 Example with southern St. Lawrence EwE model for mid-1980s
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "./RawData/South_St_Lawrence_EwE.RData"
#   Script  <- file = "Script/2-8_St_Lawrence_ex.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REFERENCE:
#   Savenkoff, to add
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
library(stringr)
load("./RawData/South_St_Lawrence_EwE.RData")
SSL <- South_St_Lawrence

SSL[[2]][which(SSL[[2]] > 0)] <- 1
rownames(SSL[[2]]) <- colnames(SSL[[2]]) <- SSL[[3]]

sp_SSL <- matrix(ncol = 2, nrow = 29, data = NA, dimnames = list(c(), c('ACCR','SP')))

sp_SSL[,1] <- c('WHA','HAS','HOS','GRS','HSE','SEA','LCO','SCO','LGH','SAP','LAP','FLO','SKA','RED','LDF','SDF','CAP','LPF','PISF','PLSF','SHR','LCRU','ECH','MOL','POL','OBI','LZOO','SZOO','PHY')

sp_SSL[,2] <- c('Balaenoptera physalus - Balaenoptera acutorostrata - Megaptera novaeangliae - Phocoena phocoena - Lagenorhynchus acutus - Lagenorhynchus albirostris',
'Pagophilus groenlandicus',
'Cystophora cristata',
'Halichoerus grypus',
'Phoca vitulina',
'Phalacrocorax carbo - Phalacrocorax auritus - Larus delawarensis - Larus argentatus - Larus marinus - Sterna hirundo - Sterna paradisaea - Cepphus grylle - Oceanodroma leucorhoa - Morus bassanus - Rissa tridactyla - Uria aalge - Alca torda - Fratercula arctica',
'Gadus morhua',
'Gadus morhua',
'Reinhardtius hippoglossoides',
'Hippoglossoides platessoides',
'Hippoglossoides platessoides',
'Limanda ferruginea - Glyptocephalus cynoglossus - Pseudopleuronectes americanus',
'Amblyraja radiata - Malacoraja senta - Leucoraja ocellata',
'Sebastes mentella - Sebastes fasciatus',
'Urophycis tenuis - Melanogrammus aeglefinus - Centroscyllium fabricii - Anarhichas - Cyclopterus lumpus - Lycodes - Macrouridae - Zoarcidae - Lophius americanus - Hippoglossus hippoglossus',
'Myoxocephalus - Tautogolabrus adspersus - Zoarces americanus',
'Mallotus villosus',
'Squalus acanthias - Pollachius virens - Merluccius bilinearis - Cetorhinus maximus',
'Scomber scombrus - Illex illecebrosus',
'Clupea harengus - Scomberesox saurus - Gonatus',
'Argis dentata - Eualus macilentus - Eualus gaimardi - Pandalus montagui',
'Chionoecetes opilio - Hyas',
'Echinarachnius parma - Stronglyocentrotus pallidus - Ophiura robusta',
'Mesodesma deauratum - Cyrtodaria siliqua',
'Parexogone hebes',
'Miscellaneous crustaceans', #to remove OBI
'Euphausiids - chaetognaths', # to remove LZOO
'Oithona similis - Temora longicornis - Pseudocalanus - Calanus finmarchicus',
'Chaetoceros affinis - Chaetoceros - Leptocylindrus minimus - Thalassiiosira nordenskioldii - Thalassiiosira - Fragilariopsis')

# Removing portions of the web for which there is no taxa usable for the analysis, 'OBI' & 'LZOO'
SSL[[2]] <- SSL[[2]][-which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO'), -which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO')]
sp_SSL <- sp_SSL[-which(sp_SSL[,1] == 'OBI' | sp_SSL[,1] == 'LZOO'), ]

S1 <- unique(unlist(str_split(sp_SSL[,2], ' - ')))

load("./RData/Tanimoto_data.RData")
# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
# Format interaction catalogue to fit this table format
    S0 <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
    S0[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
        S0[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
    }


# Have to extract taxonomy for speies that are not found in S0
S1_missing <- which(!S1 %in% S0[,1])

S1_add_S0 <- matrix(ncol = 6, nrow = length(S1_missing), data = "", dimnames = list(c(), c("taxon", "taxonomy", "resource", "non-resource", "consumer", "non-consumer")))

S1_add_S0[, 'taxon'] <- S1[S1_missing]

S1_add_S0[, 'taxonomy'] <- c('Animalia | Chordata | Mammalia | Cetartiodactyla | Delphinidae | Lagenorhynchus | Lagenorhynchus acutus',
'Animalia | Chordata | Mammalia | Carnivora | Phocidae | Halichoerus | Halichoerus grypus',
'Animalia | Chordata | Procellariiformes | Hydrobatidae | Oceanodroma | Oceanodroma leucorhoa',
'Animalia | Chordata | Aves | Pelecaniformes | Sulidae | Morus | Morus bassanus',
'Animalia | Chordata | Aves | Charadriiformes | Alcidae | Alca | Alca torda',
'Animalia | Chordata | Elasmobranchii | Rajiformes | Rajidae | Malacoraja | Malacoraja senta',
'Animalia | Chordata | Elasmobranchii | Squaliformes | Etmopteridae | Centroscyllium | Centroscyllium fabricii',
'Animalia | Arthropoda | Malacostraca | Decapoda | Crangonidae | Argis | Argis dentata',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus macilentus',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus gaimardii',
'Animalia | Echinodermata | Echinoidea | Camarodonta | Strongylocentrotidae | Strongylocentrotus | Strongylocentrotus pallidus',
'Animalia | Mollusca | Bivalvia | Imparidentia | Mesodesmatidae | Mesodesma | Mesodesma deauratum',
'Animalia | Mollusca | Bivalvia | Adapedonta | Hiatellidae | Cyrtodaria | Cyrtodaria siliqua',
'Animalia | Annelida | Polychaeta | Phyllodocida | Syllidae | Parexogone | Parexogone hebes',
'Chromista | Ochrophyta | Bacillariophyceae | Chaetocerotanae | Chaetocerotaceae | Chaetoceros | Chaetoceros affinis',
'Chromista | Ochrophyta | Bacillariophyceae | Leptocylindrales | Leptocylindraceae | Leptocylindrus | Leptocylindrus minimus',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | Thalassiosira nordenskioeldii',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | NA')

 S0 <- rbind(S0, S1_add_S0) #binding missing taxonomies
 rownames(S0) <- S0[, 'taxon']


# #Thinning down catalogue
# S02 <- S0[unique(c(which(S0[, 'resource'] != ""), which(S0[, 'consumer'] != ""))), ]
#
# S1_missing2 <- which(!S1 %in% S02[,1]) #after culling
# S1_missing3 <- S1_missing2[which(!S1_missing2 %in% S1_missing)] #taxo to keep
# S1_add_S0 <- rbind(S1_add_S0, S0[which(S0[, 'taxon'] %in% S1[S1_missing3]), ])
# rownames(S1_add_S0) <- NULL
# S0 <- rbind(S02, S1_add_S0)
# remove(S02,S1_missing3,S1_missing2,S1_missing)

# Predicting interactions
SSL_predict <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.3)

SSL_predict2 <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.2)

SSL_predict_mat <- prediction_matrix(S1 = S1, predictions = SSL_predict)
SSL_predict_mat2 <- prediction_matrix(S1 = S1, predictions = SSL_predict2)
x <- SSL_predict_mat

for(i in 1:nrow(sp_SSL)) {
    Sx <- unique(unlist(str_split(sp_SSL[i,2], ' - ')))
    for(j in 1:length(Sx)){
        for(k in 1:length(S1))
        if(S1[k] %in% Sx == TRUE) {
            colnames(SSL_predict_mat)[k] <- rownames(SSL_predict_mat)[k] <- sp_SSL[i, 2]
            colnames(SSL_predict_mat2)[k] <- rownames(SSL_predict_mat2)[k] <- sp_SSL[i, 2]
        }
    }
}

SSL_predict_mat_combine <- dupl_sp(SSL_predict_mat)
SSL_predict_mat_combine2 <- dupl_sp(SSL_predict_mat2)

SSL_emp <- SSL[[2]]
colnames(SSL_emp) <- rownames(SSL_emp) <- sp_SSL[,2]
SSL_emp <-  dupl_sp(SSL_emp)

accuracy_SSL <- prediction_accuracy_id(predicted = SSL_predict_mat_combine, empirical = SSL_emp)
accuracy_SSL2 <- prediction_accuracy_id(predicted = SSL_predict_mat_combine2, empirical = SSL_emp)
accuracy_SSL
accuracy_SSL2

for(i in 2:nrow(accuracy_SSL[[4]])) {
    print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]))
}

for(i in 2:nrow(accuracy_SSL[[3]])) {
    print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]))
}


SSL_bin_inter <- bin_inter(SSL_predict_mat_combine)
SSL_bin_inter2 <- bin_inter(SSL_predict_mat_combine2)
SSL_emp_bin <- bin_inter(SSL_emp)
SSL_bin_inter <- SSL_bin_inter[which(SSL_bin_inter[, 'FeedInter'] == '1'), ]
SSL_bin_inter2 <- SSL_bin_inter2[which(SSL_bin_inter2[, 'FeedInter'] == '1'), ]
SSL_emp_bin <- SSL_emp_bin[which(SSL_emp_bin[, 'FeedInter'] == '1'), ]

# SSL species with interactions noted in catalogue
x <- which(S0[, 'taxon'] %in% S1)
length(which(S0[x,'resource'] != "" | S0[x,'consumer'] != ""))

id_b <- matrix(nrow = nrow(accuracy_SSL[[4]]), ncol = 2, data = NA, dimnames = list(c(), c('consumer','resource')))
for(i in 2:nrow(accuracy_SSL[[4]])) {
    id_b[i,1] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]
    id_b[i,2] <- rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]]
}



# Load package
library(networkD3)
# Plot
simpleNetwork(as.data.frame(SSL_bin_inter[, c(1,3)]))
simpleNetwork(as.data.frame(SSL_emp_bin[, c(1,3)]))





# remplace , par ' - '
# remplacer les noms de colonnes et lignes
# combiner duplicatas
# rouler fonction du catalogue pour séparer les lignes et colonnes qui ont plusieurs entrées?
# faire l'analyse en séparant toutes les espèces listées, puis comparer l'analyse divisée, compartimenter les résultats (combiner les interactions des espèces qui sont dans un compartiment), et la réseau présenté dans l'article à partir de la matrice de diète.
S0 <- matrix(nrow = 12, ncol = 4, data = NA, dimnames = list(c(),c('taxon','taxonomy','resource','consumer')))
S0[1, ] <- c('1', 'a | b | c', '2 | 3 | 12', '4')
S0[2, ] <- c('2', 'e | f | g', '', '1 | 5')
S0[3, ] <- c('3', 'i | j | k', '', '5')
S0[4, ] <- c('4', 'm | n | o', '1 | 5', '')
S0[5, ] <- c('5', 'a | b | d', '8 | 9', '4')
S0[6, ] <- c('6', 'i | q | r', '2 | 8', '4')
S0[7, ] <- c('7', 'e | f | h', '', '1 | 6')
S0[8, ] <- c('8', 's | t | u', '', '5 | 6')
S0[9, ] <- c('9', 's | t | v', '', '5')
S0[10, ] <- c('10', 'i | j | l', '', '')
S0[11, ] <- c('11', 'm | n | p', '', '')
S0[12, ] <- c('12', 'q | r | s', '', '1')
rownames(S0) <- S0[,'taxon']

S1 <- c('1','9','10','11','12')

example0 <- full_algorithm(Kc = 2, Kr = 2, S0 = S0, S1 = S1, MW = 0, wt = 0, minimum_threshold = 0)
example05 <- full_algorithm(Kc = 2, Kr = 2, S0 = S0, S1 = S1, MW = 0, wt = 0.5, minimum_threshold = 0)
example1 <- full_algorithm(Kc = 2, Kr = 2, S0 = S0, S1 = S1, MW = 0, wt = 1, minimum_threshold = 0)

example0
example05
example1

cons0 <- similarity_taxon(S0 = S0, wt = 0, taxa = 'consumer')
res0 <- similarity_taxon(S0 = S0, wt = 0, taxa = 'resource')
taxo <- similarity_taxon(S0 = S0, wt = 1, taxa = 'consumer')

sim.example <- matrix(nrow = nrow(cons0), ncol = ncol(cons0))
sim.example[upper.tri(sim.example)] <- cons0[upper.tri(cons0)]
sim.example[lower.tri(sim.example)] <- taxo[lower.tri(taxo)]
diag(sim.example) <- S0[, 'taxon']


library(DiagrammeR)
grViz("

digraph boxes_and_circles{

    node [shape = box
            fixedsize = TRUE
            width = 2]
    1 [label = <<I>T<SUB>1</SUB></I>>]
    2 [label = <<I>T<SUB>9</SUB></I>>]
    3 [label = <<I>T<SUB>10</SUB></I>>]
    4 [label = <<I>T<SUB>11</SUB></I>>]
    5 [label = <<I>T<SUB>12</SUB></I>>]

1 -> 2
1 -> 5

}
")

grViz("
digraph boxes_and_circles{

    node [shape = box
            fixedsize = TRUE
            width = 0.2
            fontsize = 9
            color = white]
    6 [label = <<I>T<SUB>1</SUB></I>>]
    7 [label = <<I>T<SUB>9</SUB></I>>]
    8 [label = <<I>T<SUB>10</SUB></I>>]
    9 [label = <<I>T<SUB>11</SUB></I>>]
    10 [label = <<I>T<SUB>12</SUB></I>>]

    1 [label = <<I>T<SUB>1</SUB></I>>]
    2 [label = <<I>T<SUB>9</SUB></I>>]
    3 [label = <<I>T<SUB>10</SUB></I>>]
    4 [label = <<I>T<SUB>11</SUB></I>>]
    5 [label = <<I>T<SUB>12</SUB></I>>]


    1 -> 2 [arrowsize = 0.5]
    1 -> 3 [arrowsize = 0.5]
    1 -> 5 [arrowsize = 0.5]
    3 -> 2 [arrowsize = 0.5]
    3 -> 5 [arrowsize = 0.5]
    4 -> 1 [arrowsize = 0.5]
    5 -> 2 [arrowsize = 0.5]

    6 -> 7 [arrowsize = 0.5]
    6 -> 8 [color = 'white'; arrowsize = 0]
    6 -> 10 [arrowsize = 0.5]
    8 -> 7 [color = 'white'; arrowsize = 0]
    8 -> 10 [color = 'white'; arrowsize = 0]
    9 -> 6 [color = 'white'; arrowsize = 0]
    10 -> 7 [color = 'white'; arrowsize = 0]


    graph [ranksep = 0.15
            rank = source
            # rankdir = LR
            ]
}
")
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".", options = c()) {
            private$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
                script <- SlurmBashScript$new(dir, private$options)
            }
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        options = NULL,
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            # Display helpful message to the user
            stain_message_globals(globals)

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
library(staticdocs)

sd_section(
  "Connecting to Spark",
  "Functions for installing Spark components and managing connections to Spark.",
  c(
    "spark_config",
    "spark_connect",
    "spark_disconnect",
    "spark_install",
    "spark_log",
    "spark_web"
  )
)

sd_section(
  "Reading and Writing Data",
  "Functions for reading and writing Spark DataFrames.",
  c(
    "spark_read_csv",
    "spark_read_json",
    "spark_read_parquet",
    "spark_write_csv",
    "spark_write_json",
    "spark_write_parquet",
    "sdf-saveload"
  )
)

sd_section(
  "dplyr Interface",
  "Functions implementing a dplyr backend for Spark DataFrames.",
  c(
    "copy_to",
    "tbl_cache",
    "tbl_uncache"
  )
)

sd_section(
  "Spark DataFrames",
  "Functions for maniplulating Spark DataFrames.",
  c(
    "na.replace",
    "sdf_copy_to",
    "sdf_mutate",
    "sdf_partition",
    "sdf_predict",
    "sdf_read_column",
    "sdf_register",
    "sdf_sample",
    "sdf_sort",
    "sdf_with_unique_id"
  )
)

sd_section(
  "Machine Learning Algorithms",
  "Functions for invoking machine learning algorithms.",
  c(
    "ml_als_factorization",
    "ml_decision_tree",
    "ml_generalized_linear_regression",
    "ml_gradient_boosted_trees",
    "ml_kmeans",
    "ml_lda",
    "ml_linear_regression",
    "ml_logistic_regression",
    "ml_multilayer_perceptron",
    "ml_naive_bayes",
    "ml_one_vs_rest",
    "ml_pca",
    "ml_random_forest",
    "ml_survival_regression"
  )
)

sd_section(
  "Machine Learning Transformers",
  "Functions for transforming features in Spark DataFrames.",
  c(
    "ft_binarizer",
    "ft_bucketizer",
    "ft_discrete_cosine_transform",
    "ft_elementwise_product",
    "ft_index_to_string",
    "ft_one_hot_encoder",
    "ft_quantile_discretizer",
    "ft_sql_transformer",
    "ft_string_indexer",
    "ft_vector_assembler"
  )
)

sd_section(
  "Machine Learning Utilities",
  "Functions for interacting with Spark ML model fits.",
  c(
    "ml_binary_classification_eval",
    "ml_classification_eval",
    "ml_tree_feature_importance",
    "ml_saveload"
  )
)

sd_section(
  "Machine Learning Extensions",
  "Functions for creating custom wrappers to other Spark ML algorithms.",
  c(
    "ensure",
    "ml_create_dummy_variables",
    "ml_model",
    "ml_options",
    "ml_prepare_dataframe",
    "ml_prepare_response_features_intercept"
  )
)

sd_section(
  "Extensions API",
  "Functions for creating extensions to the sparklyr package",
  c(
    "compile_package_jars",
    "connection_config",
    "find_scalac",
    "hive_context",
    "invoke",
    "java_context",
    "register_extension",
    "spark_compilation_spec",
    "spark_default_compilation_spec",
    "spark_connection",
    "spark_context",
    "spark_dataframe",
    "spark_dependency",
    "spark_jobj",
    "spark_session",
    "spark_version"
  )
)
###############################################
### COMMONLY USED PACKAGES IN AIM R SCRIPTS ###
###############################################

#### DATA WRANGLING ####
install.packages(
  c(
    "dplyr", ## Notably useful for data frame manipulation with group_by(), summarize(), and mutate() and the piping operator %>%. Do you have a moment to hear the good news of our savior, piping?
    "tidyr", ## Lots of useful things, but specifically gather() and spread() for converting wide data frames into long ones and vice versa
    "stringr", ## All about character strings. Great for str_split() in particular, but the whole str_ family of functions are A+
    "RODBC", ## Allows R to pass SQL queries to Access databases and pull out the results
    "XLSX", ## Read in modern Excel workbooks and spreadsheets
    "broom" ## Get stats objects into tidy data frames. Not as common
  )
)

#### SPATIAL DATA ####
install.packages(
  c(
    "sp", ## Functions for manipulating spatial objects. If you want a Spatial _____ Data Frame, this is part of the deal
    "spsurvey", ## Contains plenty, but the most important to AIM is the GRTS function
    "rgeos", ## Additional spatial object functions
    "rgdal", ## Contains the mission critical readOGR() function that we read shapefiles in with
    "raster" ## Everything you didn't know you needed for dealing with rasters
  )
)

#### DATA VISUALIZATION ####
install.packages(
  c(
    "ggplot2", ## The go-to for figure generation. Most R-using scientists AND Nate Silver use it, so you should too
    "ggthemes", ## Quick themes to painlessly apply to figures from ggplot
    "ggmap", ## Mapping support for ggplot
    "RColorBrewer" ## All about making beautiful color palettes for maps and figures
  )
)

#### MISCELLANEOUS PACKAGES ####
## These are more ala carte. Pick and choose as you need them
install.packages("markdown") ## Generates documents with figures and everything based on your script, which means that if you change the data, the document changes to reflect it. POWERFUL.
install.packages("rJava") ## Chances are really good that this is already installed as a dependency for another package, but just to be safe, here it is
install.packages("devtools") ## For more granular control of the R environment when you need it, which may not be very often at all
install.packages("git2r") ## If you're going to use Git, this is important because it lets you use git from within R. It's a dependency of devtools though, so it may already be installed
install.packages("arcgisbinding") ## Young and finicky, but once you have it all installed (an ordeal) you should be able to read from and write to file geodatabases from R
install.packages("gridExtra") ## Lets you make grid objects that you can place ggplot figures into. May occasionally be preferable to faceting in ggplot, but rarely
install.packages("shiny") ## Required for working with Shiny tools in any form. Can be maddening
install.packages("purrr") ## Really, really useful for writing functions, particularly those that fail gracefully
install.packages("gstat") ## For spatial and spatio-temporal geostatistical modelling and simulation
install.packages("foreach") ## Parallel looping structures. Sarah McCord's thesis work required this
install.packages("snow") ## If you're doing distributed computing across multiple machines, grab thislibrary(staticdocs)

sd_section(
  "Connecting to Spark",
  "Functions for installing Spark components and managing connections to Spark",
  c(
    "spark_config",
    "spark_connect",
    "spark_disconnect",
    "spark_install",
    "spark_log",
    "spark_web"
  )
)

sd_section(
  "Reading and Writing Data",
  "Functions for reading and writing Spark DataFrames",
  c(
    "spark_read_csv",
    "spark_read_json",
    "spark_read_parquet",
    "spark_write_csv",
    "spark_write_json",
    "spark_write_parquet",
    "sdf-saveload"
  )
)

sd_section(
  "dplyr Interface",
  "Functions implementing a dplyr backend for Spark DataFrames",
  c(
    "copy_to",
    "tbl_cache",
    "tbl_uncache"
  )
)

sd_section(
  "Spark DataFrames",
  "Functions for maniplulating Spark DataFrames",
  c(
    "na.replace",
    "sdf_copy_to",
    "sdf_mutate",
    "sdf_partition",
    "sdf_predict",
    "sdf_read_column",
    "sdf_register",
    "sdf_sample",
    "sdf_sort",
    "sdf_with_unique_id"
  )
)

sd_section(
  "Machine Learning Algorithms",
  "Functions for invoking machine learning algorithms",
  c(
    "ml_als_factorization",
    "ml_decision_tree",
    "ml_generalized_linear_regression",
    "ml_gradient_boosted_trees",
    "ml_kmeans",
    "ml_lda",
    "ml_linear_regression",
    "ml_logistic_regression",
    "ml_multilayer_perceptron",
    "ml_naive_bayes",
    "ml_one_vs_rest",
    "ml_pca",
    "ml_random_forest",
    "ml_survival_regression"
  )
)

sd_section(
  "Machine Learning Transformers",
  "Functions for transforming features in Spark DataFrames",
  c(
    "ft_binarizer",
    "ft_bucketizer",
    "ft_discrete_cosine_transform",
    "ft_elementwise_product",
    "ft_index_to_string",
    "ft_one_hot_encoder",
    "ft_quantile_discretizer",
    "ft_sql_transformer",
    "ft_string_indexer",
    "ft_vector_assembler"
  )
)

sd_section(
  "Machine Learning Utilities",
  "Functions for interacting with Spark ML model fits",
  c(
    "ml_binary_classification_eval",
    "ml_classification_eval",
    "ml_tree_feature_importance",
    "ml_saveload"
  )
)

sd_section(
  "Machine Learning Extensions",
  "Functions for creating custom wrappers to other Spark ML algorithms",
  c(
    "ensure",
    "ml_create_dummy_variables",
    "ml_model",
    "ml_options",
    "ml_prepare_dataframe",
    "ml_prepare_response_features_intercept"
  )
)

sd_section(
  "Extensions API",
  "Functions for creating extensions to the sparklyr package",
  c(
    "compile_package_jars",
    "connection_config",
    "find_scalac",
    "hive_context",
    "invoke",
    "java_context",
    "register_extension",
    "spark_compilation_spec",
    "spark_default_compilation_spec",
    "spark_connection",
    "spark_context",
    "spark_dataframe",
    "spark_dependency",
    "spark_jobj",
    "spark_session",
    "spark_version"
  )
)
library(staticdocs)

sd_section(
  "Connecting to Spark",
  "Functions for installing Spark components and managing connections to Spark",
  c(
    "spark_config",
    "spark_connect",
    "spark_disconnect",
    "spark_install",
    "spark_log",
    "spark_web"
  )
)

sd_section(
  "Reading and Writing Data",
  "Functions for reading and writing Spark DataFrames",
  c(
    "spark_read_csv",
    "spark_read_json",
    "spark_read_parquet",
    "spark_write_csv",
    "spark_write_json",
    "spark_write_parquet"
  )
)

sd_section(
  "dplyr Interface",
  "Functions implementing a dplyr backend for Spark DataFrames",
  c(
    "copy_to",
    "tbl_cache",
    "tbl_uncache"
  )
)

sd_section(
  "Spark DataFrames",
  "Functions for maniplulating Spark DataFrames",
  c(
    "sdf_copy_to",
    "sdf_mutate",
    "sdf_partition",
    "sdf_predict",
    "sdf_read_column",
    "sdf_register",
    "sdf_sample",
    "sdf_sort",
    "sdf_with_unique_id"
  )
)

sd_section(
  "Machine Learning Algorithms",
  "Functions for invoking machine learning algorithms",
  c(
    "ml_als_factorization",
    "ml_decision_tree",
    "ml_generalized_linear_regression",
    "ml_gradient_boosted_trees",
    "ml_kmeans",
    "ml_lda",
    "ml_linear_regression",
    "ml_logistic_regression",
    "ml_multilayer_perceptron",
    "ml_naive_bayes",
    "ml_one_vs_rest",
    "ml_pca",
    "ml_random_forest",
    "ml_survival_regression"
  )
)

sd_section(
  "Machine Learning Utilities",
  "Functions for interacting with Spark ML model fits",
  c(
    "ml_binary_classification_eval",
    "ml_classification_eval",
    "ml_tree_feature_importance"
  )
)

sd_section(
  "Machine Learning Transformers",
  "Functions for transforming features in Spark DataFrames",
  c(
    "ft_binarizer",
    "ft_bucketizer",
    "ft_discrete_cosine_transform",
    "ft_elementwise_product",
    "ft_index_to_string",
    "ft_one_hot_encoder",
    "ft_quantile_discretizer",
    "ft_sql_transformer",
    "ft_string_indexer",
    "ft_vector_assembler"
  )
)

sd_section(
  "Machine Learning Utility Functions",
  "Functions for creating custom wrappers to other Spark ML algorithms",
  c(
    "ensure",
    "ml_create_dummy_variables",
    "ml_model",
    "ml_options",
    "ml_prepare_dataframe",
    "ml_prepare_response_features_intercept"
  )
)

sd_section(
  "Extensions API",
  "Functions for creating extensions to the sparklyr package",
  c(
    "compile_package_jars",
    "connection_config",
    "find_scalac",
    "hive_context",
    "invoke",
    "java_context",
    "register_extension",
    "spark_compilation_spec",
    "spark_default_compilation_spec",
    "spark_connection",
    "spark_context",
    "spark_dataframe",
    "spark_dependency",
    "spark_jobj",
    "spark_session",
    "spark_version"
  )
)
library(staticdocs)

sd_section(
  "Connecting to Spark",
  "Functions for installing Spark components and managing connections to Spark",
  c(
    "spark_config",
    "spark_connect",
    "spark_disconnect",
    "spark_install",
    "spark_log",
    "spark_web"
  )
)

sd_section(
  "Reading and Writing Data",
  "Functions for reading and writing Spark DataFrames",
  c(
    "spark_read_csv",
    "spark_read_json",
    "spark_read_parquet",
    "spark_write_csv",
    "spark_write_json",
    "spark_write_parquet"
  )
)

sd_section(
  "dplyr Interface",
  "Functions implementing a dplyr backend for Spark DataFrames",
  c(
    "copy_to",
    "tbl_cache",
    "tbl_uncache"
  )
)

sd_section(
  "Spark DataFrames",
  "Functions for maniplulating Spark DataFrames",
  c(
    "sdf_copy_to",
    "sdf_import",
    "sdf_mutate",
    "sdf_partition",
    "sdf_predict",
    "sdf_read_column",
    "sdf_register",
    "sdf_sample",
    "sdf_sort",
    "sdf_with_unique_id"
  )
)

sd_section(
  "Machine Learning Algorithms",
  "Functions for invoking machine learning algorithms",
  c(
    "ml_als_factorization",
    "ml_decision_tree",
    "ml_generalized_linear_regression",
    "ml_gradient_boosted_trees",
    "ml_kmeans",
    "ml_lda",
    "ml_linear_regression",
    "ml_logistic_regression",
    "ml_multilayer_perceptron",
    "ml_naive_bayes",
    "ml_one_vs_rest",
    "ml_pca",
    "ml_random_forest",
    "ml_survival_regression"
  )
)

sd_section(
  "Machine Learning Utilities",
  "Functions for interacting with Spark ML model fits",
  c(
    "ml_binary_classification_eval",
    "ml_classification_eval",
    "ml_tree_feature_importance"
  )
)

sd_section(
  "Machine Learning Transformers",
  "Functions for transforming features in Spark DataFrames",
  c(
    "ft_binarizer",
    "ft_bucketizer",
    "ft_discrete_cosine_transform",
    "ft_elementwise_product",
    "ft_index_to_string",
    "ft_one_hot_encoder",
    "ft_quantile_discretizer",
    "ft_sql_transformer",
    "ft_string_indexer",
    "ft_vector_assembler"
  )
)

sd_section(
  "Machine Learning Utility Functions",
  "Functions for creating custom wrappers to other Spark ML algorithms",
  c(
    "ensure_scalar_boolean",
    "ensure_scalar_character",
    "ensure_scalar_double",
    "ensure_scalar_integer",
    "ml_create_dummy_variables",
    "ml_model",
    "ml_options",
    "ml_prepare_dataframe",
    "ml_prepare_response_features_intercept"
  )
)

sd_section(
  "Extensions API",
  "Functions for creating extensions to the sparklyr package",
  c(
    "compile_package_jars",
    "connection_config",
    "find_scalac",
    "hive_context",
    "invoke",
    "invoke_new",
    "invoke_static",
    "java_context",
    "register_extension",
    "spark_compilation_spec",
    "spark_default_compilation_spec",
    "spark_connection",
    "spark_context",
    "spark_dataframe",
    "spark_dependency",
    "spark_jobj",
    "spark_session",
    "spark_version"
  )
)
sd_section("Connecting to Spark",
           "Functions for installing Spark components and managing connections to Spark.",
           c("spark_install",
             "spark_connect",
             "spark_log",
             "spark_web",
             "spark_disconnect",
             "spark_config")
)

sd_section("Reading and Writing Data",
           "Functions for reading and writing Spark DataFrames",
           c("spark_read_csv",
             "spark_read_json",
             "spark_read_parquet",
             "spark_write_csv",
             "spark_write_json",
             "spark_write_parquet")
)

sd_section("dplyr Interface",
           "Functions implementing a dplyr backend for Spark DataFrames",
           c("copy_to",
             "tbl_cache",
             "tbl_uncache")
)

sd_section("Spark DataFrames",
           "Functions for maniplulating Spark DataFrames",
           c("sdf_copy_to",
             "sdf_partition",
             "sdf_mutate",
             "sdf_sample",
             "sdf_sort",
             "sdf_predict",
             "sdf_register",
             "sdf_with_unique_id")
)

sd_section("Machine Learning Algorithms.",
           "Functions for invoking machine learning algorithms.",
           c("ml_kmeans",
             "ml_linear_regression",
             "ml_logistic_regression",
             "ml_survival_regression",
             "ml_generalized_linear_regression",
             "ml_decision_tree",
             "ml_random_forest",
             "ml_gradient_boosted_trees",
             "ml_pca",
             "ml_naive_bayes",
             "ml_multilayer_perceptron",
             "ml_lda",
             "ml_one_vs_rest",
             "ml_als_factorization",
             "ml_saveload")
)

sd_section("Machine Learning Transformers",
           "Functions for transforming features in Spark DataFrames",
           c("ft_binarizer",
             "ft_bucketizer",
             "ft_discrete_cosine_transform",
             "ft_elementwise_product",
             "ft_index_to_string",
             "ft_quantile_discretizer",
             "ft_sql_transformer",
             "ft_string_indexer",
             "ft_vector_assembler",
             "ft_one_hot_encoder"
           )
)

sd_section("Machine Learning Utility Functions",
           "Functions for creating custom wrappers to other Spark ML algorithms",
           c("ensure",
             "ml_model",
             "ml_prepare_dataframe",
             "ml_prepare_response_features_intercept",
             "ml_create_dummy_variables"
           )
)

sd_section("Extensions API",
           "Functions for creating extensions to the sparklyr package",
           c("invoke",
             "spark_connection",
             "connection_config",
             "spark_version",
             "spark_jobj",
             "spark_dataframe",
             "spark_context",
             "java_context",
             "hive_context",
             "register_extension",
             "spark_dependency")
)




# library(DiagrammeR)
grViz("

digraph boxes_and_circles{

    node [shape = box
            # fixedsize = TRUE
            # width = 2.5
            ]
            1 [label = <I(<I>T<SUB><font point-size='8'>C</font></SUB></I>) in <I>S0</I>?>]
            2 [label = <I(<I>T<sub><font point-size='8'>C</font></sub>,T<sub><font point-size='8'>R</font></sub></I>) in <I>S1</I>?>]
            3 [label = <Add I(<I>T<sub><font point-size='8'>C</font></sub>,T<sub><font point-size='8'>R</font></sub></I>) to<br/>predictions>]
            4 [label = <<I>K </I> most similar<br/>resource <I>T<sub><font point-size='8'>R&apos;</font></sub></I>>]
            5 [label = <I(<I>T<sub><font point-size='8'>C</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub></I>) in <I>C<SUB><font point-size='8'>R</font></SUB></I>?>]
            6 [label = <Add weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I><br/>to I(<I>T<sub><font point-size='8'>C</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub></I>) in <I>C<SUB><font point-size='8'>R</font></SUB></I> if<br/><I>t </I> &gt; minimum threshold>]
            7 [label = <Add I(<I>T<sub><font point-size='8'>C</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub></I>) to <I>C<SUB><font point-size='8'>R</font></SUB></I><br/>with weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I> if<br/><I>t </I> &gt; minimum threshold>]
            8 [label = <<I>K </I> most similar<br/>consumer <I>T<sub><font point-size='8'>C&apos;</font></sub></I>>]
            9 [label = <I(<I>T<sub><font point-size='8'>C&apos;</font></sub>,T<sub><font point-size='8'>R</font></sub></I>) in <I>S1</I>?>]
            10 [label = <I(<I>T<sub><font point-size='8'>C&apos;</font></sub>,T<sub><font point-size='8'>R</font></sub></I>) in <I>C<SUB><font point-size='8'>R</font></SUB></I>?>]
            11 [label = <Add 1 to I(<I>T<sub><font point-size='8'>C&apos;</font></sub>,T<sub><font point-size='8'>R</font></sub></I>)<br/>weight in <I>C<SUB><font point-size='8'>R</font></SUB></I>>]
            12 [label = <Add I(<I>T<sub><font point-size='8'>C&apos;</font></sub>,T<sub><font point-size='8'>R</font></sub></I>) to <I>C<SUB><font point-size='8'>R </font></SUB></I><br/>with weight = 1>]
            13 [label = <<I>K </I> most similar<br/>resource <I>T<sub><font point-size='8'>R&apos;</font></sub></I>>]
            14 [label = <I(<I>T<sub><font point-size='8'>C&apos;</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub></I>) in <I>C<SUB><font point-size='8'>R</font></SUB></I>?>]
            15 [label = <Add weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I><br/>to I(<I>T<sub><font point-size='8'>C</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub></I>) in <I>C<SUB><font point-size='8'>R</font></SUB></I> if<br/><I>t </I> &gt; minimum threshold>]
            16 [label = <Add I(<I>T<sub><font point-size='8'>C</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub></I>) to <I>C<SUB><font point-size='8'>R</font></SUB></I><br/>with weight = <I>t(T<sub><font point-size='8'>R</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub>,w<sub><font point-size='8'>t</font></sub>) </I> if<br/><I>t </I> &gt; minimum threshold>]
            17 [label = <Add I(<I>T<sub><font point-size='8'>C</font></sub>,T<sub><font point-size='8'>R&apos;</font></sub></I>) to predictions if weight &gt; minimum weight>]

1 -> 2 [label = 'Yes', headport = 'n', tailport = 'w']
1 -> 3 [color = 'transparent']
1 -> 4 [color = 'transparent']
1 -> 5 [color = 'transparent']
1 -> 6 [color = 'transparent']
1 -> 7 [color = 'transparent']
1 -> 8 [color = 'transparent']
2 -> 3 [label = 'Yes']
2 -> 4 [label = 'No']
4 -> 5
5 -> 6 [label = 'Yes']
5 -> 7 [label = 'No']
6 -> 17
7 -> 17
1 -> 8 [label = 'No', headport = 'n', tailport = 'e']
8 -> 9
9 -> 10 [label = 'Yes']
10 -> 11 [label = 'Yes']
10 -> 12 [label = 'No']
11 -> 17
12 -> 17
9 -> 13 [label = 'No']
13 -> 14
14 -> 15 [label = 'Yes']
14 -> 16 [label = 'No']
15 -> 17
16 -> 17

graph [ranksep = 0.15
        rank = sink
        # rankdir = LR
        # splines = ortho
        ]


}
")
# Script for producing animation on danish population

# convert -delay 10 -loop 0 frame* befolkning.gif


IMAGEFILE = '~/tmp/frame%03d.png'
PLOTTITLE = 'Population, Denmark, %s'
data1 <- read.csv("befolkningstal1901-1970.csv", head=TRUE, row.names = 1)
# For same reason All lables are prefixed with an X. 
colnames(data1) = gsub("X","",colnames(data1))

data2 <- read.csv("befolkningstal.csv")

frameI = 1

# maxcount =  max(data1, na.rm = TRUE)
# for(i in 1:ncol(data1)){
# 	frameName = sprintf(IMAGEFILE, frameI)
# 	frameI = frameI + 1

# 	plotTitle = sprintf(PLOTTITLE, colnames(data1)[i])
# 	png(frameName)
# 	barplot(data1[,i], main = plotTitle, ylab = "Count", xlab = "Age", ylim = c(0,maxcount), xlim = c(0,25), names.arg = rownames(data1))
# 	dev.off()
# }

maxcount =  max(data2, na.rm = TRUE)
originYear = 1970
for(i in 1:ncol(data2)){
	frameName = sprintf(IMAGEFILE, frameI)
	frameI = frameI + 1
	totalPopulation = sum(data2[,i], na.rm = TRUE)
	plotTitle = sprintf("Population, Denmark, %d 
Total Population: %d", originYear + i, totalPopulation)

	png(frameName)
	barplot(data2[,i], main = plotTitle, ylab = "Count", xlab ="Age", ylim=c(0,maxcount),
	 xlim = c(0,100), border = NA, space = 0, names.arg = 1:nrow(data2)-1)
	dev.off()
}

require(dplyr)
require(rvest)
require(gsubfn)

url<-'https://en.wikipedia.org/wiki/2014%E2%80%9315_NBA_season'

#stran <- html_session(url) %>% read_html(encoding = "UTF-8")
#tabela <- stran %>% html_nodes(xpath ="//table[5]") %>% .[[1]] %>% html_table()

podatki<-read.csv("podatki.csv", header=TRUE, sep=",", dec=".", stringsAsFactors = FALSE, na.strings = ".")
podatki$Rk<-NULL
podatki$eFG.<-NULL
a<-c(6:28)
suppressWarnings(podatki[a]<-lapply(podatki[a], as.numeric))
podatki<-podatki[!is.na(podatki$PTS),]
#podatki<-na.omit(podatki)
colnames(podatki)[28]<-"PTS"
podatki<-podatki[order(podatki[,28], decreasing = TRUE),]

link<-'http://www.spotrac.com/widget/sport/nba/current-year/rankings-cap/"'
site<-html_session(link) %>% read_html(encoding = "UTF-8")
salaries<-site %>% html_nodes(xpath ="//table") %>% .[[1]] %>% html_table()
place<-site %>% html_nodes(xpath ="//table") %>% .[[1]] %>% html_table()
place<-place[-1]
salaries<-salaries[-1]
salaries$Pos.<-NULL

celatabela<-inner_join(podatki, salaries, by = "Player")
colnames(celatabela)<-c("Player","Position" ,"Age","Team","Games","Started","Minutes","FG Made", "FG Att","FG %","3Pt Made", "3Pt Att", "3Pt %", "2Pt Made", "2Pt Att", "2Pt %", "FT Made", "FT Att", "FT %", "Off. Reb", "Def. Reb", "Tot. Reb", "Assists", "Steals", "Blocks", "Turnovers", "Fouls", "Points", "Salary")
celatabela$Salary<-as.factor(celatabela$Salary)
celatabela$Salary<-gsub("\\$", "", celatabela$Salary)
celatabela$Salary<-gsub("\\,", "", celatabela$Salary)
celatabela$Salary<-as.numeric(celatabela$Salary)

strelci<-data.frame(Player=celatabela$Player, Points=celatabela$Points)

zlink<-'http://hoopshype.com/2015/02/24/where-are-nba-players-born/'
zstran <- html_session(zlink) %>% read_html(encoding = "UTF-8")
ztabela <- zstran %>% html_nodes(xpath ="//table[2]") %>% .[[1]]  %>% html_table()
ztabela<-na.omit(ztabela)
ztabela<-ztabela[-1,-3]
colnames(ztabela)<-c('City','Players')
ztabela$City<-as.factor(ztabela$City)
ztabela$Players<-as.numeric(ztabela$Players)
ztabela$City<-gsub('[[:digit:]]+', '', ztabela$City)
ztabela$City<-gsub('\\.', '', ztabela$City)
ztabela<-ztabela[-11,]
ztabela1<-ztabela
ztabela$Lat<-c('34.052235', '40.792240', '41.881832', '40.002785', '32.736259', '39.790942', '47.608013', '30.471165', '35.040031', '39.299236', '29.761993', '33.753746', '38.889931', '33.792461', '38.627003')
ztabela$Long<-c('-118.243683', '-73.138260', '-87.623177', '-75.183739', '-96.864586', '-86.147685', '-122.335167', '-91.147385', '-89.981873', '-76.609383', '-95.366302', '-84.386330', '-77.009003', '-118.185005', '-90.199402')
ztabela$STATE_NAME<-c('California', 'New York', 'Illinois', 'Pennsylvania', 'Texas', 'Indiana', 'Washington', 'Louisiana', 'Tennessee', 'Maryland', 'Texas', 'Georgia', 'District of Columbia', 'California', 'Missouri')
ztabela$Lat<-as.numeric(ztabela$Lat)
ztabela$Long<-as.numeric(ztabela$Long)
source("lib/uvozi.zemljevid.r", encoding = "UTF-8")
library(ggplot2)

pretvori.zemljevid <- function(zemljevid) {
  fo <- fortify(zemljevid)
  data <- zemljevid@data
  data$id <- as.character(0:(nrow(data)-1))
  return(inner_join(fo, data, by="id"))
}

zda <- uvozi.zemljevid("http://baza.fmf.uni-lj.si/states_21basic.zip", "states")
ztabela <- preuredi(ztabela, zda, "STATE_NAME")
usa<-pretvori.zemljevid(zda)
usa.cont <- usa %>% filter(! STATE_NAME %in% c("Alaska", "Hawaii"))
map <- ggplot() + geom_polygon(data = usa.cont, color='navajowhite3', aes(x = long, y = lat, group=group),fill="navajowhite")
require(ggrepel)
map1 <- map + geom_point(data = ztabela, color = "green4", aes(x = Long, y = Lat, size = Players)) + geom_text_repel(data = ztabela, color='black', aes(x = Long, y = Lat, label = City), size=5)
map1

ekipe<-read.csv('teams__active.csv')
ekipe$Lg<-NULL
ekipe$To<-NULL
ekipe$Yrs<-NULL
ekipe$W.L.<-NULL
colnames(ekipe)<-c('Team', 'Founded', 'Games', 'Won', 'Lost', 'Playoffs', 'Div. titles', 'Conf. titles', 'Championships')
ekipe1<-ekipe
ekipe<-ekipe[-28,]
ekipe$STATE_NAME<-c('Georgia', 'Massachusetts', 'New York', 'North Carolina', 'Illinois', 'Ohio','Texas','Colorado','Michigan','California','Texas','Indiana','California','California','Tennessee','Florida','Wisconsin','Minnesota','Louisianna','New York','Oklahoma','Florida','Pennsylvania','Arizona','Oregon','California','Texas','Utah','District of Columbia')
ekipe$LAT<-c('33.75375', '42.35843', '40.35000','35.227085', '41.881832','41.505493','32.73626','39.742043','42.331429','	37.801239','29.682720','39.769653','34.052235','34.052235','35.040031',	'25.778135','43.038902','44.986656','29.951065','40.79224','35.481918','28.538336','40.00279','33.453388','45.512794','38.575764','29.424349','40.758701','38.88993')
ekipe$LONG<-c('-84.38633', '-71.05977', '-73.949997', '-80.843124','-87.623177','	-81.681290','-96.86459','	-104.991531','	-83.045753','-122.258301','-95.593239','-86.157143','-118.243683','-118.243683','-89.981873','-80.179100','-87.906471','-93.258133','-90.071533','-73.13826','-97.508469','-81.379234','-75.18374','-112.074623','-122.679565','-121.478851','-98.491142','-111.876183','-77.00900')
ekipe$LAT<-as.numeric(ekipe$LAT)
ekipe$LONG<-as.numeric(ekipe$LONG)
ekipe<-preuredi(ekipe,zda,'STATE_NAME')
map2<-map+geom_point(data=ekipe,color='red',size=2,aes(x=LONG,y=LAT)) + geom_text_repel(data=ekipe,color='black',aes(x=LONG,y=LAT,label=Team),size=5)
map2

#graf1 <- ggplot(celatabela$Points, celatabela$Salary, main="Število točk glede na plačo", xlab="Točke", ylab="Plača")
# # # setwd('C:/Users/garre/Dropbox/aa projects/DIVA')

# # backprop
# backpropagate error and update weights
# #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
backprop <- function(out_wts, in_wts, out_activation, current_target, 
                     hid_activation, hid_activation_raw, ins_w_bias, learning_rate){

  # # # calc error on output units
  out_delta <- 2 * (out_activation - current_target)
  
  # # # calc error on hidden units
  hid_delta <- out_delta %*% t(out_wts)
  hid_delta <- hid_delta[,2:ncol(hid_delta)] * sigmoid_grad(hid_activation_raw)
  
  # # # calc weight changes
  out_delta <- learning_rate * (t(hid_activation) %*% out_delta)
  hid_delta <- learning_rate * (t(ins_w_bias) %*% hid_delta)

  # # # adjust wts
  out_wts <- out_wts - out_delta
  in_wts <- in_wts - hid_delta

  return(list(out_wts = out_wts, 
              in_wts  = in_wts))

}

# forward_pass
# conduct forward pass
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
forward_pass <- function(in_wts, out_wts, inputs, out_rule) {
  # # # init needed vars
  num_feats <- ncol(out_wts)
  num_cats  <- dim(out_wts)[3]
  num_stims <- nrow(inputs)
  if (is.null(num_stims)) {num_stims <- 1}

  
  # # # add bias to ins
  bias_units <- matrix(rep(1, num_stims), ncol = 1, nrow = num_stims)
  ins_w_bias <- cbind(bias_units,
    matrix(inputs, nrow = num_stims, ncol = num_feats, byrow = TRUE))

  # # # ins to hids propagation
  hid_activation_raw <- ins_w_bias %*% in_wts
  hid_activation <- sigmoid(hid_activation_raw)

  # # # add bias unit to hid activation
  hid_activation <- cbind(bias_units, hid_activation)  

  # # # hids to outs propagation
  out_activation <- array(rep(0, (num_stims * num_feats * num_cats)), 
    dim = c(num_stims, num_feats, num_cats))
  
  # # NEED VECTORIZED HERE
  # # # get output activation
  for (category in 1:num_cats) {
  	out_activation[,,category] <- hid_activation %*% out_wts[,,category]
  }
  
  # # # apply output activatio rule
  if(out_rule == 'sigmoid') {
  	out_activation <- sigmoid(out_activation)
  }

  return(list(out_activation     = out_activation, 
              hid_activation     = hid_activation,
              hid_activation_raw = hid_activation_raw, 
              ins_w_bias         = ins_w_bias))

}

# get_wts
# generate net weights
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
get_wts <- function(num_feats, num_hids, num_cats, wts_range, wts_center) {
  # # # set bias
  bias <- 1
  
  # # # generate wts between ins and hids
  in_wts <- 
    (matrix(runif((num_feats + bias) * num_hids), ncol = num_hids) - 0.5) * 2 
  in_wts <- wts_center + (wts_range * in_wts)

  # # # generate wts between hids and outs
  out_wts <- 
    (array(runif((num_hids + bias) * num_feats * num_cats), 
      dim = c((num_hids + bias), num_feats, num_cats)) - 0.5) * 2
  out_wts <- wts_center + (wts_range * out_wts)   
  
  return(list(in_wts  = in_wts, 
              out_wts = out_wts))

}

# global_scale
# scale inputs to 0/1
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
global_scale <- function(x) { x / 2 + 0.5 }

#plot training
# function to produce line plot of training
train_plot <- function(training){
  n_cats <- dim(training)[2]
  xrange <- c(1, dim(training)[1])
  yrange <- range(training)

  pdf('training_plot.pdf')

  plot(xrange, c(.01, yrange[2]), xlab = 'Block Number', ylab = 'Accuracy')

  colors <- rainbow(n_cats)
  line_type <- c(1:n_cats)
  plot_char <- seq(18, 18 + n_cats, 1)

  for (i in 1:n_cats) {
    target_cat <- training[,i]
    lines(seq(1, xrange[2], 1), target_cat, type = 'b', lwd = 1.5, 
      lty = line_type[i], col = colors[i],  pch = plot_char[i])
  }

  title('DIVA Training Accuracy across Blocks')

  legend('bottomright', y = NULL, 1:n_cats, cex = 0.8, col = colors, 
    pch = plot_char, lty = line_type, title = 'SHJ Categories')

  dev.off()
}

# response_rule
# convert output activations to classification
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
response_rule <- function(out_activation, target_activation, beta_val){
  num_feats <- ncol(out_activation)
  num_cats  <- dim(out_activation)[3]
  num_stims <- nrow(target_activation)
  if (is.null(num_stims)) {num_stims <- 1}

  # # # calc error  
  ssqerror <- array(as.vector(
    apply(out_activation, 3, function(x) {x - target_activation})),
      c(num_stims, num_feats, num_cats))
  ssqerror <- ssqerror ^ 2
  ssqerror[ssqerror < 1e-7] <- 1e-7

  # # # generate focus weights
  if(dim(out_activation)[3] > 2 | dim(out_activation)[1] > 1){
    stop('Not coded for >2 channels or batch mode, sorry!')
  } else {
    
    # # # get pairwise differences for feature activation
    # # # this needs to be coded to adjust for n>2 cats
    diversities <- 
      exp(beta_val * diag(as.matrix(dist(out_activation, upper = TRUE))[1:3,4:6]))
    diversities[diversities > 1e+7] <- 1e+7

    # divide diversities by sum of diversities
    fweights = diversities / sum(diversities)

    # # # apply focus weights; then get sum for each category
    ssqerror <- t(apply(ssqerror, 3, function(x) sum(x * fweights))) 
    ssqerror <- 1 / ssqerror
  }

return(list(ps       = (ssqerror / sum(ssqerror)), 
            fweights = fweights, 
            ssqerror = ssqerror))

}

# run_diva
# trains vanilla diva
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
run_diva <- function(model) {
  
  # # # get new seed
  seed <- runif(1) * 100000 * runif(1)
  set.seed(seed)
  
  # # # set mean value of weights
  model$wts_center <- 0 
  # # # convert targets to 0/1
  model$targets <- global_scale(model$inputs) 
  # # # init size parameter variables
  model$num_feats   <- ncol(model$inputs)
  model$num_stims   <- nrow(model$inputs)
  model$num_cats    <- length(unique(model$labels))
  model$num_updates <- model$num_blocks * model$num_stims
  # # # init training accuracy matrix
  training <- 
    matrix(rep(NA, model$num_updates * model$num_inits), 
      nrow = model$num_updates, ncol = model$num_inits)
  
  # # # initialize and run DIVA models
  for (model_num in 1:model$num_inits) {
    
    # # # generate weights
    wts <- get_wts(model$num_feats, model$num_hids, model$num_cats, model$wts_range, model$wts_center)

    # # # generate presentation order
    prez_order <- as.vector(apply(replicate(model$num_blocks, 
      seq(1, model$num_stims)), 2, sample, model$num_stims))

    # # # iterate over each trial in the presentation order 
    for (trial_num in 1:model$num_updates) {
      current_input  <- model$inputs[prez_order[[trial_num]], ]
      current_target <- model$targets[prez_order[[trial_num]], ]
      current_class  <- model$labels[prez_order[[trial_num]]] 

      # # # complete forward pass
      fp <- forward_pass(wts$in_wts, wts$out_wts, current_input, model$out_rule)
    
      # # # calculate classification probability
      response <- response_rule(fp$out_activation, current_target, model$beta_val)

      # # # store classification accuracy
      training[trial_num, model_num] = response$ps[current_class]

      # # # back propagate error to adjust weights
      class_wts <- wts$out_wts[,,current_class]
      class_activation <- fp$out_activation[,,current_class]

      adjusted_wts <- backprop(class_wts, wts$in_wts, class_activation, current_target,  
               fp$hid_activation, fp$hid_activation_raw, fp$ins_w_bias, model$learning_rate)

      wts$out_wts[,,current_class] <- adjusted_wts$out_wts
      wts$in_wts <- adjusted_wts$in_wts
  
    }

  }

training_means <- 
  rowMeans(matrix(rowMeans(training), nrow = model$num_blocks, ncol = model$num_stims, byrow = TRUE))

return(list(training = training_means))

}

# shj_cats
# loads shj category structures
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
shj_cats <- function(type){
  
  if (type == 1) {
    in_patterns <- 
      matrix(c(1,  1,  1,
	             1,  1, -1,
	             1, -1,  1,
  	           1, -1, -1,
	            -1, -1,  1,
	            -1, -1, -1,
	            -1,  1,  1,
	            -1,  1, -1), nrow = 8, ncol = 3, byrow = TRUE)		

  } else if (type == 2){
  	in_patterns <-
  	  matrix(c(1,  1,  1,
  	  	       1,  1, -1,
       	      -1, -1,	 1,
	            -1, -1, -1,
	            -1,	 1,	 1,
	            -1,	 1, -1,
	  	         1, -1,	 1,
		           1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 3){
  	in_patterns <-
  	  matrix(c(1,  1,  1,
  	  	       1,  1, -1,
  	  	       1, -1,  1, 
  	          -1,  1, -1,
  	           1, -1, -1, 
  	          -1,  1,  1, 
  	          -1, -1,  1, 
  	          -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 4){
    in_patterns <-
      matrix(c(1,  1,  1,
               1,  1, -1,
               1, -1,  1,
              -1,  1,  1,
               1, -1, -1,
              -1,  1, -1,
              -1, -1,  1,
              -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 5){
    in_patterns <-
      matrix(c(1,  1,  1,
               1,  1, -1,
               1, -1,  1,
              -1, -1, -1,
               1, -1, -1,
              -1,  1,  1,
              -1,  1, -1,
              -1, -1,  1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 6){
    in_patterns <-
      matrix(c(1,  1,  1,
               1, -1, -1,
              -1,  1, -1,
              -1, -1,  1,
               1,  1, -1,
               1, -1,  1,
              -1,  1,  1,
              -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  }

cat_assignment <- c(1, 1, 1, 1, 2, 2, 2, 2)

return(list(inputs = in_patterns, 
			      labels = cat_assignment))

}

# sigmoid
# returns sigmoid evaluated elementwize in X
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
sigmoid <- function(x) {
  g = 1 / (1 + exp(-x))
  return(g)

}

# sigmoid gradient
# returns the gradient of the sigmoid function evaluated at x
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
sigmoid_grad <- function(x) {
  return(g = ((sigmoid(x)) * (1 - sigmoid(x))))

}# # # setwd('C:/Users/garre/Dropbox/aa projects/DIVA')

# # backprop
# #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
backprop <- function(out_wts, in_wts, out_activation, current_target, 
                     hid_activation, hid_activation_raw, ins_w_bias, learning_rate){

  # # # calc error on output units
  out_delta <- 2 * (out_activation - current_target)
  
  # # # calc error on hidden units
  hid_delta <- out_delta %*% t(out_wts)
  hid_delta <- hid_delta[,2:ncol(hid_delta)] * sigmoid_grad(hid_activation_raw)
  
  # # # calc weight changes
  out_delta <- learning_rate * (t(hid_activation) %*% out_delta)
  hid_delta <- learning_rate * (t(ins_w_bias) %*% hid_delta)

  # # # adjust wts
  out_wts <- out_wts - out_delta
  in_wts <- in_wts - hid_delta

  return(list(out_wts = out_wts, 
              in_wts  = in_wts))

}

# forward_pass
# conduct forward pass
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
forward_pass <- function(in_wts, out_wts, inputs, out_rule) {
  # # # init needed vars
  num_feats <- ncol(out_wts)
  num_cats  <- dim(out_wts)[3]
  num_stims <- nrow(inputs)
  if (is.null(num_stims)) {num_stims <- 1}

  
  # # # add bias to ins
  bias_units <- matrix(rep(1, num_stims), ncol = 1, nrow = num_stims)
  ins_w_bias <- cbind(bias_units,
    matrix(inputs, nrow = num_stims, ncol = num_feats, byrow = TRUE))

  # # # ins to hids propagation
  hid_activation_raw <- ins_w_bias %*% in_wts
  hid_activation <- sigmoid(hid_activation_raw)

  # # # add bias unit to hid activation
  hid_activation <- cbind(bias_units, hid_activation)  

  # # # hids to outs propagation
  out_activation <- array(rep(0, (num_stims * num_feats * num_cats)), 
    dim = c(num_stims, num_feats, num_cats))
  # # NEED VECTORIZED HERE
  for (category in 1:num_cats) {
  	out_activation[,,category] <- hid_activation %*% out_wts[,,category]
  }
  
  # # # apply output activatio rule
  if(out_rule == 'sigmoid') {
  	out_activation <- sigmoid(out_activation)
  }

  return(list(out_activation     = out_activation, 
              hid_activation     = hid_activation,
              hid_activation_raw = hid_activation_raw, 
              ins_w_bias         = ins_w_bias))

}

# get_wts
# generate net weights
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
get_wts <- function(num_feats, num_hids, num_cats, wts_range, wts_center) {
  # # # set bias
  bias <- 1
  
  # # # generate wts between ins and hids
  in_wts <- 
    (matrix(runif((num_feats + bias) * num_hids), ncol = num_hids) - 0.5) * 2 
  in_wts <- wts_center + (wts_range * in_wts)

  # # # generate wts between hids and outs
  out_wts <- 
    (array(runif((num_hids + bias) * num_feats * num_cats), 
      dim = c((num_hids + bias), num_feats, num_cats)) - 0.5) * 2
  out_wts <- wts_center + (wts_range * out_wts)   
  
  return(list(in_wts  = in_wts, 
              out_wts = out_wts))

}

# global_scale
# scale inputs to 0/1
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
global_scale <- function(x) { x / 2 + 0.5 }

#plot training
# function to produce line plot of training
train_plot <- function(training){
  n_cats <- dim(training)[2]
  xrange <- c(1, dim(training)[1])
  yrange <- range(training)

  pdf('training_plot.pdf')

  plot(xrange, c(.01, yrange[2]), xlab = 'Block Number', ylab = 'Accuracy')

  colors <- rainbow(n_cats)
  line_type <- c(1:n_cats)
  plot_char <- seq(18, 18 + n_cats, 1)

  for (i in 1:n_cats) {
    target_cat <- training[,i]
    lines(seq(1, xrange[2], 1), target_cat, type = 'b', lwd = 1.5, 
      lty = line_type[i], col = colors[i],  pch = plot_char[i])
  }

  title('DIVA Training Accuracy across Blocks')

  legend('bottomright', y = NULL, 1:n_cats, cex = 0.8, col = colors, 
    pch = plot_char, lty = line_type, title = 'SHJ Categories')

  dev.off()
}

# response_rule
# convert output activations to classification
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
response_rule <- function(out_activation, target_activation, beta_val){
  num_feats <- ncol(out_activation)
  num_cats  <- dim(out_activation)[3]
  num_stims <- nrow(target_activation)
  if (is.null(num_stims)) {num_stims <- 1}

  # # # calc error  
  ssqerror <- array(as.vector(
    apply(out_activation, 3, function(x) {x - target_activation})),
      c(num_stims, num_feats, num_cats))
  ssqerror <- ssqerror ^ 2
  ssqerror[ssqerror < 1e-7] <- 1e-7

  # # # generate focus weights
  if(dim(out_activation)[3] > 2 | dim(out_activation)[1] > 1){
    stop('Not coded for >2 channels or batch mode, sorry!')
  } else {
    
    # # # get pairwise differences for feature activation
    # # # this needs to be coded to adjust for n>2 cats
    diversities <- 
      exp(beta_val * diag(as.matrix(dist(out_activation, upper = TRUE))[1:3,4:6]))
    diversities[diversities > 1e+7] <- 1e+7

    # divide diversities by sum of diversities
    fweights = diversities / sum(diversities)

    # # # apply focus weights; then get sum for each category
    ssqerror <- t(apply(ssqerror, 3, function(x) sum(x * fweights))) 
    ssqerror <- 1 / ssqerror
  }

return(list(ps       = (ssqerror / sum(ssqerror)), 
            fweights = fweights, 
            ssqerror = ssqerror))

}

# run_diva
# trains vanilla diva
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
run_diva <- function(model) {
  # # # get new seed
  seed <- runif(1) * 100000 * runif(1)
  set.seed(seed)
  # # # set mean value of weights
  model$wts_center <- 0 
  # # # convert targets to 0/1
  model$targets <- global_scale(model$inputs) 
  
  # # # init size parameter variables
  model$num_feats   <- ncol(model$inputs)
  model$num_stims   <- nrow(model$inputs)
  model$num_cats    <- length(unique(model$labels))
  model$num_updates <- model$num_blocks * model$num_stims
  
  # # # init training accuracy matrix
  training <- 
    matrix(rep(NA, model$num_updates * model$num_inits), 
      nrow = model$num_updates, ncol = model$num_inits)
  
  # # # initialize and run DIVA models
  for (model_num in 1:model$num_inits) {
    
    # # # generate weights
    wts <- get_wts(model$num_feats, model$num_hids, model$num_cats, model$wts_range, model$wts_center)

    # # # generate presentation order
    prez_order <- rep(1:model$num_stims, model$num_blocks)

    # # # iterate over each trial in the presentation order 
    for (trial_num in 1:model$num_updates) {
      current_input  <- model$inputs[prez_order[[trial_num]], ]
      current_target <- model$targets[prez_order[[trial_num]], ]
      current_class  <- model$labels[prez_order[[trial_num]]] 

      # # # complete forward pass
      fp <- forward_pass(wts$in_wts, wts$out_wts, current_input, model$out_rule)
    
      # print(hid_activation)
      # print(out_activation)
      # readline(' ')
      # # # calculate classification probability
      response <- response_rule(fp$out_activation, current_target, model$beta_val)

      # # # store classification accuracy
      training[trial_num, model_num] = response$ps[current_class]

      # # # back propagate error to adjust weights
      class_wts <- wts$out_wts[,,current_class]
      class_activation <- fp$out_activation[,,current_class]

      adjusted_wts <- backprop(class_wts, wts$in_wts, class_activation, current_target,  
               fp$hid_activation, fp$hid_activation_raw, fp$ins_w_bias, model$learning_rate)

      wts$out_wts[,,current_class] <- adjusted_wts$out_wts
      wts$in_wts <- adjusted_wts$in_wts

      # print(in_wts)
      # print(out_wts[,,current_class])
      # readline(' ')
      
    }

  }

training_means <- 
  rowMeans(matrix(rowMeans(training), nrow = model$num_blocks, ncol = model$num_stims, byrow = TRUE))

return(list(training = training_means))

}

# shj_cats
# loads shj category structures
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
shj_cats <- function(type){
  
  if (type == 1) {
    in_patterns <- 
      matrix(c(1,  1,  1,
	             1,  1, -1,
	             1, -1,  1,
  	           1, -1, -1,
	            -1, -1,  1,
	            -1, -1, -1,
	            -1,  1,  1,
	            -1,  1, -1), nrow = 8, ncol = 3, byrow = TRUE)		

  } else if (type == 2){
  	in_patterns <-
  	  matrix(c(1,  1,  1,
  	  	       1,  1, -1,
       	      -1, -1,	 1,
	            -1, -1, -1,
	            -1,	 1,	 1,
	            -1,	 1, -1,
	  	         1, -1,	 1,
		           1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 3){
  	in_patterns <-
  	  matrix(c(1,  1,  1,
  	  	       1,  1, -1,
  	  	       1, -1,  1, 
  	          -1,  1, -1,
  	           1, -1, -1, 
  	          -1,  1,  1, 
  	          -1, -1,  1, 
  	          -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 4){
    in_patterns <-
      matrix(c(1,  1,  1,
               1,  1, -1,
               1, -1,  1,
              -1,  1,  1,
               1, -1, -1,
              -1,  1, -1,
              -1, -1,  1,
              -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 5){
    in_patterns <-
      matrix(c(1,  1,  1,
               1,  1, -1,
               1, -1,  1,
              -1, -1, -1,
               1, -1, -1,
              -1,  1,  1,
              -1,  1, -1,
              -1, -1,  1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 6){
    in_patterns <-
      matrix(c(1,  1,  1,
               1, -1, -1,
              -1,  1, -1,
              -1, -1,  1,
               1,  1, -1,
               1, -1,  1,
              -1,  1,  1,
              -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  }

cat_assignment <- c(1, 1, 1, 1, 2, 2, 2, 2)

return(list(inputs = in_patterns, 
			      labels = cat_assignment))

}

# sigmoid
# returns sigmoid evaluated elementwize in X
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
sigmoid <- function(x) {
  g = 1 / (1 + exp(-x))
  return(g)

}

# sigmoid gradient
# returns the gradient of the sigmoid function evaluated at x
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
sigmoid_grad <- function(x) {
  return(g = ((sigmoid(x)) * (1 - sigmoid(x))))

}# Prediction efficiency in two ways, plus identity of taxa for which we obtain a, b, c or d
prediction_accuracy_id <- function(predicted, empirical) {
    # Parameters:
    #   predicted   matrix of predicted interactions
    #   empirical   matrix of empirical interactions

    #   Output      vector of a, b, c, d, and TSS
    #       a       number of links predicted (1) and observed (1)
    #       b       number predicted (1) but not observed (0)
    #       c       number predicted absent (0) but observed (1)
    #       d       number of predicted absent (0) and observed absent (0)
    #       TSS     TSS = (ad-bc)/[(a+c)(b+d)]
    #                   "[...] quantifies the proportion of prediction success relative to false predictions
    #                   and returns values ranging between 1 (perfect predictions) and 1 (inverted forecast)
    #                   (Allouche, Tsoar & Kadmon 2006)." Gravel et al. 2013
    #       ScoreY1 Fraction of 1 correctly predicted a / (a + c)
    #       ScoreY0 Fraction of 0 correctly predicted d / (b + d)
    #       FSS     FSS = ScoreY1 + ScoreY0 / sum(a, b, c, d)^2

    if(identical(colnames(predicted), colnames(empirical)) == FALSE ||
        identical(rownames(predicted), rownames(empirical)) == FALSE ||
        identical(dim(predicted), dim(empirical)) == FALSE) {
            print('matrices need to have same dimensions and row and column names')
            break
    }

    efficiency <- numeric(8)
    aa <- bb <- cc <- dd <-  numeric(2)
    names(efficiency) <- c('a','b','c','d','TSS','ScoreY1','ScoreY0','FSS')

    for(i in 1:ncol(predicted)){
        for(j in 1:nrow(predicted)) {
            if(predicted[i,j] == 1 && empirical[i,j] == 1) {
                efficiency[1] <- efficiency[1] + 1
                aa <- rbind(aa,c(i,j))
            } else if(predicted[i,j] == 1 && empirical[i,j] == 0) {
                efficiency[2] <- efficiency[2] + 1
                bb <- rbind(bb,c(i,j))
            } else if(predicted[i,j] == 0 && empirical[i,j] == 1) {
                efficiency[3] <- efficiency[3] + 1
                cc <- rbind(cc,c(i,j))
            } else if(predicted[i,j] == 0 && empirical[i,j] == 0) {
                efficiency[4] <- efficiency[4] + 1
                dd <- rbind(dd,c(i,j))
            }
        }
    }

    a <- efficiency[1]
    b <- efficiency[2]
    c <- efficiency[3]
    d <- efficiency[4]

    efficiency[5] <- ((a * d) - (b * c)) / ((a + c) * (b + d))  # TSS
    efficiency[6] <- a / (a + c)                                # ScoreY1
    efficiency[7] <- d / (b + d)                                # ScoreY0
    efficiency[8] <- (a + d) / sum(a, b, c, d)    # FSS

    efficiency.id <- vector('list',5)
    efficiency.id[[1]] <- efficiency
    efficiency.id[[2]] <- aa
    efficiency.id[[3]] <- bb
    efficiency.id[[4]] <- cc
    efficiency.id[[5]] <- dd

    return(efficiency.id)
}
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2.8 Example with southern St. Lawrence EwE model for mid-1980s
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "./RawData/South_St_Lawrence_EwE.RData"
#   Script  <- file = "Script/2-8_St_Lawrence_ex.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REFERENCE:
#   Savenkoff, to add
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
library(stringr)
load("./RawData/South_St_Lawrence_EwE.RData")
SSL <- South_St_Lawrence

SSL[[2]][which(SSL[[2]] > 0)] <- 1
rownames(SSL[[2]]) <- colnames(SSL[[2]]) <- SSL[[3]]

sp_SSL <- matrix(ncol = 2, nrow = 29, data = NA, dimnames = list(c(), c('ACCR','SP')))

sp_SSL[,1] <- c('WHA','HAS','HOS','GRS','HSE','SEA','LCO','SCO','LGH','SAP','LAP','FLO','SKA','RED','LDF','SDF','CAP','LPF','PISF','PLSF','SHR','LCRU','ECH','MOL','POL','OBI','LZOO','SZOO','PHY')

sp_SSL[,2] <- c('Balaenoptera physalus - Balaenoptera acutorostrata - Megaptera novaeangliae - Phocoena phocoena - Lagenorhynchus acutus - Lagenorhynchus albirostris',
'Pagophilus groenlandicus',
'Cystophora cristata',
'Halichoerus grypus',
'Phoca vitulina',
'Phalacrocorax carbo - Phalacrocorax auritus - Larus delawarensis - Larus argentatus - Larus marinus - Sterna hirundo - Sterna paradisaea - Cepphus grylle - Oceanodroma leucorhoa - Morus bassanus - Rissa tridactyla - Uria aalge - Alca torda - Fratercula arctica',
'Gadus morhua',
'Gadus morhua',
'Reinhardtius hippoglossoides',
'Hippoglossoides platessoides',
'Hippoglossoides platessoides',
'Limanda ferruginea - Glyptocephalus cynoglossus - Pseudopleuronectes americanus',
'Amblyraja radiata - Malacoraja senta - Leucoraja ocellata',
'Sebastes mentella - Sebastes fasciatus',
'Urophycis tenuis - Melanogrammus aeglefinus - Centroscyllium fabricii - Anarhichas - Cyclopterus lumpus - Lycodes - Macrouridae - Zoarcidae - Lophius americanus - Hippoglossus hippoglossus',
'Myoxocephalus - Tautogolabrus adspersus - Zoarces americanus',
'Mallotus villosus',
'Squalus acanthias - Pollachius virens - Merluccius bilinearis - Cetorhinus maximus',
'Scomber scombrus - Illex illecebrosus',
'Clupea harengus - Scomberesox saurus - Gonatus',
'Argis dentata - Eualus macilentus - Eualus gaimardi - Pandalus montagui',
'Chionoecetes opilio - Hyas',
'Echinarachnius parma - Stronglyocentrotus pallidus - Ophiura robusta',
'Mesodesma deauratum - Cyrtodaria siliqua',
'Parexogone hebes',
'Miscellaneous crustaceans', #to remove OBI
'Euphausiids - chaetognaths', # to remove LZOO
'Oithona similis - Temora longicornis - Pseudocalanus - Calanus finmarchicus',
'Chaetoceros affinis - Chaetoceros - Leptocylindrus minimus - Thalassiiosira nordenskioldii - Thalassiiosira - Fragilariopsis')

# Removing portions of the web for which there is no taxa usable for the analysis, 'OBI' & 'LZOO'
SSL[[2]] <- SSL[[2]][-which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO'), -which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO')]
sp_SSL <- sp_SSL[-which(sp_SSL[,1] == 'OBI' | sp_SSL[,1] == 'LZOO'), ]

S1 <- unique(unlist(str_split(sp_SSL[,2], ' - ')))

load("./RData/Tanimoto_data.RData")
# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
# Format interaction catalogue to fit this table format
    S0 <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
    S0[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
        S0[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
    }


# Have to extract taxonomy for speies that are not found in S0
S1_missing <- which(!S1 %in% S0[,1])

S1_add_S0 <- matrix(ncol = 6, nrow = length(S1_missing), data = "", dimnames = list(c(), c("taxon", "taxonomy", "resource", "non-resource", "consumer", "non-consumer")))

S1_add_S0[, 'taxon'] <- S1[S1_missing]

S1_add_S0[, 'taxonomy'] <- c('Animalia | Chordata | Mammalia | Cetartiodactyla | Delphinidae | Lagenorhynchus | Lagenorhynchus acutus',
'Animalia | Chordata | Mammalia | Carnivora | Phocidae | Halichoerus | Halichoerus grypus',
'Animalia | Chordata | Procellariiformes | Hydrobatidae | Oceanodroma | Oceanodroma leucorhoa',
'Animalia | Chordata | Aves | Pelecaniformes | Sulidae | Morus | Morus bassanus',
'Animalia | Chordata | Aves | Charadriiformes | Alcidae | Alca | Alca torda',
'Animalia | Chordata | Elasmobranchii | Rajiformes | Rajidae | Malacoraja | Malacoraja senta',
'Animalia | Chordata | Elasmobranchii | Squaliformes | Etmopteridae | Centroscyllium | Centroscyllium fabricii',
'Animalia | Arthropoda | Malacostraca | Decapoda | Crangonidae | Argis | Argis dentata',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus macilentus',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus gaimardii',
'Animalia | Echinodermata | Echinoidea | Camarodonta | Strongylocentrotidae | Strongylocentrotus | Strongylocentrotus pallidus',
'Animalia | Mollusca | Bivalvia | Imparidentia | Mesodesmatidae | Mesodesma | Mesodesma deauratum',
'Animalia | Mollusca | Bivalvia | Adapedonta | Hiatellidae | Cyrtodaria | Cyrtodaria siliqua',
'Animalia | Annelida | Polychaeta | Phyllodocida | Syllidae | Parexogone | Parexogone hebes',
'Chromista | Ochrophyta | Bacillariophyceae | Chaetocerotanae | Chaetocerotaceae | Chaetoceros | Chaetoceros affinis',
'Chromista | Ochrophyta | Bacillariophyceae | Leptocylindrales | Leptocylindraceae | Leptocylindrus | Leptocylindrus minimus',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | Thalassiosira nordenskioeldii',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | NA')

 S0 <- rbind(S0, S1_add_S0) #binding missing taxonomies
 rownames(S0) <- S0[, 'taxon']


# #Thinning down catalogue
# S02 <- S0[unique(c(which(S0[, 'resource'] != ""), which(S0[, 'consumer'] != ""))), ]
#
# S1_missing2 <- which(!S1 %in% S02[,1]) #after culling
# S1_missing3 <- S1_missing2[which(!S1_missing2 %in% S1_missing)] #taxo to keep
# S1_add_S0 <- rbind(S1_add_S0, S0[which(S0[, 'taxon'] %in% S1[S1_missing3]), ])
# rownames(S1_add_S0) <- NULL
# S0 <- rbind(S02, S1_add_S0)
# remove(S02,S1_missing3,S1_missing2,S1_missing)

# Predicting interactions
SSL_predict <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.3)

SSL_predict2 <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.2)

SSL_predict_mat <- prediction_matrix(S1 = S1, predictions = SSL_predict)
SSL_predict_mat2 <- prediction_matrix(S1 = S1, predictions = SSL_predict2)
x <- SSL_predict_mat

for(i in 1:nrow(sp_SSL)) {
    Sx <- unique(unlist(str_split(sp_SSL[i,2], ' - ')))
    for(j in 1:length(Sx)){
        for(k in 1:length(S1))
        if(S1[k] %in% Sx == TRUE) {
            colnames(SSL_predict_mat)[k] <- rownames(SSL_predict_mat)[k] <- sp_SSL[i, 2]
            colnames(SSL_predict_mat2)[k] <- rownames(SSL_predict_mat2)[k] <- sp_SSL[i, 2]
        }
    }
}

SSL_predict_mat_combine <- dupl_sp(SSL_predict_mat)
SSL_predict_mat_combine2 <- dupl_sp(SSL_predict_mat2)

SSL_emp <- SSL[[2]]
colnames(SSL_emp) <- rownames(SSL_emp) <- sp_SSL[,2]
SSL_emp <-  dupl_sp(SSL_emp)

accuracy_SSL <- prediction_accuracy_id(predicted = SSL_predict_mat_combine, empirical = SSL_emp)
accuracy_SSL2 <- prediction_accuracy_id(predicted = SSL_predict_mat_combine2, empirical = SSL_emp)
accuracy_SSL
accuracy_SSL2

for(i in 2:nrow(accuracy_SSL[[4]])) {
    print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]))
}

for(i in 2:nrow(accuracy_SSL[[3]])) {
    print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]))
}


SSL_bin_inter <- bin_inter(SSL_predict_mat_combine)
SSL_bin_inter2 <- bin_inter(SSL_predict_mat_combine2)
SSL_emp_bin <- bin_inter(SSL_emp)
SSL_bin_inter <- SSL_bin_inter[which(SSL_bin_inter[, 'FeedInter'] == '1'), ]
SSL_bin_inter2 <- SSL_bin_inter2[which(SSL_bin_inter2[, 'FeedInter'] == '1'), ]
SSL_emp_bin <- SSL_emp_bin[which(SSL_emp_bin[, 'FeedInter'] == '1'), ]

# SSL species with interactions noted in catalogue
x <- which(S0[, 'taxon'] %in% S1)
length(which(S0[x,'resource'] != "" | S0[x,'consumer'] != ""))




# Load package
library(networkD3)
# Plot
simpleNetwork(as.data.frame(SSL_bin_inter[, c(1,3)]))
simpleNetwork(as.data.frame(SSL_emp_bin[, c(1,3)]))





# remplace , par ' - '
# remplacer les noms de colonnes et lignes
# combiner duplicatas
# rouler fonction du catalogue pour séparer les lignes et colonnes qui ont plusieurs entrées?
# faire l'analyse en séparant toutes les espèces listées, puis comparer l'analyse divisée, compartimenter les résultats (combiner les interactions des espèces qui sont dans un compartiment), et la réseau présenté dans l'article à partir de la matrice de diète.
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2.8 Example with southern St. Lawrence EwE model for mid-1980s
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "./RawData/South_St_Lawrence_EwE.RData"
#   Script  <- file = "Script/2-8_St_Lawrence_ex.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REFERENCE:
#   Savenkoff, to add
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
library(stringr)
load("./RawData/South_St_Lawrence_EwE.RData")
SSL <- South_St_Lawrence

SSL[[2]][which(SSL[[2]] > 0)] <- 1
rownames(SSL[[2]]) <- colnames(SSL[[2]]) <- SSL[[3]]

sp_SSL <- matrix(ncol = 2, nrow = 29, data = NA, dimnames = list(c(), c('ACCR','SP')))

sp_SSL[,1] <- c('WHA','HAS','HOS','GRS','HSE','SEA','LCO','SCO','LGH','SAP','LAP','FLO','SKA','RED','LDF','SDF','CAP','LPF','PISF','PLSF','SHR','LCRU','ECH','MOL','POL','OBI','LZOO','SZOO','PHY')

sp_SSL[,2] <- c('Balaenoptera physalus - Balaenoptera acutorostrata - Megaptera novaeangliae - Phocoena phocoena - Lagenorhynchus acutus - Lagenorhynchus albirostris',
'Pagophilus groenlandicus',
'Cystophora cristata',
'Halichoerus grypus',
'Phoca vitulina',
'Phalacrocorax carbo - Phalacrocorax auritus - Larus delawarensis - Larus argentatus - Larus marinus - Sterna hirundo - Sterna paradisaea - Cepphus grylle - Oceanodroma leucorhoa - Morus bassanus - Rissa tridactyla - Uria aalge - Alca torda - Fratercula arctica',
'Gadus morhua',
'Gadus morhua',
'Reinhardtius hippoglossoides',
'Hippoglossoides platessoides',
'Hippoglossoides platessoides',
'Limanda ferruginea - Glyptocephalus cynoglossus - Pseudopleuronectes americanus',
'Amblyraja radiata - Malacoraja senta - Leucoraja ocellata',
'Sebastes mentella - Sebastes fasciatus',
'Urophycis tenuis - Melanogrammus aeglefinus - Centroscyllium fabricii - Anarhichas - Cyclopterus lumpus - Lycodes - Macrouridae - Zoarcidae - Lophius americanus - Hippoglossus hippoglossus',
'Myoxocephalus - Tautogolabrus adspersus - Zoarces americanus',
'Mallotus villosus',
'Squalus acanthias - Pollachius virens - Merluccius bilinearis - Cetorhinus maximus',
'Scomber scombrus - Illex illecebrosus',
'Clupea harengus - Scomberesox saurus - Gonatus',
'Argis dentata - Eualus macilentus - Eualus gaimardi - Pandalus montagui',
'Chionoecetes opilio - Hyas',
'Echinarachnius parma - Stronglyocentrotus pallidus - Ophiura robusta',
'Mesodesma deauratum - Cyrtodaria siliqua',
'Parexogone hebes',
'Miscellaneous crustaceans', #to remove OBI
'Euphausiids - chaetognaths', # to remove LZOO
'Oithona similis - Temora longicornis - Pseudocalanus - Calanus finmarchicus',
'Chaetoceros affinis - Chaetoceros - Leptocylindrus minimus - Thalassiiosira nordenskioldii - Thalassiiosira - Fragilariopsis')

# Removing portions of the web for which there is no taxa usable for the analysis, 'OBI' & 'LZOO'
SSL[[2]] <- SSL[[2]][-which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO'), -which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO')]
sp_SSL <- sp_SSL[-which(sp_SSL[,1] == 'OBI' | sp_SSL[,1] == 'LZOO'), ]

S1 <- unique(unlist(str_split(sp_SSL[,2], ' - ')))

load("./RData/Tanimoto_data.RData")
# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
# Format interaction catalogue to fit this table format
    S0 <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
    S0[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
        S0[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
    }


# Have to extract taxonomy for speies that are not found in S0
S1_missing <- which(!S1 %in% S0[,1])

S1_add_S0 <- matrix(ncol = 6, nrow = length(S1_missing), data = "", dimnames = list(c(), c("taxon", "taxonomy", "resource", "non-resource", "consumer", "non-consumer")))

S1_add_S0[, 'taxon'] <- S1[S1_missing]

S1_add_S0[, 'taxonomy'] <- c('Animalia | Chordata | Mammalia | Cetartiodactyla | Delphinidae | Lagenorhynchus | Lagenorhynchus acutus',
'Animalia | Chordata | Mammalia | Carnivora | Phocidae | Halichoerus | Halichoerus grypus',
'Animalia | Chordata | Procellariiformes | Hydrobatidae | Oceanodroma | Oceanodroma leucorhoa',
'Animalia | Chordata | Aves | Pelecaniformes | Sulidae | Morus | Morus bassanus',
'Animalia | Chordata | Aves | Charadriiformes | Alcidae | Alca | Alca torda',
'Animalia | Chordata | Elasmobranchii | Rajiformes | Rajidae | Malacoraja | Malacoraja senta',
'Animalia | Chordata | Elasmobranchii | Squaliformes | Etmopteridae | Centroscyllium | Centroscyllium fabricii',
'Animalia | Arthropoda | Malacostraca | Decapoda | Crangonidae | Argis | Argis dentata',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus macilentus',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus gaimardii',
'Animalia | Echinodermata | Echinoidea | Camarodonta | Strongylocentrotidae | Strongylocentrotus | Strongylocentrotus pallidus',
'Animalia | Mollusca | Bivalvia | Imparidentia | Mesodesmatidae | Mesodesma | Mesodesma deauratum',
'Animalia | Mollusca | Bivalvia | Adapedonta | Hiatellidae | Cyrtodaria | Cyrtodaria siliqua',
'Animalia | Annelida | Polychaeta | Phyllodocida | Syllidae | Parexogone | Parexogone hebes',
'Chromista | Ochrophyta | Bacillariophyceae | Chaetocerotanae | Chaetocerotaceae | Chaetoceros | Chaetoceros affinis',
'Chromista | Ochrophyta | Bacillariophyceae | Leptocylindrales | Leptocylindraceae | Leptocylindrus | Leptocylindrus minimus',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | Thalassiosira nordenskioeldii',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | NA')

 S0 <- rbind(S0, S1_add_S0) #binding missing taxonomies
 rownames(S0) <- S0[, 'taxon']


# #Thinning down catalogue
# S02 <- S0[unique(c(which(S0[, 'resource'] != ""), which(S0[, 'consumer'] != ""))), ]
#
# S1_missing2 <- which(!S1 %in% S02[,1]) #after culling
# S1_missing3 <- S1_missing2[which(!S1_missing2 %in% S1_missing)] #taxo to keep
# S1_add_S0 <- rbind(S1_add_S0, S0[which(S0[, 'taxon'] %in% S1[S1_missing3]), ])
# rownames(S1_add_S0) <- NULL
# S0 <- rbind(S02, S1_add_S0)
# remove(S02,S1_missing3,S1_missing2,S1_missing)

# Predicting interactions
SSL_predict <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.3)

SSL_predict2 <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.2)

SSL_predict_mat <- prediction_matrix(S1 = S1, predictions = SSL_predict)
SSL_predict_mat2 <- prediction_matrix(S1 = S1, predictions = SSL_predict2)
x <- SSL_predict_mat

for(i in 1:nrow(sp_SSL)) {
    Sx <- unique(unlist(str_split(sp_SSL[i,2], ' - ')))
    for(j in 1:length(Sx)){
        for(k in 1:length(S1))
        if(S1[k] %in% Sx == TRUE) {
            colnames(SSL_predict_mat)[k] <- rownames(SSL_predict_mat)[k] <- sp_SSL[i, 2]
            colnames(SSL_predict_mat2)[k] <- rownames(SSL_predict_mat2)[k] <- sp_SSL[i, 2]
        }
    }
}

SSL_predict_mat_combine <- dupl_sp(SSL_predict_mat)
SSL_predict_mat_combine2 <- dupl_sp(SSL_predict_mat2)

SSL_emp <- SSL[[2]]
colnames(SSL_emp) <- rownames(SSL_emp) <- sp_SSL[,2]
SSL_emp <-  dupl_sp(SSL_emp)

accuracy_SSL <- prediction_accuracy_id(predicted = SSL_predict_mat_combine, empirical = SSL_emp)
accuracy_SSL2 <- prediction_accuracy_id(predicted = SSL_predict_mat_combine2, empirical = SSL_emp)
accuracy_SSL
accuracy_SSL2

for(i in 2:nrow(accuracy_SSL[[4]])) {
    print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]]))
}

for(i in 2:nrow(accuracy_SSL[[3]])) {
    print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 2]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[3]][i, 1]]))
}


SSL_bin_inter <- bin_inter(SSL_predict_mat_combine)
SSL_bin_inter2 <- bin_inter(SSL_predict_mat_combine2)
SSL_emp_bin <- bin_inter(SSL_emp)
SSL_bin_inter <- SSL_bin_inter[which(SSL_bin_inter[, 'FeedInter'] == '1'), ]
SSL_bin_inter2 <- SSL_bin_inter2[which(SSL_bin_inter2[, 'FeedInter'] == '1'), ]
SSL_emp_bin <- SSL_emp_bin[which(SSL_emp_bin[, 'FeedInter'] == '1'), ]

# Load package
library(networkD3)
# Plot
simpleNetwork(as.data.frame(SSL_bin_inter[, c(1,3)]))
simpleNetwork(as.data.frame(SSL_emp_bin[, c(1,3)]))





# remplace , par ' - '
# remplacer les noms de colonnes et lignes
# combiner duplicatas
# rouler fonction du catalogue pour séparer les lignes et colonnes qui ont plusieurs entrées?
# faire l'analyse en séparant toutes les espèces listées, puis comparer l'analyse divisée, compartimenter les résultats (combiner les interactions des espèces qui sont dans un compartiment), et la réseau présenté dans l'article à partir de la matrice de diète.
###############################################
### COMMONLY USED PACKAGES IN AIM R SCRIPTS ###
###############################################

#### DATA WRANGLING ####
install.packages(
  c(
    "dplyr", ## Notably useful for data frame manipulation with group_by(), summarize(), and mutate() and the piping operator %>%. Do you have a moment to hear the good news of our savior, piping?
    "tidyr", ## Lots of useful things, but specifically gather() and spread() for converting wide data frames into long ones and vice versa
    "stringr", ## All about character strings. Great for str_split() in particular, but the whole str_ family of functions are A+
    "RODBC", ## Allows R to pass SQL queries to Access databases and pull out the results
    "XLSX", ## Read in modern Excel workbooks and spreadsheets
    "broom" ## Get stats objects into tidy data frames. Not as common
  )
)

#### SPATIAL DATA ####
install.packages(
  c(
    "sp", ## Functions for manipulating spatial objects. If you want a Spatial _____ Data Frame, this is part of the deal
    "spsurvey", ## Contains plenty, but the most important to AIM is the GRTS function
    "rgeos", ## Additional spatial object functions
    "rgdal", ## Contains the mission critical readOGR() function that we read shapefiles in with
    "raster" ## Everything you didn't know you needed for dealing with rasters
  )
)

#### DATA VISUALIZATION ####
install.packages(
  c(
    "ggplot2", ## The go-to for figure generation. Most R-using scientists AND Nate Silver use it, so you should too
    "ggthemes", ## Quick themes to painlessly apply to figures from ggplot
    "ggmap" ## Mapping support for ggplot
  )
)

#### MISCELLANEOUS PACKAGES ####
install.packages("arcgisbinding") ## Young and finicky, but once you have it all installed (an ordeal) you should be able to read from and write to file geodatabases from R
install.packages("gridExtra") ## Lets you make grid objects that you can place ggplot figures into. May occasionally be preferable to faceting in ggplot, but rarely
install.packages("shiny") ## Required for working with Shiny tools in any form. Can be maddening
install.packages("purrr") ## Really, really useful for writing functions, particularly those that fail gracefully
require(dplyr)
require(rvest)
require(gsubfn)

url<-'https://en.wikipedia.org/wiki/2014%E2%80%9315_NBA_season'

stran <- html_session(url) %>% read_html(encoding = "UTF-8")
tabela <- stran %>% html_nodes(xpath ="//table[5]") %>% .[[1]] %>% html_table()

podatki<-read.csv("podatki.csv", header=TRUE, sep=",", dec=".", stringsAsFactors = FALSE, na.strings = ".")
podatki$Rk<-NULL
podatki$eFG.<-NULL
a<-c(6:28)
suppressWarnings(podatki[a]<-lapply(podatki[a], as.numeric))
podatki<-podatki[!is.na(podatki$PTS),]
#podatki<-na.omit(podatki)
colnames(podatki)[28]<-"PTS"
podatki<-podatki[order(podatki[,28], decreasing = TRUE),]

link<-'http://www.spotrac.com/widget/sport/nba/current-year/rankings-cap/"'
site<-html_session(link) %>% read_html(encoding = "UTF-8")
salaries<-site %>% html_nodes(xpath ="//table") %>% .[[1]] %>% html_table()
place<-site %>% html_nodes(xpath ="//table") %>% .[[1]] %>% html_table()
place<-place[-1]
salaries<-salaries[-1]
salaries$Pos.<-NULL

celatabela<-inner_join(podatki, salaries, by = "Player")
colnames(celatabela)<-c("Player","Position" ,"Age","Team","Games","Started","Minutes","FG Made", "FG Att","FG %","3Pt Made", "3Pt Att", "3Pt %", "2Pt Made", "2Pt Att", "2Pt %", "FT Made", "FT Att", "FT %", "Off. Reb", "Def. Reb", "Tot. Reb", "Assists", "Steals", "Blocks", "Turnovers", "Fouls", "Points", "Salary")
celatabela$Salary<-as.factor(celatabela$Salary)
celatabela$Salary<-gsub("\\$", "", celatabela$Salary)
celatabela$Salary<-gsub("\\,", "", celatabela$Salary)
celatabela$Salary<-as.numeric(celatabela$Salary)

strelci<-data.frame(Player=celatabela$Player, Points=celatabela$Points)

zlink<-'http://hoopshype.com/2015/02/24/where-are-nba-players-born/'
zstran <- html_session(zlink) %>% read_html(encoding = "UTF-8")
ztabela <- zstran %>% html_nodes(xpath ="//table[2]") %>% .[[1]]  %>% html_table()
ztabela<-na.omit(ztabela)
ztabela<-ztabela[-1,-3]
colnames(ztabela)<-c('City','Players')
ztabela$City<-as.factor(ztabela$City)
ztabela$Players<-as.numeric(ztabela$Players)
ztabela$City<-gsub('[[:digit:]]+', '', ztabela$City)
ztabela$City<-gsub('\\.', '', ztabela$City)
ztabela<-ztabela[-11,]
ztabela1<-ztabela
ztabela$Lat<-c('34.052235', '40.792240', '41.881832', '40.002785', '32.736259', '39.790942', '47.608013', '30.471165', '35.040031', '39.299236', '29.761993', '33.753746', '38.889931', '33.792461', '38.627003')
ztabela$Long<-c('-118.243683', '-73.138260', '-87.623177', '-75.183739', '-96.864586', '-86.147685', '-122.335167', '-91.147385', '-89.981873', '-76.609383', '-95.366302', '-84.386330', '-77.009003', '-118.185005', '-90.199402')
ztabela$STATE_NAME<-c('California', 'New York', 'Illinois', 'Pennsylvania', 'Texas', 'Indiana', 'Washington', 'Louisiana', 'Tennessee', 'Maryland', 'Texas', 'Georgia', 'District of Columbia', 'California', 'Missouri')
ztabela$Lat<-as.numeric(ztabela$Lat)
ztabela$Long<-as.numeric(ztabela$Long)
source("lib/uvozi.zemljevid.r", encoding = "UTF-8")
library(ggplot2)

pretvori.zemljevid <- function(zemljevid) {
  fo <- fortify(zemljevid)
  data <- zemljevid@data
  data$id <- as.character(0:(nrow(data)-1))
  return(inner_join(fo, data, by="id"))
}

zda <- uvozi.zemljevid("http://baza.fmf.uni-lj.si/states_21basic.zip", "states")
ztabela <- preuredi(ztabela, zda, "STATE_NAME")
usa<-pretvori.zemljevid(zda)
usa.cont <- usa %>% filter(! STATE_NAME %in% c("Alaska", "Hawaii"))
map1 <- ggplot() + geom_polygon(data = usa.cont, color='black', aes(x = long, y = lat, group=group)) + geom_point(data = ztabela, color = "green", aes(x = Long, y = Lat, size = Players)) + geom_text(data = ztabela, color='white', aes(x = Long, y = Lat, label = City), size=7,vjust=1)

ekipe<-read.csv('teams__active.csv')
ekipe$Lg<-NULL
ekipe$To<-NULL
ekipe$Yrs<-NULL
ekipe$W.L.<-NULL
colnames(ekipe)<-c('Team', 'Founded', 'Games', 'Won', 'Lost', 'Playoffs', 'Div. titles', 'Conf. titles', 'Championships')
ekipe1<-ekipe
ekipe<-ekipe[-28,]
ekipe$STATE_NAME<-c('Georgia', 'Massachusetts', 'New York', 'North Carolina', 'Illinois', 'Ohio','Texas','Colorado','Michigan','California','Texas','Indiana','California','California','Tennessee','Florida','Wisconsin','Minnesota','Louisianna','New York','Oklahoma','Florida','Pennsylvania','Arizona','Oregon','California','Texas','Utah','District of Columbia')
ekipe$LAT<-c('33.75375', '42.35843', '40.35000','35.227085', '41.881832','41.505493','32.73626','39.742043','42.331429','	37.801239','29.682720','39.769653','34.052235','34.052235','35.040031',	'25.778135','43.038902','44.986656','29.951065','40.79224','35.481918','28.538336','40.00279','33.453388','45.512794','38.575764','29.424349','40.758701','38.88993')
ekipe$LONG<-c('-84.38633', '-71.05977', '-73.949997', '-80.843124','-87.623177','	-81.681290','-96.86459','	-104.991531','	-83.045753','-122.258301','-95.593239','-86.157143','-118.243683','-118.243683','-89.981873','-80.179100','-87.906471','-93.258133','-90.071533','-73.13826','-97.508469','-81.379234','-75.18374','-112.074623','-122.679565','-121.478851','-98.491142','-111.876183','-77.00900')
ekipe$LAT<-as.numeric(ekipe$LAT)
ekipe$LONG<-as.numeric(ekipe$LONG)
ekipe<-preuredi(ekipe,zda,'STATE_NAME')
require(ggrepel)
map2<-map1+geom_point(data=ekipe,color='red',size=2,aes(x=LONG,y=LAT)) + geom_text_repel(data=ekipe,color='cyan',aes(x=LONG,y=LAT,label=Team),size=7)
map2

# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2.8 Example with southern St. Lawrence EwE model for mid-1980s
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "./RawData/South_St_Lawrence_EwE.RData"
#   Script  <- file = "Script/2-8_St_Lawrence_ex.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REFERENCE:
#   Savenkoff, to add
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
library(stringr)
load("./RawData/South_St_Lawrence_EwE.RData")
SSL <- South_St_Lawrence

SSL[[2]][which(SSL[[2]] > 0)] <- 1
rownames(SSL[[2]]) <- colnames(SSL[[2]]) <- SSL[[3]]

sp_SSL <- matrix(ncol = 2, nrow = 29, data = NA, dimnames = list(c(), c('ACCR','SP')))

sp_SSL[,1] <- c('WHA','HAS','HOS','GRS','HSE','SEA','LCO','SCO','LGH','SAP','LAP','FLO','SKA','RED','LDF','SDF','CAP','LPF','PISF','PLSF','SHR','LCRU','ECH','MOL','POL','OBI','LZOO','SZOO','PHY')

sp_SSL[,2] <- c('Balaenoptera physalus - Balaenoptera acutorostrata - Megaptera novaeangliae - Phocoena phocoena - Lagenorhynchus acutus - Lagenorhynchus albirostris',
'Pagophilus groenlandicus',
'Cystophora cristata',
'Halichoerus grypus',
'Phoca vitulina',
'Phalacrocorax carbo - Phalacrocorax auritus - Larus delawarensis - Larus argentatus - Larus marinus - Sterna hirundo - Sterna paradisaea - Cepphus grylle - Oceanodroma leucorhoa - Morus bassanus - Rissa tridactyla - Uria aalge - Alca torda - Fratercula arctica',
'Gadus morhua',
'Gadus morhua',
'Reinhardtius hippoglossoides',
'Hippoglossoides platessoides',
'Hippoglossoides platessoides',
'Limanda ferruginea - Glyptocephalus cynoglossus - Pseudopleuronectes americanus',
'Amblyraja radiata - Malacoraja senta - Leucoraja ocellata',
'Sebastes mentella - Sebastes fasciatus',
'Urophycis tenuis - Melanogrammus aeglefinus - Centroscyllium fabricii - Anarhichas - Cyclopterus lumpus - Lycodes - Macrouridae - Zoarcidae - Lophius americanus - Hippoglossus hippoglossus',
'Myoxocephalus - Tautogolabrus adspersus - Zoarces americanus',
'Mallotus villosus',
'Squalus acanthias - Pollachius virens - Merluccius bilinearis - Cetorhinus maximus',
'Scomber scombrus - Illex illecebrosus',
'Clupea harengus - Scomberesox saurus - Gonatus',
'Argis dentata - Eualus macilentus - Eualus gaimardi - Pandalus montagui',
'Chionoecetes opilio - Hyas',
'Echinarachnius parma - Stronglyocentrotus pallidus - Ophiura robusta',
'Mesodesma deauratum - Cyrtodaria siliqua',
'Parexogone hebes',
'Miscellaneous crustaceans', #to remove OBI
'Euphausiids - chaetognaths', # to remove LZOO
'Oithona similis - Temora longicornis - Pseudocalanus - Calanus finmarchicus',
'Chaetoceros affinis - Chaetoceros - Leptocylindrus minimus - Thalassiiosira nordenskioldii - Thalassiiosira - Fragilariopsis')

# Removing portions of the web for which there is no taxa usable for the analysis, 'OBI' & 'LZOO'
SSL[[2]] <- SSL[[2]][-which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO'), -which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO')]
sp_SSL <- sp_SSL[-which(sp_SSL[,1] == 'OBI' | sp_SSL[,1] == 'LZOO'), ]

S1 <- unique(unlist(str_split(sp_SSL[,2], ' - ')))

load("./RData/Tanimoto_data.RData")
# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
# Format interaction catalogue to fit this table format
    S0 <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
    S0[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
        S0[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
    }


# Have to extract taxonomy for speies that are not found in S0
S1_missing <- which(!S1 %in% S0[,1])

S1_add_S0 <- matrix(ncol = 6, nrow = length(S1_missing), data = "", dimnames = list(c(), c("taxon", "taxonomy", "resource", "non-resource", "consumer", "non-consumer")))

S1_add_S0[, 'taxon'] <- S1[S1_missing]

S1_add_S0[, 'taxonomy'] <- c('Animalia | Chordata | Mammalia | Cetartiodactyla | Delphinidae | Lagenorhynchus | Lagenorhynchus acutus',
'Animalia | Chordata | Mammalia | Carnivora | Phocidae | Halichoerus | Halichoerus grypus',
'Animalia | Chordata | Procellariiformes | Hydrobatidae | Oceanodroma | Oceanodroma leucorhoa',
'Animalia | Chordata | Aves | Pelecaniformes | Sulidae | Morus | Morus bassanus',
'Animalia | Chordata | Aves | Charadriiformes | Alcidae | Alca | Alca torda',
'Animalia | Chordata | Elasmobranchii | Rajiformes | Rajidae | Malacoraja | Malacoraja senta',
'Animalia | Chordata | Elasmobranchii | Squaliformes | Etmopteridae | Centroscyllium | Centroscyllium fabricii',
'Animalia | Arthropoda | Malacostraca | Decapoda | Crangonidae | Argis | Argis dentata',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus macilentus',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus gaimardii',
'Animalia | Echinodermata | Echinoidea | Camarodonta | Strongylocentrotidae | Strongylocentrotus | Strongylocentrotus pallidus',
'Animalia | Mollusca | Bivalvia | Imparidentia | Mesodesmatidae | Mesodesma | Mesodesma deauratum',
'Animalia | Mollusca | Bivalvia | Adapedonta | Hiatellidae | Cyrtodaria | Cyrtodaria siliqua',
'Animalia | Annelida | Polychaeta | Phyllodocida | Syllidae | Parexogone | Parexogone hebes',
'Chromista | Ochrophyta | Bacillariophyceae | Chaetocerotanae | Chaetocerotaceae | Chaetoceros | Chaetoceros affinis',
'Chromista | Ochrophyta | Bacillariophyceae | Leptocylindrales | Leptocylindraceae | Leptocylindrus | Leptocylindrus minimus',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | Thalassiosira nordenskioeldii',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | NA')

 S0 <- rbind(S0, S1_add_S0) #binding missing taxonomies
 rownames(S0) <- S0[, 'taxon']


# #Thinning down catalogue
# S02 <- S0[unique(c(which(S0[, 'resource'] != ""), which(S0[, 'consumer'] != ""))), ]
#
# S1_missing2 <- which(!S1 %in% S02[,1]) #after culling
# S1_missing3 <- S1_missing2[which(!S1_missing2 %in% S1_missing)] #taxo to keep
# S1_add_S0 <- rbind(S1_add_S0, S0[which(S0[, 'taxon'] %in% S1[S1_missing3]), ])
# rownames(S1_add_S0) <- NULL
# S0 <- rbind(S02, S1_add_S0)
# remove(S02,S1_missing3,S1_missing2,S1_missing)

# Predicting interactions
SSL_predict <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.3)

SSL_predict2 <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.2)

SSL_predict_mat <- prediction_matrix(S1 = S1, predictions = SSL_predict)
SSL_predict_mat2 <- prediction_matrix(S1 = S1, predictions = SSL_predict2)
x <- SSL_predict_mat

for(i in 1:nrow(sp_SSL)) {
    Sx <- unique(unlist(str_split(sp_SSL[i,2], ' - ')))
    for(j in 1:length(Sx)){
        for(k in 1:length(S1))
        if(S1[k] %in% Sx == TRUE) {
            colnames(SSL_predict_mat)[k] <- rownames(SSL_predict_mat)[k] <- sp_SSL[i, 2]
            colnames(SSL_predict_mat2)[k] <- rownames(SSL_predict_mat2)[k] <- sp_SSL[i, 2]
        }
    }
}

SSL_predict_mat_combine <- dupl_sp(SSL_predict_mat)
SSL_predict_mat_combine2 <- dupl_sp(SSL_predict_mat2)

SSL_emp <- SSL[[2]]
colnames(SSL_emp) <- rownames(SSL_emp) <- sp_SSL[,2]
SSL_emp <-  dupl_sp(SSL_emp)

accuracy_SSL <- prediction_accuracy_id(predicted = SSL_predict_mat_combine, empirical = SSL_emp)
accuracy_SSL2 <- prediction_accuracy_id(predicted = SSL_predict_mat_combine2, empirical = SSL_emp)
accuracy_SSL
accuracy_SSL2

for(i in 2:nrow(accuracy_SSL[[4]])) {
    print(paste(rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 1]], "EATS", rownames(SSL_predict_mat_combine)[accuracy_SSL[[4]][i, 2]]))
}


SSL_bin_inter <- bin_inter(SSL_predict_mat_combine)
SSL_bin_inter2 <- bin_inter(SSL_predict_mat_combine2)
SSL_emp_bin <- bin_inter(SSL_emp)
SSL_bin_inter <- SSL_bin_inter[which(SSL_bin_inter[, 'FeedInter'] == '1'), ]
SSL_bin_inter2 <- SSL_bin_inter2[which(SSL_bin_inter2[, 'FeedInter'] == '1'), ]
SSL_emp_bin <- SSL_emp_bin[which(SSL_emp_bin[, 'FeedInter'] == '1'), ]

# Load package
library(networkD3)
# Plot
simpleNetwork(as.data.frame(SSL_bin_inter[, c(1,3)]))
simpleNetwork(as.data.frame(SSL_emp_bin[, c(1,3)]))





# remplace , par ' - '
# remplacer les noms de colonnes et lignes
# combiner duplicatas
# rouler fonction du catalogue pour séparer les lignes et colonnes qui ont plusieurs entrées?
# faire l'analyse en séparant toutes les espèces listées, puis comparer l'analyse divisée, compartimenter les résultats (combiner les interactions des espèces qui sont dans un compartiment), et la réseau présenté dans l'article à partir de la matrice de diète.
# Run init.r before other scripts
rm(list=ls())
 # for use in R console.
 # set own relevant directory if working in R console, otherwise ignore if in terminal
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "./Script/0-1-Tanimoto_data.r
#           RData <- file = './RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "./Script/0-1-Interactions_sources.r
#           RData <- file = "./RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = './Script/1-Similarity_matrix.r'
#       RData <- file = './RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = './Script/2-1-Tanimoto_analysis.r'
#           RData <- file = './RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = './Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = './RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("./Script/tanimoto.r") # basic tanimoto similarity
source("./Script/tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("./Script/similarity_taxon.r") # similarity matrix for set of taxa
source("./Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("./Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("./Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/consumer_set_of_resource.R")
source("./Script/resource_set_of_consumer.R")
source("./Script/prediction_accuracy.r") #
source("./Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("./Script/serialNext.r") # function to avoid overwriting existing files in temporary analyses folder
source("./Script/eplot.r") # empty plot for figure generation
source("./Script/tanimoto_analysis.r")
source("./Script/catalog_predictions.r") # computing prediction accuracy ~ # taxa in catalog
source("./Script/catalog_predictions_accuracy.r") # accuracy of predictions for accuracy ~ # taxa in catalog

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2.8 Example with southern St. Lawrence EwE model for mid-1980s
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "./RawData/South_St_Lawrence_EwE.RData"
#   Script  <- file = "Script/2-8_St_Lawrence_ex.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REFERENCE:
#   Savenkoff, to add
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
library(stringr)
load("./RawData/South_St_Lawrence_EwE.RData")
SSL <- South_St_Lawrence

SSL[[2]][which(SSL[[2]] > 0)] <- 1
rownames(SSL[[2]]) <- colnames(SSL[[2]]) <- SSL[[3]]

sp_SSL <- matrix(ncol = 2, nrow = 29, data = NA, dimnames = list(c(), c('ACCR','SP')))

sp_SSL[,1] <- c('WHA','HAS','HOS','GRS','HSE','SEA','LCO','SCO','LGH','SAP','LAP','FLO','SKA','RED','LDF','SDF','CAP','LPF','PISF','PLSF','SHR','LCRU','ECH','MOL','POL','OBI','LZOO','SZOO','PHY')

sp_SSL[,2] <- c('Balaenoptera physalus - Balaenoptera acutorostrata - Megaptera novaeangliae - Phocoena phocoena - Lagenorhynchus acutus - Lagenorhynchus albirostris',
'Pagophilus groenlandicus',
'Cystophora cristata',
'Halichoerus grypus',
'Phoca vitulina',
'Phalacrocorax carbo - Phalacrocorax auritus - Larus delawarensis - Larus argentatus - Larus marinus - Sterna hirundo - Sterna paradisaea - Cepphus grylle - Oceanodroma leucorhoa - Morus bassanus - Rissa tridactyla - Uria aalge - Alca torda - Fratercula arctica',
'Gadus morhua',
'Gadus morhua',
'Reinhardtius hippoglossoides',
'Hippoglossoides platessoides',
'Hippoglossoides platessoides',
'Limanda ferruginea - Glyptocephalus cynoglossus - Pseudopleuronectes americanus',
'Amblyraja radiata - Malacoraja senta - Leucoraja ocellata',
'Sebastes mentella - Sebastes fasciatus',
'Urophycis tenuis - Melanogrammus aeglefinus - Centroscyllium fabricii - Anarhichas - Cyclopterus lumpus - Lycodes - Macrouridae - Zoarcidae - Lophius americanus - Hippoglossus hippoglossus',
'Myoxocephalus - Tautogolabrus adspersus - Zoarces americanus',
'Mallotus villosus',
'Squalus acanthias - Pollachius virens - Merluccius bilinearis - Cetorhinus maximus',
'Scomber scombrus - Illex illecebrosus',
'Clupea harengus - Scomberesox saurus - Gonatus',
'Argis dentata - Eualus macilentus - Eualus gaimardi - Pandalus montagui',
'Chionoecetes opilio - Hyas',
'Echinarachnius parma - Stronglyocentrotus pallidus - Ophiura robusta',
'Mesodesma deauratum - Cyrtodaria siliqua',
'Parexogone hebes',
'Miscellaneous crustaceans', #to remove OBI
'Euphausiids - chaetognaths', # to remove LZOO
'Oithona similis - Temora longicornis - Pseudocalanus - Calanus finmarchicus',
'Chaetoceros affinis - Chaetoceros - Leptocylindrus minimus - Thalassiiosira nordenskioldii - Thalassiiosira - Fragilariopsis')

# Removing portions of the web for which there is no taxa usable for the analysis, 'OBI' & 'LZOO'
SSL[[2]] <- SSL[[2]][-which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO'), -which(colnames(SSL[[2]]) == 'OBI' | colnames(SSL[[2]]) == 'LZOO')]
sp_SSL <- sp_SSL[-which(sp_SSL[,1] == 'OBI' | sp_SSL[,1] == 'LZOO'), ]

S1 <- unique(unlist(str_split(sp_SSL[,2], ' - ')))

load("./RData/Tanimoto_data.RData")
# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
# Format interaction catalogue to fit this table format
    S0 <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
    S0[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        S0[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
        S0[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
    }


# Have to extract taxonomy for speies that are not found in S0
S1_missing <- which(!S1 %in% S0[,1])

S1_add_S0 <- matrix(ncol = 6, nrow = length(S1_missing), data = "", dimnames = list(c(), c("taxon", "taxonomy", "resource", "non-resource", "consumer", "non-consumer")))

S1_add_S0[, 'taxon'] <- S1[S1_missing]

S1_add_S0[, 'taxonomy'] <- c('Animalia | Chordata | Mammalia | Cetartiodactyla | Delphinidae | Lagenorhynchus | Lagenorhynchus acutus',
'Animalia | Chordata | Mammalia | Carnivora | Phocidae | Halichoerus | Halichoerus grypus',
'Animalia | Chordata | Procellariiformes | Hydrobatidae | Oceanodroma | Oceanodroma leucorhoa',
'Animalia | Chordata | Aves | Pelecaniformes | Sulidae | Morus | Morus bassanus',
'Animalia | Chordata | Aves | Charadriiformes | Alcidae | Alca | Alca torda',
'Animalia | Chordata | Elasmobranchii | Rajiformes | Rajidae | Malacoraja | Malacoraja senta',
'Animalia | Chordata | Elasmobranchii | Squaliformes | Etmopteridae | Centroscyllium | Centroscyllium fabricii',
'Animalia | Arthropoda | Malacostraca | Decapoda | Crangonidae | Argis | Argis dentata',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus macilentus',
'Animalia | Arthropoda | Malacostraca | Decapoda | Thoridae | Eualus | Eualus gaimardii',
'Animalia | Echinodermata | Echinoidea | Camarodonta | Strongylocentrotidae | Strongylocentrotus | Strongylocentrotus pallidus',
'Animalia | Mollusca | Bivalvia | Imparidentia | Mesodesmatidae | Mesodesma | Mesodesma deauratum',
'Animalia | Mollusca | Bivalvia | Adapedonta | Hiatellidae | Cyrtodaria | Cyrtodaria siliqua',
'Animalia | Annelida | Polychaeta | Phyllodocida | Syllidae | Parexogone | Parexogone hebes',
'Chromista | Ochrophyta | Bacillariophyceae | Chaetocerotanae | Chaetocerotaceae | Chaetoceros | Chaetoceros affinis',
'Chromista | Ochrophyta | Bacillariophyceae | Leptocylindrales | Leptocylindraceae | Leptocylindrus | Leptocylindrus minimus',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | Thalassiosira nordenskioeldii',
'Chromista | Ochrophyta | Bacillariophyceae | Thalassiosirales | Thalassiosiraceae | Thalassiosira | NA')

 S0 <- rbind(S0, S1_add_S0) #binding missing taxonomies
 rownames(S0) <- S0[, 'taxon']


# #Thinning down catalogue
# S02 <- S0[unique(c(which(S0[, 'resource'] != ""), which(S0[, 'consumer'] != ""))), ]
#
# S1_missing2 <- which(!S1 %in% S02[,1]) #after culling
# S1_missing3 <- S1_missing2[which(!S1_missing2 %in% S1_missing)] #taxo to keep
# S1_add_S0 <- rbind(S1_add_S0, S0[which(S0[, 'taxon'] %in% S1[S1_missing3]), ])
# rownames(S1_add_S0) <- NULL
# S0 <- rbind(S02, S1_add_S0)
# remove(S02,S1_missing3,S1_missing2,S1_missing)

# Predicting interactions
SSL_predict <- full_algorithm(Kc = 4,
                            Kr = 4,
                            S0 = S0,
                            S1 = S1,
                            MW = 1,
                            wt = 0.5,
                            minimum_threshold = 0.3)


# remplace , par ' - '
# remplacer les noms de colonnes et lignes
# combiner duplicatas
# rouler fonction du catalogue pour séparer les lignes et colonnes qui ont plusieurs entrées?
# faire l'analyse en séparant toutes les espèces listées, puis comparer l'analyse divisée, compartimenter les résultats (combiner les interactions des espèces qui sont dans un compartiment), et la réseau présenté dans l'article à partir de la matrice de diète.

tanimoto_analysis <- function(min.tx, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, blind = FALSE) {


load("./RData/interactions_source.RData")
filename <- 'multiple_parameters2'




                        i = 1
                        j = 1
                        Kc = 4
                        Kr = 4
                        S0 = S0
                        S1 = S1
                        MW = 1
                        wt = 0.5
                        minimum_threshold = 0.3
# Uvozimo knižnjice
source("lib/libraries.r", encoding = "UTF-8")



#tabela po mesecih


stolpci1 <- c("Leto", "Mesec", "Št.sklenitev")
PoMesecih <-read.csv2("podatki/pomesecih.csv", sep = ";", as.is = TRUE, header = FALSE,
                      col.names = stolpci1, skip = 2, nrows = (372-3), fileEncoding = "cp1250")

#zapolnimo prazne prostore z NA in potem nadomestimo z vrednostmi, ki ji pripradajo:

for (i in stolpci1[-3]){
  PoMesecih[i][PoMesecih[i] == " "] <- NA
  PoMesecih[i] <- na.locf(PoMesecih[i], na.rm = FALSE)
}

#izbrišemo vrstice, ki so NA v zadnjem stolpcu:

PoMesecih <- PoMesecih[!is.na(PoMesecih$Št.sklenitev),]


#Spremenim vrstni red mesecev, da bo pravilen
PoMesecih$Mesec <- factor(PoMesecih$Mesec, levels = 
                  c("Januar", "Februar", "Marec", "April", "Maj", "Junij",
                    "Julij", "Avgust", "September", "Oktober", "November", "December"))


#Leto spremenim v številsko spremenljivko
PoMesecih$Leto <- as.numeric(PoMesecih$Leto)




#tabela po regiji

stolpci2 <- c("Spol", "Regija", "Starost", "Leto", "Število")
Po_Regijah_Letih <- read.csv2("podatki/poregijahinletih.csv", sep = ";", as.is = TRUE,
                              header = FALSE, col.names = stolpci2,
                              skip = 3, nrows = (821-3), fileEncoding = "cp1250")


#Urejanje - NA:

for (i in stolpci2[c(-5)]){
  Po_Regijah_Letih[[i]][Po_Regijah_Letih[i] == " "] <- NA
  Po_Regijah_Letih[[i]] <- na.locf(Po_Regijah_Letih[[i]], na.rm = FALSE)
}


#izbrišemo vrstice, ki so NA v zadnjem stolpcu:

Po_Regijah_Letih <- Po_Regijah_Letih[!is.na(Po_Regijah_Letih$Število),]

Starost <- factor(Po_Regijah_Letih$Starost, levels = 
                  c("Pod 15 let","15-19 let","20-24 let","25-29 let",
                    "30-34 let","35-39 let","40-44 let","45-49 let",
                    "50-54 let","55-59 let","60 ali več let"))
Po_Regijah_Letih$Starost <- Starost

Po_Regijah_Letih$Regija <- as.factor(Po_Regijah_Letih$Regija)






##Naredim novo tabelo iz tabele Po_Regijah_Letih tako da vzamem samo Regije in starostno skupino
Starost_Regije <- Po_Regijah_Letih %>% group_by(Regija, Starost) %>% summarise(Število = sum(Število))

#Tvorim novo tabelo, kjer bo prikazana najbolj pogosta starost za posamezno regijo
Tabela <- data.frame(Regija = levels(Po_Regijah_Letih$Regija), Starost = rep("starost"))

Starost_stopnje <- rep('srednje', length(Tabela$Regija))
Starost <- factor(Starost_stopnje,levels = c('mladi', 'srednje', 'stari'),ordered = TRUE)

Mladi <- c("Pod 15 let", "15-19 let", "20-24 let", "25-29 let")
Srednje <- c("35-39 let", "40-44 let", "45-49 let")
Stari <- c("50-54 let", "55-59 let", "60 ali več let")

for (i in levels(Tabela$Regija)){
  a <- Po_Regijah_Letih %>% group_by(Regija, Starost) %>% summarise(Število = sum(Število)) %>%
    filter(Regija == i, Število == max(Število))
  a <- a$Starost
  Tabela[[i]][Tabela[i] == "starost"] <- a
}

Visina.stopnje <- rep('normalna', length(Umrli_stopnje$Groba.stopnja.umrljivosti))
Stopnja <- factor(Visina.stopnje,levels = c('nizka', 'normalna', 'visoka'),ordered = TRUE)
Stopnja[Umrli_stopnje$Groba.stopnja.umrljivosti <= 1000] <- 'nizka'
Stopnja[Umrli_stopnje$Groba.stopnja.umrljivosti >= 1600] <- 'visoka'
Umrli_stopnje$Stopnja <- Stopnja

#Tabela iz HTML

#link <- "http://www.stat.si/StatWeb/prikazi-novico?id=5241&idp=17&headerbar=15" 


#stran <- html_session(link) %>% read_html(encoding = "UTF-8") 
#tabele <- stran %>% html_nodes(xpath ="//table[@rules='all']") 
#tabela1 <- tabele %>% .[[1]] %>% html_table()  

#names(tabela1)<- tabela1[1,] 
#tabela1 = tabela1[-1,] 
#tabela1 = tabela1[-3,] 
#tabela1 = tabela1[-5,]
#tabela1 = tabela1[-7,]
#tabela1 = tabela1[-10,]
#Encoding(tabela1[[1]]) <- "UTF-8" 
#tabela1[2,1] <- 'Sklenitve zakonskih zvez na 1000 prebivalcev' 
#tabela1[3,1] <- 'Povprečna starost ženina' 
#tabela1[4,1] <- 'Povprečna starost neveste'
#tabela1[5,1] <- 'Povprečna starost ob sklenitvi prve zakonske zveze ženina'
#tabela1[6,1] <- 'Povprečna starost ob sklenitvi prve zakonske zveze neveste'
#tabela1[7,1] <- 'Registrirane istospolne partnerske skupnosti'
#tabela1[8,1] <- 'Registrirane istospolne partnerske skupnosti med miškima'
#tabela1[9,1] <- 'Registrirane istospolne partnerske skupnosti med ženskama'
#tabela1 = tabela1[-10,]
#tabela1 = tabela1[-10,]
#tabela1 = tabela1[-10,]

#tabela1[,2:3] <- apply(tabela1[,2:3], 2, . %>% gsub("\\.", "", .) %>% 
 #                        gsub(",", ".", .) %>% 
  #                       as.numeric()) 




## GRAFI:

#Prvi graf bo prikazoval število sklenitev glede na mesec ter primerjal leti 1990 in 2014
#Najprej leto spremenimo v FAKTOR, da bomo lahko primerjali leto 1990 in leto 2014

PoMesecih$Leto <- as.factor(PoMesecih$Leto)

GRAF1 <- ggplot(filter(PoMesecih, Leto == 1990 | Leto == 2014), aes(x=Mesec, y=Št.sklenitev, fill=Leto)) + 
  geom_bar(stat = "identity", position = "dodge") + 
  labs(title ="Sklenitve zakonskih zvez po mesecih")+
  theme_minimal()+
  theme(axis.text.x = element_text(angle = 45, vjust = 0.5))


##Drugi graf narišem glede na starost in spet primerjam leto, ponovno spremenim leto v faktor
Po_Regijah_Letih$Leto <- as.factor(Po_Regijah_Letih$Leto)

GRAF2 <- ggplot(data = group_by(Po_Regijah_Letih,Starost, Leto)
                %>% summarise(Število = sum(Število)),
                aes(x=Starost, y=Število, color=Leto)) + 
  geom_line(aes(color = Leto, group=Leto))+
  labs(title ="Sklenitve zakonskih zvez po starostnih skupinah")+
  theme_minimal()+
  theme(axis.text.x = element_text(angle = 45, vjust = 0.5))


##Tortni graf glede na leto, da vidim koliko procentov vseh porok je bilo glede na leto
##Izberem 3 leta: 1990, 2000, 2014
GRAF3 <- ggplot(data = PoMesecih %>% filter(Leto == 1990 |Leto == 2000 |Leto == 2014) %>%
                  group_by(Leto) %>% summarise(Št.sklenitev = sum(Št.sklenitev)),
                aes(x="", y=Št.sklenitev, fill=Leto)) + 
  geom_bar(width = 1,, stat = "identity") + 
  geom_text(aes(y = Št.sklenitev/3 + 
                  c(0, cumsum(Št.sklenitev)[-length(Št.sklenitev)]), 
                label = percent(Št.sklenitev/sum(Št.sklenitev))), size=5)+
  coord_polar(theta = "y")+
  scale_y_continuous(breaks=NULL)+
  theme_minimal()+
  guides(fill=guide_legend(ncol=2, title=NULL))+
  labs(title ="Število sklenitev glede na leto", x="", y="")

##Četrti graf prikazuje poroko glede na starostno skupino - Ženin/Nevesta

GRAF4 <- ggplot(data = group_by(Po_Regijah_Letih, Starost, Spol)
                %>% summarise(Število = sum(Število)),
                aes(x=Starost, y=Število, color=Spol)) + 
  geom_line(aes(color = Spol, group=Spol))+
  labs(title ="Sklenitve zakonskih zvez po starostnih skupinah glede na spol")+
  theme_minimal()+
  theme(axis.text.x = element_text(angle = 45, vjust = 0.5))




###############################################
### COMMONLY USED PACKAGES IN AIM R SCRIPTS ###
###############################################

#### DATA WRANGLING ####
install.packages(
  c(
    "dplyr", ## Notably useful for data frame manipulation with group_by(), summarize(), and mutate() and the piping operator %>%. Do you have a moment to hear the good news of our savior, piping?
    "tidyr", ## Lots of useful things, but specifically gather() and spread() for converting wide data frames into long ones and vice versa
    "stringr", ## All about character strings. Great for str_split() in particular, but the whole str_ family of functions are A+
    "RODBC", ## Allows R to pass SQL queries to Access databases and pull out the results
    "XLSX", ## Read in modern Excel workbooks and spreadsheets
    "broom" ## Get stats objects into tidy data frames. Not as common
  )
)

#### SPATIAL DATA ####
install.packages(
  c(
    "sp", ## Functions for manipulating spatial objects. If you want a Spatial _____ Data Frame, this is part of the deal
    "spsurvey", ## Contains plenty, but the most important to AIM is the GRTS function
    "rgeos", ## Additional spatial object functions
    "rgdal", ## Contains the mission critical readOGR() function that we read shapefiles in with
    "raster" ## Everything you didn't know you needed for dealing with rasters
  )
)

#### DATA VISUALIZATION ####
install.packages(
  c(
    "ggplot2", ## The go-to for figure generation. Most R-using scientists AND Nate Silver use it, so you should too
    "ggthemes", ## Quick themes to painlessly apply to figures from ggplot
    "ggmap", ## Mapping support for ggplot
  )
)

#### MISCELLANEOUS PACKAGES ####
install.packages("arcgisbinding") ## Young and finicky, but once you have it all installed (an ordeal) you should be able to read from and write to file geodatabases from R
install.packages("gridExtra") ## Lets you make grid objects that you can place ggplot figures into. May occasionally be preferable to faceting in ggplot, but rarely
install.packages("shiny") ## Required for working with Shiny tools in any form. Can be maddening
install.packages("purrr") ## Really, really useful for writing functions, particularly those that fail gracefullystr(mtcars)

print("Sleeping for 15 seconds")
Sys.sleep(15)


print("Saving RData file")
dir.create("/var/www/html/RServer/reports/mtcars")
save(mtcars, file = "/var/www/html/RServer/reports/mtcars/mtcars.RData")


fit <- lm(mpg~am + wt + hp, data = mtcars) 
summary(fit)


print("Saving Model")
Sys.sleep(10)
save(fit, file = "/var/www/html/RServer/reports/mtcars/Model.RData")
warning("This is a warning!")

tryCatch({ 
  stop("This is an error!")
}, error = function(cond) {
  message("Caught the error.")
})   

stop("This is an error!")
print("Reached end of script!")

path <- "/var/www/html/RServer/logs"

if (Sys.info()['sysname'] == "Windows") { 
  path <- "C:/wamp/www/RServer/logs"
}

if ("DT" %in% rownames(installed.packages()) == FALSE) {
  install.packages("DT", repos='http://cran.us.r-project.org') 
} 
library(DT)
 
loadTaskData <- function(daysHistory = 60) { 
  events <- data.frame()  
  
  for (file in list.files(path, full.names = TRUE)) { 
    date <- as.Date(strsplit(file, "_", fixed = TRUE)[[1]][2]) 
    daysAgo <- as.numeric(Sys.Date() - date, units = "days")
    
    if (daysAgo <= daysHistory) {  
      res <- readLines(file)
      
      for (line in res) { 
        
        outcome <- NULL
        
        if (length(grep("R Script completed successfully", line)) > 0) {
          outcome <- "Success"
        }

        if (length(grep("R Script failed", line)) > 0 || length(grep("Unable to run R Script", line)) > 0) { 
          outcome <- "Failure"
        }
        
        if (length(grep("R Script was aborted", line)) > 0) { 
          outcome <- "Aborted"
        }
        
        if (!is.null(outcome)) {
        
          # get the task name           
          atts <- strsplit(line, ":", fixed = TRUE)[[1]]
          task <- atts[length(atts)]
          task <- sub("^\\s+|\\s+$", "", task)
          
          # get timestamp 
          atts <- strsplit(line, ": ", fixed = TRUE)[[1]]
          timestamp <- atts[1]
          
          if (grepl("UTC", line)) {
            timestamp <- gsub("UTC ","", timestamp)
            timestamp <- strptime(timestamp, "%a %b %d %H:%M:%S %Y", tz = "UTC") 
          }
          else {
            if (grepl("PDT", line)) {
              timestamp <- gsub("PDT ","", timestamp)
            }else {
              timestamp <- gsub("PST ","", timestamp)
            }
            
            timestamp <- strptime(timestamp, "%a %b %d %H:%M:%S %Y", tz = "PST8PDT") 
          }

          events <- rbind(events, data.frame(TaskName = c(task), CompletionTime = c(as.character(timestamp)), Outcome = c(outcome), timestamp = c(timestamp)))   
        } 
      }
    }
  }  

  # sort by event time 
  if (nrow(events) > 0) {
    events <- events[order(events$timestamp, decreasing = TRUE), ]
  }
  
  events$timestamp <- NULL
  return (events) 
}


libraries <- c("rmarkdown", "yaml", "scales")  
for (lib in libraries) {
  if (lib %in% rownames(installed.packages()) == FALSE) {
    install.packages(lib, repos='http://cran.us.r-project.org')  
  } 
} 

require(rmarkdown)      
render("TaskReport.rmd", output_format = "html_document", output_file = "RServerTasks.html")      

if (Sys.info()['sysname'] == "Windows") {  
  file.copy("RServerTasks.html", "C:/wamp/www/RServer/reports/RServer/RServerTasks.html", overwrite = TRUE)     
} else {
  file.copy("RServerTasks.html", "/var/www/html/RServer/reports/RServer/RServerTasks.html", overwrite = TRUE)      
}


libraries <- c("rmarkdown", "yaml", "scales")  
for (lib in libraries) {
  if (lib %in% rownames(installed.packages()) == FALSE) {
    install.packages(lib, repos='http://cran.us.r-project.org')  
  } 
} 

  
require(rmarkdown)   
render("ServerReport.Rmd", output_format = "html_document", output_file = "RServerReport.html")      
 
if (Sys.info()['sysname'] == "Windows") { 
  render("ServerReport.Rmd", output_format = "pdf_document", output_file = "RServerReport.pdf")    
  render("ServerReport.Rmd", output_format = "word_document", output_file = "RServerReport.docx")    
  
  file.copy("RServerReport.pdf", "C:/wamp/www/RServer/reports/RServer/RServerReport.pdf", overwrite = TRUE)     
  file.copy("RServerReport.html", "C:/wamp/www/RServer/reports/RServer/RServerReport.html", overwrite = TRUE)       
  file.copy("RServerReport.docx", "C:/wamp/www/RServer/reports/RServer/RServerReport.docx", overwrite = TRUE)     
   
} else {
  file.copy("RServerReport.html", "/var/www/html/RServer/reports/RServer/RServerReport.html", overwrite = TRUE)       
}print("Hello World!")
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        options = NULL,
        initialize = function(dir = ".", options = c()) {
            self$options <- SlurmOptions$new(options)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
                script <- SlurmBashScript$new(dir, self$options)
            }
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmOptions R6 object.
#'
#' An interface to SBATCH settings.
SlurmOptions <- R6::R6Class("SlurmOptions",
    public = list(
        options = c(sbatch_opts$nodes(1),
                    sbatch_opts$memory("8g"),
                    sbatch_opts$cpus_per_task(1),
                    sbatch_opts$time("00:30:00")),
        initialize = function(options = c()) {
            for (opt in options) {
                self$options <- sbatch_opts_insert(opt, self$options)
            }
        },
        for_command_line = function() {
            line <- ""

            for (opt in self$options) {
                line <- paste(line, opt)
            }

            return(line)
        },
        for_slurm_script = function() {
            comments <- "#!/bin/bash"

            for (opt in self$options) {
                comments <- paste(comments, paste("#SBATCH", opt), sep = "\n")
            }

            return(comments)
        }
    )
)
#' SlurmSettings R6 object.
#'
#' An interface to SBATCH settings.
SlurmSettings <- R6::R6Class("SlurmSettings",
    public = list(
        options = c(sbatch_opts$nodes(1),
                    sbatch_opts$memory("16g"),
                    sbatch_opts$cpus_per_task(12),
                    sbatch_opts$time("00:30:00")),
        initialize = function(options = c()) {
            for (opt in options) {
                self$options <- sbatch_opts_insert(opt, self$options)
            }
        },
        for_command_line = function() {
            line <- ""

            for (opt in self$options) {
                line <- paste(line, opt)
            }

            return(line)
        },
        for_slurm_script = function() {
            comments <- "#!/bin/bash"

            for (opt in self$options) {
                comments <- paste(comments, paste("#SBATCH", opt), sep = "\n")
            }

            return(comments)
        }
    )
)
#' Fit linear models with each column of \code{y}
#' as dependent variables and the fixed and random
#' effects as independent variables.
#' Independent variables lacking variation are omitted.
#' Returns the residual matrix.
adjust.columns <- function(y, fixed.effects=NULL, random.effects=NULL) {
    stopifnot(is.matrix(y))
    stopifnot((is.matrix(fixed.effects) || is.data.frame(fixed.effects)) && nrow(y) == nrow(fixed.effects))
    stopifnot(is.null(random.effects) || nrow(y) == nrow(random.effects))
    
    remove.invariant.columns <- function(x) {
        if (is.null(x)) return(x)
        is.variable <- apply(x, 2, function(x) length(unique(x))) > 1
        var.idx <- which(is.variable)
        if (length(var.idx) == 0) NULL
        else x[,var.idx,drop=F]
    }

    fixed.effects <- remove.invariant.columns(fixed.effects)
    random.effects <- remove.invariant.columns(random.effects)

    if (is.null(fixed.effects) && is.null(random.effects)) return(y)

    if (is.null(random.effects)) {
        if (is.data.frame(fixed.effects))
            fixed.effects <- do.call(cbind, lapply(fixed.effects, simplify.variable))        
        fit <- lm.fit(x=fixed.effects, y=y)
        return(residuals(fit))
    }
    
    data <- data.frame(random.effects, stringsAsFactors=F)
    formula <- "y ~"
    if (!is.null(fixed.effects)) {
        formula <- paste(formula, paste(colnames(fixed.effects), collapse=" + "), "+")
        data <- data.frame(data, fixed.effects, stringsAsFactors=F)
    }
    formula <- paste(formula, paste("(1 |", colnames(random.effects), ")", collapse=" + "))
    
    ret <- sapply(1:ncol(y), function(i) {
        data$y <- y[,i]
        tryCatch({
            residuals(lme4::lmer(formula, data=data))
            ## chose lme4 because it is faster than nlme
        }, error=function(e) {
            print(e)
            cat("For variable", i, "ignoring random effects.\n")
            tryCatch({
                residuals(lm(y ~ ., data=data))
            }, error=function(e) {
                print(e)
                cat("For variable", i, "setting all values to missing.\n")
                rep(NA, nrow(data))
            })
        })
    })
    dimnames(ret) <- dimnames(y)
    ret
}
#
# Example R code to install packages
# See http://cran.r-project.org/doc/manuals/R-admin.html#Installing-packages for details
#

###########################################################
# Update this line with the R packages to install:

my_packages = c('shiny', 'shinyBS', 'DT', 'tidyr', 'digest', 'RCurl', 'jsonlite', 'dplyr')

###########################################################

install_if_missing = function(p) {
  if (p %in% rownames(installed.packages()) == FALSE) {
    install.packages(p, dependencies = TRUE)
  }
  else {
    cat(paste("Skipping already installed package:", p, "\n"))
  }
}
invisible(sapply(my_packages, install_if_missing))
#!/usr/bin/env RScript
library(parallel)
library(iterators)
library(foreach)
library(doParallel)
library(proto)
library(argparse)

parser <- ArgumentParser()
parser$add_argument('input', help = 'input csv file')
parser$add_argument('gameplayInput', help = 'input gameplay video')
parser$add_argument('output', help = 'output video file')
parser$add_argument('--fps', type = 'integer', default = 3, help = 'frames per second')
parser$add_argument('--dpi', type = 'integer', default = 72, help = 'dpi for generated video frames')
parser$add_argument('--tempdir', help = 'working directory for intermediate files')
parser$add_argument('--graphcolour', default = 'red')
args <- parser$parse_args()

main <- function()
{
	fps <- args$fps
	input <- args$input
	gameplayInput <- args$gameplayInput
	output <- args$output
	dpi <- args$dpi
	frameDir <- if (is.null(args$tempdir)) tempdir() else args$tempdir
	graphColour <- args$graphcolour

	videoAttrs <- system(paste0('ffprobe -v error -show_entries stream=width,height,r_frame_rate ',
		'-of default=noprint_wrappers=1:nokey=1 ', gameplayInput), intern = T)

	videoRes = as.integer(videoAttrs[1:2])
	videoSize = videoRes / dpi
	fpsTokens = as.integer(unlist(strsplit(videoAttrs[3], '/')[1]))
	gameplayFps <- fpsTokens[1] / fpsTokens[2]
	dar <- paste0(videoRes[1], '/', videoRes[2])

	message('Input gameplay runs at ', gameplayFps, ' FPS at ', videoRes[1], 'x', videoRes[2])

	data <- read.csv(input)
	data$offsetSeconds = data$offset / 1000

	duration <- max(data$offsetSeconds)
	frames <- floor(duration * fps)
	cores <- detectCores()
	message('Rendering ', frames, ' frames using ', cores, ' cores')

	cluster <- makeCluster(cores)
	registerDoParallel(cluster)

	foreach(i = 1:frames, .packages = 'ggplot2') %dopar% {
		toRender <- subset(data, offset < i / fps * 1000)
		plot <- ggplot(toRender, aes(x = offsetSeconds, y = value)) +
			geom_line(color = graphColour, size = 2) +
			labs(x = 'Time (s)', y = 'GSR (microsiemens)') +
			ylim(c(0, ceiling(max(data$value)))) +
			xlim(c(0, duration)) +
			theme(plot.background = element_rect(fill = 'transparent'),
				panel.background = element_blank())
		ggsave(paste0(frameDir, '/', i, '.png'), plot,
			width = videoSize[1], height = videoSize[2], dpi = dpi, bg = 'transparent')
	}

	stopCluster(cluster)

	fpsRatio <- gameplayFps / fps
	tempVideoPath = paste0(frameDir, '/', 'frames.mov')
	message('Rendering video from frames: ', tempVideoPath)
	system(paste0('ffmpeg -v error -y -r ', gameplayFps, ' -framerate ', fps,
		' -i "', frameDir, '/%d.png" ',
		' -filter:v "setpts=', fpsRatio, '*PTS" -vcodec qtrle ', tempVideoPath))

	message('Merging with gameplay')
	system(paste0('ffmpeg -v error -y -r ', gameplayFps, ' -i "', gameplayInput, '" -i "', tempVideoPath, '" ',
		' -filter_complex "[0:v]format=rgba[a];',
		'[1:v]setdar=', dar, ',format=yuva420p,colorchannelmixer=aa=0.1[b];',
		'[a][b]overlay=shortest=1"',
		' ', output))
}

dummy <- main()# 4. faza: Analiza podatkov

barve <- rainbow(length(levels(obcine[[7]])))
names(barve) <- levels(obcine[[7]])
# 3. faza: Izdelava zemljevida

# Uvozimo zemljevid.
zemljevid <- uvozi.zemljevid("http://e-prostor.gov.si/fileadmin/BREZPLACNI_POD/RPE/OB.zip",
                             "OB/OB", encoding = "Windows-1250")

# Preuredimo podatke, da jih bomo lahko izrisali na zemljevid.
druzine <- preuredi(druzine, zemljevid, "OB_UIME", c("Ankaran", "Mirna"))

# Izračunamo povprečno velikost družine.
druzine$povprecje <- apply(druzine[1:4], 1, function(x) sum(x*(1:4))/sum(x))
min.povprecje <- min(druzine$povprecje, na.rm=TRUE)
max.povprecje <- max(druzine$povprecje, na.rm=TRUE)
library(knitr) 
library(ggplot2) 
require(dplyr) 
require(rvest) 
require(gsubfn) 



# Uvozimo funkcije za delo z datotekami XML.
source("lib/xml.r", encoding = "UTF-8")

# Uvozimo funkcije za pobiranje in uvoz zemljevida.
source("lib/uvozi.zemljevid.r", encoding = "UTF-8")create_dtm <- function( path ) {

  library(tm)
  library(slam)

  a <- Corpus( DirSource( path, encoding = "UTF-8" ) )

  ## bunch of cleanup and transformations
  a <- tm_map(a, removeNumbers, mc.cores=1 )
  a <- tm_map(a, stripWhitespace, mc.cores=1 )
  a <- tm_map(a, removePunctuation, mc.cores=1 )
  a <- tm_map(a, tolower, mc.cores=1 )
  a <- tm_map(a, function(x) iconv(x, to='UTF-8', sub='byte'), mc.cores=1 )
  a <- tm_map(a, removeWords, stopwords("finnish"), mc.cores=1 )

  ## transform back to plaintext documents
  a <- tm_map(a, PlainTextDocument)

  ## compute word frequencies
  dtm <-DocumentTermMatrix(a) ## , control = list( bounds = list( global = c( minDocFreq, maxDocFreq ) ) ) )

  frequency <- col_sums( dtm , na.rm = T )
  frequency <- sort(frequency, decreasing=TRUE)

  upper = floor( length( frequency ) * .005 )
  lower = floor( length( frequency) * .75 )
  upper = frequency[ upper ]
  lower = frequency[ lower ]
  upper = as.integer( upper )
  lower = as.integer( lower ) + 1

  dtm2 = DocumentTermMatrix( a , control = list( bounds = list( global = c( lower, upper ) ) ) )

  ## throw away columns with 0 indicators
  dtm3 <- dtm2[ row_sums( dtm2 ) > 0, ]

  return( dtm3 )

}

create_model <- function( dtm, k ) {

   library(topicmodels)

   burnin = 1000
   iter = 1000
   keep = 50

   model <- LDA( dtm , k = k, method = "Gibbs", control =  list(burnin = burnin, iter = iter, keep = keep) )

   return( model )

}

check_fitness <- function( dtm , k ) {

  library(topicmodels)
  library(Rmpfr)

  burnin = 1000
  iter = 1000
  keep = 50

  model <- create_model( dtm , k )
  ll <- model@logLiks[ -c(1:(burnin/keep)) ]

  precision = 2000L
  llMed <- median( ll )
  ll = as.double( llMed - log( mean( exp( -mpfr(ll , prec = precision) + llMed ) ) ) )

  return( ll )

}


## from http://www.r-bloggers.com/a-link-between-topicmodels-lda-and-ldavis/

visualize_topicmodel <- function(fitted, corpus, doc_term){
    # Required packages
    library(topicmodels)
    library(dplyr)
    library(stringi)
    library(tm)
    library(LDAvis)

    # Find required quantities
    phi <- posterior(fitted)$terms %>% as.matrix
    theta <- posterior(fitted)$topics %>% as.matrix
    vocab <- colnames(phi)
    doc_length <- vector()
    for (i in 1:length(corpus)) {
        temp <- paste(corpus[[i]]$content, collapse = ' ')
        doc_length <- c(doc_length, stri_count(temp, regex = '\\S+'))
    }
    temp_frequency <- inspect(doc_term)
    freq_matrix <- data.frame(ST = colnames(temp_frequency),
                              Freq = colSums(temp_frequency))
    rm(temp_frequency)

    # Convert to json
    json_lda <- LDAvis::createJSON(phi = phi, theta = theta,
                            vocab = vocab,
                            doc.length = doc_length,
                            term.frequency = freq_matrix$Freq)

    return(json_lda)
}
source('topics.r')

df = data.frame( k = integer(), ll =integer() )

path <- commandArgs(trailingOnly=TRUE)[0]

for( f in list.files(path) ){
	load(f)
	k <- model@k
	ll <- check_fitness_model( model )
	row = c(k, ll)
	df[ nrow(df)+1,] <- row
}

print("Best fit log likelihood", which.max( df$ll ) )
print("Best fit k", df$k[ which.max( df$ll ) ] )
#' Class for basic queuing system functions
#'
#' Provides the basic functions needed to communicate between machines
#' This should abstract most functions of rZMQ so the scheduler
#' implementations can rely on the higher level functionality
QSys = R6::R6Class("QSys",
    public = list(
        id = NA,

        initialize = function() {
            private$job_num = 1
            private$zmq_context = rzmq::init.context()
        },

        # Submits one job to the queuing system
        #
        # @param memory      The amount of memory (megabytes) to request
        # @param log_worker  Create a log file for each worker
        submit_job = function(memory=NULL, log_worker=FALSE) {
            stop("Derived class needs to overwrite submit_job()")
        },

        # Send the data common to all workers, only serialize once
        send_common_data = function() {
            if (is.null(private$common_data))
                stop("Need to set_common_data() first")

            rzmq::send.socket(socket = private$socket,
                              data = private$common_data,
                              serialize = FALSE,
                              send.more = TRUE)
        },

        # Send iterated data to one worker
        send_job_data = function(...) {
            rzmq::send.socket(socket = private$socket, data = list(...))
        },

        # Read data from the socket
        receive_data = function() {
            rzmq::receive.socket(private$socket)
        },

        # Make sure all resources are closed properly
        cleanup = function() {
        }
    ),

    private = list(
        zmq_context = NULL,
        socket = NULL,
        port = NULL,
        master = NULL,
        job_num = NULL,
        common_data = NULL,

        set_common_data = function(fun, const, seed) {
            private$common_data = serialize(list(fun=fun, const=const, seed=seed), NULL)
        },

        # Create a socket and listen on a port in range
        #
        # @param fun    The function to be called
        # @param const  Constant arguments to the function call
        # @param seed   Common seed (to be used w/ job ID)
        # @return       Sets "port" and "master" attributes
        listen_socket = function(min_port, max_port=min_port, n_tries=100) {
            if (is.null(private$zmq_context))
                stop("QSys base class not initialized")

            private$socket = rzmq::init.socket(private$zmq_context, "ZMQ_REP")

            on.exit(sink())
            sink('/dev/null')
            for (i in 1:n_tries) {
                exec_socket = sample(min_port:max_port, size=1)
                addr = paste0("tcp://*:", exec_socket)
                port_found = rzmq::bind.socket(private$socket, addr)
                if (port_found)
                    break
            }
            sink()
            on.exit()

            if (!port_found)
                stop("Could not bind to port range (6000,8000) after 100 tries")

            self$id = exec_socket
            private$port = exec_socket
            private$master = sprintf("tcp://%s:%i", Sys.info()[['nodename']], exec_socket)
        }
    ),

    cloneable = FALSE
)
#' ggplot_builder function
#'
#' This function builds a ggplot2 function to plot data
#' @param d Table of data
#' @param x,y,z Variables for each dimension
#' @param logx,logy Log the variable first. Defaults to F.
#' @param geom Select a ggplot2 geometry (currently point,line,histogram,bar,boxplot,violin)
#' @param facet Facet plot by values in a column
#' @param smooth Add a smooth line to point plots (gam,lm,loess,rlm,glm,auto)
#' @param xlim Range displayed on x-axis
#' @param ylim Range displayed on y-axis
#' @param xrotate Angle to rotate x-axis labels (90=vertical)
#' @param colour A variable to colour by
#' @param fill A variable to fill by
#' @param man_colour Select a solid colour
#' @param man_fill Select a solid fill colour
#' @param bar.position Position of bars in a bar plot (stack,dodge,fill)
#' @param bins Add a stat_bin with this number of bins
#' @param binwidth Size of binwidth in binned plots (histogram)
#' @param outliers Set outliers=F to remove outliers from boxplot
#' @param varwidth Set varwidth=T to plot boxplots with variable width based on dataset size
#' @param gradient Select gradient colour scheme (default,Matlab)
#' @param gradient.steps Set number of shades in gradient
#' @param gradient.range Set range of values covered by gradient
#' @param colourset Select colour scheme (default,Set1,Set2,Set3,Spectral)
#' @param cut_method Select method for binning continuous X axis in boxplots (number,interval,width see cut_interval etc.)
#' @param cut.n Binning number applied to cut_method
#' @param enable.plotly convert to interactive Plotly plot
#' @param theme Set ggplot theme (grey,bw,dark,light,void,linedraw,minimal,classsic)
#' @param factorlim Set maximum levels allowed to use factors for plotting (default=50)
#' @param stat.method Set stat method for barplots (count,identity,summary) (default=bin)
#' @param stat.func Set summary function for stat.method="summary" (default=mean)
#' @param coord_flip Flip the x and y axes (default=F)
#' @param tile_height Set height of tile for geom_tile
#' @param tile_width Set width of tile for geom_tile
#' @param condense Use bigvis package to summarise overlapping points in large datasets
#' @param condense.func Function used to condense (mean,median,sum,count)
#' @param condense.x Size of bin to use on X axis to find overlapping points
#' @param condense.y Size of bin to use on Y axis to find overlapping points
#' @keywords ggplot wrapper builder
#' @export
#' @examples
#' ggplot_builder()


ggplot_builder<-function(d,x,y=NA,geom="point",facet=NA,smooth=NA,smooth.se=T,xlim=NA,ylim=NA,xrotate=0,colour=NA,
                         fill=NA,bar.position="stack",binwidth=0,bins=0,outliers=T,varwidth=F,enable.plotly=F,
                         theme="grey",logx=F,logy=F,man_colour=NA,man_fill=NA,tile_height=NA,tile_width=NA,
                         gradient="default",gradient.steps=10,gradient.range=NA,colourset="default",coord_flip=F,
                         cut_method="number",cut.n=10,factorlim=50,stat.method="count",stat.func="mean",
                         condense=F,condense.func="mean",condense.x=10,condense.y=10){
library(plotly)
library(colorRamps)
library(ggplot2)
library(bigvis)

###Avoid plotting with large factors
for(i in c(facet,colour,fill,x)){
  factor_limit(d,i,factorlim)
}
if(!geom %in% c("histogram","bar") | (geom=="bar" & stat.method!="count")){ ##Check Y variable if applicable
  factor_limit(d,y,factorlim)
}

ml<-matlab.like2(gradient.steps)

###build plot
a<-list()
g<-list()
if(geom=="point"){
  a$x<-x
  a$y<-y
  if(!is.na(colour)){
    a$colour<-colour
  }
  if(!is.na(man_colour)){
    g$colour<-man_colour
  }
  as<-do.call(aes_string,a)
  geo<-do.call(geom_point,g)
}
if(geom=="tile"){
  a$x<-x
  a$y<-y
  if(!is.na(fill)){
    a$fill<-fill
  }
  if(!is.na(man_fill)){
    g$fill<-man_fill
  }
  if(!is.na(tile_width)){
    g$width<-tile_width
  }
  if(!is.na(tile_height)){
    g$height<-tile_height
  }
  as<-do.call(aes_string,a)
  geo<-do.call(geom_tile,g)
  ##BigVis data
  if(condense){
    tab<-condense(x=bin(d[,x],condense.x),y=bin(d[,y],condense.y),z = d[,fill],summary = condense.func)
    if(condense.func=="mean"){
      tab<-tab[,-3]
    }
    names(tab)<-c(x,y,fill)
    #if(func=="count" & gradient.log){tab[,paste0(fill,".",tile_bin.func)]<-log(tab[,paste0(fill,".",tile_bin.func)])}
    d<-tab
  }
}
if(geom=="line"){
  a$x<-x
  a$y<-y
  if(!is.na(colour)){
    a$colour<-colour
  }
  if(!is.na(man_colour)){
    g$colour<-man_colour
  }
  as<-do.call(aes_string,a)
  geo<-do.call(geom_line,g)
}
else if(geom=="bar"){
  if(!is.factor(d[,x])){
    stop("bar requires discrete x variable")
  }  
  a$x<-x
  if(stat.method!="count"){
    a$y<-y ##map a y aesthetic if using stat identity or summary
  }
  if(!is.na(fill)){
    a$fill<-fill
  }
  g$position<-bar.position
  if(!is.na(man_fill)){
    g$fill<-man_fill
  }
  if(!is.na(stat.method)){
    g$stat<-stat.method
  }
  if(stat.method=="summary"){
    g$fun.y<-stat.func
  }
  as<-do.call(aes_string,a)
  geo<-do.call(geom_bar,g)
}
else if(geom=="histogram"){
  if(is.factor(d[,x])){
    stop("Histogram requires continuous x variable")
  }
  a$x<-x
  if(!is.na(fill)){
    a$fill<-fill
  }
  if(!is.na(man_fill)){
    g$fill<-man_fill
  }
  if(binwidth>0){
    g$binwidth<-binwidth
  }
  if(bins>0){
    g$bins<-bins
  }
  as<-do.call(aes_string,a)
  geo<-do.call(geom_histogram,g)
}
else if(geom=="boxplot"){
  if(!is.numeric(d[,y])){
    stop("Boxplot requires continuous y variable")
  }
  a$x<-x
  a$y<-y
  if(!is.na(fill)){
    a$fill<-fill
  }
  if(!is.na(man_fill)){
    g$fill<-man_fill
  }
  if(!is.na(colour)){
    a$colour<-colour
  }
  if(!is.na(man_colour)){
    g$colour<-man_colour
  }
  if(is.numeric(d[,x])){
    cut<-switch(cut_method,interval=cut_interval(d[,x],n = cut.n),width=cut_width(d[,x],width=cut.n),number=cut_number(d[,x],n = cut.n))
    a$group<-cut
  }
  if(outliers==F){
    g$outlier.shape<-NA
  }
  if(varwidth==T){
    g$varwidth<-T
  }
  as<-do.call(aes_string,a)
  geo<-do.call(geom_boxplot,g)
}
else if(geom=="violin"){
  if(!is.numeric(d[,y])){
    stop("Violin requires continuous y variable")
  }
  a$x<-x
  a$y<-y
  if(!is.na(fill)){
    a$fill<-fill
  }
  if(!is.na(man_fill)){
    g$fill<-man_fill
  }
  if(!is.na(colour)){
    a$colour<-colour
  }
  if(!is.na(man_colour)){
    g$colour<-man_colour
  }
  if(is.numeric(d[,x])){
    cut<-switch(cut_method,interval=cut_interval(d[,x],n = cut.n),width=cut_width(d[,x],width=cut.n),number=cut_number(d[,x],n = cut.n))
    a$group<-cut
  }
  as<-do.call(aes_string,a)
  geo<-do.call(geom_violin,g)
}
p<-ggplot(d,as)+geo
if(!is.na(facet)){
  if(is.factor(d[,facet])&length(levels(d[,facet]))<=factorlim){
    p<-p+facet_wrap(c(facet))
  }
  else{
    stop(paste("You must facet by a factor variable with <=",factorlim,"levels"))
  }  
}
if(!is.na(smooth) & geom %in% c("point")){
  s<-list()
  if(!is.na(fill)){
    s$fill<-fill
  }
  if(!is.na(colour)){
    s$colour<-colour
  }
  if(smooth.se==F){
    s$se<-F
  }
  statas<-do.call(aes_string,s)
  p<-p+stat_smooth(method=smooth,statas)
}
if(!is.na(xlim) & is.numeric(d[,x])){
  p<-p+xlim(xlim)
}
if(!is.na(ylim)){
  if(!is.null(a$y)){#if y aesthetic exists
    if(is.numeric(d[,y])){ #if y aestheitc is numeric
      p<-p+ylim(ylim)
    }
  }
  else{
    p<-p+ylim(ylim)
  }
}
if(logx & is.numeric(d[,x])){
  p<-p+scale_x_log10()
}
if(logy){
  if(!is.null(a$y)){ #if y aesthetic exists
    if(is.numeric(d[,y])){ #if y aestheitc is numeric
      p<-p+ scale_y_log10()
    }
  }
  else{
    p<-p+ scale_y_log10()
  }
}
p<-switch(theme,grey=p+theme_grey(),dark=p+theme_dark(),light=p+theme_light(),linedraw=p+theme_linedraw(),bw=p+theme_bw(),minimal=p+theme_minimal(),classic=p+theme_classic(),void=p+theme_void(),p+theme_grey())
if(xrotate!=0){
  p<-p+theme(axis.text.x=element_text(angle=xrotate,hjust=1,vjust=0.5))
}

##set colour scales
if(!is.na(colour)){
  if(is.factor(d[,colour])){
    p<-switch(colourset,default=p,Set1=p+scale_colour_brewer(palette="Set1"),
              Set2=p+scale_colour_brewer(palette="Set2"),
              Set3=p+scale_colour_brewer(palette="Set3"),
              Spectral=p+scale_colour_brewer(palette="Spectral"))
  }
  else{
    if(!is.na(gradient.range)){
      p<-switch(gradient,default=p+scale_colour_gradient(limits=gradient.range,oob = scales::squish,space="Lab"),Matlab=p+scale_colour_gradientn(space = "Lab",limits = gradient.range,oob = scales::squish,colours=ml))
    }
    else{
      p<-switch(gradient,default=p,Matlab=p+scale_colour_gradientn(colours=ml))
    }
  }
}
if(!is.na(fill)){
  if(is.factor(d[,fill])){
    p<-switch(colourset,default=p,Set1=p+scale_fill_brewer(palette="Set1"),
              Set2=p+scale_fill_brewer(palette="Set2"),
              Set3=p+scale_fill_brewer(palette="Set3"),
              Spectral=p+scale_fill_brewer(palette="Spectral"))
  }
  else{
    if(!is.na(gradient.range)){
      p<-switch(gradient,default=p+scale_fill_gradient(limits=gradient.range,oob = scales::squish,space="Lab"),Matlab=p+scale_fill_gradientn(space = "Lab",limits = gradient.range,oob = scales::squish,colours=ml))
    }
    else{
      p<-switch(gradient,default=p,Matlab=p+scale_fill_gradientn(colours=ml))
    }  }
}
if(coord_flip){
  p<-p+coord_flip()
}
#p<-p + scale_colour_brewer(palette="Set1") + scale_fill_brewer(palette="Set1")
if(enable.plotly){
  return(ggplotly(p))
}
p
}

#+  scale_fill_brewer(palette="Set1") + scale_colour_brewer(palette="Set1")
#scale_colour_gradientn(colours=rainbow(4))
#matlab_like........

#ggplot_builder(t,"biotype","CpGdensity",geom="",xvert=T,bar.position="stack",
#               theme="dark",bins=20,fill="biotype",logy=F,outliers=F) 


#ggplot(t,aes_string("biotype","length",colour="biotype",fill="OE_direction"))+ geom_boxplot()


#bar.position = stack, dodge or fill


#ggplot_builder(d=t,x="GC",y="length",z="length",logx=F,logy=F,facet="NA",
#               geom="histogram",smooth="NA",xrotate=0,colour="NA",
#               fill=NA,bar.position = "stack",theme = "light",
#               enable.plotly = F,outliers=T,bins = 0,
#               xlim="NA",ylim="NA")
# The functions require rchart-helper.R preloaded

# getQ2TimelapsePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getQ2TimelapsePlot = function(data, names, colors, yLabel, colName="x", verticalLineDate=NULL, timezone="UTC") {
    series <- list()
    dateFactors <- list()
    col <- which(names(data[[1]])==colName)[1]
    for (i in 1:length(data)) {
        dateFactors[[i]] <- as.factor(data[[i]]$date)
        boxplot <- boxplot(data[[i]][, col] ~ dateFactors[[i]],
                          data=data.frame(dateFactors[[i]], data[[i]][, col]), plot=FALSE)
        stats <- setNames(as.data.frame(boxplot$stats), nm=NULL)

        # Timpstamp in miliseconds
        unixTimestamps <-
            1000 * as.numeric(as.POSIXct(sort(unique(data[[i]]$date)),
                                         origin="1970-01-01"))
        statsMedian <- rbind(setNames(unixTimestamps, nm=NULL), stats[3,])
        statsQ2 <- rbind(setNames(unixTimestamps, nm=NULL), stats[c(2, 4),])

        series[[2 * (i - 1) + 1]] <-
            list(name=names[i], data=statsMedian, zIndex=1, color=colors[i],
                 marker=list(fillColor="white", lineWidth=2, lineColor=colors[i]))
        series[[2 * i]] <- list(name="50th quartile", data=statsQ2, zIndex=0,
                 type="arearange", color=colors[i], lineWidth=0, linkedTo=":previous", fillOpacity=0.3)
    }

    chart <- Highcharts$new()
    xAxis <- list(type="datetime")
    if (!is.null(verticalLineDate)){
        date <- as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] <- paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=list(text=yLabel), min=0)
    chart$set(series=series)
    return(chart)
}

# Helper for creating histogram
getBinItemList = function(data, businesses, interval=100) {
    binItemList <- c()
    currentBin <- interval
    maxBin <- max(data$count) + interval
    while (currentBin < maxBin) {
        items <- filter(data, currentBin - interval <= count & count < currentBin)
        binItemList <- c(binItemList,
                        paste("< ", currentBin, "<br>",
                              paste(items$name, collapse="<br>, ")))
        currentBin <- currentBin + interval
    }
    return(binItemList)
}

# getStackedHistogram
# data[[]]$x
getStackedHistogram = function(data,
                               names,
                               xLabel,
                               colName="x",
                               minBin=NULL,
                               maxBin = NULL,
                               interval=100,
                               logScale=FALSE,
                               logBase=exp(1),
                               normalize=FALSE,
                               colors = c("#7cb5ec", "#000000")) {
    series <- list()
    plotLines <- list()
    col <- which(names(data[[1]])==colName)[1]
    actualInterval <- interval
    for (i in 1:length(data)) {
        maxBin <- max(maxBin, max(data[[i]][, col], na.rm=TRUE), na.rm=TRUE)
        minBin <- min(minBin, min(data[[i]][, col], na.rm=TRUE), na.rm=TRUE)
    }
    if (logScale) {
        maxBin <- log(maxBin + 1, base=logBase)
        minBin <- log(minBin + 1, base=logBase)
        actualInterval <- log(interval, base=logBase)
    }

    for (i in 1:length(data)){
        x <- as.vector(as.matrix(data[[i]][, col]))
        if (logScale) {
            x <- log(x + 1, base=logBase)
        }

        plotLines[[i * 2 - 1]] <-
            list(color=colors[i],
                 value=mean(x),
                 width=2,
                 label=list(text="mean", style=list(color=colors[i]), verticalAlign="middle"))
        plotLines[[i * 2]] <-
            list(color=colors[i],
                 value=median(x),
                 dashStyle="dash",
                 width=2,
                 label=list(text="median", style=list(color=colors[i]), verticalAlign="middle"))

        histogram <- hist(x, breaks=seq(minBin, maxBin + actualInterval, actualInterval), plot=FALSE)
        histNames <- getBinItemList(data[[i]], interval=actualInterval)

        nBins <- min(length(histogram$breaks), length(histogram$counts))
        counts <- histogram$counts[1:nBins]
        if (normalize) {
            counts <- 100 * counts / nrow(data[[i]])
        }
        breaks <- c(histogram$breaks[2:nBins], histogram$breaks[nBins] + actualInterval)
        bins <- getValues(
            breaks,
            counts,
            name=histNames)
        series[[i]] <- list(name=names[i], data=bins)
    }
   
    chart <- Highcharts$new()
    chart$chart(type="column")
    chart$plotOptions(
        column="{ grouping: false, pointPadding: 0, borderWidth: 0, groupPadding: 0, shadow: false}")
    chart$xAxis(title=paste("{text: '", xLabel, "'}", sep=""),
                plotLines=plotLines)
    yLabel <- "count"
    if (normalize) {
        yLabel <- "density (%)"
    }
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""))
    chart$set(series=series)
    return(chart)
}

# getTimelapseLinePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getTimelapseLinePlot = function(data, names, yLabel, colName="x", verticalLineDate=NULL, timezone="UTC") {
    series <- list()
    col <- which(names(data[[1]])==colName)[1]
    for (i in 1:length(data)){
        timelapseValues <- getTimelapseValues(
            as.POSIXlt(strptime(as.character(data[[i]]$date), "%Y-%m-%d", tz=timezone)),
            data[[i]][, col])
        series[[i]] <- list(name=names[i], data=timelapseValues)
    }


    chart <- Highcharts$new()
    xAxis <- list(type="datetime")
    if (!is.null(verticalLineDate)){
        date <- as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] <- paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""), gridLineColor="#FFFFFF")
    chart$set(series=series)
    return(chart)
}


# Difference-in-difference plot
# Use with DiffInDiffAggregate function
diffInDiffPlot = function(data,
                     idCol,
                     xCol,
                     xLabel="period",
                     yLabel="change",
                     periodNames=NULL
                     ) {
    dataChart <- Highcharts$new()
    ids <- unique(data[, idCol])
    numPeriod <- 0
    for (i in 1:length(ids)) {
        current <- data[data[, idCol] == ids[i],]
        numPeriod <- nrow(current)
        name <- current[1,][, idCol]
        x <- seq(0, numPeriod - 1, 1)
        y <- current[, xCol]
        z <- current[, xCol]
        
        seriesData <- getValues(x, y, z, name)
        visible <- TRUE
        dataChart$series(name=name,
                         data=seriesData,
                         showInLegend=TRUE,
                         visible=visible)
    }
    if (is.null(periodNames)) {
        periodNames <- paste("period", x)
    }
    dataChart$xAxis(categories=periodNames)
    dataChart$yAxis(title=list(text=yLabel), gridLineColor="#FFFFFF")
    dataChart$legend(align="right", verticalAlign="top", layout="vertical")
    dataChart$tooltip(pointFormat=getPointFormat(y=yLabel, z=NULL))
    return (dataChart)
}

# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename1 = 'catalog_predictions2'
filename2 = 'catalog_predictions3'


catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions2 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40,60,80),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename1)

catalog_predictions3 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(30,50,70,90),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename2)


# Catalog vs predictions

accuracy <- accuracy0 <- accuracy1 <- accuracy2 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) <- names(accuracy2) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy2[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, empirical.only = TRUE)
accuracy2[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, predict.only = TRUE)
accuracy2[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]], accuracy2[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]], accuracy2[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]], accuracy2[[3]])

percent_remove = c(0,10,20,30,40,50,60,70,80,90,100)
nb_iter = 50
K.values = 8
MW = 1
WT =  c(0.5,1)
minimum_threshold = 0.3

nb.pts <- length(percent_remove)

#Figure version 1
pdf(paste('./Article/','catalog_predictions','.pdf',sep=''),width=6,height=8)
j = 14 #'Score'[y]
        eplot(xmin = -1, xmax = 100 + 1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        col <- c("#FF8822",'#5ED275','#9CCBFF')
        col2 <- c("#FF8822",'#275A31','#0077FF')
        col3 <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.05)
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.05 + 2.5)
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)
            mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            mtext(text = expression(paste("Percent of taxa removed from ", italic(S0), ' (%)')), side = 1, line = 2, at = 50, font = 2, cex = 1)
            mtext(text = seq(0, 100, by = 10), side = 1, line = 0, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            mtext(text = seq(0, 100, by = 10), side = 3, line = -0.5, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            text(x = 5, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col3[1], adj = 0)
            text(x = 5, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col3[2], adj = 0)
            text(x = 5, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col3[3], adj = 0)


        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            points(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it, cex = 0.5, pch = 1, col = col[i])
            points(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it, cex = 0.5, pch = 1, col = col2[i])

            lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it), col = col[i])
            lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it), col = col2[i])

            if(i == 2 || i == 3) {
                text(x = 90, y = 0.9 + it, labels = expression(paste(italic('w'[t]), ' = 0.5')), col = col[i], font = 1, cex = 0.75)
                text(x = 90, y = 0.8 + it, labels = expression(paste(italic('w'[t]), ' = 1')), col = col2[i], font = 1, cex = 0.75)
            }

            it <- it + 1.25
        } #i
dev.off()

#Figure version 2
pdf(paste('./Article/','catalog_predictions2','.pdf',sep=''),width=6,height=8)
j = 14 #'Score'[y]
        eplot(xmin = -1, xmax = 100 + 1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        col <- c("#FF8822",'#5ED275','#9CCBFF')
        col2 <- c("#FF8822",'#275A31','#0077FF')
        col3 <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.05)
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1, cex.axis = 0.75, font.axis = 1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.05 + 2.5)
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1, cex.axis = 0.75, font.axis = 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)
            mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            mtext(text = expression(paste("Percent of taxa removed from ", italic(S0), ' (%)')), side = 1, line = 2, at = 50, font = 2, cex = 1)
            mtext(text = seq(0, 100, by = 10), side = 1, line = 0, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            mtext(text = seq(0, 100, by = 10), side = 3, line = -0.5, at = seq(0, 100, by = 10), font = 1, cex = 0.75)
            text(x = 5, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col3[1], adj = 0)
            text(x = 5, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col3[2], adj = 0)
            text(x = 5, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col3[3], adj = 0)


        it <- 0
        for(i in 1:length(accuracy)) {
            if(i == 2 || i == 3) {
                accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'pc_rm']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
                # hack: we draw arrows but with very special "arrowheads" for error bars

                arrows(seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][,1] - accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 2]+it, seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 1] + accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
                points(x = seq(0,100,by=10), y = accuracy_mean[which(accuracy_mean[, 2] == '0.5'), 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])

                arrows(seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][,1] - accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 2]+it, seq(0,100,by=10), accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 1] + accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 2]+it, length=0.025, angle=90, code=3, col = col2[i])
                points(x = seq(0,100,by=10), y = accuracy_mean[which(accuracy_mean[, 2] == '1'), 3][, 1]+it, cex = 0.75, pch = 22, col = col2[i])

                lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '0.5'), j]) + it), col = col[i])
                lines(lowess(x = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), 'pc_rm']), y = as.numeric(accuracy[[i]][which(accuracy[[i]][, 'wt'] == '1'), j]) + it), col = col2[i])

                text(x = 90, y = 0.9 + it, labels = expression(paste(italic('w'[t]), ' = 0.5')), col = col[i], font = 1, cex = 0.75)
                text(x = 90, y = 0.8 + it, labels = expression(paste(italic('w'[t]), ' = 1')), col = col2[i], font = 1, cex = 0.75)
                } else {
                    accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'pc_rm']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                    accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
                    # hack: we draw arrows but with very special "arrowheads" for error bars

                    arrows(seq(0,100,by=10), accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2]+it, seq(0,100,by=10), accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2]+it, length=0.025, angle=90, code=3, col = col3[i])
                    points(x = seq(0,100,by=10), y = accuracy_mean[, 2][, 1]+it, cex = 0.75, pch = 22, col = col3[i])

                    lines(lowess(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it), col = col3[i])
                }

            it <- it + 1.25
        } #i
dev.off()
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename <- 'multiple_parameters2'


multiple_parameters2 <- tanimoto_analysis(filename = filename,
                                            min.tx = 45,
                                            K.values = c(2,4,6,8),
                                            MW = 1,
                                            WT = c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1),
                                            blind = FALSE,
                                            minimum_threshold = 0.3)

WT = c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
K.values = c(2,4,6,8)
MW = 1

# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = multiple_parameters2, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = multiple_parameters2, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = multiple_parameters2)

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = nb.pts, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(multiple_parameters2[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(WT) * length(K.values)) + 0.5, labels = FALSE, las = 1, pos = -0.02) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, nb.pts, by = length(K.values)) + 0.5, labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)

            abline(v = seq(length(K.values)+0.5,(nb.pts-length(K.values))+0.5,by = length(K.values)), col = "grey", lty = 2)
            # abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
            abline(h = c(1.125,2.375), col = "black", lty = 2)


            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,nb.pts), accuracy_mean[, 3][,1] - accuracy_mean[, 3][, 2]+it, seq(1,nb.pts), accuracy_mean[, 3][, 1] + accuracy_mean[, 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,nb.pts), y = accuracy_mean[, 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()


#Figure2
pdf(paste('./Article/',filename,'.pdf',sep=''),width=6,height=8)
# Plots
par(mfrow=c(3,1), mar=c(4,4,4,4))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in c(10,11,9)) {
        eplot(xmin = -1, xmax = nb.pts+1, ymax = 3.6)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(multiple_parameters2[[1]][[1]][[1]])
        col <- c("#FF8822","#449955","#2288FF")

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(K.values)), labels = FALSE, las = 1, pos = -0.2) #wt
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.2)
            axis(side = 3, at = seq(0, nb.pts, by = 1), labels = FALSE, las = 1, pos = 1.2 + 2.5) #K.values
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.2))

            abline(v = seq(length(K.values),(nb.pts-length(K.values)),by = length(K.values)), col = "grey", lty = 2)
            # abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
            abline(h = c(1.125,2.375), col = "black", lty = 2)

            if(j == 9) {
                mtext(text = 'TSS', side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            } else if(j == 10) {
                mtext(text = expression('Score'[y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            } else if(j == 11) {
                mtext(text = expression('Score'[-y]), side = 2, line = 2, at = 1.75, font = 1.5, cex = 1)
            }

            mtext(text = "K values", side = 3, line = 2, at = nb.pts/2, font = 1.5, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2.5, at = nb.pts/2, font = 1.5, cex = 1)
            mtext(text = rep(K.values, times = length(WT)), side = 3, line = 1, at = seq(0.5, nb.pts-0.5, by = 1), font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 1, line = 1.5, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,nb.pts)-0.5, accuracy_mean[, 3][,1] - accuracy_mean[, 3][, 2]+it, seq(1,nb.pts)-0.5, accuracy_mean[, 3][, 1] + accuracy_mean[, 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,nb.pts)-0.5, y = accuracy_mean[, 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename1 = 'catalog_predictions2'
filename2 = 'catalog_predictions3'


catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions2 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40,60,80),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename1)

catalog_predictions3 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(30,50,70,90),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename2)


# Catalog vs predictions

accuracy <- accuracy0 <- accuracy1 <- accuracy2 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) <- names(accuracy2) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy2[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, empirical.only = TRUE)
accuracy2[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, predict.only = TRUE)
accuracy2[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]], accuracy2[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]], accuracy2[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]], accuracy2[[3]])

percent_remove = c(0,10,20,30,40,50,60,70,80,90,100)
nb_iter = 100
K.values = 8
MW = 1
WT =  0.5
minimum_threshold = 0.3

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

# Graph
for(j in 13:16) {
        eplot(xmin = -0.09, xmax = 100, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.1) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            # mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            # mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 0.1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 0.1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 0.1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            points(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it, cex = 0.5, pch = 1, col = col[i])
            lines(lowess(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it))
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
#' Class for basic queuing system functions
#'
#' Provides the basic functions needed to communicate between machines
#' This should abstract most functions of rZMQ so the scheduler
#' implementations can rely on the higher level functionality
QSys = R6::R6Class("QSys",
    public = list(
        initialize = function() {
            private$job_num = 1
            private$zmq.context = rzmq::init.context()
        },

        # Submits one job to the queuing system
        #
        # @param memory      The amount of memory (megabytes) to request
        # @param log_worker  Create a log file for each worker
        submit_job = function(...) {
            stop("Derived class needs to overwrite submit_job()")
        },

        # Send the data common to all workers, only serialize once
        send_common_data = function() {
            if (is.null(private$common_data))
                stop("Need to set_common_data() first")

            rzmq::send.socket(socket = private$socket,
                              data = private$common_data,
                              serialize = FALSE,
                              send.more = TRUE)
        },

        # Send iterated data to one worker
        send_job_data = function(...) {
            rzmq::send.socket(socket = private$socket, data = list(...))
        },

        # Read data from the socket
        receive_data = function() {
            rzmq::receive.socket(private$socket)
        },

        # Make sure all resources are closed properly
        cleanup = function() {
        }
    ),

    private = list(
        job_num = NULL,
        zmq.context = NULL,
        socket = NULL,
        port = NULL,
        master = NULL,

        set_common_data = function(fun, const, seed) {
            private$common_data = serialize(list(fun=fun, const=const, seed=seed), NULL)
        },

        # Create a socket and listen on a port in range
        #
        # @param fun    The function to be called
        # @param const  Constant arguments to the function call
        # @param seed   Common seed (to be used w/ job ID)
        # @return       Sets "port" and "master" attributes
        listen_socket = function(min_port, max_port=min_port, n_tries=100) {
            private$socket = rzmq::init.socket(private$zmq.context, "ZMQ_REP")

            sink('/dev/null')
            for (i in 1:n_tries) {
                exec_socket = sample(min_port:max_port, size=1)
                addr = paste0("tcp://*:", exec_socket)
                port_found = rzmq::bind.socket(private$socket, addr)
                if (port_found)
                    break
            }
            sink()

            if (!port_found)
                stop("Could not bind to port range (6000,8000) after 100 tries")

            private$port = exec_socket
            private$master = sprintf("tcp://%s:%i", Sys.info()[['nodename']], exec_socket)
        }
    ),

    cloneable = FALSE
)
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename <- 'multiple_parameters2'


multiple_parameters2 <- tanimoto_analysis(filename = filename,
                                            min.tx = 45,
                                            K.values = c(2,4,6,8),
                                            MW = 1,
                                            WT = c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1),
                                            blind = FALSE,
                                            minimum_threshold = 0.3)

WT = c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
K.values = c(2,4,6,8)
MW = 1

# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = multiple_parameters2, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = multiple_parameters2, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = multiple_parameters2)

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = nb.pts, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(multiple_parameters2[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(WT) * length(K.values)) + 0.5, labels = FALSE, las = 1, pos = -0.02) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, nb.pts, by = length(K.values)) + 0.5, labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)

            abline(v = seq(length(K.values)+0.5,(nb.pts-length(K.values))+0.5,by = length(K.values)), col = "grey", lty = 2)
            # abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
            abline(h = c(1.125,2.375), col = "black", lty = 2)


            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,2]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,nb.pts), accuracy_mean[, 3][,1] - accuracy_mean[, 3][, 2]+it, seq(1,nb.pts), accuracy_mean[, 3][, 1] + accuracy_mean[, 3][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,nb.pts), y = accuracy_mean[, 3][, 1]+it, cex = 0.75, pch = 22, col = col[i])
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
library("ggplot2")
library("reshape2")
setwd("~/dev/BitFunnel/src/Scripts")

# png(filename="wat.png",width=800,height=600)
png(filename="talk.png",width=1600,height=1200)
# df <- read.csv(header=FALSE, file="wat.csv")
df <- read.csv(header=FALSE, file="talk.csv")
## df <- read.csv(file="wat.csv")
## munged <- melt(df)
## ggplot(munged, aes(x=variable, y=value)) + geom_point()

# plot single
# ggplot(data=df, aes(x=factor(V1), y=V2)) + geom_bar(stat="identity") + labs(x = "Number of cache misses", y = "count")

# plot uniform 20 vs. buggy distribution
# ggplot(data=df, aes(x=factor(V1), y=V2)) + geom_bar(stat="identity") + facet_wrap(~ V3, ncol=1) + labs(x = "Number of cache misses", y = "count")

# plot for talk
ggplot(data=df, aes(x=factor(V1), y=V2)) + geom_bar(stat="identity") + labs(x = "Memory accesses", y = "Percent") +
  theme(axis.text = element_text(size=40),
        axis.title = element_text(size=40))

dev.off()
catalog_predictions <- function(min.tx = 45, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, percent_remove = 0, nb_iter = 1, comm_id = FALSE, community) {

    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        if(comm_id == FALSE) {
            to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        } else { # comm_id = TRUE
            to.delete <- which(!Cm %in% community)
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        }

    # Setting up lists to store the results
    # weights
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        #Minimum weight
        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

        #Number of iterations
        iter <- vector('list', nb_iter)
            for(i in 1:nb_iter) {
                iter[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- iter
        names(Tanimoto_analysis) <- seq(1,nb_iter)
        remove(iter)


        # Percent remove in communities
        pc_rm <- vector('list', length(percent_remove))
            for(i in 1:length(percent_remove)) {
                pc_rm[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- pc_rm
        names(Tanimoto_analysis) <- percent_remove
        remove(pc_rm)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(percent_remove) * nb_iter * length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(p in 1:length(percent_remove)){
        percent_rm <- percent_remove[p]
        for(o in 1:nb_iter){
            for(n in 1:length(MW)) {
                mw <- MW[n]
                for(m in 1:length(K.values)) {

                    # Tanimoto analysis with different weights for different communities
                        # Parameters:
                            Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                            Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                            # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                        #   wt  Weight of traits in similarity measurement
                        #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                        #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                        # Output:
                        #   A vector of sets of resources for each taxon
                        for(i in 1:length(WT)){ #1st loop for all types of wt values
                            wt <- WT[i]
                            for(j in 1:length(Cm)) { #2nd loop for all C[i]
                                S1 <- communities[[j]]
                                S0 <- S0_catalog

                                if(similarity == 'both') { # For similarity matrices already evaluated
                                    similarity.consumer <- similarity.consumers[[i]]
                                    similarity.resource <- similarity.resources[[i]]
                                } else if(similarity == 'consumer') {
                                    similarity.consumer <- similarity.consumers[[i]]
                                } else if (similarity == 'resource') {
                                    similarity.resource <- similarity.resources[[i]]
                                }

                                # setting up the iterative process to evaluate the accuracy ~ # taxa in catalog
                                # removing a certain percentage of the # of species for which there are interactions as consumers described in the original food web.

                                # inter_Cm <- unique(subset(interactions_sources[, 'consumer'], interactions_sources[, 'source'] == Cm[j] & interactions_sources[, 'inter'] == "1")) # Species for which there are interactions as consumer in Cm[j]

                                interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3] # interaction catalog without interactions coming from Cm[j]

                                # inter_Cm2 <- unique(interactions[which(interactions[, 'consumer'] %in% inter_Cm), 'consumer']) # consumers in Cm[j] for which information is still available in catalog after deletion of Cm[j] from catalog

                                #Removing a percentage of consumers described in catalog
                                    # sample_iter <- sample(x = inter_Cm2, size = round((percent_rm / 100) * length(inter_Cm2)), replace = FALSE)
                                    sample_iter <- sample(x = S1, size = round((percent_rm / 100) * length(S1)), replace = FALSE) # To use if removing a percent of all taxa in original web

                                    if(length(sample_iter) == 0) {
                                        S1_no_mod <- S1
                                    } else {
                                        for(k in 1:length(sample_iter)) {
                                          S0[sample_iter[k], 'resource'] <- ""
                                          S0[sample_iter[k], 'non-resource'] <- ""
                                          S0[sample_iter[k], 'consumer'] <- ""
                                          S0[sample_iter[k], 'non-consumer'] <- ""
                                        }
                                        S1_no_mod <- which(!S1 %in% sample_iter)
                                    }

                                # 2. Preexisting information kept to inform algorithm
                                    if(length(S1_no_mod) == 0) {
                                        NULL
                                    } else {
                                    # Only modifying those that are loosing data from the catalogue, less time
                                        to.change <- numeric()
                                        for(k in 1:length(S1_no_mod)) {
                                            to.change <- c(to.change, which(interactions[, 'consumer'] == S1_no_mod[k]), which(interactions[, 'resource'] == S1_no_mod[k]))
                                        }
                                        to.change <- unique(to.change)

                                    # Modifying sets of resources and non-resources for taxa in S1_no_mod
                                        interactions <- interactions[to.change, ]
                                        rownames(interactions) <- seq(1,nrow(interactions))
                                        resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                                  resource = interactions[, 'resource'],
                                                                                  inter_type = interactions[, 'inter'])

                                        consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                                resource = interactions[, 'resource'],
                                                                                inter_type = interactions[, 'inter'])


                                    # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                        for(k in 1:nrow(resource_set)) {
                                          S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                          S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                        }
                                        for(k in 1:nrow(consumer_set)) {
                                          S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                          S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                        }
                                    remove(interactions, resource_set, to.change)
                                    }#if

                                # Recalculate similarity
                                    similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.consumer,
                                                                                        taxa = 'consumer')

                                    similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.resource,
                                                                                        taxa = 'resource')

                                # Predicting interactions
                                    Tanimoto_analysis[[p]][[o]][[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                            Kr = Kr,
                                                                                            S0 = S0,
                                                                                            S1 = S1,
                                                                                            MW = mw,
                                                                                            similarity.consumer = similarity.consumer,
                                                                                            similarity.resource = similarity.resource,
                                                                                            minimum_threshold = minimum_threshold)

                                save(x = Tanimoto_analysis, file = file.to.save)
                                remove(S0, S1, similarity.consumer, similarity.resource)
                                iteration <- iteration + 1
                                setTxtProgressBar(pb, iteration)
                            }#2nd loop for all C[i]

                            save(x = Tanimoto_analysis, file = file.to.save)
                            remove(wt)

                        }#1st loop for all types of wt values
                }#m
            }#n
        }#o
    }#p
    #Saving number of species in original web vs catalog once web removed
    # percent_original <- length(inter_Cm2) / length(inter_Cm)
    # x <- c(percent_original, length(inter_Cm), length(inter_Cm2))
    # file.to.save2 <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis_pc_tx.RData")
    # save(x = x, file = file.to.save2)

    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
marginOfError =
function(prob,  # sample probability (or response rate)
         n,  # sample size
         N=NULL,
         conf.level=0.95  # Confidence interval
         ) {
    z <- qnorm(p=1.0 - (1.0 - conf.level) * 0.5)
    moe <- z * sqrt(prob * (1 - prob) / n)

    if (!is.null(N)) {
        # tmp <- z ^ 2 * (prob * (1 - prob)) / moe^2
        # n <- tmp / (1 + tmp / N)
        # n + n/N * tmp <- tmp
        # n <- tmp * (1 - n/N)
        tmp <- n / (1 - n / N)
        moe <- sqrt(z ^ 2 * (prob * (1 - prob)) / tmp)
    }
    return(moe)
}

sampleSize =
function(prob,
         moe,  # Margin of error
         N=NULL,  # Population size
         conf.level=0.95
         ) {
    z <- qnorm(p=1.0 - (1.0 - conf.level) * 0.5)
    n <- (z ^ 2 * (prob * (1 - prob)) / moe^2)
    if (!is.null(N)) {
        n <- n / (1 + (z ^ 2 * (prob * (1 - prob)) / (moe^2 * N)))
    }
    return(n)
}


binom.test =
function() {
    prob <- 0.15
    moe <- 0.025
    N <- 1000
    n <- sampleSize(prob=prob, moe=moe, N=N)
    message(n)
    message("Expected margin of error: ", moe)
    moe <- marginOfError(prob=prob, n=n, N=N)
    message(moe)
}
REBOL [
    System: "REBOL [R3] Language Interpreter and Run-time Environment"
    Title: "Make Reb-Lib related files"
    Rights: {
        Copyright 2012 REBOL Technologies
        REBOL is a trademark of REBOL Technologies
    }
    License: {
        Licensed under the Apache License, Version 2.0
        See: http://www.apache.org/licenses/LICENSE-2.0
    }
    Author: "Carl Sassenrath"
    Needs: 2.100.100
]

do %common.r

print "--- Make Reb-Lib Headers ---"

verbose: true

lib-ver: 2

preface: "RL_"

src-dir: %../core/
reb-lib: src-dir/a-lib.c
ext-lib: src-dir/f-extension.c

args: parse-args system/options/args
output-dir: to file! any [args/OUTDIR %../]
output-dir: fix-win32-path output-dir
out-dir: output-dir/include
mkdir/deep out-dir

reb-ext-lib:  out-dir/reb-lib.h   ; for Host usage
reb-ext-defs: out-dir/reb-lib-lib.h  ; for REBOL usage

ver: load %../boot/version.r

do %common.r
do %common-parsers.r

do %form-header.r

;-----------------------------------------------------------------------------
;-----------------------------------------------------------------------------

proto-count: 0

xlib-buffer: make string! 20000
rlib-buffer: make string! 1000
mlib-buffer: make string! 1000
dlib-buffer: make string! 1000
comments-buffer: make string! 1000
xsum-buffer: make string! 1000

emit:  func [d] [append repend xlib-buffer d newline]
emit-rlib: func [d] [append repend rlib-buffer d newline]
emit-dlib: func [d] [append repend dlib-buffer d newline]
emit-comment: func [d] [append repend comments-buffer d newline]
emit-mlib: proc [d /nol] [
    repend mlib-buffer d
    if not nol [append mlib-buffer newline]
]

count: func [s c /local n] [
    if find ["()" "(void)"] s [return "()"]
    out: copy "(a"
    n: 1
    while [s: find/tail s c][
        repend out [#"," #"a" + n]
        n: n + 1
    ]
    append out ")"
]

in-sub: func [text pattern /local position] [
    all [
        position: find text pattern ":"
        insert position "^/:"
        position: find next position newline
        remove position
        insert position " - "
    ]
]

gen-doc: func [name proto text] [
    replace/all text "**" "  "
    replace/all text "/*" "  "
    replace/all text "*/" "  "
    trim text
    append text newline

    insert find text "Arguments:" "^/:"
    bb: beg: find/tail text "Arguments:"
    insert any [find bb "notes:" tail bb] newline
    while [
        all [
            beg: find beg " - "
            positive? offset-of beg any [find beg "notes:" tail beg]
        ]
    ][
        insert beg </tt>
        insert find/tail/reverse beg newline {<br><tt class=word>}
        beg: find/tail beg " - "
    ]

    beg: insert bb { - } ;<div style="white-space: pre;">}
    remove find beg newline
    remove/part find beg "<br>" 4 ; extra <br>

    remove find text "^/Returns:"
    in-sub text "Returns:"
    in-sub text "Notes:"

    insert text reduce [
        ":Function: - " <tt class=word> proto </tt>
        "^/^/:Summary: - "
    ]
    emit-comment ["===" name newline newline text]
]

pads: func [start col] [
    str: copy ""
    col: col - offset-of start tail start
    head insert/dup str #" " col
]

emit-proto: proc [
    proto
] [

    if all [
        proto
        trim proto
        pos.id: find proto preface
        find proto #"("
    ] [
        emit ["RL_API " proto ";"] ;    // " the-file]
        append xsum-buffer proto
        fn.declarations: copy/part proto pos.id
        pos.lparen: find pos.id #"("
        fn.name: copy/part pos.id pos.lparen
        fn.name.upper: uppercase copy fn.name
        fn.name.lower: lowercase copy find/tail fn.name preface

        emit-dlib [tab fn.name ","]

        emit-rlib [tab fn.declarations "(*" fn.name.lower ")" pos.lparen ";"]

        args: count pos.lparen #","
        mlib.tail: tail mlib-buffer
        emit-mlib/nol ["#define " fn.name.upper args]
        emit-mlib [pads mlib.tail 35 " RL->" fn.name.lower args]

        comment-text: proto-parser/notes
        encode-lines comment-text {**} { }

        emit-mlib ["/*^/**^-" proto "^/**^/" comment-text "*/" newline]

        gen-doc fn.name proto comment-text

        proto-count: proto-count + 1
    ]
]

process: func [file] [
    if verbose [probe [file]]
    data: read the-file: file
    data: to-string data

    proto-parser/proto-prefix: "RL_API "
    proto-parser/emit-proto: :emit-proto
    proto-parser/process data
]

write-if: proc [file data] [
    if data != attempt [to string! read file][
        print ["UPDATE:" file]
        write file data
    ]
]

;-----------------------------------------------------------------------------

emit-rlib {
typedef struct rebol_ext_api ^{}

emit-comment [{Host/Extension API

=r3

=*Updated for A} ver/3 { on } now/date {

=*Describes the functions of reb-lib, the REBOL API (both the DLL and extension library.)

=!This document is auto-generated and changes should not be made within this wiki.

=note WARNING: PRELIMINARY Documentation

=*This API is under development and subject to change. Various functions may be moved, removed, renamed, enhanced, etc.

Also note: the formatting of this document will be enhanced in future revisions.

=/note

==Concept

The REBOL API provides common API functions needed by the Host-Kit and also by
REBOL extension modules. This interface is commonly referred to as "reb-lib".

There are two methods of linking to this code:

*Direct calls as you would use functions within any DLL.

*Indirect calls through a set of macros (that use a structure pointer to the library.)

==Functions
}]

;-----------------------------------------------------------------------------

process reb-lib
process ext-lib

;-----------------------------------------------------------------------------

emit-rlib "} RL_LIB;"

out: to-string reduce [
form-header/gen "REBOL Host and Extension API" %reb-lib.r %make-reb-lib.r
{
// These constants are created by the release system and can be used to check
// for compatiblity with the reb-lib DLL (using RL_Version.)
#define RL_VER } ver/1 {
#define RL_REV } ver/2 {
#define RL_UPD } ver/3 {


// Function entry points for reb-lib (used for MACROS below):}
rlib-buffer
{
// Extension entry point functions:
#ifdef TO_WINDOWS
    #define RXIEXT __declspec(dllexport)
#else
    #define RXIEXT extern
#endif

#ifdef __cplusplus
extern "C" ^{
#endif

RXIEXT const char *RX_Init(int opts, RL_LIB *lib);
RXIEXT int RX_Quit(int opts);
RXIEXT int RX_Call(int cmd, RXIFRM *frm, void *data);

// The macros below will require this base pointer:
extern RL_LIB *RL;  // is passed to the RX_Init() function

// Macros to access reb-lib functions (from non-linked extensions):

}
mlib-buffer
{

#define RL_MAKE_BINARY(s) RL_MAKE_STRING(s, FALSE)

#ifndef REB_EXT // not extension lib, use direct calls to r3lib

}
xlib-buffer
{
#endif // REB_EXT

#ifdef __cplusplus
^}
#endif

}
]

write-if reb-ext-lib out

;-----------------------------------------------------------------------------

out: to-string reduce [
form-header/gen "REBOL Host/Extension API" %reb-lib-lib.r %make-reb-lib.r
{RL_LIB Ext_Lib = ^{
}
dlib-buffer
{^};
}
]

write-if reb-ext-defs out

write-if %../reb-lib-doc.txt comments-buffer

;ask "Done"
print "   "
REBOL [
    System: "Ren/C Core Extraction of the Rebol System"
    Title: "Common Routines for Tools"
    Rights: {
        Rebol is Copyright 1997-2015 REBOL Technologies
        REBOL is a trademark of REBOL Technologies

        Ren/C is Copyright 2015 MetaEducation
    }
    License: {
        Licensed under the Apache License, Version 2.0
        See: http://www.apache.org/licenses/LICENSE-2.0
    }
    Author: "@HostileFork"
    Version: 2.100.0
    Needs: 2.100.100
    Purpose: {
        These are some common routines used by the utilities
        that build the system, which are found in %src/tools/
    }
]

;-- !!! BACKWARDS COMPATIBILITY: this does detection on things that have
;-- changed, in order to adapt the environment so that the build scripts
;-- can still work in older as well as newer Rebols.  Thus the detection
;-- has to be a bit "dynamic"

do %r2r3-future.r


spaced-tab: rejoin [space space space space]


to-c-name: function [
    {Take a Rebol value and transliterate it as a (likely) valid C identifier.}

    value
        {Any Rebol value (will be FORM'd before processing)}
    /scope
        {See scope rules: http://stackoverflow.com/questions/228783/}
    word [word!]
        {Either 'global or 'local (defaults global)}
][
    c-chars: charset [
        #"a" - #"z"
        #"A" - #"Z"
        #"0" - #"9"
        #"_"
    ]

    string: form value

    string: switch/default attempt [to-word string] [
        ; Take care of special cases of singular symbols

        ; Used specifically by t-routine.c to make SYM_ELLIPSIS
        ... [copy "ellipsis"]

        ; Used to make SYM_HYPHEN which is needed by `charset [#"A" - #"Z"]`
        - [copy "hyphen"]

        ; Used by u-dialect apparently
        * [copy "asterisk"]

        ; None of these are used at present, but included in case
        . [copy "period"]
        ? [copy "question"]
        ! [copy "exclamation"]
        + [copy "plus"]
        ~ [copy "tilde"]
        | [copy "bar"]
    ][
        ; If these symbols occur composite in a longer word, they use a
        ; shorthand; e.g. `true?` => `true_q`

        for-each [reb c] [
            -   "_"
            *   "_p"    ; !!! because it symbolizes a (p)ointer in C??
            .   "_"     ; !!! same as hyphen?
            ?   "_q"
            !   "_x"    ; e(x)clamation
            +   "_a"    ; (a)ddition
            ~   "_t"
            |   "_b"

        ][
            replace/all string (form reb) c
        ]

        string
    ]

    if empty? string [
        fail [
            "empty identifier produced by to-c-name for"
            (mold value) "of type" (mold type-of value)
        ]
    ]

    comment [
        ; Don't worry about leading digits at the moment, because currently
        ; the code will do a to-c-name transformation and then often prepend
        ; something to it.

        if find charset [#"0" - #"9"] string/1 [
            fail ["identifier" string "starts with digit in to-c-name"]
        ]
    ]

    for-each char string [
        if char = space [
            ; !!! The way the callers seem to currently be written is to
            ; sometimes throw "foo = 2" kinds of strings and expect them to
            ; be converted to a "C string".  Only check the part up to the
            ; first space for legitimacy then.  :-/
            break
        ]

        unless find c-chars char [
            fail ["Non-alphanumeric or hyphen in" string "in to-c-name"]
        ]
    ]

    unless scope [word: 'global] ; default to assuming global need

    ; Easiest rule is just "never start a global identifier with underscore",
    ; but we check the C rules.  Since currently this routine is sometimes
    ; called to produce a partial name, it may not be a problem if that part
    ; starts with an underscore if something legal will be prepended.  But
    ; there are no instances of that need so better to plant awareness.

    catch [case/all [
        string/1 != "_" [throw string]

        word = 'global [
            fail [
                "global identifiers in C starting with underscore"
                "are reserved for standard library usage"
            ]
        ]

        word = 'local [
            unless find charset [#"A" - #"Z"] value/2 [
                throw string
            ]
            fail [
                "local identifiers in C starting with underscore and then"
                "a capital letter are reserved for standard library usage"
            ]
        ]

        'default [fail "scope word must be 'global or 'local"]
    ]]

    string
]


; http://stackoverflow.com/questions/11488616/
binary-to-c: func [
    {Converts a binary to a string of C source that represents an initializer
    for a character array.  To be "strict" C standard compatible, we do not
    use a string literal due to length limits (509 characters in C89, and
    4095 characters in C99).  Instead we produce an array formatted as
    '{0xYY, ...}' with 8 bytes per line}

    data [binary!]
    ; !!! Add variable name to produce entire 'const char *name = {...};' ?
     /local out str comma-count
] [
    out: make string! 6 * (length data)
    while [not tail? data] [
        append out spaced-tab

        ;-- grab hexes in groups of 8 bytes
        hexed: enbase/base (copy/part data 8) 16
        data: skip data 8
        for-each [digit1 digit2] hexed [
            append out rejoin [{0x} digit1 digit2 {,} space]
        ]

        take/last out ;-- drop the last space
        if tail? data [
            take/last out ;-- lose that last comma
        ]
        append out newline ;-- newline after each group, and at end
    ]

    ;-- Sanity check (should be one more byte in source than commas out)
    parse out [(comma-count: 0) some [thru "," (++ comma-count)] to end]
    assert [(comma-count + 1) = (length head data)]

    out
]

;
; Rebol needs to bootstrap using old versions prior to having definitionally
; scoped returns implemented.  Hence don't assume passing a body with
; RETURN in it will return from the *caller*.  It will just wind up returning
; from *this loop wrapper* (in older Rebols) when the call is finished!
;
for-each-record-NO-RETURN: proc [
    {Iterate a table with a header by creating an object for each row}

    'record [word!]
        {Word to set each time to the row made into an object}
    table [block!]
        {Table of values with header block as first element}
    body [block!]
        {Block to evaluate each time}
    /local headings result spec
] [
    unless block? first table [
        fail {Table of records does not start with a header block}
    ]
    headings: map-each word first table [
        unless word? word [
            fail [{Heading} word {is not a word}]
        ]
        to-set-word word
    ]

    table: next table

    ; Note: this code must run in R3-Alpha, so can't just use `result:`
    ; like in Ren-C (which will unset the variable if VOID? argument)
    ;
    set/opt (quote result:) while [not empty? table] [
        if (length headings) > (length table) [
            fail {Element count isn't even multiple of header count}
        ]

        spec: collect [
            for-each column-name headings [
                keep column-name
                keep compose/only [quote (table/1)]
                table: next table
            ]
        ]

        set record has spec

        do body
    ]

    :result
]

find-record-unique: func [
    {Get a record in a table as an object, error if duplicate, blank if absent}
    ;; return: [object! blank!]
    table [block!] {Table of values with header block as first element}
    key [word!] {Object key to search for a match on}
    value {Value that the looked up key must be uniquely equal to}
    /local rec result
] [
    unless find first table key [
        fail [key {not found in table headers:} (first table)]
    ]

    result: _
    for-each-record-NO-RETURN rec table [
        unless value = select rec key [continue]

        if result [
            fail [{More than one table record matches} key {=} value]
        ]

        result: rec

        ; RETURN won't work.  We could break, but walk whole table to verify
        ; that it is well-formed.  (Here, correctness is more important.)
    ]
    result
]

parse-args: func [
	args ;args in form of "NAME=VALUE"
	/local a name value ret
][
	ret: make block! 4
	args: any [args copy []]
	unless block? args [args: split args [some " "]]
	foreach a args [
		if found? idx: find a #"=" [
			name: to word! copy/part a (index-of idx) - 1
			value: copy next idx
			append ret reduce [name value]
		]
	]
	ret
]

fix-win32-path: func [
	path [file!]
	/local letter colon
][
    if 3 != fourth system/version [return path] ;non-windows system

    drive: first path
    colon: second path

    if all [
    	any [
	    all [#"A" <= drive #"Z" >= drive] 
	    all [#"a" <= drive #"z" >= drive] 
	]
	#":" = colon
    ][
    	insert path #"/"
	remove skip path 2 ;remove ":"
    ]

    path
]
library(plyr)
library(ggplot2)
setwd("Desktop/Hannuus_lines_repeat_analysis")
lines <- read.table("all_lines_family_stats_6-30.tsv",header=T,sep="\t",comment.char="")
lines.filtered <- lines[lines$GenomeFrac >= 0.01,]
ggplot(alllines.filt, aes(x=reorder(Identifier, GenomeFrac), y=GenomeFrac)) + geom_bar(aes(fill=Family, order=desc(Family)), stat="identity") + theme_bw() + theme(axis.text.x = element_text(angle=90, hjust=1, color="black"), axis.text.y = element_text(color="black"), axis.title.x = element_blank(), axis.text.y = element_blank())
alllines.noha <- alllines[!alllines$Line == "HA",]
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename1 = 'catalog_predictions2'
filename2 = 'catalog_predictions3'


catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions2 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40,60,80),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename1)

catalog_predictions3 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(30,50,70,90),
                                            nb_iter = 50,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  c(0.5,1),
                                            minimum_threshold = 0.3,
                                            filename = filename2)


# Catalog vs predictions

accuracy <- accuracy0 <- accuracy1 <- accuracy2 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) <- names(accuracy2) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy2[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, empirical.only = TRUE)
accuracy2[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, predict.only = TRUE)
accuracy2[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]], accuracy2[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]], accuracy2[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]], accuracy2[[3]])

percent_remove = c(0,10,20,40,60,80,100)
nb_iter = 100
K.values = 8
MW = 1
WT =  0.5
minimum_threshold = 0.3

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

# Graph
for(j in 13:16) {
        eplot(xmin = -0.09, xmax = 100, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.1) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            # mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            # mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 0.1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 0.1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 0.1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            points(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it, cex = 0.5, pch = 1, col = col[i])
            lines(lowess(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it))
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
catalog_predictions <- function(min.tx = 45, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, percent_remove = 0, nb_iter = 1, comm_id = FALSE, community) {

    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        if(comm_id == FALSE) {
            to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        } else { # comm_id = TRUE
            to.delete <- which(!Cm %in% community)
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        }

    # Setting up lists to store the results
    # weights
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        #Minimum weight
        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

        #Number of iterations
        iter <- vector('list', nb_iter)
            for(i in 1:nb_iter) {
                iter[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- iter
        names(Tanimoto_analysis) <- seq(1,nb_iter)
        remove(iter)


        # Percent remove in communities
        pc_rm <- vector('list', length(percent_remove))
            for(i in 1:length(percent_remove)) {
                pc_rm[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- pc_rm
        names(Tanimoto_analysis) <- percent_remove
        remove(pc_rm)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(percent_remove) * nb_iter * length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(p in 1:length(percent_remove)){
        percent_rm <- percent_remove[p]
        for(o in 1:nb_iter){
            for(n in 1:length(MW)) {
                mw <- MW[n]
                for(m in 1:length(K.values)) {

                    # Tanimoto analysis with different weights for different communities
                        # Parameters:
                            Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                            Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                            # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                        #   wt  Weight of traits in similarity measurement
                        #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                        #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                        # Output:
                        #   A vector of sets of resources for each taxon
                        for(i in 1:length(WT)){ #1st loop for all types of wt values
                            wt <- WT[i]
                            for(j in 1:length(Cm)) { #2nd loop for all C[i]
                                S1 <- communities[[j]]
                                S0 <- S0_catalog

                                if(similarity == 'both') { # For similarity matrices already evaluated
                                    similarity.consumer <- similarity.consumers[[i]]
                                    similarity.resource <- similarity.resources[[i]]
                                } else if(similarity == 'consumer') {
                                    similarity.consumer <- similarity.consumers[[i]]
                                } else if (similarity == 'resource') {
                                    similarity.resource <- similarity.resources[[i]]
                                }

                                # setting up the iterative process to evaluate the accuracy ~ # taxa in catalog
                                # removing a certain percentage of the # of species for which there are interactions as consumers described in the original food web.

                                # inter_Cm <- unique(subset(interactions_sources[, 'consumer'], interactions_sources[, 'source'] == Cm[j] & interactions_sources[, 'inter'] == "1")) # Species for which there are interactions as consumer in Cm[j]

                                interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3] # interaction catalog without interactions coming from Cm[j]

                                # inter_Cm2 <- unique(interactions[which(interactions[, 'consumer'] %in% inter_Cm), 'consumer']) # consumers in Cm[j] for which information is still available in catalog after deletion of Cm[j] from catalog

                                #Removing a percentage of consumers described in catalog
                                    # sample_iter <- sample(x = inter_Cm2, size = round((percent_rm / 100) * length(inter_Cm2)), replace = FALSE)
                                    sample_iter <- sample(x = S1, size = round((percent_rm / 100) * length(S1)), replace = FALSE) # To use if removing a percent of all taxa in original web

                                    for(k in 1:length(sample_iter)) {
                                      S0[sample_iter[k], 'resource'] <- ""
                                      S0[sample_iter[k], 'non-resource'] <- ""
                                      S0[sample_iter[k], 'consumer'] <- ""
                                      S0[sample_iter[k], 'non-consumer'] <- ""
                                    }

                                    S1_no_mod <- which(!S1 %in% sample_iter)

                                # 2. Preexisting information kept to inform algorithm
                                    if(length(S1_no_mod) == 0) {
                                        NULL
                                    } else {

                                    # Only modifying those that are loosing data from the catalogue, less time
                                        to.change <- numeric()
                                        for(k in 1:length(S1_no_mod)) {
                                            to.change <- c(to.change, which(interactions[, 'consumer'] == S1[S1_no_mod[k]]), which(interactions[, 'resource'] == S1[S1_no_mod[k]]))
                                        }
                                        to.change <- unique(to.change)

                                    # Modifying sets of resources and non-resources for taxa in S1_no_mod
                                        interactions <- interactions[to.change, ]
                                        rownames(interactions) <- seq(1,nrow(interactions))
                                        resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                                  resource = interactions[, 'resource'],
                                                                                  inter_type = interactions[, 'inter'])

                                        consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                                resource = interactions[, 'resource'],
                                                                                inter_type = interactions[, 'inter'])


                                    # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                        for(k in 1:nrow(resource_set)) {
                                          S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                          S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                        }
                                        for(k in 1:nrow(consumer_set)) {
                                          S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                          S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                        }
                                    remove(interactions, resource_set, to.change)
                                    }#if

                                # Recalculate similarity
                                    similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.consumer,
                                                                                        taxa = 'consumer')

                                    similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.resource,
                                                                                        taxa = 'resource')

                                # Predicting interactions
                                    Tanimoto_analysis[[p]][[o]][[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                            Kr = Kr,
                                                                                            S0 = S0,
                                                                                            S1 = S1,
                                                                                            MW = mw,
                                                                                            similarity.consumer = similarity.consumer,
                                                                                            similarity.resource = similarity.resource,
                                                                                            minimum_threshold = minimum_threshold)

                                save(x = Tanimoto_analysis, file = file.to.save)
                                remove(S0, S1, similarity.consumer, similarity.resource)
                                iteration <- iteration + 1
                                setTxtProgressBar(pb, iteration)
                            }#2nd loop for all C[i]

                            save(x = Tanimoto_analysis, file = file.to.save)
                            remove(wt)

                        }#1st loop for all types of wt values
                }#m
            }#n
        }#o
    }#p
    #Saving number of species in original web vs catalog once web removed
    # percent_original <- length(inter_Cm2) / length(inter_Cm)
    # x <- c(percent_original, length(inter_Cm), length(inter_Cm2))
    # file.to.save2 <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis_pc_tx.RData")
    # save(x = x, file = file.to.save2)

    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
# 2. FAZA
source("lib/libraries.r", encoding = "UTF-8")


naslov1 = "http://www.multpl.com/us-gdp-inflation-adjusted/table"
gdp <- readHTMLTable(naslov1, which=1, encoding = "UTF-8", stringsAsFactors = FALSE)
gdp[[1]] <- strapplyc(gdp[[1]], "([0-9]+)$") %>% as.numeric()
gdp[[2]] <- strapplyc(gdp[[2]], "^([0-9.]+)") %>% as.numeric()
colnames(gdp) <- c("Leto", "BDP (v trilijonih $)")
gdp <- gdp %>% filter(Leto <= 2015 & Leto >= 1950)
gdp <- gdp %>% arrange(Leto)


naslov2 = "http://www.multpl.com/us-real-gdp-per-capita/table/by-year"
gdppc <- readHTMLTable(naslov2, which=1, encoding = "UTF-8", stringsAsFactors = FALSE)
gdppc[[1]] <- strapplyc(gdppc[[1]], "([0-9]+)$") %>% as.numeric()
gdppc[[2]] <- gsub(",", "", gdppc[[2]]) %>% as.numeric()
colnames(gdppc) <- c("Letnica", "BDPp.c. (v $)")
gdppc <- gdppc %>% filter(Letnica <= 2015 & Letnica >= 1950)
gdppc <- gdppc %>% arrange(Letnica)


naslov3 = "http://www.multpl.com/us-real-gdp-growth-rate/table/by-year"
gr <- readHTMLTable(naslov3, which=1, encoding = "UTF-8", stringsAsFactors = FALSE)
gr[[1]] <- strapplyc(gr[[1]], "([0-9]+)$") %>% as.numeric()
gr[[2]] <- strapplyc(gr[[2]], "^([-, 0-9.]+)") %>% as.numeric()
colnames(gr) <- c("Letnica", "Stopnja rasti")
gr <- gr %>% filter(Letnica <= 2015 & Letnica >=1950)
gr <- gr %>% arrange(Letnica)


naslov4 = "http://www.usinflationcalculator.com/inflation/consumer-price-index-and-annual-percent-changes-from-1913-to-2008/"
cpi <- htmlTreeParse(naslov4, encoding = "UTF-8", useInternal = TRUE)
cpi <- readHTMLTable(naslov4,which=1, stringsAsFactors = FALSE)
cpi <- cpi[-c(1,2), c(1, 14)]
cpi <- apply(cpi, 2, . %>% strapplyc("([0-9.]+)") %>% as.numeric(.)) %>% data.frame()
colnames(cpi) <- c("Letnica", "Indeks cen")
cpi <- cpi %>% filter(Letnica <= 2015 & Letnica >= 1950)
cpi <- cpi %>% arrange(Letnica)


naslov5 = "http://www.usinflationcalculator.com/inflation/historical-inflation-rates/"
usinf <- readHTMLTable(naslov5, which=1, encoding = "UTF-8", stringsAsFactors = FALSE)
usinf <- usinf[-c(1), c(1, 14)]
usinf[[1]] <- strapplyc(usinf[[1]], "([0-9]+)$") %>% as.numeric()
usinf[[2]] <- strapplyc(usinf[[2]], "^([-, 0-9.]+)") %>% as.numeric()
colnames(usinf) <- c("Letnica", "Stopnja inflacije (v %)")
usinf <- usinf %>% filter(Letnica <= 2015 & Letnica >= 1950)
usinf <- usinf %>% arrange(Letnica)


naslov6 = "http://www.multpl.com/unemployment/table"
unemp <- readHTMLTable(naslov6, which=1, encoding = "UTF-8", stringsAsFactors = FALSE)
unemp[[1]] <- strapplyc(unemp[[1]], "([0-9]+)$") %>% as.numeric()
unemp[[2]] <- strapplyc(unemp[[2]], "^([0-9.]+)") %>% as.numeric()
colnames(unemp) <- c("Letnica", "Stopnja brezposlenosti (v %)")
unemp <- unemp %>% filter(Letnica <= 2015 & Letnica >= 1950)
unemp <- unemp %>% arrange(Letnica)


skupna.tabela <- cbind(gdp, gdppc, gr, cpi, usinf, unemp)
skupna.tabela <- skupna.tabela[names(skupna.tabela) != "Letnica"]

skupna.tabela2 <- skupna.tabela %>% arrange(-Leto)

naslov7 <- "http://www.usgovernmentspending.com/gdp_by_state" 
stran <- html_session(naslov7) %>% read_html(encoding = "UTF-8") 
GSP_tabele <- stran %>% html_nodes(xpath ="//table") 
GSP <- GSP_tabele %>% .[[7]] %>% html_table(fill = TRUE) 
GSP <- GSP[c(-1,-46,-54),c(2,5)] 
names(GSP) <- c("Država", "GSP (v milijon $)") 
GSP[2] <- apply(GSP[2], 2, .%>% gsub("\\$", "", .) %>% gsub("\\,", "", .)) %>% as.numeric()
GSP3 <- GSP %>% arrange (`GSP (v milijon $)`)



### GRAFI
graf1 <- ggplot(data = gdp, aes(x=Leto, y=`BDP (v trilijonih $)`), height=5, width=5)+
                            geom_line(size=1, color='red')+ggtitle("BDP")
graf2 <- ggplot(data = gdppc, aes(x=Letnica, y=`BDPp.c. (v $)`))+geom_line(size=1, color='darkgreen')+
                            ggtitle("BDP per capita skozi leta")
graf3 <- ggplot(data = gr, aes(x=Letnica, y=`Stopnja rasti`))+geom_line(size=1, color='blue')+
                            ggtitle("Stopnja rasti skozi leta (v%)")
graf4 <- ggplot(data = cpi, aes(x=Letnica, y=`Indeks cen`))+geom_line(size=1, color='orange')+
                            ggtitle("Spreminjanje indeksa cen")
graf5 <- ggplot(data = usinf, aes(x=Letnica, y=`Stopnja inflacije (v %)`))+geom_line(size=1, color='purple')+
                            ggtitle("Stopnja inflacije v ZDA (v %)")
graf6 <- ggplot(data = unemp, aes(x=Letnica, y=`Stopnja brezposlenosti (v %)`))+geom_line(size=1, color='black')+
                            ggtitle("Brezposelnost skozi leta (v %)")



# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename = 'catalog_predictions2'

catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions2 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40,60,80),
                                            nb_iter = 100,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = filename)

catalog_predictions3 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(30,50,70,90),
                                            nb_iter = 100,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = filename)


# Catalog vs predictions

accuracy <- accuracy0 <- accuracy1 <- accuracy2 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) <- names(accuracy2) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions2)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy2[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, empirical.only = TRUE)
accuracy2[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3, predict.only = TRUE)
accuracy2[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions3)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]], accuracy2[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]], accuracy2[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]], accuracy2[[3]])

percent_remove = c(0,10,20,40,60,80,100)
nb_iter = 100
K.values = 8
MW = 1
WT =  0.5
minimum_threshold = 0.3

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

# Graph
for(j in 13:16) {
        eplot(xmin = -0.09, xmax = 100, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = -0.1) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -1)
            axis(side = 3, at = seq(0, 100, by = 10), labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = 100 + 1)

            abline(h = c(1.125,2.375), col = "black", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            # mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            # mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 0.1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 0.1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 0.1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            points(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it, cex = 0.5, pch = 1, col = col[i])
            lines(lowess(x = as.numeric(accuracy[[i]][, 'pc_rm']), y = as.numeric(accuracy[[i]][, j]) + it))
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
catalog_predictions <- function(min.tx = 45, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, percent_remove = 0, nb_iter = 1, comm_id = FALSE, community) {

    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        if(comm_id == FALSE) {
            to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        } else { # comm_id = TRUE
            to.delete <- which(!Cm %in% community)
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        }

    # Setting up lists to store the results
    # weights
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        #Minimum weight
        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

        #Number of iterations
        iter <- vector('list', nb_iter)
            for(i in 1:nb_iter) {
                iter[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- iter
        names(Tanimoto_analysis) <- seq(1,nb_iter)
        remove(iter)


        # Percent remove in communities
        pc_rm <- vector('list', length(percent_remove))
            for(i in 1:length(percent_remove)) {
                pc_rm[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- pc_rm
        names(Tanimoto_analysis) <- percent_remove
        remove(pc_rm)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(percent_remove) * nb_iter * length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(p in 1:length(percent_remove)){
        percent_rm <- percent_remove[p]
        for(o in 1:nb_iter){
            for(n in 1:length(MW)) {
                mw <- MW[n]
                for(m in 1:length(K.values)) {

                    # Tanimoto analysis with different weights for different communities
                        # Parameters:
                            Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                            Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                            # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                        #   wt  Weight of traits in similarity measurement
                        #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                        #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                        # Output:
                        #   A vector of sets of resources for each taxon
                        for(i in 1:length(WT)){ #1st loop for all types of wt values
                            wt <- WT[i]
                            for(j in 1:length(Cm)) { #2nd loop for all C[i]
                                S1 <- communities[[j]]
                                S0 <- S0_catalog

                                if(similarity == 'both') { # For similarity matrices already evaluated
                                    similarity.consumer <- similarity.consumers[[i]]
                                    similarity.resource <- similarity.resources[[i]]
                                } else if(similarity == 'consumer') {
                                    similarity.consumer <- similarity.consumers[[i]]
                                } else if (similarity == 'resource') {
                                    similarity.resource <- similarity.resources[[i]]
                                }

                                # setting up the iterative process to evaluate the accuracy ~ # taxa in catalog
                                # removing a certain percentage of the # of species for which there are interactions as consumers described in the original food web.

                                inter_Cm <- unique(subset(interactions_sources[, 'consumer'], interactions_sources[, 'source'] == Cm[j] & interactions_sources[, 'inter'] == "1")) # Species for which there are interactions as consumer in Cm[j]

                                interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3] # interaction catalog without interactions coming from Cm[j]

                                inter_Cm2 <- unique(interactions[which(interactions[, 'consumer'] %in% inter_Cm), 'consumer']) # consumers in Cm[j] for which information is still available in catalog after deletion of Cm[j] from catalog

                                #Removing a percentage of consumers described in catalog
                                    sample_iter <- sample(x = inter_Cm2, size = round((percent_rm / 100) * length(inter_Cm2)), replace = FALSE)
                                    # sample_iter <- sample(x = seq(1,length(S1)), size = round((percent_rm / 100) * length(S1)), replace = FALSE) # To use if removing a percent of all taxa in original web
                                    # for(k in sample_iter) {
                                    #   S0[S1[k], 'resource'] <- ""
                                    #   S0[S1[k], 'non-resource'] <- ""
                                    #   S0[S1[k], 'consumer'] <- ""
                                    #   S0[S1[k], 'non-consumer'] <- ""
                                    # }

                                    for(k in length(sample_iter)) {
                                      S0[sample_iter[k], 'resource'] <- ""
                                      S0[sample_iter[k], 'non-resource'] <- ""
                                      S0[sample_iter[k], 'consumer'] <- ""
                                      S0[sample_iter[k], 'non-consumer'] <- ""
                                    }

                                    S1_no_mod <- which(!S1 %in% sample_iter)

                                # 2. Preexisting information kept to inform algorithm
                                    # if(length(S1_no_mod) == length(S1)) {
                                        # NULL
                                    # } else {

                                    # Only modifying those that are loosing data from the catalogue, less time
                                        to.change <- numeric()
                                        for(k in 1:length(S1_no_mod)) {
                                            to.change <- c(to.change, which(interactions[, 'consumer'] == S1[S1_no_mod[k]]), which(interactions[, 'resource'] == S1[S1_no_mod[k]]))
                                        }
                                        to.change <- unique(to.change)

                                    # Modifying sets of resources and non-resources for taxa in S1_no_mod
                                        interactions <- interactions[to.change, ]
                                        rownames(interactions) <- seq(1,nrow(interactions))
                                        resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                                  resource = interactions[, 'resource'],
                                                                                  inter_type = interactions[, 'inter'])

                                        consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                                resource = interactions[, 'resource'],
                                                                                inter_type = interactions[, 'inter'])


                                    # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                        for(k in 1:nrow(resource_set)) {
                                          S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                          S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                        }
                                        for(k in 1:nrow(consumer_set)) {
                                          S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                          S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                        }
                                    remove(interactions, resource_set, to.change)
                                    # }#if

                                # Recalculate similarity
                                    similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.consumer,
                                                                                        taxa = 'consumer')

                                    similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.resource,
                                                                                        taxa = 'resource')

                                # Predicting interactions
                                    Tanimoto_analysis[[p]][[o]][[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                            Kr = Kr,
                                                                                            S0 = S0,
                                                                                            S1 = S1,
                                                                                            MW = mw,
                                                                                            similarity.consumer = similarity.consumer,
                                                                                            similarity.resource = similarity.resource,
                                                                                            minimum_threshold = minimum_threshold)

                                save(x = Tanimoto_analysis, file = file.to.save)
                                remove(S0, S1, similarity.consumer, similarity.resource)
                                iteration <- iteration + 1
                                setTxtProgressBar(pb, iteration)
                            }#2nd loop for all C[i]

                            save(x = Tanimoto_analysis, file = file.to.save)
                            remove(wt)

                        }#1st loop for all types of wt values
                }#m
            }#n
        }#o
    }#p
    #Saving number of species in original web vs catalog once web removed
    percent_original <- length(inter_Cm2) / length(inter_Cm)
    x <- c(percent_original, length(inter_Cm), length(inter_Cm2))
    file.to.save2 <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis_pc_tx.RData")
    save(x = x, file = file.to.save2)

    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container_dir, settings) {
            private$settings <- settings

            private$cat_main_file_magic(container_dir)
            private$write_slurm_script(container_dir)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir) {
            main_file <- ".default_stain_main.R"
            file <- paste0(dir, "/.stain/sources/", main_file)
            sourcing <- paste("sapply(list.files('./.stain/sources', full.names = TRUE)[!(list.files('./.stain/sources')) %in%",
                              paste0("'", main_file, "'"), "], source)")
            loading <- paste("sapply(list.files('./.stain/objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./.stain $PFSDIR
cd $PFSDIR

mkdir .data
mv ./.stain/data/* ./.data

module load hpc-ods
module load pandoc

R CMD BATCH ./.stain/sources/.default_stain_main.R

cp -r * $SLURM_SUBMIT_DIR/output"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, "submit.slurm", sep = "/"))
        }
    )
)
library(shiny)
library(shinydashboard)

shinyUI(dashboardPage(
  title="Quest",
  skin="yellow",
  dashboardHeader(title = "Quest", titleWidth = 220),
  dashboardSidebar(width=220,
      sidebarMenu(
        #sidebarSearchForm(textId = "searchText", buttonId = "searchButton",label = "Search..."),
        menuItem("Files",tabName="files",icon=shiny::icon("upload")),
        menuItem("Data Table",tabName="data",icon=shiny::icon("database")),
        menuItem("1D plots",tabName="1d",icon=shiny::icon("line-chart")),
        menuItem("2D plots",tabName="2d",icon=shiny::icon("line-chart")),
        menuItem("ggplot wrapper",tabName="gg",icon=shiny::icon("line-chart")),
        menuItem("Binned plots",tabName="bin",icon=shiny::icon("line-chart")),
        menuItem("3D tile plots",tabName="3d",icon=shiny::icon("line-chart")),
        menuItem("Heatmaps",tabName="heatmap",icon=shiny::icon("th")),
        menuItem("Settings",tabName="settings",icon=shiny::icon("cogs")),
        menuItem("Help",tabName="help",icon=shiny::icon("question")),
        checkboxInput("auto","Auto-plot",value = T),
        checkboxInput("freeze","Freeze inputs",value = F),
        checkboxInput("execute","Apply R code",value = F),
        actionButton("close","Close Quest",icon = shiny::icon("close"),style="color: #fff; background-color: #337ab7; border-color: #2e6da4")
      )
  ),
  dashboardBody(
   tags$head(
    tags$link(rel = "stylesheet", type = "text/css", href = "custom.css")
   ),
   tabItems(
     tabItem(tabName="files",
               fluidRow(
                 box(
                   title="Load from your computer",width = 12,status="primary",solidHeader=TRUE,
                   #htmlOutput("fileUI"),
                   selectInput("inputType","Input file location:",choices=c("Upload","Server","Environment")),
                   conditionalPanel(
                     condition = "input.inputType == 'Upload'",
                     fileInput("file", "Input File",multiple = FALSE) ##May add upload file option)
                   ),
                   conditionalPanel(
                     condition = "input.inputType == 'Server'",
                     textInput("dir","Select file directory:",value=getwd()),
                     checkboxInput("recursive", "Search directory recursively", FALSE),
                     textInput("pattern","Search pattern","",placeholder="*.tab"),
                     actionButton("list_dir","List",icon = shiny::icon("folder-open")),
                     uiOutput("inFiles")
                   ),
                   conditionalPanel(
                     condition = "input.inputType == 'Environment'",
                     uiOutput("inObjects")
                   ),
                   #checkboxInput("show", "Show columns", FALSE),
                   #checkboxInput('show_all', 'All/None', TRUE),
                   #conditionalPanel(
                   #condition = "input.show == true",
                    #uiOutput("show_cols")
                   #),
                   checkboxInput("header", "File has column headers", TRUE)
                 ),
                 box(
                   title="Download table",width = 12,status="primary",solidHeader=TRUE,
                   uiOutput("downloadFiles")
                 )
             )
     ),
     tabItem(tabName="data",
             fluidRow(
               box(
                 title = "Data Table", width = 12, status = "primary",solidHeader=TRUE,
                 div(style = 'overflow-x: scroll', dataTableOutput('table'))
               )
             )
     ),
     tabItem(tabName="1d",
             fluidRow(
               box(
                 title="1D plots",width = 8,status="primary",solidHeader=TRUE,
                 plotOutput("plot")
               ),
               box(
                 title="Controls",width = 4,collapsible = T,status="success",solidHeader=TRUE,
                 wellPanel(p(strong("Data")), 
                           uiOutput("plot_cols")
                 ),
                 wellPanel(p(strong("Controls")),
                           selectInput("type","Plot Type:",choices=c("boxplot","histogram")),
                           conditionalPanel(condition="input.type=='boxplot'",
                                            textInput("bversus","Add filters to plot against a rival",value="")
                           ),
                           conditionalPanel(condition="input.type=='histogram'",
                                            checkboxInput("hlogx","Log X-axis",value = F),
                                            numericInput("breaks","Breaks",0),
                                            helpText("Uses default if set to 0")
                           )          
                 )
               )
             )
     ),
     tabItem(tabName="2d",
             fluidRow(
               box(
                   title="2D plots",width = 8,status="primary",solidHeader=TRUE,
                   plotOutput("dplot")
               ),
               box(
                 title="Controls",width = 4,collapsible = T,status="success",solidHeader=TRUE,
                 wellPanel(p(strong("Data")), 
                           uiOutput("dplot_cols")
                 ),
                 wellPanel(p(strong("Controls")),
                           selectInput("dtype","Plot type",choices=c("scatter","smoothScatter")),
                           checkboxInput("logx","Log X-axis",value = F),
                           checkboxInput("logy","Log Y-axis",value = F),
                           textInput("hilite","Highlight subset",value="")
                 )
               )
             )
     ),
     tabItem(tabName="gg",
             fluidRow(
               box(
                 title="gg plot",width = 8,status="primary",solidHeader=TRUE,
                 conditionalPanel(condition="input.gg_plotly==false",
                  plotOutput("ggplot")
                 ),
                 conditionalPanel(condition = "input.gg_plotly==true",
                  plotlyOutput("ggplotly")
                 )
               ),
               tabBox(
                 width = 4,
                 tabPanel("Inputs",uiOutput("ggplot_cols")),
                 tabPanel("Colours",uiOutput("ggplot_colours")),
                 tabPanel("Layout",uiOutput("ggplot_plot")),
                 tabPanel("Controls",uiOutput("ggplot_controls"))
               )
             )
     ),
     tabItem(tabName="bin",
             fluidRow(
               box(
                 title="Binned plot",width = 8,status="primary",solidHeader=TRUE,
                 plotOutput("bplot")
               ),
               box(
                 title="Controls",width = 4,status="success",solidHeader=TRUE,
                 div(style = 'overflow-y: scroll', 
                 wellPanel(p(strong("Data")), 
                           uiOutput("bin_cols")
                 ),
                 wellPanel(p(strong("Controls")),style = 'overflow-y: scroll; max-height: 400px',
                           numericInput("bw","Bin size",200,min=1),
                           numericInput("bs","Step size",40,min=1),
                           numericInput("bys","Rescale y-axis ",1,min=1),
                           selectInput("bf","Operation",choices=c("mean","median","boxes","sum","max","min")),
                           selectInput("bscale","Scale",choices=c("linear","log","bins")), 
                           selectInput("bleg","Legend Position",choices=c("topleft","topright","bottomleft","bottomright")),
                           textInput("bmin","Minimum y-axis value","default"),
                           textInput("bmax","Maximum y-axis value","default"),
                           numericInput("bystep","Y axis step size",0,min=0),
                           textInput("bylab","Y axis label",""),
                           textInput("bfeature","Name of features","data points")
                 )
                 )
                 )
             )
     ),
     tabItem(tabName="3d",
             fluidRow(
               box(
                   title="3D tile plot",width = 8,status="primary",solidHeader=TRUE,
                   plotOutput("tplot")
               ),
               box(
                 title="Data",width = 4,status="success",solidHeader=TRUE,
                 wellPanel(p(strong("Data")),style = 'overflow-y: scroll; max-height: 300px',
                  uiOutput("t_cols")
                 )
               )
             ),
             fluidRow(
               box(
                 title="Controls",width = 12,status="success",solidHeader=TRUE,
                 wellPanel(p(strong("Controls")),style = 'overflow-y: scroll; max-height: 400px',
                           numericInput("bins","Bins",1,min=1,max=1000),
                           selectInput("tsummary","Operation",choices=c("mean","median","sum","count")),                                   
                           checkboxInput("tzman","Manually alter colour scale",F),
                           conditionalPanel("input.tzman == true",
                             numericInput("tzmin","Minimum colour scale",0),
                             numericInput("tzmax","Maximum colour scale",0)
                           ),
                           checkboxInput("txman","Manually alter X scale",F),
                           conditionalPanel("input.tzman == true",
                             numericInput("txmin","Minimum x-axis value",0),
                             numericInput("txmax","Maximum x-axis value",0)
                           ),
                           checkboxInput("tyman","Manually alter Y scale",F),
                           conditionalPanel("input.tzman == true",                                                    
                            numericInput("tymin","Minimum y-axis value",0),
                            numericInput("tymax","Maximum y-axis value",0)
                           )
                 )
               )
             )
     ),
     tabItem(tabName="heatmap",
             fluidRow(
               box(
                 title="Heatmaps",width = 8,status="primary",solidHeader=TRUE,
                 d3heatmapOutput("hmap")
               ),
               box(
                 title="Data",width = 4,status="success",solidHeader=TRUE,
                 uiOutput("h_cols")
               )
             ),
             fluidRow(
               box(
                 title="Controls",width = 12,status="success",solidHeader=TRUE,
                 numericInput("hnrow","Row limit",100,min=1,max=2000),
                 numericInput("hkrow","Number of K-means clusters",5,min=1,max=10)
               )
             )
     ),
     tabItem(tabName="settings",
             fluidRow(
               box(
                   title="Settings",width = 12,status="primary",solidHeader=TRUE,
                   numericInput("factorlim","Limit on factor levels to process in plots",50)
               )
             )
     ),
     tabItem(tabName="help",
             fluidRow(
               box(
                 title="Help",width = 12,status="primary",solidHeader=TRUE,
                 includeMarkdown("README.md")
               )
             )
     )
   ), 
   fluidRow(
     box(
       title="R Code",width = 12,status="danger",collapsible=TRUE,collapsed = TRUE,solidHeader=TRUE,
       HTML('<textarea id="add" rows="6" cols="150"></textarea>'),
       helpText("See help tab for examples")
     )
   )
  )
)
)#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        settings = NULL,
        initialize = function(dir = ".", settings = c()) {
            self$settings <- SlurmSettings$new(settings)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
                script <- SlurmBashScript$new(dir, self$settings)
            }
        },
        save_globals = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
#'
#' @export
Stain <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        settings = NULL,
        initialize = function(dir = ".", settings = c()) {
            self$settings <- SlurmSettings$new(settings)

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
                script <- SlurmBashScript$new(dir, self$settings)
            }
        },
        save_objects = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, "/.stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, "/.stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#SNOPSIS
#calculates genomic estimated breeding values (GEBVs) using rrBLUP,
#GBLUP method

#AUTHOR
# Isaak Y Tecle (iyt2@cornell.edu)

options(echo = FALSE)

library(rrBLUP)
library(plyr)
library(stringr)
library(lme4)
library(randomForest)
library(data.table)
library(genetics)

allArgs <- commandArgs()

inputFiles  <- scan(grep("input_files", allArgs, ignore.case = TRUE, perl = TRUE, value = TRUE),
                   what = "character")

outputFiles <- scan(grep("output_files", allArgs, ignore.case = TRUE,perl = TRUE, value = TRUE),
                    what = "character")

traitsFile <- grep("traits", inputFiles, ignore.case = TRUE, value = TRUE)
traitFile  <- grep("trait_info", inputFiles, ignore.case = TRUE, value = TRUE)
traitInfo  <- scan(traitFile, what = "character",)
traitInfo  <- strsplit(traitInfo, "\t");
traitId    <- traitInfo[[1]]
trait      <- traitInfo[[2]]

datasetInfoFile <- grep("dataset_info", inputFiles, ignore.case = TRUE, value = TRUE)
datasetInfo     <- c()

if (length(datasetInfoFile) != 0 ) { 
    datasetInfo <- scan(datasetInfoFile, what = "character")    
    datasetInfo <- paste(datasetInfo, collapse = " ")   
  } else {   
    datasetInfo <- c('single population')  
  }

validationTrait <- paste("validation", trait, sep = "_")
validationFile  <- grep(validationTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(validationFile)) {
  stop("Validation output file is missing.")
}

kinshipTrait <- paste("kinship", trait, sep = "_")
blupFile     <- grep(kinshipTrait, outputFiles, ignore.case = TRUE, value = TRUE)

if (is.null(blupFile)) {
  stop("GEBVs file is missing.")
}
markerTrait <- paste("marker", trait, sep = "_")
markerFile  <- grep(markerTrait, outputFiles, ignore.case = TRUE, value = TRUE)

traitPhenoFile <- paste("phenotype_trait", trait, sep = "_")
traitPhenoFile <- grep(traitPhenoFile, outputFiles,ignore.case = TRUE, value = TRUE)

varianceComponentsFile <- grep("variance_components", outputFiles, ignore.case = TRUE, value = TRUE)

formattedPhenoFile <- grep("formatted_phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE)

formattedPhenoData <- c()
phenoData          <- c()

if (length(formattedPhenoFile) != 0 && file.info(formattedPhenoFile)$size != 0) {
    formattedPhenoData <- as.data.frame(fread(formattedPhenoFile,
                                              na.strings = c("NA", " ", "--", "-", ".")
                                              ))
      
    row.names(formattedPhenoData) <- formattedPhenoData[, 1]
    formattedPhenoData[, 1]       <- NULL    
} else {
  phenoFile <- grep("\\/phenotype_data", inputFiles, ignore.case = TRUE, value = TRUE, perl = TRUE)
  phenoData <- fread(phenoFile, na.strings = c("NA", " ", "--", "-", "."), header = TRUE) 
}

phenoData  <- as.data.frame(phenoData)
phenoTrait <- c()

if (datasetInfo == 'combined populations') {
  
   if (!is.null(formattedPhenoData)) {
      phenoTrait <- subset(formattedPhenoData, select = trait)
      phenoTrait <- na.omit(phenoTrait)
   
    } else {
      dropColumns <- grep(trait, names(phenoData), ignore.case = TRUE, value = TRUE)
      phenoTrait  <- phenoData[, !(names(phenoData) %in% dropColumns)]
   
      phenoTrait            <- as.data.frame(phenoTrait)
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1]       <- NULL
      colnames(phenoTrait)  <- trait
    }
   
} else {

  if (!is.null(formattedPhenoData)) {
    phenoTrait <- subset(formattedPhenoData, select = trait)
    phenoTrait <- na.omit(phenoTrait)
   
  } else {
    dropColumns <- c("uniquename", "stock_name")
    phenoData   <- phenoData[, !(names(phenoData) %in% dropColumns)]
    
    phenoTrait <- subset(phenoData, select = c("object_name", "object_id", "design", "block", "replicate", trait))
   
    experimentalDesign <- phenoTrait[2, 'design']
  
    if (class(phenoTrait[, trait]) != 'numeric') {
      phenoTrait[, trait] <- as.numeric(as.character(phenoTrait[, trait]))
    }
      
    if (is.na(experimentalDesign) == TRUE) {experimentalDesign <- c('No Design')}
    
    if ((experimentalDesign == 'Augmented' || experimentalDesign == 'RCBD')  &&  unique(phenoTrait$block) > 1) {

      message("GS experimental design: ", experimentalDesign)

      augData <- subset(phenoTrait, select = c("object_name", "object_id",  "block",  trait))

      colnames(augData)[1] <- "genotypes"
      colnames(augData)[4] <- "trait"

      model <- try(lmer(trait ~ 0 + genotypes + (1|block),
                        augData,
                        na.action = na.omit))

      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
        
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))  
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
      }
            
    } else if (experimentalDesign == 'Alpha') {
   
      message("Experimental desgin: ", experimentalDesign)
      
      alphaData <- subset(phenoData,
                            select = c("object_name", "object_id","block", "replicate", trait)
                            )
      
      colnames(alphaData)[1] <- "genotypes"
      colnames(alphaData)[5] <- "trait"
         
      model <- try(lmer(trait ~ 0 + genotypes + (1|replicate/block),
                        alphaData,
                        na.action = na.omit))
        
      if (class(model) != "try-error") {
        phenoTrait <- data.frame(fixef(model))
      
        colnames(phenoTrait) <- trait

        nn <- gsub('genotypes', '', rownames(phenoTrait))     
        rownames(phenoTrait) <- nn
      
        phenoTrait <- round(phenoTrait, digits = 2)
        
      }
      
    } else {

      phenoTrait <- subset(phenoData,
                           select = c("object_name", "object_id",  trait))
       
      if (sum(is.na(phenoTrait)) > 0) {
        message("No. of pheno missing values: ", sum(is.na(phenoTrait)))      
        phenoTrait <- na.omit(phenoTrait)
      }

        #calculate mean of reps/plots of the same accession and
        #create new df with the accession means    
     
      phenoTrait   <- phenoTrait[order(row.names(phenoTrait)), ]
      phenoTrait   <- data.frame(phenoTrait)
      message('phenotyped lines before averaging: ', length(row.names(phenoTrait)))
   
      phenoTrait<-ddply(phenoTrait, "object_name", colwise(mean))
      message('phenotyped lines after averaging: ', length(row.names(phenoTrait)))
        
      phenoTrait <- subset(phenoTrait, select = c("object_name", trait))
      row.names(phenoTrait) <- phenoTrait[, 1]
      phenoTrait[, 1] <- NULL
       
        #format all-traits population phenotype dataset
        ## formattedPhenoData <- phenoData
        ## dropColumns <- c("object_id", "stock_id", "design", "block", "replicate" )

        ## formattedPhenoData <- formattedPhenoData[, !(names(formattedPhenoData) %in% dropColumns)]
        ## formattedPhenoData <- ddply(formattedPhenoData,
        ##                             "object_name",
        ##                             colwise(mean)
        ##                             )

        ## row.names(formattedPhenoData) <- formattedPhenoData[, 1]
        ## formattedPhenoData[, 1] <- NULL

        ## formattedPhenoData <- round(formattedPhenoData,
        ##                             digits=3
        ##                             )     
    }
  }
}

genoFile <- grep("genotype_data", inputFiles, ignore.case = TRUE, value = TRUE)
genoData <- fread(genoFile, na.strings = c("NA", " ", "--", "-"),  header = TRUE)

#remove markers with > 60% missing marker data
message('no of markers before filtering out: ', ncol(genoData))
genoData[, which(colSums(is.na(genoData)) >= nrow(genoData) * 0.6) := NULL]
message('no of markers after filtering out 60% missing: ', ncol(genoData))

#remove indls with > 80% missing marker data
genoData[, noMissing := apply(.SD, 1, function(x) sum(is.na(x)))]
genoData <- genoData[noMissing <= ncol(genoData) * 0.8]
genoData[, noMissing := NULL]
message('no of indls after filtering out ones with 80% missing: ', nrow(genoData))

genoData           <- as.data.frame(genoData)
rownames(genoData) <- genoData[, 1]
genoData[, 1]      <- NULL

predictionTempFile <- grep("prediction_population", inputFiles, ignore.case = TRUE, value = TRUE)
predictionFile     <- c()

message('prediction temp genotype file: ', predictionTempFile)

if (length(predictionTempFile) !=0 ) {
  predictionFile <- scan(predictionTempFile, what = "character")
}

message('prediction genotype file: ', predictionFile)

predictionPopGEBVsFile <- grep("prediction_pop_gebvs", outputFiles, ignore.case = TRUE, value = TRUE)
message("prediction gebv file: ",  predictionPopGEBVsFile)

predictionData <- c()

if (length(predictionFile) !=0 ) {

  predictionData <- fread(predictionFile, na.strings = c("NA", " ", "--", "-"),)
  message('selection population: no of markers before filtering out: ', ncol(genoData))
  predictionData[, which(colSums(is.na(predictionData)) >= nrow(predictionData) * 0.6) := NULL]

  predictionData           <- as.data.frame(predictionData)
  rownames(predictionData) <- predictionData[, 1]
  predictionData[, 1]      <- NULL
 
}

#impute genotype values for obs with missing values,
#based on mean of neighbouring 10 (arbitrary) obs
genoDataMissing <- c()

if (sum(is.na(genoData)) > 0) {
  genoDataMissing<- c('yes')

  message("sum of geno missing values, ", sum(is.na(genoData)) )  
  genoData <- na.roughfix(genoData)
  genoData <- data.matrix(genoData)
}

genoData <- genoData[order(row.names(genoData)), ]

#create phenotype and genotype datasets with
#common stocks only
message('phenotyped lines: ', length(row.names(phenoTrait)))
message('genotyped lines: ', length(row.names(genoData)))

#extract observation lines with both
#phenotype and genotype data only.
commonObs <- intersect(row.names(phenoTrait), row.names(genoData))
commonObs <- data.frame(commonObs)
rownames(commonObs)<-commonObs[, 1]

message('lines with both genotype and phenotype data: ', length(row.names(commonObs)))

#include in the genotype dataset only observation lines
#with phenotype data
message("genotype lines before filtering for phenotyped only: ", length(row.names(genoData)))        
genoDataFiltered <- genoData[(rownames(genoData) %in% rownames(commonObs)), ]
message("genotype lines after filtering for phenotyped only: ", length(row.names(genoDataFiltered)))

#drop observation lines without genotype data
message("phenotype lines before filtering for genotyped only: ", length(row.names(phenoTrait)))        
phenoTrait <- merge(data.frame(phenoTrait), commonObs, by=0, all=FALSE)
rownames(phenoTrait) <- phenoTrait[, 1]
phenoTrait <- subset(phenoTrait, select=trait)

message("phenotype lines after filtering for genotyped only: ", length(row.names(phenoTrait)))
#a set of only observation lines with genotype data

traitPhenoData   <- data.frame(round(phenoTrait, digits = 2))           
phenoTrait       <- data.matrix(phenoTrait)
genoDataFiltered <- data.matrix(genoDataFiltered)

#impute missing data in prediction data
predictionDataMissing <- c()
if (length(predictionData) != 0) {
  #purge markers unique to both populations
  commonMarkers    <- intersect(names(data.frame(genoDataFiltered)), names(predictionData))
  predictionData   <- subset(predictionData, select = commonMarkers)
  genoDataFiltered <- subset(genoDataFiltered, select= commonMarkers)
  
 # predictionData <- data.matrix(predictionData)
 
  if (sum(is.na(predictionData)) > 0) {
    predictionDataMissing <- c('yes')
    message("sum of geno missing values, ", sum(is.na(predictionData)) )  
    predictionData <- data.matrix(na.roughfix(predictionData))
    
  }
}

relationshipMatrixFile <- grep("relationship_matrix", outputFiles, ignore.case = TRUE, value = TRUE)

message("relationship matrix file: ", relationshipMatrixFile)

relationshipMatrix <- c()
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size > 0 ) {
    relationshipDf <- as.data.frame(fread(relationshipMatrixFile))

    rownames(relationshipDf) <- relationshipDf[, 1]
    relationshipDf[, 1]      <- NULL
    relationshipMatrix       <- data.matrix(relationshipDf)
  }
}


#change genotype coding to [-1, 0, 1], to use the A.mat ) if  [0, 1, 2]
genoTrCode <- grep("2", genoDataFiltered[1, ], value = TRUE)
if(length(genoTrCode) != 0) {
  genoDataFiltered <- genoDataFiltered - 1
}

if (length(predictionData) != 0 ) {
  genoSlCode <- grep("2", predictionData[1, ], value = TRUE)
  if (length(genoSlCode) != 0 ) {
    predictionData <- predictionData - 1
  }
}

#MAF calculation

ordered.markerEffects <- c()
if ( length(predictionData) == 0 ) {
  markerEffects <- mixed.solve(y = phenoTrait,
                               Z = genoDataFiltered
                               )

  ordered.markerEffects <- data.matrix(markerEffects$u)
  ordered.markerEffects <- data.matrix(ordered.markerEffects [order (-ordered.markerEffects[, 1]), ])
  ordered.markerEffects <- round(ordered.markerEffects, digits=5)

  colnames(ordered.markerEffects) <- c("Marker Effects")

}

#additive relationship model
#calculate the inner products for
#genotypes (realized relationship matrix)
if (length(relationshipMatrixFile) != 0) {
  if (file.info(relationshipMatrixFile)$size == 0) {
    relationshipMatrix <- tcrossprod(data.matrix(genoData))
  }
}
relationshipMatrixFiltered <- relationshipMatrix[(rownames(relationshipMatrix) %in% rownames(commonObs)),]
relationshipMatrixFiltered <- relationshipMatrixFiltered[, (colnames(relationshipMatrixFiltered) %in% rownames(commonObs))]

#construct an identity matrix for genotypes
identityMatrix <- diag(nrow(phenoTrait))

relationshipMatrixFiltered <- data.matrix(relationshipMatrixFiltered)

iGEBV  <- mixed.solve(y = phenoTrait, Z = identityMatrix, K = relationshipMatrixFiltered) 
iGEBVu <- iGEBV$u

heritability  <- c()

if ( is.null(predictionFile) == TRUE ) {
  additiveEffects <- data.frame(iGEBVu)
 
  pN <- nrow(phenoTrait)
  aN <- nrow(additiveEffects)

  if (pN <= 1 || pN != aN) {
    stop("phenoTrait and additiveEffects have different lengths: ",
         pN, " and ", aN, ".")
  }
      
  if (TRUE %in% is.na(phenoTrait) || TRUE %in% is.na(additiveEffects)) {
    stop(" Arguments phenoTrait and additiveEffects have missing values.")
  }
  
  phenoVariance <- var(phenoTrait)
  gebvVariance  <- var(additiveEffects)
  heritability  <- round((gebvVariance / phenoVariance), digits = 2)
      
  cat("\n", file = varianceComponentsFile,  append = FALSE)
  cat('Error variance', iGEBV$Ve, file = varianceComponentsFile, sep = "\t", append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Additive genetic variance',  iGEBV$Vu, file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Phenotype mean', iGEBV$beta,file = varianceComponentsFile, sep = '\t', append = TRUE)
  cat("\n", file = varianceComponentsFile,  append = TRUE)
  cat('Heritability (h)', heritability, file = varianceComponentsFile, sep = '\t', append = TRUE)
}

iGEBV         <- data.matrix(iGEBVu)
ordered.iGEBV <- as.data.frame(iGEBV[order(-iGEBV[, 1]), ])
ordered.iGEBV <- round(ordered.iGEBV, digits = 3)

combinedGebvsFile <- grep('selected_traits_gebv', outputFiles, ignore.case = TRUE,value = TRUE)

allGebvs<-c()
if (length(combinedGebvsFile) != 0) {
    fileSize <- file.info(combinedGebvsFile)$size
    if (fileSize != 0 ) {
        combinedGebvs <- as.data.frame(fread(combinedGebvsFile))

        rownames(combinedGebvs) <- combinedGebvs[,1]
        combinedGebvs[,1]       <- NULL

        colnames(ordered.iGEBV) <- c(trait)
      
        traitGEBV <- as.data.frame(ordered.iGEBV)
        allGebvs <- merge(combinedGebvs, traitGEBV,
                          by = 0,
                          all = TRUE                     
                          )

        rownames(allGebvs) <- allGebvs[,1]
        allGebvs[,1] <- NULL
     }
  }

colnames(ordered.iGEBV) <- c(trait)
                  
#cross-validation
validationAll <- c()

if(is.null(predictionFile)) {
  genoNum <- nrow(phenoTrait)
if(genoNum < 20 ) {
  warning(genoNum, " is too small number of genotypes.")
}
  
reps <- round_any(genoNum, 10, f = ceiling) %/% 10

genotypeGroups <-c()

if (genoNum %% 10 == 0) {
    genotypeGroups <- rep(1:10, reps)
  } else {
    genotypeGroups <- rep(1:10, reps) [- (genoNum %% 10) ]
  }

set.seed(4567)                                   
genotypeGroups <- genotypeGroups[ order (runif(genoNum)) ]

for (i in 1:10) {
  tr <- paste("trPop", i, sep = ".")
  sl <- paste("slPop", i, sep = ".")
 
  trG <- which(genotypeGroups != i)
  slG <- which(genotypeGroups == i)
  
  assign(tr, trG)
  assign(sl, slG)

  kblup <- paste("rKblup", i, sep = ".")
  
  result <- kinship.BLUP(y = phenoTrait[trG, ],
                         G.train = genoDataFiltered[trG, ],
                         G.pred = genoDataFiltered[slG, ],                      
                         mixed.method = "REML",
                         K.method = "RR",
                         )
 
  assign(kblup, result)

#calculate cross-validation accuracy  
  valCorData <- merge(phenoTrait[slG, ], result$g.pred, by=0, all=FALSE)
  rownames(valCorData) <- valCorData[, 1]
  valCorData[, 1]      <- NULL
 
  accuracy <- try(cor(valCorData))
  validation <- paste("validation", i, sep = ".")

  cvTest <- paste("Validation test", i, sep = " ")

  if ( class(accuracy) != "try-error")
    {
      accuracy <- round(accuracy[1,2], digits = 3)
      accuracy <- data.matrix(accuracy)
    
      colnames(accuracy) <- c("correlation")
      rownames(accuracy) <- cvTest

      assign(validation, accuracy)
      
      if (!is.na(accuracy[1,1])) {
        validationAll <- rbind(validationAll, accuracy)
      }    
    }
}

validationAll <- data.matrix(validationAll[order(-validationAll[, 1]), ])
     
if (!is.null(validationAll)) {
    validationMean <- data.matrix(round(colMeans(validationAll), digits = 2))
   
    rownames(validationMean) <- c("Average")
     
    validationAll <- rbind(validationAll, validationMean)
    colnames(validationAll) <- c("Correlation")
  }
}

predictionPopResult <- c()
predictionPopGEBVs  <- c()

if (length(predictionData) != 0) {
    message("running prediction for selection candidates...marker data", ncol(predictionData), " vs. ", ncol(genoDataFiltered))

    predictionPopResult <- kinship.BLUP(y = phenoTrait,
                                        G.train = genoDataFiltered,
                                        G.pred = predictionData,
                                        mixed.method = "REML",
                                        K.method = "RR"
                                        )
 message("running prediction for selection candidates...DONE!!")

    predictionPopGEBVs <- round(data.matrix(predictionPopResult$g.pred), digits = 3)
    predictionPopGEBVs <- data.matrix(predictionPopGEBVs[order(-predictionPopGEBVs[, 1]), ])
   
    colnames(predictionPopGEBVs) <- c(trait)
  
}

if (!is.null(predictionPopGEBVs) & length(predictionPopGEBVsFile) != 0)  {
    write.table(predictionPopGEBVs,
                file = predictionPopGEBVsFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if(!is.null(validationAll)) {
    write.table(validationAll,
                file = validationFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.markerEffects)) {
    write.table(ordered.markerEffects,
                file = markerFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (!is.null(ordered.iGEBV)) {
    write.table(ordered.iGEBV,
                file = blupFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                append = FALSE
                )
}

if (length(combinedGebvsFile) != 0 ) {
    if(file.info(combinedGebvsFile)$size == 0) {
        write.table(ordered.iGEBV,
                    file = combinedGebvsFile,
                    sep = "\t",
                    col.names = NA,
                    quote = FALSE,
                    )
      } else {
      write.table(allGebvs,
                  file = combinedGebvsFile,
                  sep = "\t",
                  quote = FALSE,
                  col.names = NA,
                  )
    }
}

if (!is.null(traitPhenoData) & length(traitPhenoFile) != 0) {
    write.table(traitPhenoData,
                file = traitPhenoFile,
                sep = "\t",
                col.names = NA,
                quote = FALSE,
                )
}



## if (!is.null(genoDataMissing)) {
##   write.table(genoData,
##               file = genoFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##             )

## }

## if (!is.null(predictionDataMissing)) {
##   write.table(predictionData,
##               file = predictionFile,
##               sep = "\t",
##               col.names = NA,
##               quote = FALSE,
##               )
## }


if (file.info(relationshipMatrixFile)$size == 0) {
  write.table(relationshipMatrix,
              file = relationshipMatrixFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}


if (file.info(formattedPhenoFile)$size == 0 && !is.null(formattedPhenoData) ) {
  write.table(formattedPhenoData,
              file = formattedPhenoFile,
              sep = "\t",
              col.names = NA,
              quote = FALSE,
              )
}

message("Done.")

q(save = "no", runLast = FALSE)
# # # currently working on response rule and (subtracting small mat from larger) 

source('utils.r')

# # # CHECK AND CLOSE PDFS
# # # LOAD PACKAGES?

# # # Initialize model parameters
model <- list(num_blocks    = 20,
			  num_inits     = 5,
			  wts_range     = 1,
			  num_hids      = 3,
			  learning_rate = 0.15,
			  beta_val      = 5,
			  out_rule      = 'sigmoid') # linear / tan not implemented

training = matrix(rep(0, model$num_blocks * 6), ncol = 6)
for (shj in 1:6) { 
  
  # # # get shj stimuli
  cases <- shj_cats(shj)
  model$inputs <- cases$inputs
  model$labels <- cases$labels

  # # # train model
  result <- run_diva(model)

# # # add result to training matrix
training[,shj] <- result$training

}

# display results
print(training)
train_plot(training)
save.image(paste0('diva_run.rdata'))

# warnings()


two_way_tanimoto_predict <- function(Kc, Kr, S0, S1, MW, similarity.consumer, similarity.resource, minimum_threshold) {
    # Two-way Tanimoto Algorithm
    # ===========================

    # Parameters:
    #   Kc  Integer, how many neighbors to select for consumers
    #   Kr  Integer, how many neighbors to select for resources
    #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
    #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name
    #   MW  Mimimum weight to accept a candidate as a prey
    #

    # // TODO: I think MW should be a function of Kc & Kr and perhaps of the number of candidate resources. For example, a similar consumer could have multiple prey, which would artificially inflate the weight added to each prey in the candidate list. For exemple, Atlantic cod has over 600 prey species listed in the interaction catalogue... Hence, the longer the candidate list, the more likely a very small similarity will be turned into a predicted interaction
    # // REVIEW: Multiply similar.consumer[similarity] * similar.resource[similarity]? It's a similarity of a similarity in a sense...

    # // TODO: Different similarity measurement for resources and consumers

    # // REVIEW: Remove cannibalism from empirical data, or allow for it, or add parameter that allows or prevents cannibalism in the predictions


    # Output
    #   A vector of sets (the preys for each species)

    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # List of things to adjust - make it
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    # Process steps:
      # A prior process to this is to get the similarity matrix between all combinations of catalogue taxa and species in S1
      # For each species in S1:
      # 1. Identify resources already known in interaction catalogue (S0) for S1 species
        # 1.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
        # 1.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

      # 2. Identify Kc similar consumers to S1 in S0
        # 2.1 Extract set of candidate resources from each similar consumer, if any
        # 2.2 If candidate resource is in S1, add it to candidate list with weight 1
        # 2.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

      # 3. Make predictions:
        # 3.1 Remove taxa with weight < to minimum weight (MW) from prediction list
        # 3.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed


    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # !!! étendre predator et non predator pour resource... il faudrait aussi calculer la similarité des proies sur la base de leurs prédateurs partagés !!!
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    predictions <- matrix(nrow = length(S1), ncol = 3, data = "", dimnames = list(c(S1), c('consumer','resource_empirical','resource_predictions'))) # empty object for resource predictions
    predictions[, 'consumer'] <- S1

    # pb <- txtProgressBar(min = 0,max = length(S1), style = 3)
    for(i in 1:length(S1)) { # loop through each taxon in S1
        candidates <- matrix(nrow = 0, ncol = 2, dimnames = list(c(), c('resource', 'weight')), data = NA) # empty matrix for resource candidate list for S1[i], with taxon name and weight
        resources.S1 <- unlist(strsplit(S0[S1[i], 'resource'], " \\|\\ ")) # resources of S1[i]

        # Add resources that are already listed as resources for S1[i] in predictions[, 'resource_empirical'] or
        # Find similar resources to resources for S1[i] in S1
        if(length(resources.S1) > 0) {
            empirical <- character()
            for(j in 1:length(resources.S1)) { #loop through empirical resources for S1
                if(resources.S1[j] %in% S1) {
                    empirical <- c(empirical, resources.S1[j]) # observed resource found in S1 are automatically added to the column resource_empirical
                } else { # selecting Kr most similar resources in S1
                    # Let's assume for this part that we are not compiling a different similarity measure for predators and preys.
                    similar.resource <- matrix(nrow = length(S1)-1, ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources
                    similar.resource[, 'resource'] <- names(sort(similarity.resource[S1[-which(S1 == S1[i])], resources.S1[j]], decreasing = TRUE))
                    similar.resource[, 'similarity'] <- sort(similarity.resource[S1[-which(S1 == S1[i])], resources.S1[j]], decreasing = TRUE)

                    # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
                    if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {
                        same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])
                        similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]
                        similar.resource <- similar.resource[1:Kr, ]
                    } else {
                        similar.resource <- similar.resource[1:Kr, ]
                    }# if for random draw

                    for(l in 1:Kr) { # extracting resource candidates
                        if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break
                            break
                        } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                            NULL
                            # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed
                        } else if(similar.resource[l, 'similarity'] < minimum_threshold) {
                            NULL
                        } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add resource' with wt to its weight
                          candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])
                        } else {
                              candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it resource' with wt to its weight
                        }#if3
                    }#l
                }#if
            }#j
            predictions[S1[i], 'resource_empirical'] <- paste(empirical, collapse = ' | ')
        }#if1

        # Identify similar consumers to S1[i]
        similar.consumer <- matrix(nrow = nrow(similarity.consumer)-1, ncol = 2, dimnames = list(c(), c('consumer','similarity')), data = NA) # emporting K nearest neighbors for consumers
        similar.consumer[, 'consumer'] <- names(sort(similarity.consumer[-which(colnames(similarity.consumer) == S1[i]), S1[i]], decreasing = TRUE))
        similar.consumer[, 'similarity'] <- sort(similarity.consumer[-which(colnames(similarity.consumer) == S1[i]), S1[i]], decreasing = TRUE)

        # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
        if(similar.consumer[Kc+1, 'similarity'] == similar.consumer[Kc, 'similarity']) {
            same.similarity <- which(similar.consumer[, 'similarity'] == similar.consumer[Kc, 'similarity'])
            similar.consumer[same.similarity, ] <- similar.consumer[sample(same.similarity), ]
            similar.consumer <- similar.consumer[1:Kc, ]
        } else {
            similar.consumer <- similar.consumer[1:Kc, ]
        }# if for random draw


        # Est-ce que la valeur de similarité a de l'importance pour l'attribution des proies?
        # If yes, we could add an argument call wt_predator.
          # if(wt_predator == FALSE) {
          #   resources <- unique of all prey species of all similar predators
          # } else {}

        for(j in 1:Kc) { #loop through consumers

            if(all.equal(similar.consumer[, 'similarity'], rep('0',Kc)) == TRUE) { # if similarities all == 0, break
                break
            } else if(similar.consumer[j, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                NULL
            } else {

                # It's possible that consumers in the list have high taxonomic similarity, but no recorded resource
                candidate.resource <- unlist(strsplit(S0[similar.consumer[j, 'consumer'], 'resource'], " \\|\\ ")) # list of resources for consumer j
                # candidate.resource <- candidate.resource[(candidate.resource %in% resources.S1) == FALSE] # substracting candidate resources that are already listed as resources for S1[i] and hence considered in the preceding code segment

                for(k in 1:length(candidate.resource)) { # loop through resources of consumer j
                    if(length(candidate.resource) == 0) { # if candidate resource list is empty, break
                        break
                    } else if(candidate.resource[1] == "") { # if candidate list is an empty vector "", break
                        break
                    } else if(candidate.resource[k] == S1[i]) {
                    #   #// FIXME: if candidate resource is taxon for which predictions are being made, break (unless we want to allow CANIBALISM). Add argument for cannibalism allowed or not
                         NULL
                    } else if((candidate.resource[k] %in% S1) == TRUE) {
                        if((candidate.resource[k] %in% candidates[, 'resource']) == TRUE) {# if candidate is already in candidate list, add 1 to its weight
                            candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight']) + 1
                        } else {
                            candidates <- rbind(candidates, c(candidate.resource[k], 1)) # if candidate is not in the list, add it with 1 to its weight
                        }#if2

                    } else {
                        # Let's assume for this part that we are not compiling a different similarity measure for predators and preys.
                        similar.resource <- matrix(nrow = length(S1)-1, ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources
                        similar.resource[, 'resource'] <- names(sort(similarity.resource[S1[-which(S1 == S1[i])], candidate.resource[k]], decreasing = TRUE))
                        similar.resource[, 'similarity'] <- sort(similarity.resource[S1[-which(S1 == S1[i])], candidate.resource[k]], decreasing = TRUE)

                        # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
                        if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {
                            same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])
                            similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]
                            similar.resource <- similar.resource[1:Kr, ]
                        } else {
                            similar.resource <- similar.resource[1:Kr, ]
                        }# if for random draw

                        for(l in 1:Kr) { # extracting resource candidates
                            if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break
                                break
                            } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                                NULL
                                # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed
                            } else if(similar.resource[l, 'similarity'] < minimum_threshold) {
                                NULL
                            } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add 1 to its weight
                              candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])
                            } else {
                                  candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it with its weight = similarity
                            }#if3
                        }#l
                    } #if1
                }#k
            }#if
        }#j

        candidates <- candidates[which(candidates[, 'weight'] >= MW), ] # remove candidates with a weight below MW
        if(is.matrix(candidates) == TRUE) { #if it's a vector, there's only one predicted resource, no need to order
            candidates[order(candidates[, 'weight']), ] # sorts candidates according to their weight
            predictions[S1[i], 'resource_predictions'] <- paste(candidates[, 'resource'], collapse = ' | ')
        } else {
          predictions[S1[i], 'resource_predictions'] <- paste(candidates['resource'], collapse = ' | ')
        }#if
    # setTxtProgressBar(pb, i)
    }#i
    # close(pb)
    return(predictions)
}#two_way_tanimoto_predict function
#' Find unassigned global variables.
#'
#' This funciton sources files and loads objects into an environment
#' and then runs \code{codetools::findGlobals} on the environment.
#'
#' NOTE: Globals are determined for the \code{main()} function only!
#'
#' @param source_files R files containing globals to exclude such as
#' function declarations.
#'
#' @param object_files Rdata files that contain globals to exclude.
#'
#' @return A list of globals without assignments.
find_globals = function(source_files, object_files = c()) {
    e <- new.env()

    for (file in source_files) {
        testthat::source_file(file, e)
    }

    for (object_file in object_files) {
        load(object_file, envir = e)
    }

    globals <- list()

    tryCatch({
        globals <- codetools::findGlobals(e$main)
    }, error = function(e) {
        warning("No main() function was found. Globals cannot be set until a main function is found.")
        return(globals)
    })

    # Filter known `findGlobals` errors
    known_errors <- c("{", "}", "::")
    globals <- globals[!(globals %in% known_errors)]

    # Filter all functions in loaded packages
    for (package in (.packages())) {
        package <- paste0("package:", package)
        exports <- names(as.list(as.environment(package)))
        globals <- globals[!(globals %in% exports)]
    }

    # Filter functions and variables in source files
    globals <- globals[!(globals %in% names(as.list(e)))]

    nglobals <- length(globals)

    if (nglobals > 0) {
        if (nglobals == 1) {
            vars <- "var"
            t_vars <- "this var"
        } else {
            vars <- "vars"
            t_vars <- "these vars"
        }

        cat(paste("Found", nglobals, vars, "to specify:"))
        for (global in globals) {
            cat(paste("\n    -", global))
        }

        cat(paste("\n\nSet", t_vars, "in the `params` property of your `SlurmJob` instance."))
    }

    # Set the values of all gobals to NA
    global_list <- list()

    for (global in globals) {
        global_list[[global]] <- NA
    }

    return(global_list)
}
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container_dir, settings) {
            private$settings <- settings

            private$cat_main_file_magic(container_dir)
            private$write_slurm_script(container_dir)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir) {
            main_file <- ".default_stain_main.R"
            file <- paste0(dir, "/.stain/sources/", main_file)
            sourcing <- paste("sapply(list.files('./.stain/sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", main_file, "'"), "], source)")
            loading <- paste("sapply(list.files('./.stain/objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./.stain $PFSDIR
cd $PFSDIR

mkdir .data
mv ./.stain/data/* ./.data

module load hpc-ods
module load pandoc

R CMD BATCH ./.stain/sources/.default_stain_main.R

cp -r * $SLURM_SUBMIT_DIR/output"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, "submit.slurm", sep = "/"))
        }
    )
)
# # # setwd('C:/Users/garre/Dropbox/aa projects/DIVA')

# # backprop
# #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
backprop <- function(out_wts, in_wts, out_activation, current_target, 
                     hid_activation, hid_activation_raw, ins_w_bias, learning_rate){

  # # # calc error on output units
  out_delta <- 2 * (out_activation - current_target)
  
  # # # calc error on hidden units
  hid_delta <- out_delta %*% t(out_wts)
  hid_delta <- hid_delta[,2:ncol(hid_delta)] * sigmoid_grad(hid_activation_raw)
  
  # # # calc weight changes
  out_delta <- learning_rate * (t(hid_activation) %*% out_delta)
  hid_delta <- learning_rate * (t(ins_w_bias) %*% hid_delta)

  # # # adjust wts
  out_wts <- out_wts - out_delta
  in_wts <- in_wts - hid_delta

  return(list(out_wts = out_wts, 
              in_wts  = in_wts))

}

# forward_pass
# conduct forward pass
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
forward_pass <- function(in_wts, out_wts, inputs, out_rule) {
  # # # init needed vars
  num_feats <- ncol(out_wts)
  num_cats  <- dim(out_wts)[3]
  num_stims <- nrow(inputs)
  if (is.null(num_stims)) {num_stims <- 1}

  
  # # # add bias to ins
  bias_units <- matrix(rep(1, num_stims), ncol = 1, nrow = num_stims)
  ins_w_bias <- cbind(bias_units,
    matrix(inputs, nrow = num_stims, ncol = num_feats, byrow = TRUE))

  # # # ins to hids propagation
  hid_activation_raw <- ins_w_bias %*% in_wts
  hid_activation <- sigmoid(hid_activation_raw)

  # # # add bias unit to hid activation
  hid_activation <- cbind(bias_units, hid_activation)  

  # # # hids to outs propagation
  out_activation <- array(rep(0, (num_stims * num_feats * num_cats)), 
    dim = c(num_stims, num_feats, num_cats))
  # # NEED VECTORIZED HERE
  for (category in 1:num_cats) {
  	out_activation[,,category] <- hid_activation %*% out_wts[,,category]
  }
  
  # # # apply output activatio rule
  if(out_rule == 'sigmoid') {
  	out_activation <- sigmoid(out_activation)
  }

  return(list(out_activation     = out_activation, 
              hid_activation     = hid_activation,
              hid_activation_raw = hid_activation_raw, 
              ins_w_bias         = ins_w_bias))

}

# get_wts
# generate net weights
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
get_wts <- function(num_feats, num_hids, num_cats, wts_range, wts_center) {
  # # # set bias
  bias <- 1
  
  # # # generate wts between ins and hids
  in_wts <- 
    (matrix(runif((num_feats + bias) * num_hids), ncol = num_hids) - 0.5) * 2 
  in_wts <- wts_center + (wts_range * in_wts)

  # # # generate wts between hids and outs
  out_wts <- 
    (array(runif((num_hids + bias) * num_feats * num_cats), 
      dim = c((num_hids + bias), num_feats, num_cats)) - 0.5) * 2
  out_wts <- wts_center + (wts_range * out_wts)   
  
  return(list(in_wts  = in_wts, 
              out_wts = out_wts))

}

# global_scale
# scale inputs to 0/1
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
global_scale <- function(x) { x / 2 + 0.5 }

# response_rule
# convert output activations to classification
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
response_rule <- function(out_activation, target_activation, beta_val){
  num_feats <- ncol(out_activation)
  num_cats  <- dim(out_activation)[3]
  num_stims <- nrow(target_activation)
  if (is.null(num_stims)) {num_stims <- 1}

  # # # calc error  
  ssqerror <- array(as.vector(
    apply(out_activation, 3, function(x) {x - target_activation})),
      c(num_stims, num_feats, num_cats))
  ssqerror <- ssqerror ^ 2
  ssqerror[ssqerror < 1e-7] <- 1e-7
  
  # # # generate focus weights
  if(dim(out_activation)[3] > 2 | dim(out_activation)[1] > 1){
    stop('Not coded for >2 channels or batch mode, sorry!')
  } else {
    
    # # # candidate for errors:
    diversities <- 
      exp(beta_val * abs(matrix(dist(out_activation))[num_feats:((num_feats*2)-1)]))  
    diversities[diversities > 1e+7] <- 1e+7

    # divide diversities by sum of diversities
    fweights = diversities / sum(diversities)

    # # # apply focus weights; then get sum for each category
    ssqerror <- t(apply(ssqerror, 3, function(x) sum(x * fweights))) 
    ssqerror <- 1 / ssqerror
  }

return(list(ps       = (ssqerror / sum(ssqerror)), 
            fweights = fweights, 
            ssqerror = ssqerror))

}

# run_diva
# trains vanilla diva
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
run_diva <- function(model) {
  # # # extract model vars
  attach(model)
  # # # get new seed
  seed <- runif(1) * 100000 * runif(1)
  set.seed(seed)
  # # # set mean value of weights
  wts_center <- 0 
  # # # convert targets to 0/1
  targets <- global_scale(model$inputs) 
  
  # # # init size parameter variables
  num_feats   <- ncol(inputs)
  num_stims   <- nrow(inputs)
  num_cats    <- length(unique(labels))
  num_updates <- num_blocks * num_stims
  
  # # # init training accuracy matrix
  training <- 
    matrix(rep(NA, num_updates * num_inits), nrow = num_updates, ncol = num_inits)
  
  # # # initialize and run DIVA models
  for (model_num in 1:num_inits) {
  	
    # # # generate weights
  	wts_list <- get_wts(num_feats, num_hids, num_cats, wts_range, wts_center)
    attach(wts_list)

    # # # generate presentation order
  	prez_order <- as.vector(apply(replicate(num_blocks, seq(1, num_stims)), 
  	  2, sample, num_stims))

    # # # iterate over each trial in the presentation order 
    for (trial_num in 1:num_updates) {
      current_input  <- inputs[prez_order[[trial_num]], ]
      current_target <- targets[prez_order[[trial_num]], ]
      current_class  <- labels[prez_order[[trial_num]]] 

      # # # complete forward pass
      fp_result <- forward_pass(in_wts, out_wts, current_input, out_rule)
      attach(fp_result)

      # # # calculate classification probability
      rr_result <- response_rule(out_activation, current_target, beta_val)
      attach(rr_result)

      # # # store classification accuracy
      training[trial_num, model_num] = ps[current_class]

      # # # back propagate error to adjust weights
      class_wts <- out_wts[,,current_class]
      class_activation <- out_activation[,,current_class]

      adjusted_wts <- backprop(class_wts, in_wts, class_activation, current_target,  
               hid_activation, hid_activation_raw, ins_w_bias, learning_rate)

      out_wts[,,current_class] <- adjusted_wts$out_wts
      in_wts <- adjusted_wts$in_wts

      detach(fp_result)
      detach(rr_result)

    }
    
    detach(wts_list)
  
  }

print(rowMeans(matrix(rowMeans(training), nrow = num_blocks, ncol = num_stims, byrow = TRUE)))
detach(model)
#return(list(training = training))
}

# shj_cats
# loads shj category structures
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
shj_cats <- function(type){
  
  if (type == 1) {
    in_patterns <- 
      matrix(c(1,  1,  1,
	             1,  1, -1,
	             1, -1,  1,
  	           1, -1, -1,
	            -1, -1,  1,
	            -1, -1, -1,
	            -1,  1,  1,
	            -1,  1, -1), nrow = 8, ncol = 3, byrow = TRUE)		

  } else if (type == 2){
  	in_patterns <-
  	  matrix(c(1,  1,  1,
  	  	       1,  1, -1,
       	      -1, -1,	 1,
	            -1, -1, -1,
	            -1,	 1,	 1,
	            -1,	 1, -1,
	  	         1, -1,	 1,
		           1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 3){
  	in_patterns <-
  	  matrix(c(1,  1,  1,
  	  	       1,  1, -1,
  	  	       1, -1,  1, 
  	          -1,  1, -1,
  	           1, -1, -1, 
  	          -1,  1,  1, 
  	          -1, -1,  1, 
  	          -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 4){
    in_patterns <-
      matrix(c(1,  1,  1,
               1,  1, -1,
               1, -1,  1,
              -1,  1,  1,
               1, -1, -1,
              -1,  1, -1,
              -1  -1,  1,
              -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 5){
    in_patterns <-
      matrix(c(1,  1,  1,
               1,  1, -1,
               1, -1,  1,
              -1, -1, -1,
               1, -1, -1,
              -1,  1,  1,
              -1,  1, -1,
              -1, -1,  1), nrow = 8, ncol = 3, byrow = TRUE)
  
  } else if (type == 6){
    in_patterns <-
      matrix(c(1,  1,  1,
               1, -1, -1,
              -1,  1, -1,
              -1, -1,  1,
               1,  1, -1,
               1, -1,  1,
              -1,  1,  1,
              -1, -1, -1), nrow = 8, ncol = 3, byrow = TRUE)
  }

cat_assignment <- c(1, 1, 1, 1, 2, 2, 2, 2)

return(list(inputs = in_patterns, 
			      labels = cat_assignment))

}

# sigmoid
# returns sigmoid evaluated elementwize in X
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
sigmoid <- function(x) {
  g = 1 / (1 + exp(-x))
  return(g)

}

# sigmoid gradient
# returns the gradient of the sigmoid function evaluated at x
#  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #  #
sigmoid_grad <- function(x) {
  return(g = ((sigmoid(x)) * (1 - sigmoid(x))))

}# 4. faza: Analiza podatkov

#Iščemo, kdo je bil najbolj uspešen v klubu
normaliziran <- scale(as.matrix(IGRALCI[c(3:4, 8)]))
matrikarazdalj<-dist(normaliziran)
razdelitev<- hclust(matrikarazdalj, method = "complete")
plot(razdelitev, hang=-1, cex=0.6, main = "USPEŠNOST")
rect.hclust(razdelitev,k=4,border="red")
#Iz tabele vidimo, da so gralci, ki so se najbolj izkazali Dennis Wise,
#George Mills, Dick Spence in Frank Lampard

p <- cutree(razdelitev, k=4)
barve=c("red", "green", "blue","yellow")
table(p)
barve



pairs(normaliziran, col = barve[p])

IGRALCI[p %in% c(1),]

razdelitev1 <- hclust(matrikarazdalj, method = "single")
plot(razdelitev1, hang=-1, cex=0.6, main = "USPEŠNOST 1")
rect.hclust(razdelitev1,k=4,border="red")

#Iščemo najboljšo sezono po uspešnosti
#Normaliziramo število zmag, danih golov in doseženih točk
normaliziran2 <- scale(as.matrix(ZGODOVINA[c(2,5,7)]))
matrikarazdalj2<-dist(normaliziran2)
razdelitev2<- hclust(matrikarazdalj2, method = "complete")
plot(razdelitev2, hang=-1, cex=0.6, main = "USPEŠNOST2")
rect.hclust(razdelitev2,k=4,border="red")
#Vidimo, da so bili najbolj uspešni v letih 1983, 1988 in 2009, ko so tudi osvojili prvo mesto
# Container for plot parameters
PlotParams <- function(args) {
  this <- list(
    depth = ('-d' %in% args),
    orphaned = ('-or' %in% args),
    inverted = ('-v' %in% args),
    samestrand = ('-ss' %in% args),
    secondary = ('-se' %in% args),
    supplementary = ('-su' %in% args),
    hardclipped = ('-hc' %in% args),
    ins = ('-i' %in% args),
    refgene = ('-r' %in% args),
    svMAF = ('-af' %in% args),
    legend = ('-l' %in% args)
  )
  
  class(this) <- append(class(this), "PlotParams")
  return (this)
}

# Container for data for a given sample
Sample <- function(folder, sample, label = FALSE) {
  depths <- read.delim(paste0(folder, sample, '/depths.tsv'), header = TRUE,  sep = '\t')
  bin_size <- depths$bin[2] -  depths$bin[1]
  num_bins <- nrow(depths)
  xlims <- c(depths$bin[1], (depths$bin[nrow(depths)] + bin_size))
  #read in SV calls for this sample
  svs <- read.delim(paste0(folder, sample, '/svs.tsv'), header = TRUE, sep = '\t')
  #convert to list, separating calls from different vcfs
  svs <- split.data.frame(svs, svs$vcf)
  svTracks <- lapply(svs, function(x) get_tracks(x$start, x$end))
  #read in foward and reverse inserts
  fwd_ins <- read.table(paste0(folder, sample, '/fwd_ins.tsv'), fill=TRUE, sep="\t", stringsAsFactors = FALSE, header = FALSE)
  rvs_ins <- read.delim(paste0(folder, sample, '/rvs_ins.tsv'), fill=TRUE, sep="\t", stringsAsFactors = FALSE, header = FALSE)
  #convert inserts from strings to numerics
  fwd_ins <- cbind(fwd_ins[,1], lapply(fwd_ins[,2], function(x) as.numeric(unlist(strsplit(x, ',')))))
  rvs_ins <- cbind(rvs_ins[,1], lapply(rvs_ins[,2], function(x) as.numeric(unlist(strsplit(x, ',')))))
  #read aln_stats
  aln_stats <- read.delim(paste0(folder, sample, '/aln_stats.tsv'), header = TRUE,  sep = '\t')
  aln_stats_bin_size <- aln_stats$bin[2] - aln_stats$bin[1]
  split <- FALSE
  for (i in 3:nrow(aln_stats)){
    if (aln_stats_bin_size != aln_stats$bin[i] - aln_stats$bin[i-1]){
      split = i
    }
  }
  ins_ylim <- max(max(unlist(sapply(fwd_ins, function(x)  estimate_upper_bound(x)))),  max(unlist(sapply(rvs_ins, function(x) estimate_upper_bound(x)))))
  
  this <- list(
    Name = sample,
    Depths = depths,
    Bin_size = bin_size,
    Num_bins = num_bins,
    Xlims = xlims,
    SVs = svs,
    SVtracks = svTracks,
    Fwd_ins = fwd_ins,
    Rvs_ins = rvs_ins,
    Aln_stats = aln_stats,
    Split = split,
    Ins_ylim = ins_ylim
  )
  class(this) <- append(class(this), "Sample")
  return(this)
}
#container for annotations
Annotations <- function(folder) {
  #check if refgenes file exists, if so read
  genes_file <- paste0(folder, 'refgene.tsv')
  if (file.exists(genes_file)) {
    genes <- read.delim(genes_file, header = TRUE, sep = '\t')
  } else {
    genes = NULL
  }
  #check if SV_AF file exists, if so read
  SV_AF_file = paste0(folder, 'SV_AF.tsv')
  if (file.exists(SV_AF_file)) {
    SV_AF <- read.delim(SV_AF_file, header = TRUE, sep = '\t')
    SV_AF <- split.data.frame(SV_AF, SV_AF$vcf)
    AF_tracks <-
      lapply(SV_AF, function(x)
        get_tracks(x$start, x$end))
  } else {
    SV_AF = NULL
    AF_tracks = NULL
  }
  
  this <- list(
    Genes = genes,
    SV_AF = SV_AF,
    AF_tracks = AF_tracks
  )
  class(this) <- append(class(this), "Annotations")
  return(this)
}

#add a border around a given plot area
add_border <- function(xlims, ylims, lwd = 0.5) {
  rect(xlims[1], ylims[1], xlims[2], ylims[2], lwd = lwd)
}

#horizontal line separator between samples
separator <- function() {
  empty_plot(c(0, 1))
  par(xpd = NA)
  abline(h = 0.5, lwd = 4, col = 'gray25')
  par(xpd = FALSE)
}

#create an empty plot
empty_plot <- function(xlim,ylim = c(0, 1),type = 'n',bty = 'n', xaxt = 'n', yaxt = 'n', ylab = '', xlab = '') {
    plot(1, type = type, ylim = ylim, xlim = xlim, bty = bty, xaxt = xaxt, yaxt = yaxt, ylab = ylab, xlab = xlab)
}

# add axis to a plot
add_position_axis <- function(xlims, side) {
  units <- get_units(xlims[2] - xlims[1])
  empty_plot(xlims / units$val)
  mtext( paste0('Position (', units$sym, ')'), side = side, line = -1, cex = 0.85
  )
  axis(side = side, line = -3)
}

#plot read depth and mapping quality
plot_depth <- function(depth, xlims) {
  par(las = 1)
  bin_size = depth$bin[2] - depth$bin[1]
  ylims = c(0, 1.2 * max(depth$total - depth$mapQ0 - depth$mapQltT, na.rm = TRUE))
  empty_plot(xlims, ylim = ylims)
  title(ylab = 'Depth\n(reads/ bp)', line=2)
  add_border(xlims, ylims)
  #add depth$total depth
  rect(depth$bin, c(0), (depth$bin + bin_size), depth$total, col = '#74C476')
  #add depth$mapQ0 to depth
  rect(depth$bin, depth$total, (depth$bin + bin_size), (depth$total - depth$mapQ0), col = 'white')
  #add depth$mapQltT to depth
  rect(depth$bin, (depth$total - depth$mapQ0), (depth$bin + bin_size), depth$total - (depth$mapQ0 + depth$mapQltT), col = 'khaki1')
  axis(2, tick = TRUE, labels = TRUE, line = -1)
}

# add the legend
add_legend <- function() {
  # create a plot with room for four legends: depth, inserts, mapping stats, svtype/freq
  empty_plot(c(0, 4), ylim = c(0, 1))
  add_border(c(0, 1), c(0, 1))
  add_border(c(1, 2), c(0, 1))
  add_border(c(2, 3), c(0, 1))
  add_border(c(3, 4), c(0, 1))
  par(font = 2)
  text(c(0.5, 1.5, 2.5, 3.5), 1,  pos = 1, labels = c("Read MapQ", "Inferred Insert Size", "Mapping Stats", "SV Allele Frequency"))
  par(font = 1)
  # constants
  bottom = 0.20
  top = bottom + 0.20
  # depth legend
  rect(c((1 / 6 - 0.1), (3 / 6 - 0.1), (5 / 6 - 0.1)), bottom, c((1 / 6 + 0.1), (3 / 6 + 0.1), (5 / 6 + 0.1)), top,  col = c('seagreen3', 'darkolivegreen1', 'gray95'))
  text( c((1 / 6), (3 / 6), (5 / 6)), c(top + 0.1), pos = 3, labels = c(">= 30", "< 30", "= 0") )
  
  # inferred insert size legend
  
  text(1.5, top + 0.25, labels = c("Proportion in position x\nwith mapping distance y"))
  rect(1.15 + 0.7 / 10 * (0:9), bottom, 1.15 + 0.7 / 10 * (1:10), top, col=insert_size_pallete(10)[(1:10)])
  text(c(1.18, 1.82), bottom - 0.08, as.character(c(0, 1)))
  
  # Mapping stats legend 
  text(2.5, top + 0.1, pos = 3, labels = c("proportion of reads in position x"))
  rect(2.15 + 0.7 / 10 * (0:9), bottom, 2.15 + 0.7 / 10 * (1:10), top, col=aln_stats_pallete(10)[(1:10)])
  text(c(2.18, 2.82), bottom - 0.08, as.character(c(0, 1)))
  
  #SV AF legend
  sv_types <- c("DEL", "DUP", "CNV", "INV")
  height = 0.13
  top = bottom + 0.15 * length(sv_types)
  par(family='mono', font = 2)
  for (i in 1:length(sv_types)){
    rect(3.20 + 0.7 / 10 * (0:9), bottom + (i-1) * height, 3.20 + 0.7 / 10 * (1:10), bottom + (i) * height, col=sapply(1:10, function(x) get_sv_col(sv_types[i], x/10)))
    text(3.20, bottom + (i-0.5) * height, sv_types[i], pos=2)
  }
  par(family='sans', font = 1)
  text(c(3.23, 3.87), bottom - 0.08, as.character(c(0, 1)))
}

aln_stats_pallete <- function(n){
  return(colorRampPalette(c("gray95", "#FDAE6B", "#FD8D3C", "#F16913", "#D94801", "#A63603", "#7F2704"))(n))
}
# plot alignment stats
plot_aln_stats <- function(total, numerator, label, split, spacer=2) {
    if (split) {end = length(total)+4*spacer} else { end = length(total)}
    empty_plot(c(0, end))
    par(las = 1)
    mtext(label, side = 2, line = -1,  cex = 0.75)
    #brewer YlGnBu pallete
    if (split){
      rect(spacer:(spacer+split-2), c(0), (spacer+1):(spacer+split-1), c(1), col=aln_stats_pallete(20)[(19 * numerator[1:(split-1)] / total[1:(split-1)]) + 1], border =NA)
      add_border(c(spacer, spacer+split-1), c(0, 1))
      rect((3*spacer+split-1):(3*spacer+length(total)-1), c(0), (3*spacer+split):(3*spacer+length(total)), c(1), col=aln_stats_pallete(20)[(19 * numerator[split:length(total)] / total[split:length(total)]) + 1], border =NA)
      add_border(c(3*spacer+split-1, 3*spacer+length(total)), c(0, 1))
    } else {
      rect(0:(end-1), c(0), 1:end, c(1), col=aln_stats_pallete(20)[(19 * numerator[1:end] / total[1:end]) + 1], border =NA)
      add_border(c(0, end), c(0, 1))
    }
}

#returns a list of the form (1000, "kb")
get_units <- function(num_bp) {
  if (num_bp < 1000) {
    return(list(val = 1, sym = 'bp'))
  } else if (num_bp < 1000000) {
    return(list(val = 1000, sym = 'kbp'))
  } else if (num_bp < 1000000000) {
    return(list(val = 1000000, sym = 'Mbp'))
  } else {
    return(list(val = 1000000000, sym = 'Gbp'))
  }
}

# return the lowest insert size in the highest top 15%
# simple heuristic for avoiding outliers (assumes outliers are less than 15% abundant, and true inserts are at least 15% abundant)
estimate_upper_bound <- function(ins) {
  return(1.1 * sort(ins)[floor(length(ins) * 0.85)])
}

insert_size_pallete <- function(n){
  return(colorRampPalette(c("gray95", "#C6DBEF", "#9ECAE1", "#6BAED6", "#4292C6", "#2171B5", "#08519C", "#08306B"))(n))
}

#plots the inserts in specifiend interval
plot_binned_inserts <- function(binned_inserts, num_y_bins, split, spacer=2){
  if (split) {end = nrow(binned_inserts) + 4*spacer} else {end = nrow(binned_inserts)}
  empty_plot(c(0,end), ylab = '' ,ylim = c(0, num_y_bins + 1))
  if (split){
    for (i in 1:(num_y_bins + 1)) {
      rect(spacer:(spacer+split-2), i - 1, (spacer+1):(spacer+split-1), i, col=insert_size_pallete(25)[24 * binned_inserts[1:(split-1), i] + 1],  border = NA)
      rect((3*spacer+split-1):(3*spacer+nrow(binned_inserts)-1), i - 1, (3*spacer+split):(3*spacer+nrow(binned_inserts)), i, col=insert_size_pallete(25)[24 * binned_inserts[(split:nrow(binned_inserts)), i] + 1],  border = NA)
      add_border(c(spacer, spacer+split-1), c(0, num_y_bins))
      add_border(c(spacer, spacer+split-1), c(num_y_bins, num_y_bins + 1))
      add_border(c(3*spacer+split-1, 3*spacer+nrow(binned_inserts)), c(0, num_y_bins))
      add_border(c(3*spacer+split-1, 3*spacer+nrow(binned_inserts)), c(num_y_bins, num_y_bins + 1))
    }
  } else {
    for (i in 1:(num_y_bins + 1)) {
      rect((1:nrow(binned_inserts))-1, i - 1, (1:nrow(binned_inserts)), i, col=insert_size_pallete(25)[24 * binned_inserts[(1:nrow(binned_inserts)), i] + 1],  border = NA)
      add_border(c(0, end), c(0, num_y_bins))
      add_border(c(0, end), c(num_y_bins, num_y_bins + 1))
    }
  }
}

plot_insert_sizes <- function(fwd_ins, rvs_ins, ylim, split, num_y_bins = 10) {
  #divide into 10 bins spaced equally between 0 and ylim
  ybin_size <- ylim / num_y_bins
  #create an extra bin to store anythin larger than ylim
  fwd_bins <- matrix(nrow = nrow(fwd_ins), ncol = (num_y_bins + 1))
  rvs_bins <- matrix(nrow = nrow(rvs_ins), ncol = (num_y_bins + 1))
  #get counts for each bin
  for (i in 1:num_y_bins) {
    fwd_bins[, i] = sapply(fwd_ins[,2], function(x) sum((((i - 1) * ybin_size)  <= x) & (x < ((i) * ybin_size))))
    rvs_bins[, i] = sapply(rvs_ins[,2], function(x) sum((((i - 1) * ybin_size)  <= x) & (x < ((i) * ybin_size))))
  }
  fwd_bins[, (num_y_bins + 1)] = sapply(fwd_ins[,2], function(x) sum(ylim <= x))
  rvs_bins[, (num_y_bins + 1)] = sapply(rvs_ins[,2], function(x) sum(ylim <= x))
  
  #convert to proportions
  fwd_bins = fwd_bins / rowSums(fwd_bins)
  #fwd_bins[is.nan(fwd_bins)] <- 0
  rvs_bins = rvs_bins / rowSums(rvs_bins)
  #rvs_bins[is.nan(rvs_bins)] <- 0
  
  #organise sensible units for ticks on plot
  units <- get_units(ylim / 2)
  ylim <- ylim / units$val
  mid <- round(ylim / 2)
  interval <- round(mid * 2 / 3)
  ticks_at <- c((mid - interval), mid, (mid + interval))

  #plot binned foward inserts
  par(las = 1)
  plot_binned_inserts(fwd_bins, num_y_bins, split)
  axis(2, at = 10 * ticks_at / ylim,  labels = as.character(ticks_at),  line = -1)
  title(ylab=paste0('forward\ninsert\nlength (', units$sym, ')'), line=2)
  par(xpd = NA)
  text(0, num_y_bins + 0.5, labels =">", cex = 0.85, pos = 2)
  
  #plot binned reverse inserts
  plot_binned_inserts(rvs_bins, num_y_bins, split)
  axis( 2, at = 10 * ticks_at / ylim,  labels = as.character(ticks_at), line = -1)
  title(ylab=paste0('reverse\ninsert\nlength (', units$sym, ')'), line=2)
  text(0, num_y_bins + 0.5, labels =">", cex = 0.85, pos = 2)
  par(xpd = FALSE)
}

plot_svs <- function(svs, xlims, tracks, AF=TRUE) {
  empty_plot(xlims)
  add_border(xlims,c(0,1))
  mtext(svs$vcf, side = 2, line = -1, cex = 0.8)
  if (is.null(svs)) {
    text(0.5 * (xlims[1] + xlims[2]), 0.5, labels = "None")
  }
  #get mapping of svs to tracks to ensure no overlap
  scale = 1 / max(tracks)
  par(las = 1)
  par(font = 2)
  for (i in 1:nrow(svs)) {
    #create a rectange covering each sv call
    #this is fine for DEL/DUP/INV
    #need a different for INS
    #lines(xlims, rep(((tracks[i] - 0.5)*scale), times =2))
    start <- max(xlims[1], svs$start[i])
    end <- min(xlims[2], svs$end[i])
    x_prop <- (end - start) / (xlims[2] - xlims[1])
    bottom <- ((tracks[i] - 1) * scale)
    top <- ((tracks[i]) * scale)
    spacer = 0.1*(top-bottom)
    #outer rect for sv type
    
    #label the sv, if it is of sufficient length to not overlap bounds
    if (!AF){
      rect(start, bottom + spacer, end, top - spacer, col=get_sv_col(svs$svtype[i], 0.8*(0.5*grepl('1', svs$gt[i]) + 0.5*grepl('1/1', svs$gt[i]))), border=get_sv_col(svs$svtype[i], 1), lwd=2)
      if (x_prop > 1/5){
        text(  0.5 * (max(xlims[1], svs$start[i]) + min(xlims[2], svs$end[i])), ((tracks[i] - 0.5) * scale), labels = paste(svs$svtype[i], ':', svs$gt[i], ':', as.character(svs$end[i] - svs$start[i]), 'bp' ))
      } else {
        text(  0.5 * (max(xlims[1], svs$start[i]) + min(xlims[2], svs$end[i])), ((tracks[i] - 0.5) * scale), labels = svs$gt[i])
      }
    } else {
      rect(start, bottom + spacer, end, top - spacer, col=get_sv_col(svs$svtype[i], as.numeric(svs$MAF[i])), border=get_sv_col(svs$svtype[i], 1), lwd=2)
      if (x_prop > 1/5){
        len <- svs$end[i] - svs$start[i]
        units = get_units(len)
        text(0.5 * (start + end), 0.5 * (top + bottom), labels = paste0(svs$svtype[i], ' : AF = ', as.character(round(as.numeric(svs$MAF[i]), digits = 3)), ' : ',as.character(round(len/units$val, digits=2)), " ", units$sym))
      } else if (x_prop > 1/10){
        text(0.5 * (start + end), 0.5 * (top + bottom), labels = paste0('AF = ', as.character(round(as.numeric(svs$MAF[i]), digits = 3))))
      }
    }
  }
  par(font = 1)
}

gt_to_intensity <- function(gt){
  if (grepl("0/1", gt)){
    return(0.3)
  } else if (grepl("0/1", gt)){
    return(1)
  } else {
    return(0)
  }
}
#return a colour for a given SV type
# intensity is a value between 0 and 1, if intensity is zero white is alwaya returned
get_sv_col <- function(type, intensity) {
  if ((is.na(intensity)) | (is.nan(intensity))){
    return('white')
  } else if (intensity == 0){
    return('white')
  } else if ((grepl('DEL', type))) {
      return(colorRampPalette(c("#FFF5F0", "#FEE0D2", "#FCBBA1", "#FC9272", "#FB6A4A", "#EF3B2C", "#CB181D", "#A50F15"))(100)[20 + floor(80 * intensity)])
  } else if ((grepl('DUP', type))) {
      return(colorRampPalette(c("#F7FBFF", "#DEEBF7", "#C6DBEF", "#9ECAE1", "#6BAED6", "#4292C6", "#2171B5", "#08519C"))(100)[20 + floor(80 * intensity)])
  } else if ((grepl('INV', type))) {
      return(colorRampPalette(c("#F7FCF5", "#E5F5E0", "#C7E9C0", "#A1D99B", "#74C476", "#41AB5D", "#238B45", "#006D2C"))(100)[20 + floor(80 * intensity)])
  } else if ((grepl('CNV', type))) {
    return(colorRampPalette(c("#FCFBFD", "#EFEDF5", "#DADAEB", "#BCBDDC", "#9E9AC8", "#807DBA", "#6A51A3", "#54278F"))(100)[20 + floor(80 * intensity)])
  } else {
    return(colorRampPalette(c("#FFFFFF", "#F0F0F0", "#D9D9D9", "#BDBDBD", "#969696", "#737373", "#525252", "#252525"))(100)[20 + floor(80 * intensity)])
  }
}

#plot specified tracks for a given sample
plot_sample <- function(sample, plot_params, ins_ylim) {
  #plot sample title
  empty_plot(sample$Xlims)
  par(font = 2)
  text(sample$Xlims[1], 0.5, paste("Sample:", sample$Name), cex = 1, pos = 4)
  #lines(sample$Xlims, c(1,1))
  par(font = 1)
  #plot sample SVs
  #length(sample$SVs)) --  fix this, returns zero length currently
  par(las=1)
  for (i in 1:length(sample$SVs)) {
    plot_svs(sample$SVs[[i]], sample$Xlims, sample$SVtracks[[i]], AF=FALSE)
  }
  #plot sample depth
  if (plot_params$depth) { plot_depth(sample$Depths, sample$Xlims)}
  # plot zoom details
  if (sample$Split){
    add_zoom_detail(sample$Xlims, sample$Aln_stats$bin[1], sample$Aln_stats$bin[sample$Split-1], sample$Aln_stats$bin[sample$Split], sample$Aln_stats$bin[length(sample$Aln_stats$bin)], length(sample$Aln_stats$bin))
  }
  #plot sample insert sizes
  if (plot_params$ins) {
    plot_insert_sizes(sample$Fwd_ins, sample$Rvs_ins, ins_ylim, sample$Split)
  }
  #plot remaining tracks
  if (plot_params$hardclipped) {
    plot_aln_stats( sample$Aln_stats$reads, sample$Aln_stats$hardclipped, 'hardclipped', sample$Split)
  }
  if (plot_params$secondary) {
    plot_aln_stats( sample$Aln_stats$reads, sample$Aln_stats$secondary, 'secondary', sample$Split)
  }
  if (plot_params$supplementary) {
    plot_aln_stats( sample$Aln_stats$reads, sample$Aln_stats$supplementary, 'supplementary', sample$Split)
  }
  if (plot_params$orphaned) {
    plot_aln_stats( sample$Aln_stats$reads, sample$Aln_stats$orphaned, 'orphaned', sample$Split)
  }
  if (plot_params$inverted) {
    plot_aln_stats( sample$Aln_stats$reads, sample$Aln_stats$inverted, 'inverted', sample$Split)
  }
  if (plot_params$samestrand) {
    plot_aln_stats( sample$Aln_stats$reads, sample$Aln_stats$samestrand, 'samestrand', sample$Split)
  }
  # plot zoom details
  if (sample$Split){
    add_zoom_detail(sample$Xlims, sample$Aln_stats$bin[1], sample$Aln_stats$bin[sample$Split-1], sample$Aln_stats$bin[sample$Split], sample$Aln_stats$bin[length(sample$Aln_stats$bin)], length(sample$Aln_stats$bin), axes=TRUE)
  }
  #add separator
  separator()
}

plot_details <- function(bin_size, num_bins) {
  mtext( paste("Bin size: ", as.character(bin_size), "    Num bins: ", as.character(num_bins), "    Date: ", as.character(Sys.Date()) ), side = 1, line = 0, adj = 0, cex = 0.65 )
}
# graphical representation of linear transformation between depth plot and zoomed in inserts size and aln stats plots
add_zoom_detail <- function(xlims, start_1, end_1, start_2, end_2, num_bins, col='black', spacer=2, axes = FALSE){
  range = xlims[2] - xlims[1]
  zoom_start_1 = xlims[1] + (spacer/(num_bins+4*spacer))*range
  zoom_end_1 = xlims[1] + ((spacer + 0.5*num_bins)/(num_bins+4*spacer))*range
  zoom_start_2 = xlims[1] + ((3*spacer+0.5*num_bins)/(num_bins+4*spacer))*range
  zoom_end_2 = xlims[1] + ((3*spacer+num_bins)/(num_bins+4*spacer))*range
  empty_plot(xlims)
  if (axes){
    # add axes for the zoomed regions
    units <- get_units(end_1-start_1)
    at = (zoom_start_1 + (zoom_end_1-zoom_start_1)*c((1/6),(1/2),(5/6)))
    labels = ((start_1 + (end_1-start_1)*c((1/6),(1/2),(5/6)))/units$val)
    axis(side=1, at=at, labels=paste(as.character(round(labels, digits=1)), units$sym), line=-2)
    at = (zoom_start_2 + (zoom_end_2-zoom_start_2)*c((1/6),(1/2),(5/6)))
    labels = ((start_2 + (end_2-start_2)*c((1/6),(1/2),(5/6)))/units$val)
    axis(side=1, at=at, labels=paste(as.character(round(labels, digits=1)), units$sym),line=-2)
  } else {
    #show the level of zoom
    segments(c(start_1, end_1, start_2, end_2), c(0.7), c(start_1, end_1, start_2, end_2), c(2), col=col, lwd=2)
    segments(c(start_1, end_1, start_2, end_2), c(0.7), c(zoom_start_1, zoom_end_1, zoom_start_2, zoom_end_2), c(0.3), col=col, lwd=2)
    segments(c(zoom_start_1, zoom_end_1, zoom_start_2, zoom_end_2), c(0.3), c(zoom_start_1, zoom_end_1, zoom_start_2, zoom_end_2), c(-1), col=col, lwd=2)
  }
}

#returns an assignment to tracks for a set of regions such that there are no overlaps
get_tracks <- function(starts, ends) {
  #assume that starts and ends are of same length
  #assume also that they are sorted by lowest start first
  tracks <- vector("integer", length = length(starts))
  tracks[1] = 1
  if (length(starts) >= 2) {
    for (i in 2:length(starts)) {
      for (j in 1:i) {
        overlap = FALSE
        if (j %in% tracks) {
          check = which(tracks %in% j)
          for (k in 1:length(check)) {
            if (starts[i] <= ends[check[k]]) {
              overlap = TRUE
              break
            }
          }
        }
        if (!overlap) {
          tracks[i] = j
          break
        }
      }
    }
  }
  return(tracks)
}

plot_refgenes <- function(refgenes, xlims) {
  empty_plot(xlims)
  plot_range <- xlims[2] - xlims[1]
  #mtext("ref genes", side = 2, line = -1, cex = 0.8)
  #if no refgene annotation in region don't plot it
  if (is.null(refgenes)) {
    text(0.5 * (xlims[1] + xlims[2]), 0.5, labels = "None")
  } else {
    #ensure no genes are plotted overlapping by assigning those that do overlap to separate tracks in a greedy fashion
    #since refgenes should already be sorted by start position this is fairly straightforward
    tracks <- 1:nrow(refgenes)
    scale = 1/max(tracks)
    #/max(tracks)
    #nrow(refgenes)
    for (i in 1:(nrow(refgenes))) {
      #plot thin rectangle for whole length of transcript
      plot_start = max(xlims[1], refgenes$txStart[i])
      plot_end = min(xlims[2], refgenes$txEnd[i])
      plot_len = plot_end - plot_start + 1
      total_len = refgenes$txEnd[i] - refgenes$txStart[i] + 1
      fwd = ("+" == as.character(refgenes$strand[i]))
      if (fwd) {dir = '->'} else {dir = '<-'}
      segments(xlims[1], (tracks[i]- 0.5) * scale, xlims[2], (tracks[i]- 0.5) * scale, col='gray50')
      rect(plot_start, ((tracks[i] - 0.8) * scale), plot_end, ((tracks[i]-0.2) * scale), col = '#74C476', border='gray50')
      units <- get_units(plot_len)
      par(font=2)
      #label the gene
      par(xpd=NA)
      text(xlims[1], ((tracks[i]- 0.5) * scale), labels=paste(refgenes$name2[i], dir), pos=2)
      text(xlims[2], ((tracks[i]- 0.5) * scale), labels=paste(as.character(round(100*plot_len/total_len, digits=0)), '%'), pos=4)
      par(xpd=FALSE)
      #get the exon starts and ends
      starts = as.numeric(strsplit(as.character(refgenes$exonStarts[i]), ',')[[1]])
      ends = as.numeric(strsplit(as.character(refgenes$exonEnds[i]), ',')[[1]])
      fwd = ("+" == as.character(refgenes$strand[i]))
      min_exon_label_dist = 0.02 * (xlims[2] - xlims[1])
      last_exon_labelled = NA
      #plot exons
      for (j in 1:length(starts)) {
        #check if exon is within plot limits
        if ((ends[j] < xlims[1]) | (starts[j] > xlims[2])) { next }
        rect(max(xlims[1], starts[j]), ((tracks[i] - 0.925) * scale),  min(xlims[2], ends[j]), ((tracks[i] - 0.075) * scale), col = '#6BAED6', border='gray50')
      }
      for (j in 1:length(starts)) {
        if ((ends[j] < xlims[1]) | (starts[j] > xlims[2])) { next }
        if (fwd) {num = j} else {num = length(starts) - j + 1}
        label_pos = 0.5 * (max(xlims[1], starts[j]) + min(xlims[2], ends[j]))
        # ensure enought distance between exon labels and gene name label before annotating
        if (is.na(last_exon_labelled) | (label_pos - last_exon_labelled) > min_exon_label_dist){
          text(0.5 * (max(xlims[1], starts[j]) + min(xlims[2], ends[j])), ((tracks[i]-0.5) * scale), labels = as.character(num))
          last_exon_labelled = label_pos
        }
      }
    }
    par(font=1)
    }
  }

get_plot_layout <- function(plot_params, annotations, num_samples, vcfs_per_sample, split, max=200) {
    #note: order of plots to be as implied here
    # top x-axis
    heights <- c(3)
    #title
    heights <- c(heights,1)
    # separator
    heights <- c(heights, 1)
    for (i in 1:num_samples){
      # sample title
      heights <- c(heights, 1.5)
      #add in vcf plots
      for (j in 1:length(vcfs_per_sample[[i]])){
        heights <- c(heights, 1.5*vcfs_per_sample[[i]][j])
      }
      # depth
      if (plot_params$depth) { heights <- c(heights, 7) }
      # breakpoint zoom illustration
      if (split){ heights <- c(heights, 2) }
      # add tracks according to plot params
      if (plot_params$ins) { heights <- c(heights, 4, 4)  }
      if (plot_params$hardclipped) {  heights <- c(heights, 1) }
      if (plot_params$secondary) { heights <- c(heights, 1) }
      if (plot_params$supplementary) { heights <- c(heights, 1) }
      if (plot_params$orphaned) { heights <- c(heights, 1) }
      if (plot_params$inverted) { heights <- c(heights, 1) }
      if (plot_params$samestrand) { heights <- c(heights, 1) }
      #breakpoint zoom axes
      if (split){ heights <- c(heights, 2) }
      # separator
      heights <- c(heights, 1)
    }
    #add in heights for SV_AF tracks
    if (plot_params$svMAF) {
      for (i in 1:length(annotations$SV_AF)) {
        heights <- c(heights, 1.5*max(annotations$AF_tracks[[i]]))
      }
    }
    #add in heights for refGene annotation tracks
    if (plot_params$refgene) {
      if (!is.null(annotations$Genes)) {
        heights <- c(heights, 1*nrow(annotations$Genes))
      } else {
        heights <- c(heights, 1)
      }
    }
    #add in bottom x-axis
    heights <- c(heights, 3)
    #add room for legend
    if (plot_params$legend) {
      heights <- c(heights, 6)
    }
    return(heights)
}

#main method
visualise <- function(folder, sample_names, args, outfile, title='') {
  num_samples <- length(sample_names)
  samples <-  lapply(sample_names, function(x) Sample(folder, x))
  vcfs_per_sample <- lapply(samples, function(x) sapply(x$SVtracks, function(y) max(y)))
  xlims <- samples[[1]]$Xlims
  Ins_ylim <- max(sapply(samples, function(x) x$Ins_ylim))
  annotations <- Annotations(folder)
  plot_params <- PlotParams(args)
  heights <- get_plot_layout(plot_params, annotations, num_samples, vcfs_per_sample, samples[[1]]$Split)
  pdf(outfile, title='SVPV Graphics Output', width = 8, height = 0.15* sum(heights), bg = 'white')
  #initialise first layout
  layout(matrix(1:length(heights), length(heights), 1, byrow = TRUE), heights=heights)
  par(mar = c(0.1, 6, 0.1, 2), oma = c(1, 0.1, 0.1, 0.1))
  #plot top x-axis
  add_position_axis(xlims, 3)
  #plot title
  empty_plot(c(0,1))
  par(font = 2)
  text(0.5, 0.5, title, cex = 1.25)
  par(font = 1)
  separator()
  #plot samples
  for (i in 1:num_samples) {
    plot_sample(samples[[i]], plot_params, Ins_ylim)
  }
  #add in heights for SVMAF tracks
  if (plot_params$svMAF) {
    for (i in 1:length(annotations$SV_AF)) {
      plot_svs(annotations$SV_AF[[i]], xlims, annotations$AF_tracks[[i]])
    }
  }
  #add in heights for refGene annotation tracks
  if (plot_params$refgene) {  plot_refgenes(annotations$Genes, xlims) }
  #plot bottom x-axis
  add_position_axis(xlims, 1)
  #add legend
  if (plot_params$legend) { add_legend() }
  #add details
  plot_details(samples[[1]]$Bin_size, samples[[1]]$Num_bins)
  graphics.off()
}
#read command-line arguments
args <- commandArgs(trailingOnly = TRUE)
#args <- c("1725,1726,1815","/home/jem/DEL/chr1_212297813-212299274/","/home/jem/DEL/chr1_212297813-212299274/ex.pdf", "-d", "-ss", "-v", "-su", "-b", "-i", "-r", "-m")
sample_names <- strsplit(as.character(args[1]), ',')[[1]]
folder <- args[2]
outfile <- args[3]
title <- args[4]
visualise(folder, sample_names, args[5:length(args)], outfile, title)
tanimoto <- function(resource_x, resource_y) {
  # The Tanimoto similarity computes the sum of shared elements in vectors resource_x and resource_y and divides this by the length of the longest vector
  # If either length of resource_x or resource_y == 0, similarity == 0
  # The order of vectors consumer_x or consumer_y has no importance, as long as elements in vectors are unique

  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  # The same funcion is apparently used for trait similarity, including phylogeny
  # !!! There are NAs in the taxonomy that need to be taken into account, which is not the case at the moment !!!
  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    if(length(resource_x) == 0 || length(resource_y) == 0) {
        return(0.0)
    } else if(resource_x == "" || resource_y == "") {
        return(0.0)
    } else {
        inter <- sum(resource_x %in% resource_y)
        return(inter / ((length(resource_x) + length(resource_y)) - inter))
    }#if
}#end tanimoto function
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        settings = NULL,
        initialize = function(dir = ".", settings = SlurmSettings$new()) {
            self$settings <- settings

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
                script <- SlurmBashScript$new(dir, self$settings)
            }
        },
        save_objects = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
tanimoto <- function(resource_x, resource_y) {
  # The Tanimoto similarity computes the sum of shared elements in vectors resource_x and resource_y and divides this by the length of the longest vector
  # If either length of resource_x or resource_y == 0, similarity == 0
  # The order of vectors consumer_x or consumer_y has no importance, as long as elements in vectors are unique

  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  # The same funcion is apparently used for trait similarity, including phylogeny
  # !!! There are NAs in the taxonomy that need to be taken into account, which is not the case at the moment !!!
  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    if(length(resource_x) == 0 || length(resource_y) == 0) {
        return(0.0)
    } else if(resource_x == "" || resource_y == "") {
        return(0.0)
    } else {
        return(sum(resource_x %in% resource_y) / length(unique(c(resource_x, resource_y))))
    }#if
}#end tanimoto function
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        settings = NULL,
        initialize = function(dir = ".", settings = SlurmSettings$new()) {
            self$settings <- settings

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }

            script <- SlurmBashScript$new(container$dir, self$settings)
        },
        save_objects = function() {
            private$clean_object_files()

            for (name in names(self$globals)) {
                private$add_object(name, self$globals[[name]])
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container_dir, settings) {
            private$settings <- settings

            private$cat_main_file_magic(container_dir)
            private$write_slurm_script(container_dir)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir) {
            main_file <- ".default_stain_main.R"
            file <- paste(dir, ".stain/sources", main_file, sep = "/")
            sourcing <- paste("sapply(list.files('./.stain/sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", main_file, "'"), "], source)")
            loading <- paste("sapply(list.files('./.stain/objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./.stain $PFSDIR
cd $PFSDIR

mkdir .data
mv ./.stain/data/* ./.data

module load hpc-ods
module load pandoc

R CMD BATCH ./.stain/sources/.default_stain_main.R

cp -r * $SLURM_SUBMIT_DIR/output"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, "submit.slurm", sep = "/"))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        settings = NULL,
        initialize = function(dir = ".", settings = SlurmSettings$new()) {
            self$settings <- settings

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }

            script <- SlurmBashScript$new(container$dir, self$settings)
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && (name %in% names(globals) || length(globals) == 0)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, settings) {
            private$settings <- settings

            private$cat_main_file_magic(container$dir)
            private$write_slurm_script(container$dir)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir) {
            main_file <- ".default_stain_main.R"
            file <- paste(dir, ".stain/sources", main_file, sep = "/")
            sourcing <- paste("sapply(list.files('./.stain/sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", main_file, "'"), "], source)")
            loading <- paste("sapply(list.files('./.stain/objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./.stain $PFSDIR
cd $PFSDIR

mkdir .data
mv ./.stain/data/* ./.data

module load hpc-ods
module load pandoc

R CMD BATCH ./.stain/sources/.default_stain_main.R

cp -r * $SLURM_SUBMIT_DIR/output"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, "submit.slurm", sep = "/"))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                self$dir <- dir
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")
                self$dir <- dir

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && name %in% names(globals)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain && dir.exists(stain_dir)) {
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }

            self$dir <- dir
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        delete = function(confirmation = FALSE) {
            if (confirmation) {
                system(paste("rm -rf", self$dir))
            } else {
                warning("Container not deleted becaue TRUE must be passed to `delete`.")
            }
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, paste(dir, basename(file), sep = "/"), overwrite = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && name %in% names(globals)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, settings) {
            private$settings <- settings

            main_file <- paste0("cp_of_", main_file)

            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir, main_file) {
            main_file <- paste0(".default_stain_main.R")
            file <- paste(dir, ".stain/sources", main_file, sep = "/")
            sourcing <- paste("sapply(list.files('./.stain/sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", main_file, "'"), "], source)")
            loading <- paste("sapply(list.files('./.stain/objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./.stain $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

R CMD BATCH ./.stain/sources/.default_stain_main.R

cp -r * $SLURM_SUBMIT_DIR/output"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, "submit.slurm", sep = "/"))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, settings) {
            private$settings <- settings

            main_file <- paste0("cp_of_", main_file)

            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir, main_file) {
            main_file <- paste0("cp_of_", basename(main_file))
            file <- paste(dir, ".stain/sources", main_file, sep = "/")
            sourcing <- paste("sapply(list.files('./.stain/sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", main_file, "'"), "], source)")
            loading <- paste("sapply(list.files('./.stain/objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./.stain $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

main_file=$(basename $1)

R CMD BATCH ./.stain/sources/$main_file

cp -r * $SLURM_SUBMIT_DIR/output"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
library(ggplot2)
df <- read.csv('sueldos.sysarmy.csv')

rename <- function(df, old, wants) {
  names(df)[names(df)==old] <- wants
  return(df)
}

tukey <- function(data) {
  iqr <- IQR(data$Income)
  firstQ <- quantile(data$Income)[2]
  thirdQ <- quantile(data$Income)[4]
  low <- firstQ - (iqr * 1.5)
  high <- thirdQ + (iqr * 1.5)
  data <- subset(data, Income < high)
  data <- subset(data, Income > low)
  return(data)
}

cleanup <- function(data, handleOutliers) {
  # clean gender.
  data$Gender = ifelse(data$Soy == "Hombre", "M", "F")
  data$Gender = as.factor(data$Gender)

  # rename columns.
  data <- rename(data, "Tengo", "Age")
  data <- rename(data, "Argentina", "Region")
  data <- rename(data, "A..os.de.experiencia", "YearsExperience")
  data <- rename(data, "A..os.en.el.puesto.actual", "YearsCurrentJob")
  data <- rename(data, "Trabajo.de", "JobDescription")
  data <- rename(data, "Tipo.de.contrato", "JobType")
  data <- rename(data, "Qu...tan.conforme.est..s.con.tu.sueldo.", "Happiness")
  data <- rename(data, "Cambiaste.de.empresa.en.los...ltimos.6.meses.", "SwitchedJobsLast6Months")

  # fix region names.
  levels(data$Region)[levels(data$Region) == "Entre R\303\255os"] <- "Entre Rios"
  levels(data$Region)[levels(data$Region) == "Ciudad Aut\303\263noma de Buenos Aires"] <- "CABA"
  levels(data$Region)[levels(data$Region) == "C\303\263rdoba"] <- "Cordoba"
  levels(data$Region)[levels(data$Region) == "Neuqu\303\251n"] <- "Neuquen"
  levels(data$Region)[levels(data$Region) == "R\303\255o Negro"] <- "Rio Negro"
  levels(data$Region)[levels(data$Region) == "Tucum\303\241n"] <- "Tucuman"
  levels(data$Region)[levels(data$Region) == "Provincia de Buenos Aires"] <- "GBA"
  
  # fix age.
  levels(data$Age)[levels(data$Age) == "Menos de 18 a\303\261os"] <- "18-"

  # fix salary.
  data <- rename(data, "Salario.mensual..en.tu.moneda.local.", "Income")
  data$Income <- ifelse(data$Bruto.o.neto. == "Bruto", data$Income, data$Income/0.70)
  data$Bruto.o.neto. = NULL
  
  # fix job switch.
  data$SwitchedJobsLast6Months = ifelse(data$SwitchedJobsLast6Months == "No", 0, 1)

  # remove ficticious data.
  data <- subset(data, Income < 200000)
  data <- subset(data, Income > 1000)
  
  # handle outliers.
  data <- handleOutliers(data)
  
  keep <- c("Age", "Region", "YearsExperience", "YearsCurrentJob", "JobDescription",
            "JobType", "Happiness", "Income", "Gender", "SwitchedJobsLast6Months")
  return(data[keep])
}

all.salaries.hist <- function(df) {
  plot <- ggplot(df, aes(x=Income), ylab="") + 
    geom_histogram(binwidth = 1000, fill="#3399FF", alpha=0.9)
  return(plot)
}

all.salaries.hist.median <- function(df) {
  plot <- all.salaries.hist(df) + 
    geom_vline(aes(xintercept = mean(Income)), linetype="longdash", color="red")
  return(plot)
}

all.salaries.gender <- function(df) {
  plot <- ggplot(df, aes(x=Income, fill=Gender), ylab="") + 
    geom_histogram(binwidth = 1000, alpha=0.9)
  return(plot)
}

color.outliers <- function(df) {
  iqr <- IQR(df$Income)
  firstQ <- quantile(df$Income)[2]
  thirdQ <- quantile(df$Income)[4]
  low <- firstQ - (iqr * 1.5)
  high <- thirdQ + (iqr * 1.5)
  df$OutlierTag = "Middle"
  df$OutlierTag[df$Income <= low] = "LowOutliers"
  df$OutlierTag[df$Income >= high] = "HighOutliers"
  plot <- ggplot(df, aes(x=Income, fill=OutlierTag)) +
      geom_histogram(binwidth = 1000) +
      geom_vline(aes(xintercept = high), linetype="longdash", color="red")
  return(plot)
}

clean <- cleanup(df, handleOutliers = identity)
write.csv(clean, 'clean.csv', row.names=FALSE)

default.plot <- color.outliers
default.plot(clean)
#' Find unassigned global variables.
#'
#' This funciton sources files and loads objects into an environment
#' and then runs \code{codetools::findGlobals} on the environment.
#'
#' NOTE: Globals are determined for the \code{main()} function only!
#'
#' @param source_files R files containing globals to exclude such as
#' function declarations.
#'
#' @param object_files Rdata files that contain globals to exclude.
#'
#' @return A list of globals without assignments.
find_globals = function(source_files, object_files = c()) {
    e <- new.env()

    for (file in source_files) {
        testthat::source_file(file, e)
    }

    for (object_file in object_files) {
        load(object_file, envir = e)
    }

    globals <- list()

    tryCatch({
        globals <- codetools::findGlobals(e$main)
    }, error = function(e) {
        return(globals)
    })

    # Filter known `findGlobals` errors
    known_errors <- c("{", "}", "::")
    globals <- globals[!(globals %in% known_errors)]

    # Filter all functions in loaded packages
    for (package in (.packages())) {
        package <- paste0("package:", package)
        exports <- names(as.list(as.environment(package)))
        globals <- globals[!(globals %in% exports)]
    }

    # Filter functions and variables in source files
    globals <- globals[!(globals %in% names(as.list(e)))]

    nglobals <- length(globals)

    if (nglobals > 0) {
        if (nglobals == 1) {
            vars <- "var"
            t_vars <- "this var"
        } else {
            vars <- "vars"
            t_vars <- "these vars"
        }

        cat(paste("Found", nglobals, vars, "to specify:"))
        for (global in globals) {
            cat(paste("\n    -", global))
        }

        cat(paste("\n\nSet", t_vars, "in the `params` property of your `SlurmJob` instance."))
    }

    # Set the values of all gobals to NA
    global_list <- list()

    for (global in globals) {
        global_list[[global]] <- NA
    }

    return(global_list)
}
#' SlurmJob R6 object.
#'
#' A wrapper around SlurmContainer objects.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        data_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".",
                              source_files = list(),
                              settings = SlurmSettings$new()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                globals <- find_globals(c(main_file, source_files))
                self$params <- globals
                private$globals <- globals
                private$settings <- settings
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function(allow_creation_without_data_files = FALSE) {

            if (!allow_creation_without_data_files && length(self$data_files) == 0) {
                stop("Attempting to create slurm job without `data_files`. Pass TRUE to `create` to override.")
            }

            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in c(self$source_files, self$main_file)) {
                    container$add_source(file)
                }

                for (file in self$data_files) {
                    container$add_data(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })

            script <- SlurmBashScript$new(container, self$main_file, private$settings)
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        settings = NA
    )
)


#' Submit one or more slurm jobs.
#'
#' This function will submit your slurm job given the path
#' to a slurm container.
#'
#' @param jobs The \code{job_<alphanumeric>/} directories for
#' the slurm container. May also
#'
#' @export
submit_jobs <- function(jobs) {
    wd <- getwd()

    for (dir in jobs) {
        tryCatch({
            setwd(dir)
            system("sh submit.sh")
        }, error = function(e) {
            setwd(wd)
            stop(e)
        })

    }

    setwd(wd)
}


#' Find unassigned global variables.
#'
#' This funciton sources files and loads objects into an environment
#' and then runs \code{codetools::findGlobals} on the environment.
#'
#' NOTE: Globals are determined for the \code{main()} function only!
#'
#' @param source_files R files containing globals to exclude such as
#' function declarations.
#'
#' @param object_files Rdata files that contain globals to exclude.
#'
#' @return A list of globals without assignments.
find_globals = function(source_files, object_files = c()) {
    e <- new.env()

    for (file in source_files) {
        testthat::source_file(file, e)
    }

    for (object_file in object_files) {
        load(object_file, envir = e)
    }

    globals <- codetools::findGlobals(e$main)

    # Filter known `findGlobals` errors
    known_errors <- c("{", "}", "::")
    globals <- globals[!(globals %in% known_errors)]

    # Filter all functions in loaded packages
    for (package in (.packages())) {
        package <- paste0("package:", package)
        exports <- names(as.list(as.environment(package)))
        globals <- globals[!(globals %in% exports)]
    }

    # Filter functions and variables in source files
    globals <- globals[!(globals %in% names(as.list(e)))]

    nglobals <- length(globals)

    if (nglobals > 0) {
        if (nglobals == 1) {
            vars <- "var"
            t_vars <- "this var"
        } else {
            vars <- "vars"
            t_vars <- "these vars"
        }

        cat(paste("Found", nglobals, vars, "to specify:"))
        for (global in globals) {
            cat(paste("\n    -", global))
        }

        cat(paste("\n\nSet", t_vars, "in the `params` property of your `SlurmJob` instance."))
    }

    # Set the values of all gobals to NA
    global_list <- list()

    for (global in globals) {
        global_list[[global]] <- NA
    }

    return(global_list)
}
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            self$dir <- dir

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            if (!dir.exists(stain_dir)) {
                return()
            }

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain) {
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }

            private$update_globals()
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, dir, recursive = TRUE)
            }

            private$update_globals()
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }

            private$update_globals()
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && name %in% names(globals)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            self$dir <- dir

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            if (!dir.exists(stain_dir)) {
                return()
            }

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain) {
                private$load_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, dir, recursive = TRUE)
            }
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        load_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            # Check for the globals in the object files
            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e) && name %in% names(globals)) {
                    globals[[name]] <- e[[name]]
                }
            }

            # Copy over existing global values
            for (name in names(self$globals)) {
                if (name %in% names(globals)) {
                    globals[[name]] <- self$globals[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            self$dir <- dir

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            if (!dir.exists(stain_dir)) {
                return()
            }

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain) {
                private$load_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, dir, recursive = TRUE)
            }
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }
        },
        clean_object_files = function() {
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            for (object_file in object_files) {
                file.remove(object_file)
            }
        },
        load_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e)) {
                    globals[[name]] <- e[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            self$dir <- dir

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            if (!dir.exists(stain_dir)) {
                return()
            }

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (is_stain) {
                private$update_globals()
            } else {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, dir, recursive = TRUE)
            }
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }
        },
        update_globals = function() {
            source_files <- list.files(paste0(self$dir, ".stain/sources"), full.names = TRUE)
            object_files <- list.files(paste0(self$dir, ".stain/objects"), full.names = TRUE)

            globals <- find_globals(source_files)

            e <- new.env()
            for (object_file in object_files) {
                load(object_file, envir = e)
                name <- strsplit(basename(object_file), "[.]")[[1]][1]
                if (name %in% names(e)) {
                    globals[[name]] <- e[[name]]
                }
            }

            self$globals <- globals
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        globals = list(),
        initialize = function(dir = ".") {
            self$dir <- dir

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            if (!dir.exists(stain_dir)) {
                return()
            }

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (!is_stain) {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_objects = function(names) {
            private$remove_files(paste0(names, ".RData"), "objects")
        },
        add_sources = function(files) {
            private$add_files(files, "sources")
        },
        remove_sources = function(basenames) {
            private$remove_files(basenames, "sources")
        },
        add_data = function(files) {
            private$add_files(files, "data")
        },
        remove_data = function(basenames) {
            private$remove_files(basenames, "data")
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_files = function(files, stain_sub_dir) {
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")

            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Copy aborted.") }
            }

            for (file in files) {
                file.copy(file, dir, recursive = TRUE)
            }
        },
        remove_files = function(files, stain_sub_dir) {
            for (file in files) {
                if (!file.exists(file)) { stop("File does not exist. Removal aborted.") }
            }

            for (file in files) {
                file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
                file.remove(file)
            }
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' Find unassigned global variables.
#'
#' This funciton sources files and loads objects into an environment
#' and then runs \code{codetools::findGlobals} on the environment.
#'
#' @param source_files R files containing globals to exclude such as
#' function declarations.
#'
#' @param object_files Rdata files that contain globals to exclude.
#'
#' @return A list of globals without assignments.
find_globals = function(source_files, object_files = c()) {
    e <- new.env()

    for (file in source_files) {
        testthat::source_file(file, e)
    }

    for (object_file in object_files) {
        load(object_file, envir = e)
    }

    globals <- codetools::findGlobals(e$main)

    # Filter known `findGlobals` errors
    known_errors <- c("{", "}", "::")
    globals <- globals[!(globals %in% known_errors)]

    # Filter all functions in loaded packages
    for (package in (.packages())) {
        package <- paste0("package:", package)
        exports <- names(as.list(as.environment(package)))
        globals <- globals[!(globals %in% exports)]
    }

    # Filter functions and variables in source files
    globals <- globals[!(globals %in% names(as.list(e)))]

    nglobals <- length(globals)

    if (nglobals > 0) {
        if (nglobals == 1) {
            vars <- "var"
            t_vars <- "this var"
        } else {
            vars <- "vars"
            t_vars <- "these vars"
        }

        cat(paste("Found", nglobals, vars, "to specify:"))
        for (global in globals) {
            cat(paste("\n    -", global))
        }

        cat(paste("\n\nSet", t_vars, "in the `params` property of your `SlurmJob` instance."))
    }

    # Set the values of all gobals to NA
    global_list <- list()

    for (global in globals) {
        global_list[[global]] <- NA
    }

    return(global_list)
}
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            self$dir <- dir

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            if (!dir.exists(stain_dir)) {
                return()
            }

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (!is_stain) {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_object = function(name) {
            private$remove_file(paste0(name, ".RData"), "objects")
        },
        add_source = function(file) {
            private$add_file(file, "sources")
        },
        remove_source = function(basename) {
            private$remove_file(file, "sources")
        },
        add_data = function(file) {
            private$add_file(file, "data")
        },
        remove_data = function(basename) {
            private$remove_file(file, "data")
        },
        get_files = function() {
            return(list(
                data = list.files(paste(self$dir, ".stain", "data", sep = "/")),
                objects = list.files(paste(self$dir, ".stain", "objects", sep = "/")),
                sources = list.files(paste(self$dir, ".stain", "sources", sep = "/"))
            ))
        }
    ),
    private = list(
        add_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")
            file.copy(file, dir, recursive = TRUE)
        },
        remove_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
            file.remove(file)
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            self$dir <- dir

            sub_dirs <- c("data", "sources", "objects")
            stain_dir <- paste0(dir, ".stain")

            if (!dir.exists(stain_dir)) {
                return()
            }

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(stain_dir), basename))
            if (!is_stain) {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_object = function(name) {
            private$remove_file(paste0(name, ".RData"), "objects")
        },
        add_source = function(file) {
            private$add_file(file, "sources")
        },
        remove_source = function(basename) {
            private$remove_file(file, "sources")
        },
        add_data = function(file) {
            private$add_file(file, "data")
        },
        remove_data = function(basename) {
            private$remove_file(file, "data")
        }
    ),
    private = list(
        add_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")
            file.copy(file, dir, recursive = TRUE)
        },
        remove_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
            file.remove(file)
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            sub_dirs <- c("data", "sources", "objects")

            is_stain <- Reduce("&", sub_dirs %in% sapply(list.dirs(paste0(dir, ".stain")), basename))
            if (!is_stain) {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste(dir, ".stain", sub_dir, sep = "/"),
                               recursive = TRUE, showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }

            self$dir <- dir
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_object = function(name) {
            private$remove_file(paste0(name, ".RData"), "objects")
        },
        add_source = function(file) {
            private$add_file(file, "sources")
        },
        remove_source = function(basename) {
            private$remove_file(file, "sources")
        },
        add_data = function(file) {
            private$add_file(file, "data")
        },
        remove_data = function(basename) {
            private$remove_file(file, "data")
        }
    ),
    private = list(
        add_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")
            file.copy(file, dir, recursive = TRUE)
        },
        remove_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
            file.remove(file)
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            sub_dirs <- c("/data", "/sources", "/objects")

            is_stain <- Reduce("&", sub_dirs %in% list.dirs(dir))
            if (!is_stain) {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste0(dir, "/.stain", sub_dir), recursive = TRUE,
                               showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }

            self$dir <- dir
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        remove_object = function(name) {
            private$remove_file(paste0(name, ".RData"), "objects")
        },
        add_source = function(file) {
            private$add_file(file, "sources")
        },
        remove_source = function(basename) {
            private$remove_file(file, "sources")
        },
        add_data = function(file) {
            private$add_file(file, "data")
        },
        remove_data = function(basename) {
            private$remove_file(file, "data")
        }
    ),
    private = list(
        add_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            dir <- paste(self$dir, ".stain", stain_sub_dir, sep = "/")
            file.copy(file, dir, recursive = TRUE)
        },
        remove_file = function(file, stain_sub_dir) {
            if (!file.exists(file)) { stop("File does not exist.") }
            file <- paste(self$dir, ".stain", stain_sub_dir, file, sep = "/")
            file.remove(file)
        },
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            sub_dirs <- c("/data", "/sources", "/objects")

            is_stain <- Reduce("&", sub_dirs %in% list.dirs(dir))
            if (!is_stain) {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste0(dir, "/.stain", sub_dir), recursive = TRUE,
                               showWarnings = FALSE)
                }

                dir.create(paste0(dir, "/output"), recursive = TRUE,
                            showWarnings = FALSE)
            }

            self$dir <- dir
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        add_source = function(file) {
            if (file.exists(file)) {
                source_dir <- paste0(self$dir, "/.stain/sources")
                destination <- paste0(source_dir, paste0("/cp_of_", basename(file)))
                system(paste("cp -r", file, destination))
            } else {
                stop("Source file does not exist.")
            }
        },
        add_data = function(file) {
            if (file.exists(file)) {
                data_dir <- paste0(self$dir, "/.stain/data")
                destination <- paste0(data, paste0("/cp_of_", basename(file)))
                system(paste("cp -r", file, destination))
            } else {
                stop("Source file does not exist.")
            }
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            sub_dirs <- c("/data", "/output", "/sources", "/objects")

            is_stain <- Reduce("&", sub_dirs %in% list.dirs(dir))
            if (!is_stain) {
                name <- paste0("job_", private$rand_alphanumeric())
                dir <- paste(getwd(), dir, name, sep = "/")

                for (sub_dir in sub_dirs) {
                    dir.create(paste0(dir, "/.stain", sub_dir), recursive = TRUE,
                               showWarnings = FALSE)
                }
            }

            self$dir <- dir
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.stain/objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        add_source = function(file) {
            if (file.exists(file)) {
                source_dir <- paste0(self$dir, "/.stain/sources")
                destination <- paste0(source_dir, paste0("/cp_of_", basename(file)))
                system(paste("cp -r", file, destination))
            } else {
                stop("Source file does not exist.")
            }
        },
        add_data = function(file) {
            if (file.exists(file)) {
                data_dir <- paste0(self$dir, "/.stain/data")
                destination <- paste0(data, paste0("/cp_of_", basename(file)))
                system(paste("cp -r", file, destination))
            } else {
                stop("Source file does not exist.")
            }
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            name <- paste0("job_", private$rand_alphanumeric())
            dir <- paste(getwd(), dir, name, sep = "/")
            self$dir <- dir

            for (sub_dir in c("/input", "/output", "/sources", "/.objects")) {
                dir.create(paste0(dir, sub_dir), recursive = TRUE,
                           showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (length(value) > 1) {
                is_na <- FALSE
            } else {
                is_na <- is.na(value)
            }

            if (!is_na) {
                obj_dir <- paste0(self$dir, "/.objects")
                rdata <- paste0(name, ".Rdata")
                e <- new.env()
                e[[name]] <- value
                save(list = name, envir = e, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        add_source = function(file) {
            if (file.exists(file)) {
                source_dir <- paste0(self$dir, "/sources")
                destination <- paste0(source_dir, paste0("/cp_of_", basename(file)))
                system(paste("cp -r", file, destination))
            } else {
                stop("Source file does not exist.")
            }
        },
        add_input = function(file) {
            if (file.exists(file)) {
                input_dir <- paste0(self$dir, "/input")
                destination <- paste0(input_dir, paste0("/cp_of_", basename(file)))
                system(paste("cp -r", file, destination))
            } else {
                stop("Source file does not exist.")
            }
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
REBOL [
	System: "REBOL [R3] Language Interpreter and Run-time Environment"
	Title: "Make the R3 Core Makefile"
	Rights: {
		Copyright 2012 REBOL Technologies
		REBOL is a trademark of REBOL Technologies
	}
	License: {
		Licensed under the Apache License, Version 2.0
		See: http://www.apache.org/licenses/LICENSE-2.0
	}
	Author: "Carl Sassenrath"
	Purpose: {
		Build a new makefile for a given platform.
	}
	Note: [
		"This runs relative to ../tools directory."
		"Make OS-specific changes to the systems.r file."
	]
]

path-host:   %../os/
path-make:   %../../make/
path-incl:   %../../src/include/

;******************************************************************************

; (Warning: format is a bit sensitive to extra spacing. E.g. see macro+ func)

makefile-head:

{# REBOL Makefile -- Generated by make-make.r (!!! EDITS WILL BE LOST !!!)
# This automatically produced file was created !date

# This makefile is intentionally kept simple to make builds possible on
# a wide range of target platforms.  While this generated file has several
# capabilities, it is not tracked by version control.  So to kick off the
# process you need to use the tracked bootstrap makefile:
#
#	make -f makefile.boot
#
# See the comments in %makefile.boot for more information on the workings of
# %make-make.r and what the version numbers mean.  This generated file is a
# superset of the functionality in %makefile.boot, however.  So you can
# retarget simply by typing:
#
#    make make OS_ID=0.4.3
#
# To cross-compile using a different toolchain and include files:
#
#    $TOOLS - should point to bin where gcc is found
#    $INCL  - should point to the dir for includes
#
# Example make:
#
#    make TOOLS=~/amiga/amiga/bin/ppc-amigaos- INCL=/SDK/newlib/include
#
# !!! Efforts to be able to have Rebol build itself in absence of a make
# tool are being considered.  Please come chime in on chat if you are
# interested in that and other projects, or need support while building:
#
#	http://rebolsource.net/go/chat-faq
#

# For the build toolchain:
CC=	$(TOOLS)gcc
NM=	$(TOOLS)nm
STRIP=	$(TOOLS)strip

# CP allows different copy progs:
CP=
# LS allows different ls progs:
LS=
# UP - some systems do not use ../
UP=
# CD - some systems do not use ./
CD=
# Special tools:
T= $(UP)/src/tools
# Paths used by make:
S= ../src
R= $S/core

INCL ?= .
I= -I$(INCL) -I$S/include/ -I$S/codecs/

TO_OS_BASE?=
TO_OS_NAME?=
OS_ID?=
BIN_SUFFIX=
RAPI_FLAGS=
HOST_FLAGS=	-DREB_EXE
RLIB_FLAGS=

# Flags for core and for host:
RFLAGS= -c -D$(TO_OS_BASE) -D$(TO_OS_NAME) -DREB_API  $(RAPI_FLAGS) $I
HFLAGS= -c -D$(TO_OS_BASE) -D$(TO_OS_NAME) -DREB_CORE $(HOST_FLAGS) $I
CLIB=

# REBOL is needed to build various include files:
REBOL_TOOL= r3-make$(BIN_SUFFIX)
REBOL= $(CD)$(REBOL_TOOL) -qs

# For running tests, ship, build, etc.
R3_TARGET= r3$(BIN_SUFFIX)
R3= $(CD)$(R3_TARGET) -qs

### Build targets:
top:
	$(MAKE) $(R3_TARGET)

update:
	-cd $(UP)/; cvs -q update src

# Uses "phony target" %make that should never be the name of a file in
# this directory, hence, it will always regenerate if the make target
# is requested.  Note: Cannot call it %makefile without winding up
# running make-make.r four extra times:
#
#     http://stackoverflow.com/questions/31490689/
#
# Consider being able to continue to type `make make` instead of having
# to re-run the line including `makefile.boot` to be a special
# undocumented feature, as people are used to it...but it might go away
# someday.  Maybe.

make: $(REBOL_TOOL)
	$(REBOL) $T/make-make.r $(OS_ID)

clean:
	@-rm -rf $(R3_TARGET) libr3.so objs/

all:
	$(MAKE) clean
	$(MAKE) prep
	$(MAKE) $(R3_TARGET)
	$(MAKE) lib
	$(MAKE) host$(BIN_SUFFIX)

prep: $(REBOL_TOOL)
	$(REBOL) $T/make-natives.r
	$(REBOL) $T/make-headers.r
	$(REBOL) $T/make-boot.r $(OS_ID)
	$(REBOL) $T/make-host-init.r
	$(REBOL) $T/make-os-ext.r
	$(REBOL) $T/core-ext.r
	$(REBOL) $T/make-host-ext.r
	$(REBOL) $T/make-reb-lib.r

zlib:
	$(REBOL) $T/make-zlib.r	

### Provide more info if make fails due to no local Rebol build tool:
tmps: $S/include/tmp-bootdefs.h

$S/include/tmp-bootdefs.h: $(REBOL_TOOL)
	$(MAKE) prep

$(REBOL_TOOL):
	$(MAKE) -f makefile.boot $(REBOL_TOOL)

### Post build actions
purge:
	-rm libr3.*
	-rm host$(BIN_SUFFIX)
	$(MAKE) lib
	$(MAKE) host$(BIN_SUFFIX)

test:
	$(CP) $(R3_TARGET) $(UP)/src/tests/
	$(R3) $S/tests/test.r

install:
	sudo cp $(R3_TARGET) /usr/local/bin

ship:
	$(R3) $S/tools/upload.r

build:	libr3.so
	$(R3) $S/tools/make-build.r

cln:
	rm libr3.* r3.o

check:
	$(STRIP) -s -o r3.s $(R3_TARGET)
	$(STRIP) -x -o r3.x $(R3_TARGET)
	$(STRIP) -X -o r3.X $(R3_TARGET)
	$(LS) r3*

}

;******************************************************************************

makefile-link: {
# Directly linked r3 executable:
$(R3_TARGET): tmps objs $(OBJS) $(HOST)
	$(CC) -o $(R3_TARGET) $(OBJS) $(HOST) $(CLIB)
	$(STRIP) $(R3_TARGET)
	-$(NM) -a $(R3_TARGET)
	$(LS) $(R3_TARGET)

objs:
	mkdir -p objs
}

makefile-so: {
lib:	libr3.so

# PUBLIC: Shared library:
# NOTE: Did not use "-Wl,-soname,libr3.so" because won't find .so in local dir.
libr3.so:	$(OBJS)
	$(CC) -o libr3.so -shared $(OBJS) $(CLIB)
	$(STRIP) libr3.so
	-$(NM) -D libr3.so
	-$(NM) -a libr3.so | grep "Do_"
	$(LS) libr3.so

# PUBLIC: Host using the shared lib:
host$(BIN_SUFFIX):	$(HOST)
	$(CC) -o host$(BIN_SUFFIX) $(HOST) libr3.so $(CLIB)
	$(STRIP) host$(BIN_SUFFIX)
	$(LS) host$(BIN_SUFFIX)
	echo "export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH"
}

makefile-dyn: {
lib:	libr3.dylib

# Private static library (to be used below for OSX):
libr3.dylib:	$(OBJS)
	ld -r -o r3.o $(OBJS)
	$(CC) -dynamiclib -o libr3.dylib r3.o $(CLIB)
	$(STRIP) -x libr3.dylib
	-$(NM) -D libr3.dylib
	-$(NM) -a libr3.dylib | grep "Do_"
	$(LS) libr3.dylib

# PUBLIC: Host using the shared lib:
host$(BIN_SUFFIX):	$(HOST)
	$(CC) -o host$(BIN_SUFFIX) $(HOST) libr3.dylib $(CLIB)
	$(STRIP) host$(BIN_SUFFIX)
	$(LS) host$(BIN_SUFFIX)
	echo "export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH"
}

not-used: {
# PUBLIC: Static library (to distrirbute) -- does not work!
libr3.lib:	r3.o
	ld -static -r -o libr3.lib r3.o
	$(STRIP) libr3.lib
	-$(NM) -a libr3.lib | grep "Do_"
	$(LS) libr3.lib
}

;******************************************************************************
;** Options and Config
;******************************************************************************

do %common.r
do %systems.r

file-base: has load %file-base.r
config: config-system/guess system/options/args

print ["Option set for building:" config/id config/os-name]

; Words are cleaner-looking in the table, and hyphens look better (and are
; easier to type).  But we need a string, and one that C can accept and not
; think you're doing subtraction.  Transform it (e.g. osx-64 => "TO_OSX_X64")
to-base-def: rejoin [{TO_} uppercase to-string config/os-base]
to-name-def: rejoin [
	{TO_} replace/all (uppercase to-string config/os-name) {-} {_}
]

; Make plat id string:
plat-id: form config/id/2
if tail? next plat-id [insert plat-id #"0"]
append plat-id config/id/3

; Collect OS-specific host files:
unless (
    os-specific-objs: select file-base to word! rejoin ["os-" config/os-base]
) [
	fail [
		"make-make.r requires os-specific obj list in file-base.r"
        "blank was provided for" rejoin ["os-" config/os-base]
	]
]

; The + sign is used to tell the make-os-ext.r script to scan a host kit file
; for headers (the way make-headers.r does).  But we don't care about that
; here in make-make.r... so remove any + signs we find before processing.

remove-each item file-base/os [item = '+]
remove-each item os-specific-objs [item = '+]

outdir: path-make
make-dir outdir
make-dir outdir/objs

nl2: "^/^/"
output: make string! 10000

;******************************************************************************
;** Functions
;******************************************************************************

flag?: func ['word] [not blank? find config/build-flags word]

macro+: func [
	"Appends value to end of macro= line"
	'name
	value
	/local n a
][
	n: rejoin [newline name]
	value: form value
	unless parse makefile-head [
		any [
			thru n opt [
				any space ["=" | "?="] to newline
				insert #" " insert value to end
			]
		]
	][
		print ajoin ["Cannot find " name "= definition"]
	]
]

macro++: func ['name obj [object!] /local out] [
	out: make string! 10
	for-each n words-of obj [
		all [
			obj/:n
			flag? (n)
			repend out [space obj/:n]
		]
	]
	macro+ (name) out
]

emit: func [d] [repend output d]

pad: func [str] [head insert/dup copy "" " " 16 - length str]

to-obj: func [
	"Create .o object filename (with no dir path)."
	file
][
	;?? file

	; Use of split path to remove directory had been commented out, but
	; was re-added to incorporate the paths on codecs in a stop-gap measure
	; to use make-make.r with Atronix repo

	file: (comment [to-file file] second split-path to-file file)
	head change back tail file "o"
]

emit-obj-files: func [
	"Output a line-wrapped list of object files."
	files [block!]
	/local cnt
][
	cnt: 1
	for-each file files [
		file: to-obj file
		emit [%objs/ file " "]
		if cnt // 4 = 0 [emit "\^/^-"]
		cnt: cnt + 1
	]
	if tab = last output [clear skip tail output -3]
	emit nl2
]

emit-file-deps: func [
	"Emit compiler and file dependency lines."
	files
	;flags
	/dir path  ; from path
	/local obj
][
	for-each src files [
		obj: to-obj src
		src: rejoin pick [["$R/" src]["$S/" path src]] not dir
		emit [
			%objs/ obj ":" pad obj src
			newline tab
			"$(CC) "
			src " "
			;flags " "
			pick ["$(RFLAGS)" "$(HFLAGS)"] not dir
			" -o " %objs/ obj ; " " src
			nl2
		]
	]
]

;******************************************************************************
;** Build
;******************************************************************************

replace makefile-head "!date" now

macro+ TO_OS_BASE to-base-def
macro+ TO_OS_NAME to-name-def

macro+ OS_ID config/id
macro+ LS pick ["dir" "ls -l"] flag? DIR
macro+ CP pick [copy cp] flag? COP
unless flag? -SP [ ; Use standard paths:
	macro+ UP ".."
	macro+ CD "./"
]
if flag? EXE [macro+ BIN_SUFFIX %.exe]
macro++ CLIB linker-flags
macro++ RAPI_FLAGS compiler-flags
macro++ HOST_FLAGS construct compiler-flags [PIC: NCM: _]
macro+  HOST_FLAGS compiler-flags/f64 ; default for all

if flag? +SC [remove find os-specific-objs 'host-readline.c]

emit makefile-head
emit ["OBJS =" tab]
emit-obj-files file-base/core
emit ["HOST =" tab]
emit-obj-files append copy file-base/os os-specific-objs
emit makefile-link
emit get pick [makefile-dyn makefile-so] config/id/2 = 2
emit {
### File build targets:
b-boot.c: $(SRC)/boot/boot.r
	$(REBOL) -sqw $(SRC)/tools/make-boot.r
}
emit newline

emit-file-deps file-base/core

emit-file-deps/dir file-base/os %os/
emit-file-deps/dir os-specific-objs %os/

;print copy/part output 300 halt
print ["Created:" outdir/makefile]
write outdir/makefile output
tanimoto_analysis <- function(min.tx, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, blind = FALSE) {
    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon
                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog

                        if(similarity == 'both') { # For similarity matrices already evaluated
                            similarity.consumer <- similarity.consumers[[i]]
                            similarity.resource <- similarity.resources[[i]]
                        } else if(similarity == 'consumer') {
                            similarity.consumer <- similarity.consumers[[i]]
                        } else if (similarity == 'resource') {
                            similarity.resource <- similarity.resources[[i]]
                        }

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                              S0[S1[k], 'consumer'] <- ""
                              S0[S1[k], 'non-consumer'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                                consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                        resource = interactions[, 'resource'],
                                                                        inter_type = interactions[, 'inter'])


                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                  S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                  S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.consumer,
                                                                                taxa = 'consumer')

                            similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.resource,
                                                                                taxa = 'resource')

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.consumer = similarity.consumer,
                                                                                    similarity.resource = similarity.resource,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.consumer, similarity.resource)
                        iteration <- iteration + 1
                        setTxtProgressBar(pb, iteration)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values

        }#m
    }#n
    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
catalog_predictions <- function(min.tx = 45, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, percent_remove = 0, nb_iter = 1, comm_id = FALSE, community) {

    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        if(comm_id == FALSE) {
            to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        } else { # comm_id = TRUE
            to.delete <- which(!Cm %in% community)
            Cm <- Cm[-to.delete]
            for(i in rev(to.delete)) {
                communities[[i]] <- NULL
            }
            names(communities) <- Cm
        }

    # Setting up lists to store the results
    # weights
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        #Minimum weight
        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

        #Number of iterations
        iter <- vector('list', nb_iter)
            for(i in 1:nb_iter) {
                iter[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- iter
        names(Tanimoto_analysis) <- seq(1,nb_iter)
        remove(iter)


        # Percent remove in communities
        pc_rm <- vector('list', length(percent_remove))
            for(i in 1:length(percent_remove)) {
                pc_rm[[i]] <- Tanimoto_analysis
            }
        Tanimoto_analysis <- pc_rm
        names(Tanimoto_analysis) <- percent_remove
        remove(pc_rm)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(percent_remove) * nb_iter * length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(p in 1:length(percent_remove)){
        percent_rm <- percent_remove[p]
        for(o in 1:nb_iter){
            for(n in 1:length(MW)) {
                mw <- MW[n]
                for(m in 1:length(K.values)) {

                    # Tanimoto analysis with different weights for different communities
                        # Parameters:
                            Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                            Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                            # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                        #   wt  Weight of traits in similarity measurement
                        #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                        #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                        # Output:
                        #   A vector of sets of resources for each taxon
                        for(i in 1:length(WT)){ #1st loop for all types of wt values
                            wt <- WT[i]
                            for(j in 1:length(Cm)) { #2nd loop for all C[i]
                                S1 <- communities[[j]]
                                S0 <- S0_catalog

                                if(similarity == 'both') { # For similarity matrices already evaluated
                                    similarity.consumer <- similarity.consumers[[i]]
                                    similarity.resource <- similarity.resources[[i]]
                                } else if(similarity == 'consumer') {
                                    similarity.consumer <- similarity.consumers[[i]]
                                } else if (similarity == 'resource') {
                                    similarity.resource <- similarity.resources[[i]]
                                }

                                # setting up the iterative process to evaluate the accuracy ~ # taxa in catalog
                                    sample_iter <- sample(x = seq(1,length(S1)), size = round((percent_rm / 100) * length(S1)), replace = FALSE)
                                    for(k in sample_iter) {
                                      S0[S1[k], 'resource'] <- ""
                                      S0[S1[k], 'non-resource'] <- ""
                                      S0[S1[k], 'consumer'] <- ""
                                      S0[S1[k], 'non-consumer'] <- ""
                                    }

                                    S1_no_mod <- which(!S1 %in% sample_iter)

                                # 2. Preexisting information kept to inform algorithm
                                    if(length(S1_no_mod) == length(S1)) {
                                        NULL
                                    } else {
                                    interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                                    # Only modifying those that are loosing data from the catalogue, less time
                                        to.change <- numeric()
                                        for(k in 1:length(S1_no_mod)) {
                                            to.change <- c(to.change, which(interactions[, 'consumer'] == S1_no_mod[k]), which(interactions[, 'resource'] == S1_no_mod[k]))
                                        }
                                        to.change <- unique(to.change)

                                    # Modifying sets of resources and non-resources for taxa in S1_no_mod
                                        interactions <- interactions[to.change, ]
                                        rownames(interactions) <- seq(1,nrow(interactions))
                                        resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                                  resource = interactions[, 'resource'],
                                                                                  inter_type = interactions[, 'inter'])

                                        consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                                resource = interactions[, 'resource'],
                                                                                inter_type = interactions[, 'inter'])


                                    # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                        for(k in 1:nrow(resource_set)) {
                                          S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                          S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                          S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                          S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                        }
                                    remove(interactions, resource_set, to.change)
                                    }#if

                                # Recalculate similarity
                                    similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.consumer,
                                                                                        taxa = 'consumer')

                                    similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                        S1 = S1,
                                                                                        wt = wt,
                                                                                        similarity.matrix = similarity.resource,
                                                                                        taxa = 'resource')

                                # Predicting interactions
                                    Tanimoto_analysis[[p]][[o]][[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                            Kr = Kr,
                                                                                            S0 = S0,
                                                                                            S1 = S1,
                                                                                            MW = mw,
                                                                                            similarity.consumer = similarity.consumer,
                                                                                            similarity.resource = similarity.resource,
                                                                                            minimum_threshold = minimum_threshold)

                                save(x = Tanimoto_analysis, file = file.to.save)
                                remove(S0, S1, similarity.consumer, similarity.resource)
                                iteration <- iteration + 1
                                setTxtProgressBar(pb, iteration)
                            }#2nd loop for all C[i]

                            save(x = Tanimoto_analysis, file = file.to.save)
                            remove(wt)

                        }#1st loop for all types of wt values
                }#m
            }#n
        }#o
    }#p
    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename = 'catalog_predictions'

catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40,60,80),
                                            nb_iter = 100,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = filename)

# Catalog vs predictions
accuracy <- accuracy0 <- accuracy1 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]])


#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 50, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(WT) * length(K.values)) + 0.5, labels = FALSE, las = 1, pos = -0.02) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, nb.pts, by = length(WT)) + 0.5, labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)

            abline(v = seq(length(WT)+0.5,nb.pts-length(WT)+0.5,by = length(WT)), col = "grey", lty = 2)
            abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
            abline(h = c(1.125,2.375), col = "black", lty = 2)


            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 1, y = 0.15, labels = 'Catalog', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 1, y = 2.65, labels = 'Algorithm', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'MW']) + as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt'] + as.numeric(accuracy[[i]][, 'iter'] + as.numeric(accuracy[[i]][, 'pc_rm']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,48), accuracy_mean[, 4][,1] - accuracy_mean[, 4][, 2]+it, seq(1,48), accuracy_mean[, 4][, 1] + accuracy_mean[, 4][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,48), y = accuracy_mean[, 4][, 1]+it, cex = 0.75, pch = 22, col = col[i])
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
tanimoto <- function(resource_x, resource_y) {
  # The Tanimoto similarity computes the sum of shared elements in vectors resource_x and resource_y and divides this by the length of the longest vector
  # If either length of resource_x or resource_y == 0, similarity == 0
  # The order of vectors consumer_x or consumer_y has no importance, as long as elements in vectors are unique

  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  # The same funcion is apparently used for trait similarity, including phylogeny
  # !!! There are NAs in the taxonomy that need to be taken into account, which is not the case at the moment !!!

  # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    if(length(resource_x) == 0 || length(resource_y) == 0) {
        return(0.0)
    } else if(resource_x == "" || resource_y == "") {
        return(0.0)
    } else {
        return(sum(resource_x %in% resource_y) / max(c(length(resource_x), length(resource_y))))
    }#if
}#end tanimoto function
# The functions require rchart-helper.R preloaded

# getQ2TimelapsePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getQ2TimelapsePlot = function(data, names, colors, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    dateFactors = list()
    for (i in 1:length(data)) {
        dateFactors[[i]] = as.factor(data[[i]]$date)
        boxplot = boxplot(data[[i]]$x ~ dateFactors[[i]],
                          data=data.frame(dateFactors[[i]], data[[i]]$x), plot=FALSE)
        stats = setNames(as.data.frame(boxplot$stats), nm=NULL)

        # Timpstamp in miliseconds
        unixTimestamps =
            1000 * as.numeric(as.POSIXct(sort(unique(data[[i]]$date)),
                                         origin="1970-01-01"))
        statsMedian = rbind(setNames(unixTimestamps, nm=NULL), stats[3,])
        statsQ2 = rbind(setNames(unixTimestamps, nm=NULL), stats[c(2, 4),])

        series[[2 * (i - 1) + 1]] =
            list(name=names[i], data=statsMedian, zIndex=1, color=colors[i],
                 marker=list(fillColor="white", lineWidth=2, lineColor=colors[i]))
        series[[2 * i]] = list(name="50th quartile", data=statsQ2, zIndex=0,
                 type="arearange", color=colors[i], lineWidth=0, linkedTo=":previous", fillOpacity=0.3)
    }

    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=list(text=yLabel), min=0)
    chart$set(series=series)
    return(chart)
}

# Helper for creating histogram
getBinItemList = function(data, businesses, interval=100) {
    binItemList = c()
    currentBin = interval
    maxBin = max(data$count) + interval
    while (currentBin < maxBin) {
        items = filter(data, currentBin - interval <= count & count < currentBin)
        binItemList = c(binItemList,
                        paste("< ", currentBin, "<br>",
                              paste(items$name, collapse="<br>, ")))
        currentBin = currentBin + interval
    }
    return(binItemList)
}

# getStackedHistogram
# data[[]]$x
getStackedHistogram = function(data,
                               names,
                               xLabel,
                               minBin=NULL,
                               maxBin = NULL,
                               interval=100,
                               logScale=FALSE,
                               logBase=exp(1),
                               normalize=FALSE,
                               colors = c("#7cb5ec", "#000000")) {
    series = list()
    plotLines = list()

    actualInterval = interval
    for (i in 1:length(data)) {
        maxBin = max(maxBin, max(data[[i]]$x, na.rm=TRUE), na.rm=TRUE)
        minBin = min(minBin, min(data[[i]]$x, na.rm=TRUE), na.rm=TRUE)
    }
    if (logScale) {
        maxBin = log(maxBin + 1, base=logBase)
        minBin = log(minBin + 1, base=logBase)
        actualInterval = log(interval, base=logBase)
    }

    for (i in 1:length(data)){
        x = data[[i]]$x
        if (logScale) {
            x = log(x + 1, base=logBase)
        }

        plotLines[[i * 2 - 1]] =
            list(color=colors[i],
                 value=mean(x),
                 width=2,
                 label=list(text="mean", style=list(color=colors[i]), verticalAlign="middle"))
        plotLines[[i * 2]] =
            list(color=colors[i],
                 value=median(x),
                 dashStyle="dash",
                 width=2,
                 label=list(text="median", style=list(color=colors[i]), verticalAlign="middle"))

        histogram = hist(x, breaks=seq(minBin, maxBin + actualInterval, actualInterval), plot=FALSE)
        histNames = getBinItemList(data[[i]], interval=actualInterval)

        nBins = min(length(histogram$breaks), length(histogram$counts))
        counts = histogram$counts[1:nBins]
        if (normalize) {
            counts = counts / nrow(data[[i]])
        }
        breaks = c(histogram$breaks[2:nBins], histogram$breaks[nBins] + actualInterval)
        bins = getValues(
            breaks,
            counts,
            name=histNames)
        series[[i]] = list(name=names[i], data=bins)
    }
   
    chart <- Highcharts$new()
    chart$chart(type="column")
    chart$plotOptions(
        column="{ grouping: false, pointPadding: 0, borderWidth: 0, groupPadding: 0, shadow: false}")
    chart$xAxis(title=paste("{text: '", xLabel, "'}", sep=""),
                plotLines=plotLines)
    yLabel = "frequency"
    if (normalize) {
        yLabel = paste(yLabel, "(normalized)")
    }
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""))
    chart$set(series=series)
    return(chart)
}

# getTimelapseLinePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getTimelapseLinePlot = function(data, names, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    for (i in 1:length(data)){
        timelapseValues = getTimelapseValues(
            as.POSIXlt(strptime(as.character(data[[i]]$date), "%Y-%m-%d", tz=timezone)),
            data[[i]]$x)
        series[[i]] = list(name=names[i], data=timelapseValues)
    }


    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""), gridLineColor="#FFFFFF")
    chart$set(series=series)
    return(chart)
}


# Difference-in-difference plot
# Use with DiffInDiffAggregate function
diffInDiffPlot <- function(data,
                     idCol,
                     xCol,
                     yLabel="change",
                     periodNames=NULL
                     ) {
    dataChart <- Highcharts$new()
    ids = unique(data[, idCol])
    numPeriod = 0
    for (i in 1:length(ids)) {
        current = data[data[, idCol] == ids[i],]
        numPeriod = nrow(current)
        name = current[1,]$name
        x = seq(0, numPeriod - 1, 1)
        y = current[, xCol]
        z = current[, xCol]
        
        seriesData = getValues(x, y, z, name)
        visible = TRUE
        dataChart$series(name=name,
                         data=seriesData,
                         showInLegend=TRUE,
                         visible=visible)
    }
    if (is.null(periodNames)) {
        periodNames = paste("period", x)
    }
    dataChart$xAxis(categories=periodNames)
    dataChart$yAxis(title=list(text=yLabel), gridLineColor="#FFFFFF")
    dataChart$legend(align="right", verticalAlign="top", layout="vertical")
    dataChart$tooltip(pointFormat=getPointFormat(y=yLabel, z=xCol))
    return (dataChart)
}


library(stringr)
library(reshape2)
library(ggplot2)


#Multiplot
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
  library(grid)
  
  # Make a list from the ... arguments and plotlist
  plots <- c(list(...), plotlist)
  
  numPlots = length(plots)
  
  # If layout is NULL, then use 'cols' to determine layout
  if (is.null(layout)) {
    # Make the panel
    # ncol: Number of columns of plots
    # nrow: Number of rows needed, calculated from # of cols
    layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
                     ncol = cols, nrow = ceiling(numPlots/cols))
  }
  
  if (numPlots==1) {
    print(plots[[1]])
    
  } else {
    # Set up the page
    grid.newpage()
    pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
    
    # Make each plot, in the correct location
    for (i in 1:numPlots) {
      # Get the i,j matrix positions of the regions that contain this subplot
      matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
      
      print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
                                      layout.pos.col = matchidx$col))
    }
  }
}



filenames_all <- list.files(path = "datasets/AllAttributes/",pattern = ".csv",full.names = TRUE)
ldf <- lapply(filenames_all, read.csv, skip=0, header=TRUE, sep=";",blank.lines.skip = TRUE,strip.white = TRUE, colClasses = rep("character",7))
for(i in seq(from=1,to=length(filenames_all),by = 1)){
  ldf[[i]]$Dataset <- sapply(str_split(filenames_all, '/'), '[', 4)[i]
  ldf[[i]]$Attributes <- "All"
}


filenames_sel <- list.files(path = "datasets/ReliefFAttributeEval-FS//",pattern = ".csv",full.names = TRUE)
ldf_s <- lapply(filenames_sel, read.csv, skip=0, header=TRUE, sep=";",blank.lines.skip = TRUE,strip.white = TRUE, colClasses = rep("character",7))
for(i in seq(from=1,to=length(filenames_sel),by = 1)){
  ldf_s[[i]]$Dataset <- sapply(str_split(filenames_sel, '/'), '[', 5)[i]
  ldf_s[[i]]$Attributes <- "ReliefFAttributeEval-FS"
}

filenames_som <- list.files(path = "datasets/SOM-FS//",pattern = ".csv",full.names = TRUE)
ldf_som <- lapply(filenames_som, read.csv, skip=0, header=TRUE, sep=";",blank.lines.skip = TRUE,strip.white = TRUE, colClasses = rep("character",7))
for(i in seq(from=1,to=length(filenames_som),by = 1)){
  ldf_som[[i]]$Dataset <- sapply(str_split(filenames_som, '/'), '[', 5)[i]
  ldf_som[[i]]$Attributes <- "SOM-FS"
}

filenames_som <- list.files(path = "datasets/SOM-FS//",pattern = ".csv",full.names = TRUE)
ldf_som <- lapply(filenames_som, read.csv, skip=0, header=TRUE, sep=";",blank.lines.skip = TRUE,strip.white = TRUE, colClasses = rep("character",7))
for(i in seq(from=1,to=length(filenames_som),by = 1)){
  ldf_som[[i]]$Dataset <- sapply(str_split(filenames_som, '/'), '[', 5)[i]
  ldf_som[[i]]$Attributes <- "SOM-FS"
}

filenames_cfs <- list.files(path = "datasets/CfsSubsetEval-FS//",pattern = ".csv",full.names = TRUE)
ldf_cfs <- lapply(filenames_cfs, read.csv, skip=0, header=TRUE, sep=";",blank.lines.skip = TRUE,strip.white = TRUE, colClasses = rep("character",7))
for(i in seq(from=1,to=length(filenames_cfs),by = 1)){
  ldf_cfs[[i]]$Dataset <- sapply(str_split(filenames_cfs, '/'), '[', 5)[i]
  ldf_cfs[[i]]$Attributes <- "CfsSubsetEval-FS"
}

m_all <- do.call(rbind,ldf)
m_sel <- do.call(rbind,ldf_s)
m_som <- do.call(rbind,ldf_som)
m_cfs <- do.call(rbind,ldf_cfs)

m <- rbind(m_all,m_sel)
m <- rbind(m,m_som)
m <- rbind(m,m_cfs)

rm(m_all,m_sel,m_som,m_cfs,ldf,ldf_s,ldf_som,ldf_cfs,filenames_sel,filenames_all,filenames_som,filenames_cfs,i)

datos <- melt(data = m,id.vars = c("Method","Dataset","Attributes"),measure.vars = c("R.","MAE","RMSE","RAE","RRSE","TIME"),)

datos$Dataset <- str_replace(datos$Dataset,".csv","")

datos$error <- as.numeric(sapply(str_split(datos$value, '_'), '[', 2))
datos$value <- as.numeric(sapply(str_split(datos$value, '_'), '[', 1))

datos$variable <- as.character(datos$variable)
datos[datos$variable=="R.","variable"] <- "R^2"
dataset = unique(datos$Dataset)

ggplot(data = subset(datos,Dataset==dataset[1]), aes(x=Attributes,y=value,color=Attributes,shape=Attributes)) + geom_point(stat="identity",size=3) + 
  facet_grid(variable ~ Method,scales = "free_y",labeller = as_labeller(expression()) + 
  scale_color_grey(start=0.0,end=0.2) + labs(title=dataset[1],x="",y="") + 
  geom_errorbar(aes(ymin=value-error,ymax=value+error), width=0.2,size=0.25) + theme_bw()  + theme(legend.position="bottom", axis.title.x=element_blank(),
                                                                                                   axis.text.x=element_blank(),
                                                                                                   axis.ticks.x=element_blank())


ggplot(data = subset(datos,Dataset==dataset[1]), aes(x=Attributes,y=value,fill=Attributes,shape=Attributes)) + geom_bar(stat="identity") + 
  facet_grid(variable ~ Method,scales = "free_y",) + 
  scale_fill_grey(start=0.2,end=0.6) + labs(title=dataset[1],x="",y="") + 
  geom_errorbar(aes(ymin=value-error,ymax=value+error), width=0.5,size=0.5) + theme_bw()  + theme(legend.position="bottom", axis.title.x=element_blank(),
                                                                                                   axis.text.x=element_blank(),
                                                                                                   axis.ticks.x=element_blank())

# Publisher > Method > Metric > Attribute Selection

dataset = unique(datos$Dataset)

for(i in dataset){
  print(ggplot(data = subset(datos,Dataset==i), aes(x=Attributes,y=value,fill=Attributes,shape=Attributes)) + geom_bar(stat="identity") + 
    facet_grid(variable ~ Method,scales = "free_y") + 
    scale_fill_grey(start=0.2,end=0.6) + labs(title=i,x="",y="") + 
    geom_errorbar(aes(ymin=value-error,ymax=value+error), width=0.5,size=0.5) + theme_bw()  + theme(legend.position="bottom", axis.title.x=element_blank(),
                                                                                                    axis.text.x=element_blank(),
                                                                                             axis.ticks.x=element_blank()))
  ggsave(file=paste0("img_1_",i,".pdf"),scale=1.2)
  
}

# Attribute Selection > Publisher > Method > Metric

att = unique(datos$Attributes)

for(i in dataset){
  for(j in att){
  
print(ggplot(data = subset(datos,Attributes==j & Dataset==i), aes(x=Method,y=value,color=Attributes,shape=Attributes)) + geom_point(stat="identity",size=2) + 
  facet_grid(variable ~ Dataset,scales = "free_y") + 
  scale_color_grey(start=0.0,end=0.2) + labs(title=paste0(i," - ", j),x="",y="") + 
  geom_errorbar(aes(ymin=value-error,ymax=value+error), width=0.2,size=0.25) + theme_bw()  + theme(legend.position="none"))

  ggsave(file=paste0("img_2_",i,"-",j,".pdf"),scale=1.2)

}
}


p2 <- ggplot(data = subset(datos,Attributes==att[2]), aes(x=Method,y=value,color=Attributes,shape=Attributes)) + geom_point(stat="identity",size=2) + 
  facet_grid(variable ~ Dataset,scales = "free_y") + 
  scale_color_grey(start=0.0,end=0.2) + labs(title=att[2],x="",y="") + 
  geom_errorbar(aes(ymin=value-error,ymax=value+error), width=0.2,size=0.25) + theme_bw()  + theme(legend.position="none")

multiplot(p1,p2,cols=1)

#Time dataset, selection, method


ggplot(data = subset(datos,variable=="TIME"), aes(x=Method,y=value)) + geom_point(stat="identity",size=3) + 
  facet_grid(Dataset ~ Attributes,scales = "free_y") + 
  scale_fill_grey(start=0.2,end=0.8) + labs(title="TIME",x="Method",y="Seconds") + 
  geom_errorbar(aes(ymin=value-error,ymax=value+error), width=0.2,size=0.25) + theme_bw()  + theme(legend.position="bottom")
  

ggplot(data = subset(datos,variable=="MAE"), aes(x=Method,y=value)) + geom_bar(stat="identity",size=3) + 
  facet_grid(Dataset ~ Attributes,scales = "free_y") + 
  scale_fill_grey(start=0.2,end=0.8) + labs(title="MAE",x="Method",y="Units") + 
  geom_errorbar(aes(ymin=value-error,ymax=value+error), width=0.2,size=0.25) + theme_bw()  + theme(legend.position="bottom")

















ggplot(data = datos, aes(x=variable,y=value)) + geom_point() + facet_grid(Attributes ~ Dataset)

ggplot(data = subset(datos,variable=="R2"), aes(x=Attributes,y=value,fill=Attributes)) + geom_bar(stat="identity",position="dodge") + facet_grid(variable ~ Dataset)

ggplot(data = subset(datos), aes(x=Attributes,y=value,fill=Attributes)) + geom_bar(stat="identity",position="dodge") + 
  facet_grid(variable ~ Dataset,scales = "free_y") + theme(legend.position="bottom") + scale_fill_brewer(type="qual",palette = "Set1")


dataset = unique(datos$Dataset)

ggplot(data = subset(datos,Dataset==dataset[1]), aes(x=Attributes,y=value,fill=Attributes)) + geom_bar(stat="identity",position="dodge") + 
  facet_grid(variable ~ Method,scales = "free_y") + theme(legend.position="bottom", axis.title.x=element_blank(),
                                                          axis.text.x=element_blank(),
                                                          axis.ticks.x=element_blank()) + 
  scale_fill_grey(start=0.2,end=0.8) + labs(title=dataset[1],x="",y="")



ggplot(data = subset(datos,Dataset==dataset[1]), aes(x=Attributes,y=value,fill=Attributes)) + geom_point(stat="identity",position="dodge") + 
  facet_grid(variable ~ Method,scales = "free_y") + theme(legend.position="bottom", axis.title.x=element_blank(),
                                                          axis.text.x=element_blank(),
                                                          axis.ticks.x=element_blank()) + 
  scale_fill_grey(start=0.2,end=0.8) + labs(title=dataset[1],x="",y="")



#coverage/inst/shiny/coverage1/ui.r
#andy south 12/5/16

library(shiny)


shinyUI(fluidPage(

  #can add CSS controls in here
  #http://shiny.rstudio.com/articles/css.html
  #http://www.w3schools.com/css/css_rwd_mediaqueries.asp
  tags$head(
    tags$style(HTML("

                    [class*='col-'] {
                    padding: 10px;
                    border: 1px;
                    position: relative;
                    min-height: 1px;
                    }

                    .container {
                    margin-right: 0;
                    margin-left: 0;
                    float: left;
                    }
                    .col-sm-1 {width: 8.33%; float: left;}
                    .col-sm-2 {width: 16.66%; float: left;}
                    .col-sm-3 {width: 25%; float: left;}
                    .col-sm-4 {width: 33.33%; float: left;}
                    .col-sm-5 {width: 41.66%; float: left;}
                    .col-sm-6 {width: 50%;  float: left;}
                    .col-sm-7 {width: 58.33%; float: left;}
                    .col-sm-8 {width: 66.66%; float: left; padding: 5px;} !to make more space for plots
                    .col-sm-9 {width: 75%; float: left;}
                    .col-sm-10 {width: 83.33%; float: left;}
                    .col-sm-11 {width: 91.66%; float: left;}
                    .col-sm-12 {width: 100%; float: left;}

                    "))
    ),

  title = "coverage of vector control interventions",

  h5("Vector control demonstrator prototype. Gerry Killeen & Andy South."),
  h5("Vectors feed indoors and outdoors, on humans and cattle. Interventions target a subset of these behaviours."),
  h5("Change inputs below to see implications."),

  fluidRow(
    column(8, plotOutput('plot_feed')),
    # column(2, h5("Vector feeding"), plotOutput('plot_pie_feed') ),
    # column(2, h5("Human exposure"), plotOutput('plot_pie_expose') )
    column(2, plotOutput('plot_pie_feed') ),
    column(2, plotOutput('plot_pie_expose') )
  ), #end fluid row


  #hr(),

  fluidRow(
    column(3,
           #h4("Vector feeding"),
           sliderInput("feed_man", "vectors feeding on man", 0.7, min = 0, max = 1, step = 0.1, ticks=FALSE)
           #numericInput("feed_cow", "cattle", 0.3, min = 0, max = 1, step = 0.1),
           #sliderInput("feed_in","indoor", 0.6, min = 0, max = 1, step = 0.1)
           #numericInput("feed_out","outdoor", 0.4, min = 0, max = 1, step = 0.1)
    ),
    column(3,
           sliderInput("feed_in","vectors feeding indoors", 0.6, min = 0, max = 1, step = 0.1, ticks=FALSE)
    ),
    column(3, offset = 0,
           #h4("Intervention"),
           radioButtons("intervention","intervention",choices=c("bed nets","vet insecticide"))
           #sliderInput("target_coverage", "coverage", 0.7, min = 0, max = 1, step = 0.1)
    ),
    column(3, offset = 0,
           sliderInput("target_coverage", "intervention coverage", 0, min = 0, max = 1, step = 0.1, ticks=FALSE)
    )
           # h4("Intervention target"),
           # numericInput("target_man", "human", 0.7, min = 0, max = 1, step = 0.1),
           # numericInput("target_cow", "cattle", 0.3, min = 0, max = 1, step = 0.1),
           # numericInput("target_in","indoor", 0.6, min = 0, max = 1, step = 0.1),
           # numericInput("target_out","outdoor", 0.4, min = 0, max = 1, step = 0.1)


  ) #end fluid row

))
#coverage/inst/shiny/coverage1/server.r
#andy south 12/5/16

#https://andysouth.shinyapps.io/coverage1/

library(shiny)
#library(devtools)
#install_github('AndySouth/coverage')
library(coverage)
library(png)

shinyServer(function(input, output, session) {


  ################################
  output$plot_feed <- renderPlot({

    #add dependency on the button
    #if ( input$aButtonRun > 0 )
    #{
      #isolate reactivity of other objects
    #  isolate({

        plot_feeding( man = input$feed_man,
                      cow = 1-input$feed_man,
                      indoor = input$feed_in,
                      outdoor = 1-input$feed_in,
                      intervention = input$intervention,
                      coverage = input$target_coverage )


      #}) #end isolate
    #} #end if ( input$aButtonRun > 0 )
  })


  ####################################
  #output$plot_pie_feed <- renderPlot(width = 150, height = 150,{
  output$plot_pie_feed <- renderPlot({

    plot_pie_feeding( man = input$feed_man,
                  cow = 1-input$feed_man,
                  indoor = input$feed_in,
                  outdoor = 1-input$feed_in,
                  intervention = input$intervention,
                  coverage = input$target_coverage )
  })


  ####################################
  output$plot_pie_expose <- renderPlot({


    plot_pie_exposure(man = input$feed_man,
                      cow = 1-input$feed_man,
                      indoor = input$feed_in,
                      outdoor = 1-input$feed_in,
                      intervention = input$intervention,
                      coverage = input$target_coverage )
  })


  #to update values based on changes in others

  #stop feed_man going below feed_indoors
  #not needed now that human feed is a proportion of indoors
  #observe({ if ( input$feed_man < input$feed_in ) updateSliderInput(session, "feed_man", value = input$feed_in ) })

  #stop feedindoors going above feed_man
  # observe({ updateNumericInput(session, "feed_man", value = 1-input$feed_cow) })
  # observe({ updateNumericInput(session, "feed_cow", value = 1-input$feed_man) })
  # observe({ updateNumericInput(session, "feed_in", value = 1-input$feed_out) })
  # observe({ updateNumericInput(session, "feed_out", value = 1-input$feed_in) })


})
                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

# not used

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

# not used. and slow

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    list1 <- df1$id
    list2 <- df2$id
    for (j in 1:length(list2)) {
        id <- list2[j]
        list[id] <- NA
        i <- match(id, list1)
        if (!is.na(i)) {
            list[id] <- j - i
        }
    }
    return (list)
}

# slow. not used

getperiodmapold <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
#        list12 <- stocklistperiod[period, 2][[1]]
#        for (i in 1:max) {
#            print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
#        }
        for (i in 1:max) {
            id <- list11$id[i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
            }
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), rise, list11$id[[i]]))
        }
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
                                        #    list12 <- stocklistperiod[period, 2][[1]]
                                        #
                                        #    len <- nrow(list12)
                                        #    len <- len + 1

                                        #    for (i in 1:max) {
                                        #        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
                                        #    }

                                        #    len <- nrow(list11)
                                        #    len <- len + 1

        len <- nrow(list11)
        len <- len + 1
        for (i in 1:max) {
            id <- list11$id[len - i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
            }
            
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), rise, list11$id[[len - i]]))
        }
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, mynames, topbottom, periodtext, maindate, olddate, days) {
    dev.new()
    colours <- rainbow(topbottom)
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE, col = colours[i], pch = i)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o", lty = i, col = colours[i], pch = i)
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(mynames[1]))
        legend(1, g_range[2], mynames, cex=0.8, lty=1:6, pch=1:25, col=colours) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (type == pricetype) {
        return (df$price)
    }
    if (type == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    normalize <- 0
    if (length(ids) > 1) {
        if (periodtext == "price") {
            normalize <- 1
        }
        if (periodtext == "index") {
            normalize <- 1
        }
    }
    
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, pricetype)
        perioddata[["text"]] <- pairs
        perioddatamap[["price"]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, indextype)
        perioddata[["text"]] <- pairs
        perioddatamap[["index"]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    dayset <- list()
    ls <- list()
    mynames <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        if (normalize == 1) {
                            str("minmax")
                            str(l)
                            mymin <- abs(min(l))
                            mymax <- abs(max(l))
                            if (mymin > mymax) {
                                mymax <- mymin
                            }
                            for (j in 1:length(l)) {
                                l[j] <- l[j] * 100 / mymax;
                            }
                            str(l)
                        }
                        
                        dayset <- append(dayset, bigretl[[2]])
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        mynames[c] <- df$name
                    }
                }
            }
        }
    }
    daynames <- names(dayset)
    olddate <- min(daynames)
    newdate <- max(daynames)
    displaychart(ls, mynames, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

#coverage/inst/shiny/coverage1/server.r
#andy south 12/5/16

#https://andysouth.shinyapps.io/coverage1/

library(shiny)
#library(devtools)
#install_github('AndySouth/coverage')
library(coverage)
library(png)

shinyServer(function(input, output, session) {


  ################################
  output$plot_feed <- renderPlot({

    #add dependency on the button
    #if ( input$aButtonRun > 0 )
    #{
      #isolate reactivity of other objects
    #  isolate({

        plot_feeding( man = input$feed_man,
                      cow = 1-input$feed_man,
                      indoor = input$feed_in,
                      outdoor = 1-input$feed_in,
                      intervention = input$intervention,
                      coverage = input$target_coverage )


      #}) #end isolate
    #} #end if ( input$aButtonRun > 0 )
  })


  ####################################
  #output$plot_pie_feed <- renderPlot(width = 150, height = 150,{
  output$plot_pie_feed <- renderPlot({

    plot_pie_feeding( man = input$feed_man,
                  cow = 1-input$feed_man,
                  indoor = input$feed_in,
                  outdoor = 1-input$feed_in,
                  intervention = input$intervention,
                  coverage = input$target_coverage )
  })


  ####################################
  output$plot_pie_expose <- renderPlot({


    plot_pie_exposure(man = input$feed_man,
                      cow = 1-input$feed_man,
                      indoor = input$feed_in,
                      outdoor = 1-input$feed_in,
                      intervention = input$intervention,
                      coverage = input$target_coverage )
  })


  #to update values based on changes in others

  #stop feed_man going below feed_indoors
  observe({ if ( input$feed_man < input$feed_in ) updateSliderInput(session, "feed_man", value = input$feed_in ) })
  #stop feedindoors going above feed_man

  # observe({ updateNumericInput(session, "feed_man", value = 1-input$feed_cow) })
  # observe({ updateNumericInput(session, "feed_cow", value = 1-input$feed_man) })
  # observe({ updateNumericInput(session, "feed_in", value = 1-input$feed_out) })
  # observe({ updateNumericInput(session, "feed_out", value = 1-input$feed_in) })


})
generateBagIt {
# -----------------------------------------------------
# generateBagIt for HydroShare
# adapted by Hong Yi on May 2015 to fit HydroShare use case 
# from rulegenerateBagIt.r originally developed by Terrell 
# Russell on August 2010
# -----------------------------------------------------
#
#  University of North Carolina at Chapel Hill
#  - Requires iRODS 2.4.1
#  - Conforms to BagIt Spec v0.96
#
# -----------------------------------------------------
#
### - use the input BAGITDATA directory to generate bagit 
###   files in place without creating new bagit root directory
### - writes bagit.txt to BAGITDATA/bagit.txt
### - generates payload manifest file of BAGITDATA/data
### - writes payload manifest to BAGITDATA/manifest-sha256.txt
### - writes tagmanifest file to BAGITDATA/tagmanifest-sha256.txt
### - writes to rodsLog
#
# -----------------------------------------------------

  ### - writes bagit.txt to NEWBAGITROOT/bagit.txt
  writeLine("stdout", "BagIt-Version: 0.96");
  writeLine("stdout", "Tag-File-Character-Encoding: UTF-8");
  msiDataObjCreate("*BAGITDATA" ++ "/bagit.txt", "destRescName=" ++ "*DESTRESC" ++ "++++forceFlag=", *FD);
  msiDataObjWrite(*FD, "stdout", *WLEN);
  msiDataObjClose(*FD, *Status);
  msiFreeBuffer("stdout");

  ### - generates payload manifest file of BAGITDATA/data
  msiStrlen(*BAGITDATA, *ROOTLENGTH);
  *OFFSET = int(*ROOTLENGTH) + 1;
  *NEWBAGITDATA = "*BAGITDATA" ++ "/data";
  *ContInxOld = 1;
  *Condition = "COLL_NAME like '*NEWBAGITDATA%%'";
  msiMakeGenQuery("DATA_ID, DATA_NAME, COLL_NAME", *Condition, *GenQInp);
  msiExecGenQuery(*GenQInp, *GenQOut);
  msiGetContInxFromGenQueryOut(*GenQOut, *ContInxNew);
  while(*ContInxOld > 0) {
    foreach(*GenQOut) {
      msiGetValByKey(*GenQOut, "DATA_NAME", *Object);
      msiGetValByKey(*GenQOut, "COLL_NAME", *Coll);
      *FULLPATH = "*Coll" ++ "/" ++ "*Object";
      msiDataObjChksum(*FULLPATH, "forceChksum=", *CHKSUM);
      msiSubstr(*FULLPATH,str(*OFFSET), "null", *RELATIVEPATH);
      writeString("stdout", *CHKSUM);
      writeLine("stdout", "    *RELATIVEPATH")
    }
    *ContInxOld = *ContInxNew;
    if(*ContInxOld > 0) {
      msiGetMoreRows(*GenQInp, *GenQOut, *ContInxNew);
    }
  }

  ### - writes payload manifest to BAGITDATA/manifest-sha256.txt
  msiDataObjCreate("*BAGITDATA" ++ "/manifest-sha256.txt", "destRescName=" ++ "*DESTRESC" ++ "++++forceFlag=", *FD);
  msiDataObjWrite(*FD, "stdout", *WLEN);
  msiDataObjClose(*FD, *Status);
  msiFreeBuffer("stdout");

  ### - writes tagmanifest file to BAGITDATA/tagmanifest-sha256.txt
  msiDataObjChksum("*BAGITDATA" ++ "/bagit.txt", "forceChksum", *CHKSUM);
  writeString("stdout", *CHKSUM);
  writeLine("stdout", "    bagit.txt")
  msiDataObjChksum("*BAGITDATA" ++ "/manifest-sha256.txt", "forceChksum", *CHKSUM);
  msiExecCmd("base64", "-d"
  writeString("stdout", *CHKSUM);
  writeLine("stdout", "    manifest-sha256.txt");
  msiDataObjCreate("*BAGITDATA" ++ "/tagmanifest-sha256.txt", "destRescName=" ++ "*DESTRESC" ++ "++++forceFlag=", *FD);
  msiDataObjWrite(*FD, "stdout", *WLEN);
  msiDataObjClose(*FD, *Status);
  msiFreeBuffer("stdout");

  ### - writes to rodsLog
  msiWriteRodsLog("BagIt bag files created in place: *BAGITDATA <- *BAGITDATA", *Status);
}
INPUT *BAGITDATA="/dummy/dummy/dummy", *DESTRESC="dummy"
OUTPUT ruleExecOut
# 2. faza: Uvoz podatkov


# Funkcija, ki uvozi podatke iz datoteke druzine.csv
#uvozi.druzine <- function() {
 # return(read.table("podatki/druzine.csv", sep = ";", as.is = TRUE,
  #                  row.names = 1,
   #                 col.names = c("obcina", "en", "dva", "tri", "stiri"),
    #                fileEncoding = "Windows-1250"))
#}

# Zapišimo podatke v razpredelnico druzine.
#druzine <- uvozi.druzine()

#obcine <- uvozi.obcine()

# Če bi imeli več funkcij za uvoz in nekaterih npr. še ne bi
# potrebovali v 3. fazi, bi bilo smiselno funkcije dati v svojo
# datoteko, tukaj pa bi klicali tiste, ki jih potrebujemo v
# 2. fazi. Seveda bi morali ustrezno datoteko uvoziti v prihodnjih
# fazah.

# Funkcija, ki uvozi podatke iz datoteke druzine.csv

#Podatki za Slovenijo

         tabela_vozači_SLO<-read.csv2("podatki/vozaci.csv", skip=1,na.strings = "-", stringsAsFactors = FALSE,
                                  fileEncoding = "UTF-8", col.names = c("Vrsta prevoza","Leto in mesec", "Število potnikov"))
  
         tabela_registracije_SLO<-read.csv2("podatki/registracije.csv",na.strings = "-",stringsAsFactors = FALSE,
                                  fileEncoding = "Windows-1250",col.names = c("Leto","2004", "2005","2006","2007","2008","2009","2010","2011","2012","2013","2014"))
         names(tabela_registracije_SLO)<-gsub("X","",names(tabela_registracije_SLO))
         tabela_registracije_SLO<-melt(tabela_registracije_SLO, na.rm=FALSE,"Leto")
         names(tabela_registracije_SLO)<-c("","Leto","Stevilo")
         
         
         tabela_indeks_cen_mot_voz_SLO<-read.csv2("podatki/indeks_cen_mot_voz_SLO.csv",skip=1,na.strings="-",stringsAsFactors = FALSE,
                                  fileEncoding = "Windows-1250",col.names = c("","Leto in mesec","Tekoči mesec na isti mesec prejšnjega leta"))
        
         tabela_prometne_nesrece_SLO<-tabela_prometne_nesrece_SLO<-read.csv2("podatki/prometne_nesrece_SLO.csv",na.strings="-",stringsAsFactors = FALSE,
                                  fileEncoding = "Windows-1250")
         names(tabela_prometne_nesrece_SLO)<-gsub("X","",names(tabela_prometne_nesrece_SLO))
         tabela_prometne_nesrece_SLO<-melt(tabela_prometne_nesrece_SLO, na.rm=FALSE,"")
         names(tabela_prometne_nesrece_SLO)<-c("","Leto","Kolicina")
         
         
        
         tabela_dolzina_cest_SLO<-read.csv2("podatki/dolzina_cest_SLO.csv",na.strings="-",stringsAsFactors = FALSE,fileEncoding = "Windows-1250")
         
         
         tabela_Cestni_javni_linijski_prevoz_medkrajevni_in_mednarodni_SLO<-read.csv2("podatki/Cestni_javni_linijski_prevoz_medkrajevni_in_mednarodni.csv",
                                                                                  na.strings="-",stringsAsFactors = FALSE, fileEncoding = "Windows-1250",
                                                                                  col.names=c("Leto","Potniki v 1000","Potniški kilometri v mio"))
         
         tabela_prve_reg_vrsta_vozila_SLO_vsa<-read.csv2("podatki/prve_reg_vrsta_vozila_SLO.csv",na.strings="-",stringsAsFactors = FALSE,
                                                     fileEncoding = "Windows-1250")
         
         tabela_vozila_na_gorivo_SLO<-read.csv2("podatki/vozila_na_gorivo.csv",na.strings="",stringsAsFactors = FALSE,
                                            fileEncoding = "Windows-1250")
         names(tabela_vozila_na_gorivo_SLO)<-gsub("X","",names(tabela_vozila_na_gorivo_SLO))
         tabela_vozila_na_gorivo_SLO<-melt(tabela_vozila_na_gorivo_SLO, na.rm=FALSE,c("",".1",".2"))
         names(tabela_vozila_na_gorivo_SLO)<-c("Tip vozila","Gorivo","Dan","Leto","Kolicina")
         
         
         
         tabela_starost_vozil_SLO<-read.csv2("podatki/starost_vozil_SLO.csv",na.strings="",stringsAsFactors = FALSE,
                                             fileEncoding = "windows-1250")
         names(tabela_starost_vozil_SLO)<-gsub("X","",names(tabela_starost_vozil_SLO))
         tabela_starost_vozil_SLO<-melt(tabela_starost_vozil_SLO, na.rm=FALSE,c("",".1"))
         names(tabela_starost_vozil_SLO)<-c("Tip vozila","Starost","Leto","Kolicina")
         
#Podatki za Eu
         
         tabela_EU_vozaci<-read.csv2("podatki/EU_vozaci.csv",na.strings=":",stringsAsFactors = FALSE, 
                                     fileEncoding = "windows-1250")
         names(tabela_EU_vozaci)<-gsub("X","",names(tabela_EU_vozaci))
         tabela_EU_vozaci<-melt(tabela_EU_vozaci, na.rm=FALSE,"GEO.TIME")
         names(tabela_EU_vozaci)<-c("Drzava","Leto","Stevilo vozacev")
         tabela_EU_vozaci<-tabela_EU_vozaci[ !tabela_EU_vozaci$Drzava %in% c(""),]
         tabela_EU_vozaci$`Stevilo vozacev` <- tabela_EU_vozaci$`Stevilo vozacev` %>% {gsub("\\.", "", .)} %>% {gsub(",", ".", .)} %>% as.numeric()
         tabela_EU_vozaci$`Stevilo vozacev` <- gsub("\\.", "", tabela_EU_vozaci$`Stevilo vozacev`) %>% as.numeric()
         tabela_EU_vozaci$Drzava[grep("Germany",tabela_EU_vozaci$Drzava)] <- "Germany"
         tabela_EU_vozaci$Drzava[grep("Former Yugoslav",tabela_EU_vozaci$Drzava)] <- "Macedonia, FYR"
         
         
         
         
         tabela_EU_registracije_ostalo<-read.csv2("podatki/EU_registracije_ostalo.csv",na.strings=":",stringsAsFactors = FALSE, 
                                                      fileEncoding = "windows-1250")
         names(tabela_EU_registracije_ostalo)<-gsub("X","",names(tabela_EU_registracije_ostalo))
         tabela_EU_registracije_ostalo<-melt(tabela_EU_registracije_ostalo, na.rm=FALSE,"GEO.TIME")
         names(tabela_EU_registracije_ostalo)<-c("Drzava","Leto","Registracije ostalih vozil")
        
         
         tabela_EU_prevozeni_km<-read.csv2("podatki/EU_prevozeni_km.csv",na.strings=":",stringsAsFactors = FALSE, 
                                                  fileEncoding = "windows-1250")
         names(tabela_EU_prevozeni_km)<-gsub("X","",names(tabela_EU_prevozeni_km))
         tabela_EU_prevozeni_km<-melt(tabela_EU_prevozeni_km, na.rm=FALSE,"GEO.TIME")
         names(tabela_EU_prevozeni_km)<-c("Drzava","Leto","Prevozeni km")
         
         
         

         
           
         tabela_EU_stevilo_umrlih_prometne_nesrece<-read.csv2("podatki/EU_stevilo_umrlih_prometne_nesrece.csv",na.strings=":",stringsAsFactors = FALSE, 
                                                              fileEncoding = "windows-1250")
         names(tabela_EU_stevilo_umrlih_prometne_nesrece)<-gsub("X","",names(tabela_EU_stevilo_umrlih_prometne_nesrece))
         tabela_EU_stevilo_umrlih_prometne_nesrece<-melt(tabela_EU_stevilo_umrlih_prometne_nesrece, na.rm=FALSE,"geo.time")
         names(tabela_EU_stevilo_umrlih_prometne_nesrece)<-c("Drzava","Leto","Stevilo_umrlih")
         tabela_EU_stevilo_umrlih_prometne_nesrece<-tabela_EU_stevilo_umrlih_prometne_nesrece[ !tabela_EU_stevilo_umrlih_prometne_nesrece$Drzava %in% c(""),]
         rownames(tabela_EU_stevilo_umrlih_prometne_nesrece)<-c(1:480)
         tabela_EU_stevilo_umrlih_prometne_nesrece<-tabela_EU_stevilo_umrlih_prometne_nesrece[-c(1:162),]
         tabela_EU_stevilo_umrlih_prometne_nesrece<-tabela_EU_stevilo_umrlih_prometne_nesrece[!tabela_EU_stevilo_umrlih_prometne_nesrece$Drzava %in% c("EU (28 countries)","EU (27 countries)"),]
         tabela_EU_stevilo_umrlih_prometne_nesrece$Drzava[grep("Germany",tabela_EU_stevilo_umrlih_prometne_nesrece$Drzava)] <- "Germany"
        
         
         tabela_EU_registracije_avtomobili<-read.csv2("podatki/EU_registracije.csv",na.strings=":",stringsAsFactors = FALSE, 
                                                      fileEncoding = "windows-1250")
         names(tabela_EU_registracije_avtomobili)<-gsub("X","",names(tabela_EU_registracije_avtomobili))
         tabela_EU_registracije_avtomobili<-melt(tabela_EU_registracije_avtomobili, na.rm=FALSE,"GEO.TIME")
         names(tabela_EU_registracije_avtomobili)<-c("Drzava","Leto","Stevilo_registracij")
         tabela_EU_registracije_avtomobili$`Stevilo_registracij` <- gsub("\\.", "", tabela_EU_registracije_avtomobili$`Stevilo_registracij`) %>% as.numeric()
         tabela_EU_registracije_avtomobili$Drzava[grep("Germany",tabela_EU_registracije_avtomobili$Drzava)] <- "Germany"
         tabela_EU_registracije_avtomobili$Drzava[grep("Former Yugoslav",tabela_EU_registracije_avtomobili$Drzava)] <- "Macedonia, FYR"
         tabela_zemljevid<-tabela_EU_registracije_avtomobili
         tabela_EU_registracije_avtomobili$vozaci<-tabela_EU_vozaci$`Stevilo vozacev`
         tabela_EU_registracije_avtomobili$nesrece<-tabela_EU_stevilo_umrlih_prometne_nesrece$`Stevilo_umrlih`
         
         
         
         
         Leto<-tabela_Cestni_javni_linijski_prevoz_medkrajevni_in_mednarodni_SLO$Leto
         Število.v.tisočih<-tabela_Cestni_javni_linijski_prevoz_medkrajevni_in_mednarodni_SLO$Potniki.v.1000
         
         Vozaci<-ggplot(tabela_Cestni_javni_linijski_prevoz_medkrajevni_in_mednarodni_SLO)+
           aes(x=Leto,y=Število.v.tisočih)+
           geom_line(colour="red")+
           ggtitle("Vozači v javnem linijskem prevozu(medkrajevni in mednarodni) ")+
           theme(plot.title = element_text(lineheight=.8, face="bold"))
         

         
         
         
         
         
 #html

         
         url<-'http://left-lane.com/european-car-sales-data/audi/'
         
         stran <- html_session(url) %>% read_html(encoding = "Windows-1250")
         Audi_prodaja<- stran %>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Audi_prodaja<-Audi_prodaja[-1,]
         names(Audi_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Audi_prodaja$Mesec <- factor(Audi_prodaja$Mesec, levels =Audi_prodaja$Mesec,
                                       Audi_prodaja$Mesec, ordered = TRUE)
         Audi_prodaja[-1] <- apply(Audi_prodaja[-1], 2, as.numeric)
         Audi_prodaja$Povprečno <- apply(Audi_prodaja[-1], 1, mean, na.rm = TRUE)
         Audi_prodaja$Povprečno<-round(Audi_prodaja$Povprečno,3)
         Audi_prodaja$Proizvajalec <- "Audi"

         
         url2<-'http://left-lane.com/european-car-sales-data/bmw/'
         stran2<-html_session(url2) %>% read_html(encoding = "Windows-1250")
         
         Bmw_prodaja<-stran2%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         names(Bmw_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Bmw_prodaja<-Bmw_prodaja[-1,]
         Bmw_prodaja$Mesec <- factor(Bmw_prodaja$Mesec, levels =
                                        Bmw_prodaja$Mesec, ordered = TRUE)
         Bmw_prodaja[-1] <- apply(Bmw_prodaja[-1], 2, as.numeric)
         Bmw_prodaja$Povprečno <- apply(Bmw_prodaja[-1], 1, mean, na.rm = TRUE)
         Bmw_prodaja$Povprečno<-round(Bmw_prodaja$Povprečno,3)
         Bmw_prodaja$Proizvajalec <- "Bmw"
         
         url3<-'http://left-lane.com/european-car-sales-data/citroen/'
         stran3<-html_session(url3) %>% read_html(encoding = "Windows-1250")
         Citroen_prodaja<-stran3%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Citroen_prodaja<-Citroen_prodaja[-1,]
         names(Citroen_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Citroen_prodaja$Povprečno<-round((as.numeric(Citroen_prodaja$`2012`)+as.numeric(Citroen_prodaja$`2013`)+as.numeric(Citroen_prodaja$`2014`)+as.numeric(Citroen_prodaja$`2015`))/4,3)
         Citroen_prodaja$Mesec <- factor(Citroen_prodaja$Mesec, levels =
                                       Citroen_prodaja$Mesec, ordered = TRUE)
         Citroen_prodaja[-1] <- apply(Citroen_prodaja[-1], 2, as.numeric)
         Citroen_prodaja$Povprečno <- apply(Citroen_prodaja[-1], 1, mean, na.rm = TRUE)
         Citroen_prodaja$Povprečno<-round(Citroen_prodaja$Povprečno,3)
         Citroen_prodaja$Proizvajalec <- "Citroen"
         
         url4<-'http://left-lane.com/european-car-sales-data/ford/'
         stran4<-html_session(url4) %>% read_html(encoding = "Windows-1250")
         Ford_prodaja<-stran4%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Ford_prodaja<-Ford_prodaja[-1,]
         names(Ford_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Ford_prodaja$Povprečno<-round((as.numeric(Ford_prodaja$`2012`)+as.numeric(Ford_prodaja$`2013`)+as.numeric(Ford_prodaja$`2014`)+as.numeric(Ford_prodaja$`2015`))/4,3)
         Ford_prodaja$Mesec <- factor(Ford_prodaja$Mesec, levels =
                                       Ford_prodaja$Mesec, ordered = TRUE)
         Ford_prodaja[-1] <- apply(Ford_prodaja[-1], 2, as.numeric)
         Ford_prodaja$Povprečno <- apply(Ford_prodaja[-1], 1, mean, na.rm = TRUE)
         Ford_prodaja$Povprečno<-round(Ford_prodaja$Povprečno,3)
         Ford_prodaja$Proizvajalec <- "Ford"
         
         url5<-'http://left-lane.com/european-car-sales-data/fiat/'
         stran5<-html_session(url5) %>% read_html(encoding = "Windows-1250")
         Fiat_prodaja<-stran5%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Fiat_prodaja<-Fiat_prodaja[-1,]
         names(Fiat_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Fiat_prodaja$Povprečno<-round((as.numeric(Fiat_prodaja$`2012`)+as.numeric(Fiat_prodaja$`2013`)+as.numeric(Fiat_prodaja$`2014`)+as.numeric(Fiat_prodaja$`2015`))/4,3)
         Fiat_prodaja$Mesec <- factor(Fiat_prodaja$Mesec, levels =
                                       Fiat_prodaja$Mesec, ordered = TRUE)
         Fiat_prodaja[-1] <- apply(Fiat_prodaja[-1], 2, as.numeric)
         Fiat_prodaja$Povprečno <- apply(Fiat_prodaja[-1], 1, mean, na.rm = TRUE)
         Fiat_prodaja$Povprečno<-round(Fiat_prodaja$Povprečno,3)
         Fiat_prodaja$Proizvajalec <- "Fiat"
         
         url6<-'http://left-lane.com/european-car-sales-data/mazda/'
         stran6<-html_session(url6) %>% read_html(encoding = "Windows-1250")
         Mazda_prodaja<-stran6%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Mazda_prodaja<-Mazda_prodaja[-1,]
         names(Mazda_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Mazda_prodaja$Povprečno<-round((as.numeric(Mazda_prodaja$`2012`)+as.numeric(Mazda_prodaja$`2013`)+as.numeric(Mazda_prodaja$`2014`)+as.numeric(Mazda_prodaja$`2015`))/4,3)
         Mazda_prodaja$Mesec <- factor(Mazda_prodaja$Mesec, levels =
                                       Mazda_prodaja$Mesec, ordered = TRUE)
         Mazda_prodaja[-1] <- apply(Mazda_prodaja[-1], 2, as.numeric)
         Mazda_prodaja$Povprečno <- apply(Mazda_prodaja[-1], 1, mean, na.rm = TRUE)
         Mazda_prodaja$Povprečno<-round(Mazda_prodaja$Povprečno,3)
         Mazda_prodaja$Proizvajalec <- "Mazda"
         
         url7<-'http://left-lane.com/european-car-sales-data/peugeot/'
         stran7<-html_session(url7) %>% read_html(encoding = "Windows-1250")
         Peugeot_prodaja<-stran7%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Peugeot_prodaja<-Peugeot_prodaja[-1,]
         names(Peugeot_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Peugeot_prodaja$Povprečno<-round((as.numeric(Peugeot_prodaja$`2012`)+as.numeric(Peugeot_prodaja$`2013`)+as.numeric(Peugeot_prodaja$`2014`)+as.numeric(Peugeot_prodaja$`2015`))/4,3)
         Peugeot_prodaja$Mesec <- factor(Peugeot_prodaja$Mesec, levels =
                                       Peugeot_prodaja$Mesec, ordered = TRUE)
         Peugeot_prodaja[-1] <- apply(Peugeot_prodaja[-1], 2, as.numeric)
         Peugeot_prodaja$Povprečno <- apply(Peugeot_prodaja[-1], 1, mean, na.rm = TRUE)
         Peugeot_prodaja$Povprečno<-round(Peugeot_prodaja$Povprečno,3)
         Peugeot_prodaja$Proizvajalec <- "Peugeot"
         
         url8<-'http://left-lane.com/european-car-sales-data/renault/'
         stran8<-html_session(url8) %>% read_html(encoding = "Windows-1250")
         Renault_prodaja<-stran8%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Renault_prodaja<-Renault_prodaja[-1,]
         names(Renault_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Renault_prodaja$Povprečno<-round((as.numeric(Renault_prodaja$`2012`)+as.numeric(Renault_prodaja$`2013`)+as.numeric(Renault_prodaja$`2014`)+as.numeric(Renault_prodaja$`2015`))/4,3)
         Renault_prodaja$Mesec <- factor(Renault_prodaja$Mesec, levels =
                                       Renault_prodaja$Mesec, ordered = TRUE)
         Renault_prodaja[-1] <- apply(Renault_prodaja[-1], 2, as.numeric)
         Renault_prodaja$Povprečno <- apply(Renault_prodaja[-1], 1, mean, na.rm = TRUE)
         Renault_prodaja$Povprečno<-round(Renault_prodaja$Povprečno,3)
         Renault_prodaja$Proizvajalec <- "Renault"
         
         url9<-'http://left-lane.com/european-car-sales-data/opel-vauxhall/'
         stran9<-html_session(url9) %>% read_html(encoding = "Windows-1250")
         Opel_prodaja<-stran9%>% html_nodes(xpath ="//table") %>% .[[1]]%>% html_table(fill=TRUE)
         Opel_prodaja<-Opel_prodaja[-1,]
         names(Opel_prodaja)<-c("Mesec","2012","2013","2014","2015")
         Opel_prodaja$Povprečno<-round((as.numeric(Opel_prodaja$`2012`)+as.numeric(Opel_prodaja$`2013`)+as.numeric(Opel_prodaja$`2014`)+as.numeric(Opel_prodaja$`2015`))/4,3)
         Opel_prodaja$Mesec <- factor(Opel_prodaja$Mesec, levels =
                                       Opel_prodaja$Mesec, ordered = TRUE)
         Opel_prodaja[-1] <- apply(Opel_prodaja[-1], 2, as.numeric)
         Opel_prodaja$Povprečno <- apply(Opel_prodaja[-1], 1, mean, na.rm = TRUE)
         Opel_prodaja$Povprečno<-round(Opel_prodaja$Povprečno,3)
         Opel_prodaja$Proizvajalec <- "Opel"
         

         graf_Mazda<-ggplot(Mazda_prodaja, aes(x=Mesec, y=Povprečno, group=1)) + geom_line(colour="red")+
                               ggtitle("Povprečna prodaja avtomobilov\nznamke Mazda(2012-2015) v tisočih po mesecih")+
                               theme(plot.title = element_text(lineheight=.8, face="bold"),axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) 
  
         
         graf_Ford<-ggplot(Ford_prodaja, aes(x=Mesec, y=Povprečno, group=1)) + geom_line(colour="blue")+
                               ggtitle("Povprečna prodaja avtomobilov\nznamke Ford(2012-2015) v tisočih po mesecih")+
                               theme(plot.title = element_text(lineheight=.8, face="bold"),axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
        
         Prodaja <- rbind(Audi_prodaja, Bmw_prodaja,Citroen_prodaja,Ford_prodaja,Fiat_prodaja,Mazda_prodaja,Peugeot_prodaja,Renault_prodaja,Opel_prodaja) 
         skupni_graf<-ggplot(Prodaja, aes(x=Mesec, y=Povprečno, group=Proizvajalec, color =
                               Proizvajalec)) + geom_line() +
                               ggtitle("Povprečna prodaja avtomobilov po\nznamkah(2012-2015) v Europi po mesecih v tisočih")+
                               theme(plot.title = element_text(lineheight=.8, face="bold"),axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
         
         Prodaja<-melt(Prodaja,c("Mesec","Povprečno","Proizvajalec"))
         names(Prodaja)<-c("Mesec","Povprečno","Proizvajalec","Leto","Kolicina prodanih vozil")
         
         
         #' @export
CalcAlleleDiffs <- function(f){
  infoTable <- as.matrix(read.csv(f, header=TRUE))
  BEG1 <- as.numeric(infoTable[1,2])
  END1 <- as.numeric(infoTable[2,2])
  str1 <- toString(infoTable[4,2])
  
  for(j in BEG1:END1){
    filePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4.txt"), collapse = "")	
    if (file.exists(filePath) == TRUE){
    print("frig")
    outFilePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4_diffs.txt"), collapse = "")	
    outTable <- matrix(nrow = 1, ncol = 8)	
    k <-scan(filePath, sep = ">", what = "complex")	
    for(i in seq(2,length(k),12)){
      textMat <- matrix(nrow = 6, ncol = 8)
      allele <- strsplit(k[i],".", fixed = TRUE)
      locus <- strsplit(allele[[1]][1],"L")[[1]][2]
      copy <- allele[[1]][2]
      alleleNumber <- allele[[1]][3]
      a1 <- k[i+1]
      a2 <- k[i+4]
      a3 <- k[i+7]
      a4 <- k[i+10]
      textMat[,c(1,4)] <- locus
      textMat[,c(2,5)] <- copy
      textMat[,3] <- c(1,1,1,2,2,3)
      textMat[,6] <- c(2,3,4,3,4,4)
      textMat[,7] <- c(adist(a1,a2),adist(a1,a3), adist(a1,a4), adist(a2,a3), adist(a2,a4), adist(a3,a4))
      textMat[,8] <- nchar(a1)
      outTable <- rbind(outTable,textMat)
    }
    outTable <- outTable[2:length(outTable[,1]),]
    write.table(outTable,file = outFilePath, quote = FALSE, sep = "\t", row.names = FALSE, col.names = FALSE)
    print(j)
    
    }
    else {
     print(paste(c("I",j," FILE NOT FOUND"), collapse = ""), quote = FALSE)
    }
    
  }
  assign("infoTable",infoTable,globalenv())
}
#' @export
CalcAlleleDiffs <- function(f){
  infoTable <- as.matrix(read.csv(f, header=TRUE))
  BEG1 <- as.numeric(infoTable[1,2])
  END1 <- as.numeric(infoTable[2,2])
  str1 <- toString(infoTable[4,2])
  
  for(j in BEG1:END1){
    filePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4.txt"), collapse = "")	
    if (file.exists(filePath) == TRUE){
    outFilePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4_diffs.txt"), collapse = "")	
    outTable <- matrix(nrow = 1, ncol = 8)	
    k <-scan(filePath, sep = ">", what = "complex")	
    for(i in seq(2,length(k),12)){
      textMat <- matrix(nrow = 6, ncol = 8)
      allele <- strsplit(k[i],".", fixed = TRUE)
      locus <- strsplit(allele[[1]][1],"L")[[1]][2]
      copy <- allele[[1]][2]
      alleleNumber <- allele[[1]][3]
      a1 <- k[i+1]
      a2 <- k[i+4]
      a3 <- k[i+7]
      a4 <- k[i+10]
      textMat[,c(1,4)] <- locus
      textMat[,c(2,5)] <- copy
      textMat[,3] <- c(1,1,1,2,2,3)
      textMat[,6] <- c(2,3,4,3,4,4)
      textMat[,7] <- c(adist(a1,a2),adist(a1,a3), adist(a1,a4), adist(a2,a3), adist(a2,a4), adist(a3,a4))
      textMat[,8] <- nchar(a1)
      outTable <- rbind(outTable,textMat)
    }
    outTable <- outTable[2:length(outTable[,1]),]
    write.table(outTable,file = outFilePath, quote = FALSE, sep = "\t", row.names = FALSE, col.names = FALSE)
    print(j)
    
    }
    else {
     print(paste(c("I",j," FILE NOT FOUND"), collapse = ""), quote = FALSE)
    }
    
  }
  assign("infoTable",infoTable,globalenv())
}
#' @export
CalcAlleleDiffs <- function(f){
  infoTable <- as.matrix(read.csv(f, header=TRUE))
  BEG1 <- as.numeric(infoTable[1,2])
  END1 <- as.numeric(infoTable[2,2])
  str1 <- toString(infoTable[4,2])
  
  for(j in BEG1:END1){
    if (file.exists(filePath) == TRUE){
    
    filePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4.txt"), collapse = "")	
    outFilePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4_diffs.txt"), collapse = "")	
    outTable <- matrix(nrow = 1, ncol = 8)	
    k <-scan(filePath, sep = ">", what = "complex")	
    for(i in seq(2,length(k),12)){
      textMat <- matrix(nrow = 6, ncol = 8)
      allele <- strsplit(k[i],".", fixed = TRUE)
      locus <- strsplit(allele[[1]][1],"L")[[1]][2]
      copy <- allele[[1]][2]
      alleleNumber <- allele[[1]][3]
      a1 <- k[i+1]
      a2 <- k[i+4]
      a3 <- k[i+7]
      a4 <- k[i+10]
      textMat[,c(1,4)] <- locus
      textMat[,c(2,5)] <- copy
      textMat[,3] <- c(1,1,1,2,2,3)
      textMat[,6] <- c(2,3,4,3,4,4)
      textMat[,7] <- c(adist(a1,a2),adist(a1,a3), adist(a1,a4), adist(a2,a3), adist(a2,a4), adist(a3,a4))
      textMat[,8] <- nchar(a1)
      outTable <- rbind(outTable,textMat)
    }
    outTable <- outTable[2:length(outTable[,1]),]
    write.table(outTable,file = outFilePath, quote = FALSE, sep = "\t", row.names = FALSE, col.names = FALSE)
    print(j)
    
    }
    else {
     print(paste(c("I",j," FILE NOT FOUND"), collapse = ""), quote = FALSE)
    }
    
  }
  assign("infoTable",infoTable,globalenv())
}
#' @export
CalcAlleleDiffs <- function(f){
  infoTable <- as.matrix(read.csv(f, header=TRUE))
  BEG1 <- as.numeric(infoTable[1,2])
  END1 <- as.numeric(infoTable[2,2])
  str1 <- toString(infoTable[4,2])
  
  for(j in BEG1:END1){
    filePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4.txt"), collapse = "")	
    outFilePath <- paste(c(str1,"/I",j,"/I",j,"_allelesFromPost_4_diffs.txt"), collapse = "")	
    outTable <- matrix(nrow = 1, ncol = 8)	
    k <-scan(filePath, sep = ">", what = "complex")	
    for(i in seq(2,length(k),12)){
      textMat <- matrix(nrow = 6, ncol = 8)
      allele <- strsplit(k[i],".", fixed = TRUE)
      locus <- strsplit(allele[[1]][1],"L")[[1]][2]
      copy <- allele[[1]][2]
      alleleNumber <- allele[[1]][3]
      a1 <- k[i+1]
      a2 <- k[i+4]
      a3 <- k[i+7]
      a4 <- k[i+10]
      textMat[,c(1,4)] <- locus
      textMat[,c(2,5)] <- copy
      textMat[,3] <- c(1,1,1,2,2,3)
      textMat[,6] <- c(2,3,4,3,4,4)
      textMat[,7] <- c(adist(a1,a2),adist(a1,a3), adist(a1,a4), adist(a2,a3), adist(a2,a4), adist(a3,a4))
      textMat[,8] <- nchar(a1)
      outTable <- rbind(outTable,textMat)
    }
    outTable <- outTable[2:length(outTable[,1]),]
    write.table(outTable,file = outFilePath, quote = FALSE, sep = "\t", row.names = FALSE, col.names = FALSE)
    print(j)
    
  }
  assign("infoTable",infoTable,globalenv())
}
#!/usr/bin/env RScript
library(parallel)
library(iterators)
library(foreach)
library(doParallel)
library(proto)
library(argparse)

parser <- ArgumentParser()
parser$add_argument('input', help = 'input csv file')
parser$add_argument('gameplayInput', help = 'input gameplay video')
parser$add_argument('output', help = 'output video file')
parser$add_argument('--fps', type = 'integer', default = 3, help = 'frames per second')
parser$add_argument('--dpi', type = 'integer', default = 72, help = 'dpi for generated video frames')
parser$add_argument('--tempdir', help = 'working directory for intermediate files')
args <- parser$parse_args()

main <- function()
{
	fps <- args$fps
	input <- args$input
	gameplayInput <- args$gameplayInput
	output <- args$output
	dpi <- args$dpi
	frameDir <- if (is.null(args$tempdir)) tempdir() else args$tempdir

	videoAttrs <- system(paste0('ffprobe -v 1 -show_entries stream=width,height,r_frame_rate ',
		'-of default=noprint_wrappers=1:nokey=1 ', gameplayInput), intern = T)

	videoRes = as.integer(videoAttrs[1:2])
	videoSize = videoRes / dpi
	fpsTokens = as.integer(unlist(strsplit(videoAttrs[3], '/')[1]))
	gameplayFps <- fpsTokens[1] / fpsTokens[2]
	dar <- paste0(videoRes[1], '/', videoRes[2])

	message('Input gameplay runs at ', gameplayFps, ' FPS at ', videoRes[1], 'x', videoRes[2])

	data <- read.csv(input)
	data$offsetSeconds = data$offset / 1000

	duration <- max(data$offsetSeconds)
	frames <- floor(duration * fps)
	cores <- detectCores()
	message('Rendering ', frames, ' frames using ', cores, ' cores')

	cluster <- makeCluster(cores)
	registerDoParallel(cluster)

	foreach(i = 1:frames, .packages = 'ggplot2') %dopar% {
		toRender <- subset(data, offset < i / fps * 1000)
		plot <- ggplot(toRender, aes(x = offsetSeconds, y = value)) +
			geom_line() +
			labs(x = 'Time (s)', y = 'GSR (microsiemens)') +
			ylim(c(0, ceiling(max(data$value)))) +
			xlim(c(0, duration))
		ggsave(paste0(frameDir, '/', i, '.jpg'), plot,
			width = videoSize[1], height = videoSize[2], dpi = dpi)
	}

	stopCluster(cluster)

	fpsRatio <- gameplayFps / fps 
	tempVideoPath = paste0(frameDir, '/', 'frames.mp4')
	message('Rendering video from frames: ', tempVideoPath)
	system(paste0('ffmpeg -v 1 -y -r ', gameplayFps, ' -framerate ', fps,
		' -i "', frameDir, '/%d.jpg" ', ' -filter:v "setpts=', fpsRatio, '*PTS" ', tempVideoPath))

	message('Merging with gameplay')
	system(paste0('ffmpeg -v 1 -y -r ', gameplayFps, ' -i "', gameplayInput, '" -i "', tempVideoPath, '" ',
		' -filter_complex "[1:0]format=rgba[a];',
		'[0:0]setdar=', dar, ',format=yuva420p,colorchannelmixer=aa=0.8[b];',
		'[a][b]overlay=shortest=1"',
		' ', output))
}

dummy <- main()#!/usr/bin/env RScript
library(parallel)
library(iterators)
library(foreach)
library(doParallel)
library(proto)
library(argparse)

parser <- ArgumentParser()
parser$add_argument('input', help = 'input csv file')
parser$add_argument('gameplayInput', help = 'input gameplay video')
parser$add_argument('output', help = 'output video file')
parser$add_argument('--fps', type = 'integer', default = 3, help = 'frames per second')
parser$add_argument('--dpi', type = 'integer', default = 72, help = 'dpi for generated video frames')
parser$add_argument('--tempdir', default = tempdir(), help = 'working directory for intermediate files')
args <- parser$parse_args()

main <- function()
{
	fps <- args$fps
	input <- args$input
	gameplayInput <- args$gameplayInput
	output <- args$output
	dpi <- args$dpi
	frameDir <- args$tempdir

	videoAttrs <- system(paste0('ffprobe -v 1 -show_entries stream=width,height,r_frame_rate ',
		'-of default=noprint_wrappers=1:nokey=1 ', gameplayInput), intern = T)

	videoRes = as.integer(videoAttrs[1:2])
	videoSize = videoRes / dpi
	fpsTokens = as.integer(unlist(strsplit(videoAttrs[3], '/')[1]))
	gameplayFps <- fpsTokens[1] / fpsTokens[2]
	dar <- paste0(videoRes[1], '/', videoRes[2])

	message('Input gameplay runs at ', gameplayFps, ' FPS at ', videoRes[1], 'x', videoRes[2])

	data <- read.csv(input)
	data$offsetSeconds = data$offset / 1000

	duration <- max(data$offsetSeconds)
	frames <- floor(duration * fps)
	cores <- detectCores()
	message('Rendering ', frames, ' frames using ', cores, ' cores')

	cluster <- makeCluster(cores)
	registerDoParallel(cluster)

	foreach(i = 1:frames, .packages = 'ggplot2') %dopar% {
		toRender <- subset(data, offset < i / fps * 1000)
		plot <- ggplot(toRender, aes(x = offsetSeconds, y = value)) +
			geom_line() +
			labs(x = 'Time (s)', y = 'GSR (microsiemens)') +
			ylim(c(0, ceiling(max(data$value)))) +
			xlim(c(0, duration))
		ggsave(paste0(frameDir, '/', i, '.jpg'), plot,
			width = videoSize[1], height = videoSize[2], dpi = dpi)
	}

	stopCluster(cluster)

	fpsRatio <- gameplayFps / fps 
	tempVideoPath = paste0(frameDir, '/', 'frames.mp4')
	message('Rendering video from frames: ', tempVideoPath)
	system(paste0('ffmpeg -v 1 -y -r ', gameplayFps, ' -framerate ', fps,
		' -i "', frameDir, '/%d.jpg" ', ' -filter:v "setpts=', fpsRatio, '*PTS" ', tempVideoPath))

	message('Merging with gameplay')
	system(paste0('ffmpeg -v 1 -y -r ', gameplayFps, ' -i "', gameplayInput, '" -i "', tempVideoPath, '" ',
		' -filter_complex "[1:0]format=rgba[a];',
		'[0:0]setdar=', dar, ',format=yuva420p,colorchannelmixer=aa=0.8[b];',
		'[a][b]overlay=shortest=1"',
		' ', output))
}

dummy <- main()#!/usr/bin/env RScript
library(parallel)
library(iterators)
library(foreach)
library(doParallel)
library(proto)
library(argparse)

parser <- ArgumentParser()
parser$add_argument('input', help = 'input csv file')
parser$add_argument('output', help = 'output video file')
parser$add_argument('--fps', type = 'integer', default = 3, help = 'frames per second')
args <- parser$parse_args()

main <- function()
{
	fps <- args$fps
	input <- args$input
	output <- args$output

	data <- read.csv(input)
	data$offsetSeconds = data$offset / 1000

	duration <- max(data$offsetSeconds)
	frames <- floor(duration * fps)
	cores <- detectCores()
	message('Rendering ', frames, ' frames using ', cores, ' cores')

	cluster <- makeCluster(cores)
	registerDoParallel(cluster)

	frameDir <- tempdir()
	foreach(i = 1:frames, .packages = 'ggplot2') %dopar% {
		toRender <- subset(data, offset < i / fps * 1000)
		plot <- ggplot(toRender, aes(x = offsetSeconds, y = value)) +
			geom_line() +
			labs(x = 'Time (s)', y = 'GSR (microsiemens)') +
			ylim(c(0, ceiling(max(data$value)))) +
			xlim(c(0, duration))
		ggsave(paste0(frameDir, '/', i, '.jpg'), plot)
	}

	stopCluster(cluster)

	message('Rendering video from frames: ', output)
	system(paste0('ffmpeg -v 1 -y -r ', fps, ' -i "', frameDir, '/%d.jpg" ', output))
}

dummy <- main()#!/usr/bin/env RScript
library(ggplot2)

args <- commandArgs(trailingOnly = T)

main <- function()
{
	inputPath <- args[1]
	outputPath <- args[2]
	if (is.na(inputPath))
	{
		stop('Please specify a csv file')
	}

	if (is.na(outputPath))
	{
		stop('Please specify an output file')
	}

	data <- read.csv(inputPath)
	plot <- ggplot(data, aes(x = offset, y = value)) +
		geom_line() +
		labs(x = 'Time (ms)', y = 'GSR (microsiemens)') +
		ylim(c(0, ceiling(max(data$value))))

	ggsave(outputPath, plot)
}

dummy <- main()#!/usr/bin/env RScript
library(parallel)
library(iterators)
library(foreach)
library(doParallel)
library(proto)
library(argparse)

parser <- ArgumentParser()
parser$add_argument('input', help = 'input csv file')
parser$add_argument('output', help = 'output video file')
parser$add_argument('--fps', type = 'integer', default = 3, help = 'frames per second')
args <- parser$parse_args()

main <- function()
{
	fps <- args$fps
	input <- args$input
	output <- args$output

	data <- read.csv(input)
	data$offsetSeconds = data$offset / 1000

	duration <- max(data$offsetSeconds)
	frames <- floor(duration * fps)
	cores <- detectCores()
	message('Rendering ', frames, ' frames using ', cores, ' cores')

	cluster <- makeCluster(cores)
	registerDoParallel(cluster)

	frameDir <- tempdir()
	foreach(i = 1:frames, .packages = 'ggplot2') %dopar% {
		toRender <- subset(data, offset < i / fps * 1000)
		plot <- ggplot(toRender, aes(x = offsetSeconds, y = value)) +
			geom_line() +
			labs(x = 'Time (s)', y = 'GSR (microsiemens)') +
			ylim(c(0, ceiling(max(data$value)))) +
			xlim(c(0, duration))
		ggsave(paste0(frameDir, '/', i, '.jpg'), plot)
	}

	stopCluster(cluster)

	message('Rendering video from frames: ', output)
	system(paste0('ffmpeg.exe -v 1 -y -r ', fps, ' -i "', frameDir, '/%d.jpg" ', output))
}

dummy <- main()##
## Run this demo with
## mpirun -np 32 Rscript -e 'dir <- "your-airline-data-directory"; demo("matrix", package="pbdIO", echo=FALSE)'
##

## TODO Unfinished example code!
#suppressPackageStartupMessages(library(pbdMPI))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(pbdML))
suppressPackageStartupMessages(library(pbdIO))
suppressPackageStartupMessages(library(memuse))
init.grid()
a0 <- a <- deltime()

col_classes = c(rep("integer", 8), "character", "integer", "character",
    rep("integer", 5), "character", "character", rep("integer", 4),
    "character", rep("integer", 6))

## local subset of airline data - change to your data location!!
dir <- "/lustre/atlas/scratch/ost/stf006/airline"
air <- comm.fread(dir, verbose=3, colClasses=col_classes)
a <- deltime(a, "T Total comm.fread:")

## variables from the R Journal iodata article. Select for complete cases
##   rebalancing
xy_df <- subset(air, select=c(ArrDelay, DayOfWeek, DepTime, DepDelay, Month))
comm.cat("colnames(xy_df)", colnames(xy_df), "\n", quiet=TRUE)

## subset complete cases
## comm.print(xy_df[1:5, ], all.rank=TRUE)
comm.cat("nrow: ")
comm.cat(nrow(xy_df), " ", all.rank=TRUE, quiet=TRUE)
comm.cat("\n")
xy_df <- xy_df[complete.cases(xy_df), ]
comm.cat("nrow: ")
comm.cat(nrow(xy_df), " ", all.rank=TRUE, quiet=TRUE)
comm.cat("\n")
a <- deltime(a, "complete cases subset:")

## now rebalance after subsettng!
xy_df <- pbdIO:::comm.rebalance.df(xy_df, lo.side="right", type="equal", verbose=1)
a <- deltime(a, "rebalance:")

## separate x and y
x_df <- subset(xy_df, select=c(DayOfWeek, DepTime, DepDelay, Month))
y_df <- subset(xy_df, select=c(ArrDelay))
a <- deltime(a, "separate x and y df:")

## transform some variables
x_df$DayOfWeek <- factor(x_df$DayOfWeek, levels=1:7)
x_df$Month <- factor(x_df$Month, levels=1:12)
x_df$DepTime <- sprintf("%04d", x_df$DepTime)
x_df$DepTime <- as.numeric(substr(x_df$DepTime, 1, 2))*60 +
    as.numeric(substr(x_df$DepTime, 3, 4))
a <- deltime(a, "factors and transformations:")

## create model matrix
form = ~ DayOfWeek + DepTime + DepDelay + Month
x_mm <- model.matrix(form, x_df)
a <- deltime(a, "model matrix:")

## glue x_mm distributed pieces into a ddmatrix
colnames_x_mm <- colnames(x_mm)
comm.cat("colnames_x_mm:", colnames_x_mm, "\n")
dimnames(x_mm) <- NULL
xd_mm <- new("ddmatrix", Data=x_mm, dim=c(allreduce(nrow(x_mm)), ncol(x_mm)),
             ldim=dim(x_mm), bldim=dim(x_mm), ICTXT=2)
## comm.print(submatrix(xd_mm)[1:5, 1:5], all.rank=TRUE)
print(xd_mm)
a <- deltime(a, "xd_mm new ddmatrix:")

## glue y distributed pieces into a ddmatrix
y <- as.matrix(y_df)
dimnames(y) <- NULL
yd <- new("ddmatrix", Data=y, dim=c(allreduce(nrow(y)), 1),
             ldim=dim(y), bldim=dim(y), ICTXT=2)
print(yd)
a <- deltime(a, "y new ddmatrix:")

xd_mm <- as.blockcyclic(xd_mm, bldim=c(2, 2))
yd <- as.blockcyclic(yd, bldim=c(2, 2))
a <- deltime(a, "xd_mm and yd blockcyclic ddmatrix:")

beta <- lm.fit(xd_mm, yd)
coefs <- as.matrix(beta$coefficients)
rownames(coefs) <- colnames_x_mm
comm.print(coefs)
comm.print(names(beta))
a <- deltime(a, "lm.fit:")

beta.coef <- solve(crossprod(xd_mm), crossprod(xd_mm, yd))
beta <- as.matrix(beta.coef)
comm.print(beta)
a <- deltime(a, "solve crossprod:")

xsvd <- svd(xx)
comm.print(xsvd$d)
a <- deltime(a, "svd xx:")


a <- deltime(a0, "T Total time:")
finalize()
##
## Run this demo with
## mpirun -np 32 Rscript -e 'dir <- "your-airline-data-directory"; demo("matrix", package="pbdIO", echo=FALSE)'
##

## TODO Unfinished example code!
#suppressPackageStartupMessages(library(pbdMPI))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(pbdML))
suppressPackageStartupMessages(library(pbdIO))
suppressPackageStartupMessages(library(memuse))
init.grid()
a0 <- a <- deltime()

col_classes = c(rep("integer", 8), "character", "integer", "character",
    rep("integer", 5), "character", "character", rep("integer", 4),
    "character", rep("integer", 6))

## local subset of airline data - change to your data location!!
dir <- "/lustre/atlas/scratch/ost/stf006/airline"
air <- comm.fread(dir, verbose=3, colClasses=col_classes)
a <- deltime(a, "T Total comm.fread:")

## variables from the R Journal iodata article. Select for complete cases
##   rebalancing
xy_df <- subset(air, select=c(ArrDelay, DayOfWeek, DepTime, DepDelay, Month))
comm.cat("colnames(xy_df)", colnames(xy_df), "\n", quiet=TRUE)

## subset complete cases
comm.print(xy_df[1:5, ], all.rank=TRUE)
comm.cat("nrow: ")
comm.cat(nrow(xy_df), all.rank=TRUE, quiet=TRUE)
comm.cat("\n")
xy_df <- xy_df[complete.cases(xy_df), ]
comm.cat("nrow: ")
comm.cat(nrow(xy_df), all.rank=TRUE, quiet=TRUE)
comm.cat("\n")
a <- deltime(a, "complete cases subset:")

## now rebalance after subsettng!
xy_df <- pbdIO:::comm.rebalance.df(xy_df, lo.side="right", type="equal", verbose=1)
a <- deltime(a, "rebalance:")

## separate x and y
x_df <- subset(xy_df, select=c(DayOfWeek, DepTime, DepDelay, Month))
y_df <- subset(xy_df, select=c(ArrDelay))
a <- deltime(a, "separate x and y df:")

## transform some variables
x_df$DayOfWeek <- factor(x_df$DayOfWeek, levels=1:7)
x_df$Month <- factor(x_df$Month, levels=1:12)
x_df$DepTime <- sprintf("%04d", x_df$DepTime)
x_df$DepTime <- as.numeric(substr(x_df$DepTime, 1, 2))*60 +
    as.numeric(substr(x_df$DepTime, 3, 4))
a <- deltime(a, "factors and transformations:")

## create model matrix
form = ~ DayOfWeek + DepTime + DepDelay + Month
x_mm <- model.matrix(form, x_df)
comm.cat(comm.rank(), "class(x_mm)", class(x_mm), "\n", all.rank=TRUE, quiet=TRUE)
## comm.print(x_mm[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "model matrix:")

## glue x_mm distributed pieces into a ddmatrix
colnames_x_mm <- colnames(x_mm)
comm.cat("colnames_x_mm:", colnames_x_mm, "\n")
dimnames(x_mm) <- NULL
xd_mm <- new("ddmatrix", Data=x_mm, dim=c(allreduce(nrow(x_mm)), ncol(x_mm)),
             ldim=dim(x_mm), bldim=dim(x_mm), ICTXT=2)
## comm.print(submatrix(xd_mm)[1:5, 1:5], all.rank=TRUE)
print(xd_mm)
a <- deltime(a, "xd_mm new ddmatrix:")

## glue y distributed pieces into a ddmatrix
y <- as.matrix(y_df)
dimnames(y) <- NULL
yd <- new("ddmatrix", Data=y, dim=c(allreduce(nrow(y)), 1),
             ldim=dim(y), bldim=dim(y), ICTXT=2)
print(yd)
a <- deltime(a, "y new ddmatrix:")

xd_mm <- as.blockcyclic(xd_mm, bldim=c(2, 2))
yd <- as.blockcyclic(yd, bldim=c(2, 2))
a <- deltime(a, "xd_mm and yd blockcyclic ddmatrix:")

beta <- lm.fit(xd_mm, yd)
coefs <- as.matrix(beta$coefficients)
comm.print(coefs)
comm.print(names(beta))
a <- deltime(a, "lm.fit:")

beta.coef <- solve(crossprod(xd_mm), crossprod(xd_mm, yd))
beta <- as.matrix(beta.coef)
comm.print(beta)
a <- deltime(a, "solve crossprod:")

xsvd <- svd(xx)
comm.print(xsvd$d)
a <- deltime(a, "svd xx:")


a <- deltime(a0, "T Total time:")
finalize()
##
## Run this demo with
## mpirun -np 32 Rscript -e 'dir <- "your-airline-data-directory"; demo("matrix", package="pbdIO", echo=FALSE)'
##

## TODO Unfinished example code!
#suppressPackageStartupMessages(library(pbdMPI))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(pbdML))
suppressPackageStartupMessages(library(pbdIO))
suppressPackageStartupMessages(library(memuse))
init.grid()
a0 <- a <- deltime()

col_classes = c(rep("integer", 8), "character", "integer", "character",
    rep("integer", 5), "character", "character", rep("integer", 4),
    "character", rep("integer", 6))

## local subset of airline data - change to your data location!!
dir <- "/lustre/atlas/scratch/ost/stf006/airline"
air <- comm.fread(dir, verbose=3, colClasses=col_classes)
a <- deltime(a, "T Total comm.fread:")

## variables from the R Journal iodata article. Select for complete cases
##   rebalancing
xy_df <- subset(air, select=c(ArrDelay, DayOfWeek, DepTime, DepDelay, Month))
comm.cat("colnames(xy_df)", colnames(xy_df), "\n", quiet=TRUE)

## subset complete cases
comm.print(xy_df[1:5, ], all.rank=TRUE)
comm.cat("nrow: ")
comm.cat(nrow(xy_df), all.rank=TRUE, quiet=TRUE)
comm.cat("\n")
xy_df <- xy_df[complete.cases(xy_df), ]
comm.cat("nrow: ")
comm.cat(nrow(xy_df), all.rank=TRUE, quiet=TRUE)
comm.cat("\n")
a <- deltime(a, "complete cases subset:")

## now rebalance after subsettng!
xy_df <- pbdIO:::comm.rebalance.df(xy_df, lo.side="right", type="equal", verbose=1)
a <- deltime(a, "rebalance:")

## separate x and y
x_df <- subset(xy_df, select=c(DayOfWeek, DepTime, DepDelay, Month))
y_df <- subset(xy_df, select=c(ArrDelay))
a <- deltime(a, "separate x and y df:")

## transform some variables
x_df$DayOfWeek <- factor(x_df$DayOfWeek, levels=1:7)
x_df$Month <- factor(x_df$Month, levels=1:12)
x_df$DepTime <- sprintf("%04d", x_df$DepTime)
x_df$DepTime <- as.numeric(substr(x_df$DepTime, 1, 2))*60 +
    as.numeric(substr(x_df$DepTime, 3, 4))
a <- deltime(a, "factors and transformations:")

## create model matrix
form = ~ DayOfWeek + DepTime + DepDelay + Month
x_mm <- model.matrix(form, x_df)
comm.cat(comm.rank(), "class(x_mm)", class(x_mm), "\n", all.rank=TRUE, quiet=TRUE)
comm.print(x_mm[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "model matrix:")

## glue x_mm distributed pieces into a ddmatrix
colnames_x_mm <- colnames(x_mm)
comm.cat("colnames_x_mm:", colnames_x_mm, "\n")
dimnames(x_mm) <- NULL
xd_mm <- new("ddmatrix", Data=x_mm, dim=c(allreduce(nrow(x_mm)), ncol(x_mm)),
             ldim=dim(x_mm), bldim=dim(x_mm), ICTXT=2)
## comm.print(submatrix(xd_mm)[1:5, 1:5], all.rank=TRUE)
print(xd_mm)
a <- deltime(a, "xd_mm new ddmatrix:")

## glue y distributed pieces into a ddmatrix
y <- as.matrix(y_df)
dimnames(y) <- NULL
yd <- new("ddmatrix", Data=y, dim=c(allreduce(nrow(y)), 1),
             ldim=dim(y), bldim=dim(y), ICTXT=2)
print(yd)
a <- deltime(a, "y new ddmatrix:")

## xd_mmbc <- as.blockcyclic(xd_mm, bldim=c(2, 2))
## print(dim(submatrix(xd_mmbc)), all.rank=TRUE)
## a <- deltime(a, "matrix blockcyclic ddmatrix:")

beta <- lm.fit(xd_mm, yd)
coefs <- as.matrix(beta$coefficients)
comm.print(coefs)
comm.print(names(beta))
a <- deltime(a, "lm.fit:")

beta.coef <- solve(crossprod(xd_mm), crossprod(xd_mm, yd))
beta <- as.matrix(beta.coef)
comm.print(beta)
a <- deltime(a, "solve crossprod:")

xsvd <- svd(xx)
comm.print(xsvd$d)
a <- deltime(a, "svd xx:")


a <- deltime(a0, "T Total time:")
finalize()
##
## Run this demo with
## mpirun -np 32 Rscript -e 'dir <- "your-airline-data-directory"; demo("matrix", package="pbdIO", echo=FALSE)'
##

## TODO Unfinished example code!
#suppressPackageStartupMessages(library(pbdMPI))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(pbdML))
suppressPackageStartupMessages(library(pbdIO))
suppressPackageStartupMessages(library(memuse))
init.grid()
a0 <- a <- deltime()

col_classes = c(rep("integer", 8), "character", "integer", "character",
    rep("integer", 5), "character", "character", rep("integer", 4),
    "character", rep("integer", 6))

## local subset of airline data - change to your data location!!
dir <- "/lustre/atlas/scratch/ost/stf006/airline"
air <- comm.fread(dir, verbose=3, colClasses=col_classes)
a <- deltime(a, "T Total comm.fread:")

## for the matrix example, do pca on all data, projecting airports
## into a 2d picture. Take all numerical variables, compute PCA, and
## plot airport labels in the first two pc space.

## select the numeric columns
## comm.cat(comm.rank(), "col.classes(air)", unlist(lapply(air, class)), "\n", quiet=TRUE, all.rank=TRUE)
## airnames <- colnames(air)
## numeric <- unlist(allreduce(sapply(air, is.numeric), op="land"))

## variables from the R Journal iodata article. Select for complete cases
##   rebalancing
air_reg_df <- subset(air, select=c(ArrDelay, DayOfWeek, DepTime, DepDelay, Month))
comm.cat("colnames(air_reg_df)", colnames(air_reg_df), "\n", quiet=TRUE)

## subset complete cases
###!!!### replace with dplyr complete cases
comm.print(air_reg_df[1:5, ], all.rank=TRUE)
comm.cat(comm.rank(), "nrow:", nrow(air_reg_df), "\n", all.rank=TRUE, quiet=TRUE)
air_reg_df <- air_reg_df[complete.cases(air_reg_df), ]
comm.cat(comm.rank(), "nrow:", nrow(air_reg_df), "\n", all.rank=TRUE, quiet=TRUE)
a <- deltime(a, "complete cases subset:")

## now rebalance after subsettng!
air_reg_df <- pbdIO:::comm.rebalance.df(air_reg_df, lo.side="right", type="equal", verbose=3)
a <- deltime(a, "rebalance:")

## from the R Journal iodata article
form = ~ ArrDelay + DayOfWeek + DepTime + DepDelay + Month
## transform some variables
air_reg_df$DayOfWeek <- factor(air_reg_df$DayOfWeek, levels=1:7)
air_reg_df$Month <- factor(air_reg_df$Month, levels=1:12)
air_reg_df$DepTime <- sprintf("%04d", air_reg_df$DepTime)
air_reg_df$DepTime <- as.numeric(substr(air_reg_df$DepTime, 1, 2))*60 +
    as.numeric(substr(air_reg_df$DepTime, 3, 4))
comm.print(air_reg_df[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "factors and transformations:")

amm <- model.matrix(form, air_reg_df)
comm.cat(comm.rank(), "class(amm)", class(amm), "\n", all.rank=TRUE, quiet=TRUE)
comm.print(amm[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "model matrix:")

dimnames(amm) <- NULL
amm.d <- new("ddmatrix", Data=amm,
                 dim=c(allreduce(nrow(amm)), ncol(amm)),
                 ldim=dim(amm), bldim=dim(amm), ICTXT=2)
comm.print(submatrix(amm.d)[1:5, 1:5], all.rank=TRUE)
print(amm.d)
a <- deltime(a, "matrix new ddmatrix:")

amm.dbc <- as.blockcyclic(amm.d, bldim=c(2, 2))
print(dim(submatrix(amm.dbc)), all.rank=TRUE)
a <- deltime(a, "matrix blockcyclic ddmatrix:")

xx <- amm.dbc[, -2]
yy <- amm.dbc[, 2]
comm.print(dim(xx))
comm.print(dim(yy))
a <- deltime(a, "select columns:")

beta <- lm.fit(amm.dbc[, -2], amm.dbc[, 2])
coefs <- as.matrix(beta$coefficients)
comm.print(coefs)
comm.print(names(beta))
a <- deltime(a, "lm.fit:")
### !!! ### singal 11 here on 32 cores of 2 nodes - 12 GB x 10?
beta.coef <- solve(crossprod(xx), crossprod(xx, yy))
beta <- as.matrix(beta.coef)
comm.print(beta)
a <- deltime(a, "solve crossprod:")

xsvd <- svd(xx)
comm.print(xsvd$d)
a <- deltime(a, "svd xx:")

## redy for regression. use column indices to select response etc.

air_cross <- crossprod(amm.dbc)
print(air_cross)
a <- deltime(a, "matrix crossprod ddmatrix:")

library(pbdML)

a <- deltime(a0, "T Total time:")
finalize()
##
## Run this demo with
## mpirun -np 32 Rscript -e 'dir <- "your-airline-data-directory"; demo("matrix", package="pbdIO", echo=FALSE)'
##

## TODO Unfinished example code!
#suppressPackageStartupMessages(library(pbdMPI))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(pbdML))
suppressPackageStartupMessages(library(pbdIO))
suppressPackageStartupMessages(library(memuse))
init.grid()
a0 <- a <- deltime()

col_classes = c(rep("integer", 8), "character", "integer", "character",
    rep("integer", 5), "character", "character", rep("integer", 4),
    "character", rep("integer", 6))

## local subset of airline data - change to your data location!!
dir <- "/lustre/atlas/scratch/ost/stf006/airline"
air <- comm.fread(dir, verbose=3, colClasses=col_classes)
a <- deltime(a, "T Total comm.fread:")

## for the matrix example, do pca on all data, projecting airports
## into a 2d picture. Take all numerical variables, compute PCA, and
## plot airport labels in the first two pc space.

## select the numeric columns
comm.cat(comm.rank(), "col.classes(air)", unlist(lapply(air, class)), "\n", quiet=TRUE, all.rank=TRUE)
airnames <- colnames(air)
numeric <- unlist(allreduce(sapply(air, is.numeric), op="land"))
comm.cat("numeric\n", quiet=TRUE)
comm.cat("num", as.integer(numeric), "\n", quiet=TRUE)
## variables from the R Journal iodata article. Select for complete cases
##   rebalancing
air_reg_df <- subset(air, select=c(ArrDelay, DayOfWeek, DepTime, DepDelay, Month))
comm.cat("colnames(air_reg_df)", colnames(air_reg_df), "\n", quiet=TRUE)

## subset complete cases
###!!!### replace with dplyr complete cases
comm.print(air_reg_df[1:5, ], all.rank=TRUE)
comm.cat(comm.rank(), "nrow:", nrow(air_reg_df), "\n", all.rank=TRUE, quiet=TRUE)
air_reg_df <- air_reg_df[complete.cases(air_reg_df), ]
comm.cat(comm.rank(), "nrow:", nrow(air_reg_df), "\n", all.rank=TRUE, quiet=TRUE)
a <- deltime(a, "complete cases subset:")

## now rebalance after subsettng!
air_reg_df <- pbdIO:::comm.rebalance.df(air_reg_df, lo.side="right", type="equal", verbose=3)
a <- deltime(a, "rebalance:")

## from the R Journal iodata article
form = ~ ArrDelay + DayOfWeek + DepTime + DepDelay + Month
## transform some variables
air_reg_df$DayOfWeek <- factor(air_reg_df$DayOfWeek, levels=1:7)
air_reg_df$Month <- factor(air_reg_df$Month, levels=1:12)
air_reg_df$DepTime <- sprintf("%04d", air_reg_df$DepTime)
air_reg_df$DepTime <- as.numeric(substr(air_reg_df$DepTime, 1, 2))*60 +
    as.numeric(substr(air_reg_df$DepTime, 3, 4))
comm.print(air_reg_df[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "factors and transformations:")

amm <- model.matrix(form, air_reg_df)
comm.cat(comm.rank(), "class(amm)", class(amm), "\n", all.rank=TRUE, quiet=TRUE)
comm.print(amm[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "model matrix:")

dimnames(amm) <- NULL
amm.d <- new("ddmatrix", Data=amm,
                 dim=c(allreduce(nrow(amm)), ncol(amm)),
                 ldim=dim(amm), bldim=dim(amm), ICTXT=2)
comm.print(submatrix(amm.d)[1:5, 1:5], all.rank=TRUE)
print(amm.d)
a <- deltime(a, "matrix new ddmatrix:")

amm.dbc <- as.blockcyclic(amm.d, bldim=c(2, 2))
print(dim(submatrix(amm.dbc)), all.rank=TRUE)
a <- deltime(a, "matrix blockcyclic ddmatrix:")

xx <- amm.dbc[, -2]
yy <- amm.dbc[, 2]
comm.print(dim(xx))
comm.print(dim(yy))
a <- deltime(a, "select columns:")

beta <- lm.fit(amm.dbc[, -2], amm.dbc[, 2])
coefs <- as.matrix(beta$coefficients)
comm.print(coefs)
comm.print(names(beta))
a <- deltime(a, "lm.fit:")

beta.coef <- solve(crossprod(xx), crossprod(xx, yy))
beta <- as.matrix(beta.coef)
comm.print(beta)
a <- deltime(a, "solve crossprod:")

xsvd <- svd(xx)
comm.print(xsvd$d)
a <- deltime(a, "svd xx:")

## redy for regression. use column indices to select response etc.

air_cross <- crossprod(amm.dbc)
print(air_cross)
a <- deltime(a, "matrix crossprod ddmatrix:")

library(pbdML)

a <- deltime(a0, "T Total time:")
finalize()
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename = 'catalog_predictions'

catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')

catalog_predictions <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40,60,80),
                                            nb_iter = 100,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = filename)

# Catalog vs predictions
accuracy <- accuracy0 <- accuracy1 <-  vector('list', 3)
names(accuracy) <- names(accuracy0) <- names(accuracy1) c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions, empirical.only = TRUE)
accuracy[[2]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions, predict.only = TRUE)
accuracy[[3]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions)

accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)
accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, predict.only = TRUE)
accuracy0[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0)

accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)
accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, predict.only = TRUE)
accuracy1[[1]] <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1)

accuracy[[1]] <- rbind(accuracy[[1]], accuracy0[[1]], accuracy1[[1]])
accuracy[[2]] <- rbind(accuracy[[2]], accuracy0[[2]], accuracy1[[2]])
accuracy[[3]] <- rbind(accuracy[[3]], accuracy0[[3]], accuracy1[[3]])


#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=7,height=7)

# Plots
par(mfrow=c(2,2))
# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 1.09)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        # foodwebs <- names(similarity_cons_res_blind[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000088","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
            axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
            # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
            points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
        } #i

        ## Add legend
        if(j == 12) {
            legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        }
} #j
dev.off()
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:
    filename <- 'Multiple_parameters'
    min.tx = 45
    K.values = c(2,4,6,8)
    MW = c(1,3,5)
    WT = c(0,0.3,0.6,1)
    blind = FALSE
    minimum_threshold = 0.3
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/Tanimoto_data.RData")
load("./RData/interactions_source.RData")
suppressMessages(load("./RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
# Format interaction catalogue to fit this table format
    S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
    S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
    }

# setting up the analyses for multiple communities
# Data for communities on which to test the algorithm
    Cm <- unique(interactions_sources[, 'source'])
    communities <- vector("list", length(Cm))
    names(communities) <- Cm

    # Taxa list per community to predict
        for(i in 1:length(communities)) {
            Ci <- which(interactions_sources[, 'source'] == Cm[i])
            S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

            if(length(which(!S1 %in% S0_catalog)) > 0) {
                print('Taxa in C[i] are not all included in taxa list S0')
                break
            }

            communities[[i]] <- S1
        }

# Substracting GloBI interactions for this portion
    Cm.lg <- numeric()
    for(i in 1:length(communities)) {
        Cm.lg <- c(Cm.lg,length(communities[[i]]))
    }

    to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

    Cm <- Cm[-to.delete]
    for(i in rev(to.delete)) {
        communities[[i]] <- NULL
    }
    names(communities) <- Cm

# Setting up lists to store the results
    wt.init <- wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
    wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
    for(i in rev(wt.remove)) {
        similarity.matrices[[i]] <- NULL
    }

    sim.wt <- names(similarity.matrices)
    Tanimoto_analysis <- vector("list",length(sim.wt))
    names(Tanimoto_analysis) <- sim.wt
    for(i in 1:length(sim.wt)) {
        Tanimoto_analysis[[i]] <- vector("list", length(Cm))
        names(Tanimoto_analysis[[i]]) <- Cm
    }

# List to store results of multiple K values
K <- vector("list", length(K.values))
for(i in 1:length(K.values)) {
    K[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- K
names(Tanimoto_analysis) <- K.values
remove(K)

min.wt <- vector("list", length(MW))
for(i in 1:length(MW)) {
    min.wt[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- min.wt
names(Tanimoto_analysis) <- MW
remove(min.wt)

file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
save(x = Tanimoto_analysis, file = file.to.save)

init.time <- Sys.time()
for(n in 1:length(MW)) {
    mw <- MW[n]
    for(m in 1:length(K.values)) {

        # Tanimoto analysis with different weights for different communities
            # Parameters:
                Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
            #   wt  Weight of traits in similarity measurement
            #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
            #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

            # Output:
            #   A vector of sets of resources for each taxon

            for(i in 1:length(WT)){ #1st loop for all types of wt values
                wt <- WT[i]
                pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                for(j in 1:length(Cm)) { #2nd loop for all C[i]
                    S1 <- communities[[j]]
                    S0 <- S0_catalog
                    similarity.matrix <- similarity.matrices[[i]]

                    # Two choices here:
                    #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                    #   2. The analysis takes into account preexisting information already contained in the catalogue

                    # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                    if(blind == TRUE) {
                        for(k in 1:length(S1)) {
                          S0[S1[k], 'resource'] <- ""
                          S0[S1[k], 'non-resource'] <- ""
                        }

                    # 2. Preexisting information kept to inform algorithm
                    } else { # blind == FALSE

                        interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                        # Only modifying those that are loosing data from the catalogue, less time
                            to.change <- numeric()
                            for(k in 1:length(S1)) {
                                to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                            }
                            to.change <- unique(to.change)

                        # Modifying sets of resources and non-resources for taxa in S1
                            interactions <- interactions[to.change, ]
                            rownames(interactions) <- seq(1,nrow(interactions))
                            resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                      resource = interactions[, 'resource'],
                                                                      inter_type = interactions[, 'inter'])

                        # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                            for(k in 1:nrow(resource_set)) {
                              S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                              S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                            }
                        remove(interactions, resource_set, to.change)
                    } #if blind or not blind

                    # Recalculate similarity
                        similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                            S1 = S1,
                                                                            wt = wt,
                                                                            similarity.matrix = similarity.matrix)

                    # Predicting interactions
                        Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                Kr = Kr,
                                                                                S0 = S0,
                                                                                S1 = S1,
                                                                                MW = mw,
                                                                                similarity.matrix = similarity.matrix,
                                                                                minimum_threshold = minimum_threshold)

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(S0, S1, similarity.matrix)
                    setTxtProgressBar(pb, j)
                }#2nd loop for all C[i]

                save(x = Tanimoto_analysis, file = file.to.save)
                remove(wt)

            }#1st loop for all types of wt values
            close(pb)
    }#m
}#n
print(Sys.time() - init.time)
save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))


# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=12,height=7)
# Plots
par(mfrow=c(2,2))
# layout(matrix(c(1,2,5,5,3,4), 3, 2, byrow = TRUE), heights = c(4.5,1,4.5))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 50, ymax = 3.5)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(WT) * length(K.values)) + 0.5, labels = FALSE, las = 1, pos = -0.02) #MW
            axis(side = 2, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, nb.pts, by = length(WT)) + 0.5, labels = FALSE, las = 1, pos = 1.02 + 2.5) #wt
            axis(side = 4, at = seq(0, 1, by = 0.25), labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+1.25, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)
            axis(side = 4, at = seq(0, 1, by = 0.25)+2.5, labels = seq(0, 1, by = 0.25), las = 1, pos = (nb.pts + 0.02) + 1)

            abline(v = seq(length(WT)+0.5,nb.pts-length(WT)+0.5,by = length(WT)), col = "grey", lty = 2)
            abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)
            abline(h = c(1.125,2.375), col = "black", lty = 2)


            mtext(text = names[j-8], side = 2, line = 2, at = 1.75, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2) + 0.5, font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2) + 0.5, font = 1, cex = 0.75)
            text(x = 1, y = 0.15, labels = 'Algorithm', font = 2, cex = 1, col = col[1], adj = 0)
            text(x = 1, y = 1.40, labels = 'Predictions', font = 2, cex = 1, col = col[2], adj = 0)
            text(x = 1, y = 2.65, labels = 'Catalog', font = 2, cex = 1, col = col[3], adj = 0)

        it <- 0
        for(i in 1:length(accuracy)) {
        # for(i in 2) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'MW']) + as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,48), accuracy_mean[, 4][,1] - accuracy_mean[, 4][, 2]+it, seq(1,48), accuracy_mean[, 4][, 1] + accuracy_mean[, 4][, 2]+it, length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,48), y = accuracy_mean[, 4][, 1]+it, cex = 0.75, pch = 22, col = col[i])
            it <- it + 1.25
        } #i

        # ## Add legend
        # if(j == 9) {
        #     legend(0.5, 0.5, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j

dev.off()
#!/usr/bin/env RScript
library(ggplot2)

args <- commandArgs(trailingOnly = T)

main <- function()
{
	inputPath <- args[1]
	outputPath <- args[2]
	if (is.na(inputPath))
	{
		stop('Please specify a csv file')
	}

	if (is.na(outputPath))
	{
		stop('Please specify an output file')
	}

	data <- read.csv(inputPath)
	plot <- ggplot(data, aes(x = offset, y = value)) +
		geom_line() +
		labs(x = 'Time (ms)', y = 'GSR (microsiemens)')

	ggsave(outputPath, plot)
}

dummy <- main()##
## Run this demo with
## mpirun -np 32 Rscript -e 'dir <- "your-airline-data-directory"; demo("matrix", package="pbdIO", echo=FALSE)'
##

## TODO Unfinished example code!
#suppressPackageStartupMessages(library(pbdMPI))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(pbdML))
suppressPackageStartupMessages(library(pbdIO))
suppressPackageStartupMessages(library(memuse))
init.grid()
a0 <- a <- deltime()

col_classes = c(rep("integer", 8), "character", "integer", "character",
    rep("integer", 5), "character", "character", rep("integer", 4),
    "character", rep("integer", 6))

## local subset of airline data - change to your data location!!
dir <- "../../R_Thai_Workshop/session-parallel2/data"
air <- comm.fread(dir, verbose=3, colClasses=col_classes)
a <- deltime(a, "T Total comm.fread:")

## for the matrix example, do pca on all data, projecting airports
## into a 2d picture. Take all numerical variables, compute PCA, and
## plot airport labels in the first two pc space.

## select the numeric columns
comm.cat(comm.rank(), "col.classes(air)", unlist(lapply(air, class)), "\n", quiet=TRUE, all.rank=TRUE)
airnames <- colnames(air)
numeric <- unlist(allreduce(sapply(air, is.numeric), op="land"))
comm.cat("numeric\n", quiet=TRUE)
comm.cat("num", as.integer(numeric), "\n", quiet=TRUE)
## variables from the R Journal iodata article. Select for complete cases
##   rebalancing
air_reg_df <- subset(air, select=c(ArrDelay, DayOfWeek, DepTime, DepDelay, Month))
comm.cat("colnames(air_reg_df)", colnames(air_reg_df), "\n", quiet=TRUE)

## subset complete cases
###!!!### replace with dplyr complete cases
comm.print(air_reg_df[1:5, ], all.rank=TRUE)
comm.cat(comm.rank(), "nrow:", nrow(air_reg_df), "\n", all.rank=TRUE, quiet=TRUE)
air_reg_df <- air_reg_df[complete.cases(air_reg_df), ]
comm.cat(comm.rank(), "nrow:", nrow(air_reg_df), "\n", all.rank=TRUE, quiet=TRUE)
a <- deltime(a, "complete cases subset:")

## now rebalance after subsettng!
air_reg_df <- pbdIO:::comm.rebalance.df(air_reg_df, lo.side="right", type="equal", verbose=3)
a <- deltime(a, "rebalance:")

## from the R Journal iodata article
form = ~ ArrDelay + DayOfWeek + DepTime + DepDelay + Month
## transform some variables
air_reg_df$DayOfWeek <- factor(air_reg_df$DayOfWeek, levels=1:7)
air_reg_df$Month <- factor(air_reg_df$Month, levels=1:12)
air_reg_df$DepTime <- sprintf("%04d", air_reg_df$DepTime)
air_reg_df$DepTime <- as.numeric(substr(air_reg_df$DepTime, 1, 2))*60 +
    as.numeric(substr(air_reg_df$DepTime, 3, 4))
comm.print(air_reg_df[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "factors and transformations:")

amm <- model.matrix(form, air_reg_df)
comm.cat(comm.rank(), "class(amm)", class(amm), "\n", all.rank=TRUE, quiet=TRUE)
comm.print(amm[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "model matrix:")

dimnames(amm) <- NULL
amm.d <- new("ddmatrix", Data=amm,
                 dim=c(allreduce(nrow(amm)), ncol(amm)),
                 ldim=dim(amm), bldim=dim(amm), ICTXT=2)
comm.print(submatrix(amm.d)[1:5, 1:5], all.rank=TRUE)
print(amm.d)
a <- deltime(a, "matrix new ddmatrix:")

amm.dbc <- as.blockcyclic(amm.d, bldim=c(2, 2))
print(dim(submatrix(amm.dbc)), all.rank=TRUE)
a <- deltime(a, "matrix blockcyclic ddmatrix:")

xx <- amm.dbc[, -2]
yy <- amm.dbc[, 2]
comm.print(dim(xx))
comm.print(dim(yy))
a <- deltime(a, "select columns:")

beta <- lm.fit(amm.dbc[, -2], amm.dbc[, 2])
coefs <- as.matrix(beta$coefficients)
comm.print(coefs)
comm.print(names(beta))
a <- deltime(a, "lm.fit:")

beta.coef <- solve(crossprod(xx), crossprod(xx, yy))
beta <- as.matrix(beta.coef)
comm.print(beta)
a <- deltime(a, "solve crossprod:")

xsvd <- svd(xx)
comm.print(xsvd$d)
a <- deltime(a, "svd xx:")

## redy for regression. use column indices to select response etc.

air_cross <- crossprod(amm.dbc)
print(air_cross)
a <- deltime(a, "matrix crossprod ddmatrix:")

library(pbdML)

a <- deltime(a0, "T Total time:")
finalize()
#' comm.fread
#'
#' Given a directory, \code{comm.fread()} reads all csv files contained
#' in it in parallel with available resources.
#'
#' @param dir
#' A directory containing the files desired to be read.  The directory
#' should be accessible to all readers.
#' @param pattern
#' The pattern for files desired to be read.
#' @param readers
#' The number of readers.
#' @param verbose
#' Determines the verbosity level. Acceptable values are 0, 1, 2, and 3 for
#' least to most verbosity.
#'
#' @return
#' TODO
#'
#' @examples
#' \dontrun{
#' ### Save code in a file "demo.r" and run with 2 processors by
#' ### SHELL> mpiexec -np 2 Rscript demo.r
#' library(pbdMPI)
#' library(pbdIO)
#'
#' path <- "/tmp/read"
#' comm.print(dir(path))
#' ## [1] "a.csv" "b.csv"
#'
#' X <- comm.fread(path)
#'
#' comm.print(X, all.rank=TRUE)
#' ## COMM.RANK = 0
#' ##    a b c
#' ## 1: 1 2 3
#' ## COMM.RANK = 1
#' ##    a b c
#' ## 1: 2 3 4
#'
#' finalize()
#' }
#'
#' @importFrom data.table fread rbindlist
#'
#' @export
comm.fread <- function(dir, pattern="*.csv", readers=comm.size(),
                       verbose=0, ...) {
    if (!is.character(dir) || length(dir) != 1 || is.na(dir))
        comm.stop("argument 'dir' must be a string")
    if (!is.character(pattern) || length(pattern) != 1 || is.na(pattern))
        comm.stop("argument 'pattern' must be a string")
    if (!is.numeric(readers) || length(readers) != 1 || is.na(readers))
        comm.stop("argument 'readers' must be an integer")
    if (!(verbose %in% 0:3))
        comm.stop("argument 'verbose' must be 0, 1, 2, or 3")

    if(verbose) a <- deltime()
    files <- file.info(list.files(dir, pattern=pattern, full.names=TRUE))

    if (NROW(files) == 0)
        comm.stop(paste("Directory", dir,
                        "contains no files matching pattern", pattern))

    sizes <- files$size
    my_rank <- comm.rank()
    my_files <- comm.chunk(nrow(files), p=readers, lo.side="right",
                           form="vector")
    comm.print(my_files, all.rank=TRUE)
    if(verbose > 1) for(ifile in my_files)
                      cat(my_rank, rownames(files)[ifile], "\n")

    ## now fread all my_files and bind into one local data.frame
    l <- lapply(rownames(files)[my_files], function(file)
        suppressWarnings(fread(file, showProgress=FALSE, ...)))
    X <- rbindlist(l)

    # TODO if empty? Is length(X) is zero enough?
    ## rank 0 always reads, so it has all attributes. Propagate to NULLs.
    X0 <- bcast(X[0])
    if(length(X) == 0) X <- X0

    if(verbose) a <- deltime(a, "T    component fread time:")

    if(verbose) {
        nrow_have <- unlist(allgather(nrow(X)))
        comm.cat("nrow_have:", nrow_have, "\n")
    }

    X
}

check_sum <- function(X) {
    ## Report variable sums to check input
    my_numeric <- sapply(X, is.numeric)
    Xnumeric <- which(allreduce(my_numeric, op="land"))
    colSums(X[, Xnumeric, with=FALSE], na.rm=TRUE)
}

comm.rebalance.df <- function(X, verbose=0, ...) {
    ## Data frame X has unequal number of rows across ranks. This function
    ##   balances the rows by sending rows from ranks that have too many to
    ##   ranks that have too few.
    ##
    ## TODO makes copies with rbind(). Should this go into copyless C?
    ##
    my_rank <- comm.rank()
    nrow_have <- unlist(allgather(nrow(X)))
    N <- sum(nrow_have)

    ## TODO Three nrow_ vectors can be one with a bit more logic
    nrow_want <- comm.chunk(N, form="number", # type="equal",
                             all.rank=TRUE, ...)
    nrow_send <- pmax(nrow_have - nrow_want, 0)
    nrow_recv <- pmax(nrow_want - nrow_have, 0)
    if(verbose > 1) {
        comm.cat("nrow_have:", nrow_have, "\n")
        comm.cat("nrow_want:", nrow_want, "\n")
        comm.cat("nrow_send:", nrow_send, "\n")
        comm.cat("nrow_recv:", nrow_recv, "\n")
    }

    ## get global numeric column sums for error checking
    if(verbose > 2) before_sums <- check_sum(X)

    while(sum(nrow_send)) {
        recv_i <- 0
        senders <- (1:comm.size())[nrow_send > 0]
        for(proc_send in senders) {
            ## senders and receivers start from 1. Do -1 for rank!
            receivers <- (1:comm.size())[nrow_recv > 0]
            if(recv_i < length(receivers)) {
                recv_i <- recv_i + 1
                count_s <- nrow_send[proc_send]
                count_r <- nrow_recv[receivers[recv_i]]
                count <- min(count_s, count_r)
                if(my_rank + 1 == receivers[recv_i]) {
                    ## receivers and senders are disjoint sets
                    buffer <- matrix(NA, count, ncol(X))
                    buffer <- recv(buffer, rank.source=proc_send - 1)
                    ## can not use irecv because rbind follows!!
                    X <- rbind(X, buffer)
                }
                if(my_rank + 1 == proc_send) {
                    ## but two senders can be sending to same receiver
                    isend(X[1:count, ], rank.dest=receivers[recv_i] - 1)
                    X <- X[-(1:count), ]
                }
                nrow_recv[receivers[recv_i]] <- count_r - count
                nrow_send[proc_send] <- count_s - count
            }
        }
    }

    ## check if global column sums have not changed
    if(verbose > 2) {
        after_sums <- check_sum(X)
        equal <- all.equal(allreduce(before_sums), allreduce(after_sums))
        comm.cat("checksum equal:", equal, "on", ncol(X), "columns\n")
    }

    X
}
##
## Run this demo with
## mpirun -np 32 Rscript -e 'dir <- "your-airline-data-directory"; demo("matrix", package="pbdIO", echo=FALSE)'
##

## TODO Unfinished example code!
#suppressPackageStartupMessages(library(pbdMPI))
suppressPackageStartupMessages(library(data.table))
suppressPackageStartupMessages(library(pbdML))
suppressPackageStartupMessages(library(pbdIO))
suppressPackageStartupMessages(library(memuse))
init.grid()
a0 <- a <- deltime()

col_classes = c(rep("integer", 8), "character", "integer", "character",
    rep("integer", 5), "character", "character", rep("integer", 4),
    "character", rep("integer", 6))

## local subset of airline data - change to your data location!!
dir <- "../../R_Thai_Workshop/session-parallel2/data"
air <- comm.fread(dir, verbose=3, rebalance=TRUE, complete.cases=TRUE,
                  colClasses=col_classes)
a <- deltime(a, "T Total comm.fread:")

## for the matrix example, do pca on all data, projecting airports
## into a 2d picture. Take all numerical variables, compute PCA, and
## plot airport labels in the first two pc space.

## select the numeric columns
comm.cat(comm.rank(), "col.classes(air)", unlist(lapply(air, class)), "\n", quiet=TRUE, all.rank=TRUE)
airnames <- colnames(air)
numeric <- unlist(allreduce(sapply(air, is.numeric), op="land"))
comm.cat("numeric\n", quiet=TRUE)
comm.cat("num", as.integer(numeric), "\n", quiet=TRUE)
## variables from the R Journal iodata article. Select for complete cases
##   rebalancing
air_reg_df <- subset(air, select=c(ArrDelay, DayOfWeek, DepTime, DepDelay, Month))
comm.cat("colnames(air_reg_df)", colnames(air_reg_df), "\n", quiet=TRUE)

## subset complete cases
###!!!### replace with dplyr complete cases
comm.print(air_reg_df[1:5, ], all.rank=TRUE)
comm.cat(comm.rank(), "nrow:", nrow(air_reg_df), "\n", all.rank=TRUE, quiet=TRUE)
air_reg_df <- air_reg_df[complete.cases(air_reg_df), ]
comm.cat(comm.rank(), "nrow:", nrow(air_reg_df), "\n", all.rank=TRUE, quiet=TRUE)
a <- deltime(a, "complete cases subset:")

## now rebalance after subsettng!
air_reg_df <- pbdIO:::comm.rebalance.df(air_reg_df, lo.side="right", type="equal", verbose=3)
a <- deltime(a, "rebalance:")

## from the R Journal iodata article
form = ~ ArrDelay + DayOfWeek + DepTime + DepDelay + Month
## transform some variables
air_reg_df$DayOfWeek <- factor(air_reg_df$DayOfWeek, levels=1:7)
air_reg_df$Month <- factor(air_reg_df$Month, levels=1:12)
air_reg_df$DepTime <- sprintf("%04d", air_reg_df$DepTime)
air_reg_df$DepTime <- as.numeric(substr(air_reg_df$DepTime, 1, 2))*60 +
    as.numeric(substr(air_reg_df$DepTime, 3, 4))
comm.print(air_reg_df[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "factors and transformations:")

amm <- model.matrix(form, air_reg_df)
comm.cat(comm.rank(), "class(amm)", class(amm), "\n", all.rank=TRUE, quiet=TRUE)
comm.print(amm[1:5, 1:5], all.rank=TRUE)
a <- deltime(a, "model matrix:")

dimnames(amm) <- NULL
amm.d <- new("ddmatrix", Data=amm,
                 dim=c(allreduce(nrow(amm)), ncol(amm)),
                 ldim=dim(amm), bldim=dim(amm), ICTXT=2)
comm.print(submatrix(amm.d)[1:5, 1:5], all.rank=TRUE)
print(amm.d)
a <- deltime(a, "matrix new ddmatrix:")

amm.dbc <- as.blockcyclic(amm.d, bldim=c(2, 2))
print(dim(submatrix(amm.dbc)), all.rank=TRUE)
a <- deltime(a, "matrix blockcyclic ddmatrix:")

xx <- amm.dbc[, -2]
yy <- amm.dbc[, 2]
comm.print(dim(xx))
comm.print(dim(yy))
a <- deltime(a, "select columns:")

beta <- lm.fit(amm.dbc[, -2], amm.dbc[, 2])
coefs <- as.matrix(beta$coefficients)
comm.print(coefs)
comm.print(names(beta))
a <- deltime(a, "lm.fit:")

beta.coef <- solve(crossprod(xx), crossprod(xx, yy))
beta <- as.matrix(beta.coef)
comm.print(beta)
a <- deltime(a, "solve crossprod:")

xsvd <- svd(xx)
comm.print(xsvd$d)
a <- deltime(a, "svd xx:")

## redy for regression. use column indices to select response etc.

air_cross <- crossprod(amm.dbc)
print(air_cross)
a <- deltime(a, "matrix crossprod ddmatrix:")

library(pbdML)

a <- deltime(a0, "T Total time:")
finalize()
foo <- 5
f <- c(5, as.integer(5))
typeof(f)
mode(f)
str(f)
summary(f)

f <- list(5, as.integer(5))
typeof(f)
mode(f)
str(f)

explr <- function(x) {
  fs <- list(typeof, mode, str, summary, head)
  lapply(fs, fs, x)

}# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Analysis iteratively removing information from the catalog
# -----------------------------------------------------------------------------

# Evaluating algorithm accuracy ~ # of taxa in the catalog
# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/interactions_source.RData")
filename = 'catalog_predictions'

catalog_predictions0 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 0,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions0')
accuracy0 <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions0, empirical.only = TRUE)

catalog_predictions1 <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = 100,
                                            nb_iter = 1,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = 'catalog_predictions1')
accuracy1 <- catalog_predictions_accuracy(Tanimoto_analysis = catalog_predictions1, empirical.only = TRUE)

catalog_predictions <- catalog_predictions(comm_id = TRUE,
                                            community = "Kortsch2015_arctic",
                                            percent_remove = c(10,20,40,60,80),
                                            nb_iter = 100,
                                            K.values = 8,
                                            MW = 1,
                                            WT =  0.5,
                                            minimum_threshold = 0.3,
                                            filename = filename)















# Catalog vs predictions
load("./RData/interactions_source.RData")
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = similarity_cons_res, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = similarity_cons_res, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = similarity_cons_res)

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=7,height=7)

# Plots
par(mfrow=c(2,2))
# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 1.09)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        # foodwebs <- names(similarity_cons_res_blind[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000088","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
            axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
            # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
            points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
        } #i

        ## Add legend
        if(j == 12) {
            legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        }
} #j
dev.off()
# Run init.r before other scripts
rm(list=ls())
 # for use in R console.
 # set own relevant directory if working in R console, otherwise ignore if in terminal
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "./Script/0-1-Tanimoto_data.r
#           RData <- file = './RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "./Script/0-1-Interactions_sources.r
#           RData <- file = "./RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = './Script/1-Similarity_matrix.r'
#       RData <- file = './RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = './Script/2-1-Tanimoto_analysis.r'
#           RData <- file = './RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = './Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = './RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("./Script/tanimoto.r") # basic tanimoto similarity
source("./Script/tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("./Script/similarity_taxon.r") # similarity matrix for set of taxa
source("./Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("./Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("./Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/consumer_set_of_resource.R")
source("./Script/resource_set_of_consumer.R")
source("./Script/prediction_accuracy.r") #
source("./Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("./Script/serialNext.r") # function to avoid overwriting existing files in temporary analyses folder
source("./Script/eplot.r") # empty plot for figure generation
source("./Script/tanimoto_analysis.r")
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
#'
#' @export
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".",
                              source_files = list(),
                              settings = SlurmSettings$new()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
                private$settings <- settings
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in c(self$source_files, self$main_file)) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })

            script <- SlurmBashScript$new(container, self$main_file, private$settings)
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        settings = NA,
        find_globals = function() {
            e <- new.env()
            testthat::source_file(self$main_file, e)

            for (file in self$source_files) {
                testthat::source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                if (nglobals == 1) {
                    vars <- "var"
                    t_vars <- "this var"
                } else {
                    vars <- "vars"
                    t_vars <- "these vars"
                }

                cat(paste("Found", nglobals, vars, "to specify:"))
                for (global in globals) {
                    cat(paste("\n    -", global))
                }

                cat(paste("\n\nSet", t_vars, "in the `params` property of your `SlurmJob` instance."))
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
library(ggplot2)
df <- read.csv('sueldos.sysarmy.csv')

rename <- function(df, old, wants) {
  names(df)[names(df)==old] <- wants
  return(df)
}

# outlier removal functions.
arbitrary <- function(data) {
  data <- subset(data, Income < 120000)
  data <- subset(data, Income > 6000)
  return(data)
}

tukey <- function(data) {
  iqr <- IQR(data$Income)
  firstQ <- quantile(data$Income)[2]
  thirdQ <- quantile(data$Income)[4]
  low <- firstQ - (iqr * 1.5)
  high <- thirdQ + (iqr * 1.5)
  data <- subset(data, Income < high)
  data <- subset(data, Income > low)
  return(data)
}

cleanup <- function(data, removeOutliers) {
  # clean gender.
  data$Gender = ifelse(data$Soy == "Hombre", "M", "F")
  data$Gender = as.factor(data$Gender)

  # rename columns.
  data <- rename(data, "Tengo", "Age")
  data <- rename(data, "Argentina", "Region")
  data <- rename(data, "A..os.de.experiencia", "YearsExperience")
  data <- rename(data, "A..os.en.el.puesto.actual", "YearsCurrentJob")
  data <- rename(data, "Trabajo.de", "JobDescription")
  data <- rename(data, "Tipo.de.contrato", "JobType")
  data <- rename(data, "Qu...tan.conforme.est..s.con.tu.sueldo.", "Happiness")
  data <- rename(data, "Cambiaste.de.empresa.en.los...ltimos.6.meses.", "SwitchedJobsLast6Months")

  # fix region names.
  levels(data$Region)[levels(data$Region) == "Entre R\303\255os"] <- "Entre Rios"
  levels(data$Region)[levels(data$Region) == "Ciudad Aut\303\263noma de Buenos Aires"] <- "CABA"
  levels(data$Region)[levels(data$Region) == "C\303\263rdoba"] <- "Cordoba"
  levels(data$Region)[levels(data$Region) == "Neuqu\303\251n"] <- "Neuquen"
  levels(data$Region)[levels(data$Region) == "R\303\255o Negro"] <- "Rio Negro"
  levels(data$Region)[levels(data$Region) == "Tucum\303\241n"] <- "Tucuman"
  levels(data$Region)[levels(data$Region) == "Provincia de Buenos Aires"] <- "GBA"

  # fix age.
  levels(data$Age)[levels(data$Age) == "Menos de 18 a\303\261os"] <- "18-"

  # fix salary.
  data <- rename(data, "Salario.mensual..en.tu.moneda.local.", "Income")
  data$Income <- ifelse(data$Bruto.o.neto. == "Bruto", data$Income, data$Income/0.70)
  data$Bruto.o.neto. = NULL

  # fix job switch.
  data$SwitchedJobsLast6Months = ifelse(data$SwitchedJobsLast6Months == "No", 0, 1)

  # filter fictitious salaries.
  data <- removeOutliers(data)

  keep <- c("Age", "Region", "YearsExperience", "YearsCurrentJob", "JobDescription",
            "JobType", "Happiness", "Income", "Gender", "SwitchedJobsLast6Months")
  return(data[keep])
}

all.salaries.hist <- function(df) {
  plot <- ggplot(df, aes(x=Income), ylab="") +
    geom_histogram(binwidth = 1000, fill="#3399FF", alpha=0.9)
  return(plot)
}

all.salaries.hist.median <- function(df) {
  plot <- all.salaries.hist(df) +
    geom_vline(aes(xintercept = mean(Income)), linetype="longdash", color="red")
  return(plot)
}

all.salaries.gender = function(df) {
  plot <- ggplot(df, aes(x=Income, fill=Gender), ylab="") +
    geom_histogram(binwidth = 1000, alpha=0.9)
  return(plot)
}

clean <- cleanup(df, removeOutliers = arbitrary)
write.csv(clean, 'clean.csv', row.names=FALSE)

default.plot <- all.salaries.gender
default.plot(clean)
library(ggplot2)
df <- read.csv('sueldos.sysarmy.csv')

rename <- function(df, old, wants) {
  names(df)[names(df)==old] <- wants
  return(df)
}

cleanup <- function(data) {
  # clean gender.
  data$Gender = ifelse(data$Soy == "Hombre", "M", "F")
  data$Gender = as.factor(data$Gender)

  # rename columns.
  data <- rename(data, "Tengo", "Age")
  data <- rename(data, "Argentina", "Region")
  data <- rename(data, "A..os.de.experiencia", "YearsExperience")
  data <- rename(data, "A..os.en.el.puesto.actual", "YearsCurrentJob")
  data <- rename(data, "Trabajo.de", "JobDescription")
  data <- rename(data, "Tipo.de.contrato", "JobType")
  data <- rename(data, "Qu...tan.conforme.est..s.con.tu.sueldo.", "Happiness")
  data <- rename(data, "Cambiaste.de.empresa.en.los...ltimos.6.meses.", "SwitchedJobsLast6Months")

  # fix region names.
  levels(data$Region)[levels(data$Region) == "Entre R\303\255os"] <- "Entre Rios"
  levels(data$Region)[levels(data$Region) == "Ciudad Aut\303\263noma de Buenos Aires"] <- "CABA"
  levels(data$Region)[levels(data$Region) == "C\303\263rdoba"] <- "Cordoba"
  levels(data$Region)[levels(data$Region) == "Neuqu\303\251n"] <- "Neuquen"
  levels(data$Region)[levels(data$Region) == "R\303\255o Negro"] <- "Rio Negro"
  levels(data$Region)[levels(data$Region) == "Tucum\303\241n"] <- "Tucuman"
  levels(data$Region)[levels(data$Region) == "Provincia de Buenos Aires"] <- "GBA"
  
  # fix age.
  levels(data$Age)[levels(data$Age) == "Menos de 18 a\303\261os"] <- "18-"

  # fix salary.
  data <- rename(data, "Salario.mensual..en.tu.moneda.local.", "Income")
  data$Income <- ifelse(data$Bruto.o.neto. == "Bruto", data$Income, data$Income/0.70)
  data$Bruto.o.neto. = NULL
  
  # fix job switch.
  data$SwitchedJobsLast6Months = ifelse(data$SwitchedJobsLast6Months == "No", 0, 1)

  # filter fictitious salaries.
  data <- subset(data, Income < 120000)
  data <- subset(data, Income > 6000)

  keep <- c("Age", "Region", "YearsExperience", "YearsCurrentJob", "JobDescription",
            "JobType", "Happiness", "Income", "Gender", "SwitchedJobsLast6Months")
  return(data[keep])
}

all.salaries.hist <- function(df) {
  plot <- ggplot(df, aes(x=Income), ylab="") + 
    geom_histogram(binwidth = 1000, fill="#3399FF", alpha=0.9)
  return(plot)
}

all.salaries.hist.median <- function(df) {
  plot <- all.salaries.hist(df) + 
    geom_vline(aes(xintercept = mean(Income)), linetype="longdash", color="red")
  return(plot)
}

all.salaries.gender = function(df) {
  plot <- ggplot(df, aes(x=Income, fill=Gender), ylab="") + 
    geom_histogram(binwidth = 1000, alpha=0.9)
  return(plot)
}

clean <- cleanup(df)
write.csv(clean, 'clean.csv', row.names=FALSE)

default.plot <- all.salaries.gender
default.plot(clean)
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:
    filename <- 'Multiple_parameters'
    min.tx = 45
    K.values = c(2,4,6,8)
    MW = c(1,3,5)
    WT = c(0,0.3,0.6,1)
    blind = FALSE
    minimum_threshold = 0.3
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/Tanimoto_data.RData")
load("./RData/interactions_source.RData")
suppressMessages(load("./RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
# Format interaction catalogue to fit this table format
    S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
    S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
    }

# setting up the analyses for multiple communities
# Data for communities on which to test the algorithm
    Cm <- unique(interactions_sources[, 'source'])
    communities <- vector("list", length(Cm))
    names(communities) <- Cm

    # Taxa list per community to predict
        for(i in 1:length(communities)) {
            Ci <- which(interactions_sources[, 'source'] == Cm[i])
            S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

            if(length(which(!S1 %in% S0_catalog)) > 0) {
                print('Taxa in C[i] are not all included in taxa list S0')
                break
            }

            communities[[i]] <- S1
        }

# Substracting GloBI interactions for this portion
    Cm.lg <- numeric()
    for(i in 1:length(communities)) {
        Cm.lg <- c(Cm.lg,length(communities[[i]]))
    }

    to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

    Cm <- Cm[-to.delete]
    for(i in rev(to.delete)) {
        communities[[i]] <- NULL
    }
    names(communities) <- Cm

# Setting up lists to store the results
    wt.init <- wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
    wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
    for(i in rev(wt.remove)) {
        similarity.matrices[[i]] <- NULL
    }

    sim.wt <- names(similarity.matrices)
    Tanimoto_analysis <- vector("list",length(sim.wt))
    names(Tanimoto_analysis) <- sim.wt
    for(i in 1:length(sim.wt)) {
        Tanimoto_analysis[[i]] <- vector("list", length(Cm))
        names(Tanimoto_analysis[[i]]) <- Cm
    }

# List to store results of multiple K values
K <- vector("list", length(K.values))
for(i in 1:length(K.values)) {
    K[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- K
names(Tanimoto_analysis) <- K.values
remove(K)

min.wt <- vector("list", length(MW))
for(i in 1:length(MW)) {
    min.wt[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- min.wt
names(Tanimoto_analysis) <- MW
remove(min.wt)

file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
save(x = Tanimoto_analysis, file = file.to.save)

init.time <- Sys.time()
for(n in 1:length(MW)) {
    mw <- MW[n]
    for(m in 1:length(K.values)) {

        # Tanimoto analysis with different weights for different communities
            # Parameters:
                Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
            #   wt  Weight of traits in similarity measurement
            #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
            #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

            # Output:
            #   A vector of sets of resources for each taxon

            for(i in 1:length(WT)){ #1st loop for all types of wt values
                wt <- WT[i]
                pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                for(j in 1:length(Cm)) { #2nd loop for all C[i]
                    S1 <- communities[[j]]
                    S0 <- S0_catalog
                    similarity.matrix <- similarity.matrices[[i]]

                    # Two choices here:
                    #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                    #   2. The analysis takes into account preexisting information already contained in the catalogue

                    # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                    if(blind == TRUE) {
                        for(k in 1:length(S1)) {
                          S0[S1[k], 'resource'] <- ""
                          S0[S1[k], 'non-resource'] <- ""
                        }

                    # 2. Preexisting information kept to inform algorithm
                    } else { # blind == FALSE

                        interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                        # Only modifying those that are loosing data from the catalogue, less time
                            to.change <- numeric()
                            for(k in 1:length(S1)) {
                                to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                            }
                            to.change <- unique(to.change)

                        # Modifying sets of resources and non-resources for taxa in S1
                            interactions <- interactions[to.change, ]
                            rownames(interactions) <- seq(1,nrow(interactions))
                            resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                      resource = interactions[, 'resource'],
                                                                      inter_type = interactions[, 'inter'])

                        # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                            for(k in 1:nrow(resource_set)) {
                              S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                              S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                            }
                        remove(interactions, resource_set, to.change)
                    } #if blind or not blind

                    # Recalculate similarity
                        similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                            S1 = S1,
                                                                            wt = wt,
                                                                            similarity.matrix = similarity.matrix)

                    # Predicting interactions
                        Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                Kr = Kr,
                                                                                S0 = S0,
                                                                                S1 = S1,
                                                                                MW = mw,
                                                                                similarity.matrix = similarity.matrix,
                                                                                minimum_threshold = minimum_threshold)

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(S0, S1, similarity.matrix)
                    setTxtProgressBar(pb, j)
                }#2nd loop for all C[i]

                save(x = Tanimoto_analysis, file = file.to.save)
                remove(wt)

            }#1st loop for all types of wt values
            close(pb)
    }#m
}#n
print(Sys.time() - init.time)
save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))


# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=7,height=7)
# Plots
par(mfrow=c(2,2))

nb.pts <- length(unique(accuracy[[1]][,'MW'])) * length(unique(accuracy[[1]][,'K'])) * length(unique(accuracy[[1]][,'wt']))

# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 50)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000000","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            axis(side = 1, at = seq(0, nb.pts, by = length(WT) * length(K.values)), labels = FALSE, las = 1, pos = -0.02) #MW
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, nb.pts, by = length(WT)), labels = FALSE, las = 1, pos = 1.02) #wt
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = (nb.pts + 0.02))
            abline(v = seq(length(WT)+0.5,nb.pts-length(WT)+0.5,by = length(WT)), col = "grey", lty = 2)
            abline(v = seq((length(WT) * length(K.values))+0.5, (nb.pts - (length(WT) * length(K.values)))+0.5, by = length(WT) * length(K.values)), col = "blue", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 3, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = "Minimum weight", side = 1, line = 2, at = 25, font = 2, cex = 1)
            mtext(text = MW, side = 1, line = 1, at = seq(nb.pts/length(MW), nb.pts, by = nb.pts/length(MW)) - ((nb.pts/length(MW)) / 2), font = 1, cex = 0.75)
            mtext(text = rep(WT, times = length(WT)), side = 3, line = 1, at = seq((nb.pts/length(MW))/length(WT), nb.pts, by = ((nb.pts/length(MW)) / length(WT))) - ((nb.pts/length(MW)) / length(WT) / 2), font = 1, cex = 0.75)

        # for(i in 1:length(accuracy)) {
        for(i in 2) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'MW']) + as.numeric(accuracy[[i]][, 'K']) + as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            accuracy_mean <- accuracy_mean[order(accuracy_mean[,1]), ]
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(seq(1,48), accuracy_mean[, 4][,1] - accuracy_mean[, 4][, 2], seq(1,48), accuracy_mean[, 4][, 1] + accuracy_mean[, 4][, 2], length=0.025, angle=90, code=3, col = col[i])
            points(x = seq(1,48), y = accuracy_mean[, 4][, 1], cex = 0.75, pch = 22, col = col[i])
        } #i

        # ## Add legend
        # if(j == 12) {
        #     legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        # }
} #j
dev.off()
context("SlurmJob")


test_that("SlurmJob initializer sets main_file property.",  {
    sj <- SlurmJob$new("main.R")
    expect_equal(sj$main_file, "main.R")
    expect_error(SlurmJob$new())
})
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, settings) {
            private$settings <- settings

            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", basename(main_file), "'"), "], source)")
            loading <- paste("sapply(list.files('./.objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat("\n\n", sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

# Flatten input directory
mv -r ./input .

main_file=$(basename $1)

R CMD BATCH ./sources/$main_file

cp -r * $SLURM_SUBMIT_DIR/output
cd $SLURM_SUBMIT_DIR/output
rm -rf ./input ./sources ./objects"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
#'
#' @export
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".",
                              source_files = list(),
                              settings = SlurmSettings$new()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
                private$settings <- settings
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in c(self$source_files, self$main_file)) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })

            script <- SlurmBashScript$new(container, self$main_file, private$settings)
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        settings = NA,
        find_globals = function() {
            e <- new.env()
            testthat::source_file(self$main_file, e)

            for (file in self$source_files) {
                testthat::source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                if (nglobals == 1) {
                    vars <- "var"
                    t_vars <- "this var"
                } else {
                    vars <- "vars"
                    t_vars <- "these vars"
                }

                message(paste("Found", nglobals, vars, "to specify:"))
                for (global in globals) {
                    message(paste("    -", global))
                }

                message(paste("\nSet", t_vars, "in the `params` property."))
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
#'
#' @export
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".",
                              source_files = list(),
                              settings = SlurmSettings$new()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
                private$settings <- settings
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in c(self$source_files, self$main_file)) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })

            script <- SlurmBashScript$new(container, self$main_file, private$settings)
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        settings = NA,
        find_globals = function() {
            e <- new.env()
            testthat::source_file(self$main_file, e)

            for (file in self$source_files) {
                testthat::source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, settings) {
            private$settings <- settings

            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file)
        }
    ),
    private = list(
        settings = NA,
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", basename(main_file), "'"), "], source)")
            loading <- paste("sapply(list.files('./.objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat(sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

# Flatten input directory
mv -r ./input .

main_file=$(basename $1)

R CMD BATCH ./sources/$main_file

cp -r * $SLURM_SUBMIT_DIR/output
cd $SLURM_SUBMIT_DIR/output
rm -rf ./input ./sources ./objects"

            write(paste(private$settings$for_slurm_script(), contents, sep = "\n"),
                  file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' Create an SBATCH option
#'
#' @param key The key for the sbatch option.
#'
#' @return A function that takes a single argument representing
#' the value for the \code{key}.
sbatch_opt <- function(key) {
    return(function(value) {
        return(paste0("--", key, "=", value))
    })
}


#' Test sbatch options for equality.
#'
#' sbatch option equallity is achieved if the keys of the options
#' are the same.
#'
#' @param opt_1 An sbatch option string.
#'
#' @param opt_2 An sbatch option string.
#'
#' @return A boolean value.
sbatch_opts_equal <- function(opt_1, opt_2) {
    return(sbatch_opt_key(opt_1) == sbatch_opt_key(opt_2))
}


#' Insert an sbatch option into a set.
#'
#' @param opt The sbatch option to insert
#'
#' @param opts A set of sbatch options. Default value is the empty
#' set.
#'
#' @return A set with \code{opt} inserted.
sbatch_opts_insert <- function(opt, opts = c()) {
    for (i in 1:length(opts)) {
        if (sbatch_opts_equal(opt, opts[i])) {
            opts[i] = opt
        }
    }

    return(opts)
}


#' Get the key of an sbatch.
#'
#' @param opt An sbatch option string.
#'
#' @return The \code{opt}'s key.
sbatch_opt_key <- function(opt) {
    return(strsplit(opt, "=")[[1]][1])
}


#' A list of sbatch options.
#'
#' The value of each item in the list is a string or a function
#' which takes a string as a parameter, using \code{sbatch_opt}.
#'
#' To ensure proper formatting, the \code{mail_type} option should
#' be set using \code{sbatch_mail_types}. Multiple mail types need
#' to be comma seperated.
#'
#' @export
sbatch_opts <- list (
    begin = sbatch_opt("begin"),
    cpus_per_task = sbatch_opt("cpus-per-task"),
    mail_type = sbatch_opt("mail-type"),
    mail_user = sbatch_opt("mail-user"),
    memory = sbatch_opt("mem"),
    nodes = sbatch_opt("nodes"),
    ouput = sbatch_opt("ouput"),
    time = sbatch_opt("time")
)


#' A list of sbatch mail types.
#'
#' The value of each item in the list is a string representing
#' a mail type option.
#'
#' @export
sbatch_mail_types <- list(
    all = "ALL",
    begin = "BEGIN",
    end = "END",
    fail = "FAIL",
    none = "NONE",
    requeue = "REQUEUE",
    stage_out = "STAGE_OUT",
    time_limit = "TIME_LIMIT",
    time_limit_90 = "TIME_LIMIT_90",
    time_limit_80 = "TIME_LIMIT_80",
    time_limit_50 = "TIME_LIMIT_50"
)
#' Create an SBATCH option
#'
#' @param key The key for the sbatch option.
#'
#' @return A function that takes a single argument representing
#' the value for the \code{key}.
sbatch_opt <- function(key) {
    return(function(value) {
        return(paste0("--", key, "=", value))
    })
}


#' Test sbatch options for equality.
#'
#' sbatch option equallity is achieved if the keys of the options
#' are the same.
#'
#' @param opt_1 An sbatch option string.
#'
#' @param opt_2 An sbatch option string.
#'
#' @return A boolean value.
sbatch_opts_equal <- function(opt_1, opt_2) {
    return(sbatch_opt_key(opt_1) == sbatch_opt_key(opt_2))
}


#' Get the key of an sbatch.
#'
#' @param opt An sbatch option string.
#'
#' @return The \code{opt}'s key.
sbatch_opt_key <- function(opt) {
    return(strsplit(opt, "=")[[1]][1])
}


#' A list of sbatch options.
#'
#' The value of each item in the list is a string or a function
#' which takes a string as a parameter, using \code{sbatch_opt}.
#'
#' To ensure proper formatting, the \code{mail_type} option should
#' be set using \code{sbatch_mail_types}. Multiple mail types need
#' to be comma seperated.
#'
#' @export
sbatch_opts <- list (
    begin = sbatch_opt("begin"),
    cpus_per_task = sbatch_opt("cpus-per-task"),
    mail_type = sbatch_opt("mail-type"),
    mail_user = sbatch_opt("mail-user"),
    memory = sbatch_opt("mem"),
    nodes = sbatch_opt("nodes"),
    ouput = sbatch_opt("ouput"),
    time = sbatch_opt("time")
)


#' A list of sbatch mail types.
#'
#' The value of each item in the list is a string representing
#' a mail type option.
#'
#' @export
sbatch_mail_types <- list(
    all = "ALL",
    begin = "BEGIN",
    end = "END",
    fail = "FAIL",
    none = "NONE",
    requeue = "REQUEUE",
    stage_out = "STAGE_OUT",
    time_limit = "TIME_LIMIT",
    time_limit_90 = "TIME_LIMIT_90",
    time_limit_80 = "TIME_LIMIT_80",
    time_limit_50 = "TIME_LIMIT_50"
)
#' Create an SBATCH option
#'
#' @param key The key for the sbatch option.
#'
#' @return A function that takes a single argument representing
#' the value for the \code{key}.
sbatch_opt <- function(key) {
    return(function(value) {
        return(paste0("--", key, "=", value))
    })
}


#' A list of sbatch options.
#'
#' The value of each item in the list is a string or a function
#' which takes a string as a parameter, using \code{sbatch_opt}.
#'
#' To ensure proper formatting, the \code{mail_type} option should
#' be set using \code{sbatch_mail_types}. Multiple mail types need
#' to be comma seperated.
#'
#' @export
sbatch_opts <- list (
    begin = sbatch_opt("begin"),
    cpus_per_task = sbatch_opt("cpus-per-task"),
    mail_type = sbatch_opt("mail-type"),
    mail_user = sbatch_opt("mail-user"),
    memory = sbatch_opt("mem"),
    nodes = sbatch_opt("nodes"),
    ouput = sbatch_opt("ouput"),
    time = sbatch_opt("time")
)


#' A list of sbatch mail types.
#'
#' The value of each item in the list is a string representing
#' a mail type option.
#'
#' @export
sbatch_mail_types <- list(
    all = "ALL",
    begin = "BEGIN",
    end = "END",
    fail = "FAIL",
    none = "NONE",
    requeue = "REQUEUE",
    stage_out = "STAGE_OUT",
    time_limit = "TIME_LIMIT",
    time_limit_90 = "TIME_LIMIT_90",
    time_limit_80 = "TIME_LIMIT_80",
    time_limit_50 = "TIME_LIMIT_50"
)
#' minilog.db
#' @param DS
#' @param Y
#' @author Jae Choi
#' @return returns a plot of CPUE data by date along with the predicted line as well as a data.frame with raw data and predicted data
#' @export

  minilog.db = function( DS="", Y=NULL, plotdata=TRUE ){

    minilog.dir = project.datadirectory("bio.snowcrab", "data", "minilog" )
    minilog.rawdata.location = file.path( minilog.dir, "archive" )
    plotdir = project.datadirectory("bio.snowcrab", "data", "minilog", "figures" )

    if (!is.null(Y)) {
      iY = which( Y>=1999 )  # no historical data prior to 1999
      if (length(iY)==0) return ("No data for specified years")
      Y = Y[iY]
    }

    if ( DS %in% c("basedata", "metadata", "load") ) {
      if (DS=="basedata" ){
        flist = list.files(path=minilog.dir, pattern="basedata", full.names=T, recursive=FALSE)
        if (!is.null(Y)) {
          mm = NULL
          for (yy in Y ) {
            ll = grep( yy, flist)
            if (length(ll)==0) return( NULL) # nothing to do
            if (length(ll)>0 ) mm = c( mm, ll)
          }
          if (length(mm) > 0 ) flist= flist[mm]
        }
        out = NULL
        for ( i in flist ) {
          load( i )
          out= rbind( out, basedata )
        }
        return( out )
      }

      if (DS=="metadata" ){
        flist = list.files(path=minilog.dir, pattern="metadata", full.names=T, recursive=FALSE)
        if (!is.null(Y)) {
          mm = NULL
          for (yy in Y ) {
            ll = grep( yy, flist)
            if (length(ll)==0) return( NULL ) # nothing to do
            if (length(ll)>0 ) mm = c( mm, ll)
          }
          if (length(mm) > 0 ) flist= flist[mm]
        }
        out = NULL
        for ( i in flist ) {
          load( i )
          out= rbind( out, metadata )
        }
        return( out )
      }

      # default is to "load"
      dirlist = list.files(path=minilog.rawdata.location, full.names=T, recursive=T)
      oo = grep("backup", dirlist)
      if (length(oo) > 0) {
        backups = dirlist[ oo ]
        dirlist = dirlist[-oo]
      }

      nfiles = length(dirlist)
      filelist = matrix( NA, ncol=3, nrow=nfiles)

      for (f in 1:nfiles) {
        yr = minilogDate( fnMini=dirlist[f] )
        if (is.null(yr) ) next()
        if ( yr %in% Y ) filelist[f,] = c( f, dirlist[f], yr )
      }
      fli = which( !is.na( filelist[,1] ) )
      if ( length(fli) == 0) return( "No files matching the criteria.")

      filelist = filelist[ fli , ]

      set = snowcrab.db( DS="setInitial" )  # set$timestamp is in UTC

      for ( yr in Y ) {
        print(yr)
        fn.meta = file.path( minilog.dir, paste( "minilog", "metadata", yr, "rdata", sep="." ) )
        fn.raw = file.path( minilog.dir, paste( "minilog", "basedata", yr, "rdata", sep="." ) )
        fs = filelist[ which( as.numeric(filelist[,3])==yr ) , 2 ]

        if (length(fs)==0) next()

        basedata = NULL
        metadata = NULL
        for (f in 1:length(fs)) {
          if( yr >= 2014 ) {
            j = load.minilog.rawdata.one.file.per.day( fn=fs[f], f=f, set=set)
          } else {
            j = load.minilog.rawdata( fn=fs[f], f=f, set=set)  # variable naming conventions in the past
          }
          if (is.null(j)) next()
          metadata = rbind( metadata, j$metadata)
          basedata = rbind( basedata, j$basedata)
        }

        # now do a last pass for the "backups" ....
        # incomplete ....
        add.backup.minilogs=FALSE
        if (add.backup.minilogs) {
          stop( "TODO")
          fb = backups[ which( as.numeric(backups[,3])==yr ) , 2 ]
          for (f in 1:length(fb)) {
            j = load.minilog.rawdata.backups( fn=fb[f], f=f, set=set)
            if (is.null(j)) next()
            metadata = rbind( metadata, j$metadata)
            basedata = rbind( basedata, j$basedata)
          }
        }

        save( metadata, file=fn.meta, compress=TRUE )
        save( basedata, file=fn.raw, compress=TRUE )

      }

      minilog.db( DS="set.minilog.lookuptable.redo" )

      return ( minilog.dir )
    }

    # -----------------------------------------------

    if (DS %in% c("stats", "stats.redo" ) ) {

      if (DS %in% c("stats") ){
        flist = list.files(path=minilog.dir, pattern="stats", full.names=T, recursive=FALSE)
        if (!is.null(Y)) {
          mm = NULL
          for (yy in Y ) {
            ll = grep( yy, flist)
            if (length(ll)==0) return(NULL) # nothing to do
            if (length(ll)>0 ) mm = c( mm, ll)
          }
          if (length(mm) > 0 ) flist= flist[mm]
        }
        mini.stat = NULL
        for ( i in flist ) {
          load( i )
          mini.stat = rbind( mini.stat, miniStats )
        }
        mini.meta = minilog.db( DS="metadata", Y=Y )
        res = merge( mini.meta, mini.stat,  by="minilog_uid", all.x=TRUE, all.y=FALSE, sort=FALSE )
        if(any(duplicated(res[,c('trip','set')]))) {
            res = removeDuplicateswithNA(res,cols=c('trip','set'),idvar='dt')
          }
        #res$t0 = as.POSIXct( res$t0, tz="UTC", origin=lubridate::origin )
        #res$t1 = as.POSIXct( res$t1, tz="UTC", origin=lubridate::origin )
        #res$dt = difftime( res$t1, res$t0 )

        return (res)
      }

      # "stats.redo" is the default action

      #      bad.list = c(
      #"minilog.S02112006.9.151.22.14.142",
      #"minilog.S27042001.7.NA.18.7.17",
      #"minilog.S08112008.9.55.NA.NA.55",
      #"minilog.S12102011.12.129.NA.NA.145",
      #"minilog.S18102007.11.226.18.44.198",
      #"minilog.S23102007.6.308.13.28.232",
      #"minilog.S27092007.9.86.NA.NA.87"
      #'minilog.S12071999.1.NA.NA.NA.190',
      #'minilog.S20052000.10.NA.NA.NA.13',
      #'minilog.S19092004.8.389.NA.NA.321',
      #'minilog.S19062000.8.NA.NA.NA.165',
      #'minilog.S07092002.12.NA.NA.NA.245',
      #'minilog.S08092002.10.NA.NA.NA.254',
      #'minilog.S12102002.8.NA.15.59.349',
      #'minilog.S28052002.10.NA.19.30.445',
      #'minilog.S24112009.4.370.NA.NA.276',
      #'minilog.S08092010.3.178.NA.NA.170',
      #'minilog.S21102010.9.341.14.51.252',
      #'minilog.S25092010.8.36.NA.NA.33',
      #'minilog.S27102010.3.918.8.11.423' '
      #      )
      bad.list = NULL
      bad.list = unique( c(bad.list, p$netmensuration.problem ) )

      for ( yr in Y ) {
        print (yr )

        fn = file.path( minilog.dir, paste( "minilog.stats", yr, "rdata", sep=".") )
        mta = miniRAW = miniStats = NULL
        miniRAW = minilog.db( DS="basedata", Y=yr )
        mta = minilog.db( DS="metadata", Y=yr )
        if (is.null(mta) | is.null(miniRAW)) next()

        rid = minilog.db( DS="set.minilog.lookuptable" )
        rid = data.frame( minilog_uid=rid$minilog_uid, stringsAsFactors=FALSE )
        rid = merge( rid, mta, by="minilog_uid", all.x=TRUE, all.y=FALSE )
        rid = rid[ which(rid$yr== yr) ,]
        if (nrow(rid) == 0 ) next()

        for ( i in 1:nrow(rid)  ) {
          id = rid$minilog_uid[i]
          sso.trip = rid$trip[i]
          sso.set = rid$set[i]
          sso.station = rid$station[i]

          Mi = which( miniRAW$minilog_uid == id )
          if (length( Mi) == 0 ) next()
          M = miniRAW[ Mi, ]

          settimestamp= rid$set_timestamp[i]
          time.gate =  list( t0=settimestamp - dminutes(6), t1=settimestamp + dminutes(12) )

          print( paste( i, ":", id) )

          # default, empty container
          res = data.frame(z=NA, t=NA, zsd=NA, tsd=NA, n=NA, t0=NA, t1=NA, dt=NA)

          rii = which( M$timestamp > settimestamp &  (M$timestamp < settimestamp+dminutes(5)) )
          # first estimate in case the following does not work
          if (length(rii) > 30) {
            res$z = mean(M$depth[rii], na.rm=TRUE)
            res$t = mean(M$temperature[rii], na.rm=TRUE)
            res$zsd = sd(M$depth[rii], na.rm=TRUE)
            res$tsd = sd(M$temperature[rii], na.rm=TRUE)
          }

          if (! ( id %in% bad.list ) ) {
            ndat = length( which( !is.na(M$depth) ))
            if (ndat ==0 ) print ("No depth data in minilogs")
            if( ndat < 30 ) {
              miniStats = rbind(miniStats, cbind( minilog_uid=id, res ) )
              next()
            } else {

              bcp = list(id=id, nr=nrow(M), YR=yr, tdif.min=3, tdif.max=11, time.gate=time.gate,
                         depth.min=20, depth.range=c(-25,15), eps.depth = 2 ,
                         smooth.windowsize=5, modal.windowsize=5,
                         noisefilter.trim=0.025, noisefilter.target.r2=0.85, noisefilter.quants=c(0.025, 0.975) )
              bcp = bottom.contact.parameters( bcp ) # add other default parameters .. not specified above
              bc =  NULL
              bc = bottom.contact( x=M, bcp=bcp )

              redo = FALSE
              if ( is.null(bc) ) redo =TRUE
              if ( !is.null(bc) && exists("res", bc)) {
                if ( !is.finite(bc$res$t0 ) || !is.finite(bc$res$t1 ) ) redo = TRUE
              }
              if (redo) {
                 bcp$noisefilter.target.r2=0.8
                 bc = bottom.contact( x=M, bcp=bcp )
                 redo = FALSE
              }

              if ( is.null(bc) ) redo =TRUE
              if ( !is.null(bc) && exists("res", bc)) {
                if ( !is.finite(bc$res$t0 ) || !is.finite(bc$res$t1 ) ) redo = TRUE
              }
              if (redo) {
                 bcp$noisefilter.target.r2=0.75
                 bcp$noisefilter.trim=0.05
                 bcp$noisefilter.quants=c(0.025, 0.975)
                 bc = bottom.contact( x=M, bcp=bcp )
                 redo = FALSE
              }

              if (!is.null(bc) ) {
                if (plotdata) {
                  bottom.contact.plot( bc )
                  plotfn = file.path( plotdir, paste(id, "pdf", sep="." ) )
                  print (plotfn)
                  dev.flush()
                  dev.copy2pdf( file=plotfn )
                }
              }
              if ( !is.null(bc) && !is.null(bc$res) ) {
                res = bc$res
                miniStats = rbind(miniStats, cbind( minilog_uid=id, res ) )
              }
            } #end if dat
          } # end if badlist

        } #end nrow id

        # time needs to be reset as posix as it gets lost with rbind/cbind
        miniStats$minilog_uid =  as.character(miniStats$minilog_uid)
        miniStats$t0 = as.POSIXct(miniStats$t0,origin=lubridate::origin, tz="UTC" )
        miniStats$t1 = as.POSIXct(miniStats$t1,origin=lubridate::origin, tz="UTC")
        miniStats$dt = difftime( miniStats$t1, miniStats$t0 )

        # minidt = miniStats$dt
        # miniStats$dt = NA
        # i = which(!is.na( minidt ) )
        # if (length(i) >0 ) miniStats$dt[i] = minidt[i]

        save( miniStats, file=fn, compress=TRUE )
      } # end for year

      return ( minilog.dir )
    }

    # --------------------------------

    if (DS %in% c("set.minilog.lookuptable", "set.minilog.lookuptable.redo") ) {

      fn = file.path( minilog.dir, "set.minilog.lookuptable.rdata" )

      if (DS=="set.minilog.lookuptable" ) {
        B = NULL
        if ( file.exists( fn) ) load (fn)
        return (B)
      }

      B = minilog.db( DS="metadata" )

      # double check .. should not be necessary .. but in case
      uuid = paste( B$trip, B$set, sep="." )
      dups = which( duplicated( uuid) )

      if (length(dups > 0 ) ) {
        toremove =NULL
        for (i in dups) {
          di = which( uuid == uuid[i] )
          tdiff = difftime( B$set_timestamp[di], B$timestamp[di])
          oo = which.min( abs( tdiff) )
          toremove = c(toremove, di[-oo] )
          print("----")
          print( "Matching based upon closest time stamps")
          print(B[di, ])
          print( "Choosing: ")
          print(B[di[oo], ])
          print("")
          toremove = c(toremove, di[-oo] )
        }
        B = B[ -toremove, ]
      }
      B = B[, c("trip", "set", "minilog_uid" )]
      save(B, file=fn, compress=TRUE )
      return(fn)
    }
	}


suppressMessages(usePackage(ggplot2))
suppressMessages(usePackage(dplyr))
suppressMessages(usePackage(tidyr))
suppressMessages(usePackage(reshape2))
suppressMessages(usePackage(RColorBrewer))
suppressMessages(usePackage(MASS))
suppressMessages(usePackage(speedglm))
suppressMessages(usePackage(boot))
suppressMessages(usePackage(devtools))
suppressMessages(usePackage(psych))

source("./R/get_functions.r")

runTest <- function(cov, dir){
  covtmp <- covdat %>% filter(Cov==cov)
  if(dir=="Up"){
    covdir <- covtmp %>% filter(Est>0)
  } else {
    covdir <- covtmp %>% filter(Est<0)
  }

  dnmstmp <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", substr(chrpfdnm$SEQ, 0, 7) %in%
    paste0(covdir$Category, "_", covdir$Sequence),]
  if(nrow(dnmstmp)>=5){
    if(cov=="GC"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_gc"
      dnmstmp$GC <- gcCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/output/3bp_10k/full_bin.txt")
      dnmstmp$inside <- ifelse(dnmstmp$GC>=0.55, 1, 0)
    } else if(cov=="TIME"){
      dnmstmp$TIME <- repCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/lymph_rep_time.txt")
      if(dir=="Down"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/late_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME<=-1.25, 1, 0)
      } else if(dir=="Up"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/early_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME>=1.25, 1, 0)
      }
    } else if(cov=="RR"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_rr"
      dnmstmp$RR <- rcrCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/recomb_rate.bed")
      dnmstmp$inside <- ifelse(dnmstmp$RR>=2, 1, 0)
    } else if(cov=="DHS"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/DHS"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="CpGI"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/cpg_islands_sorted"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="LAMIN"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/lamin_B1_LADS2"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else {
      covbase <- paste0("/net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov)
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    }

    obs <- sum(dnmstmp$inside)

    seqs <- unlist(c(covdir$Sequence, lapply(covdir$Sequence, revcomp)))
    write.table(seqs, "/net/bipolar/jedidiah/mutation/seqs.txt", col.names=F, row.names=F, quote=F, sep="\t")

    grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqs.txt ", covbase, ".fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
    system(grepcmd)

    motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

    names(motifcts) <- c("Count", "SEQ")
    motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
    motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
      motifcts$SEQ, motifcts$REVSEQ)
      # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
      # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
    motifcts2 <- motifcts %>%
      group_by(Sequence) %>%
      summarise(Count=sum(Count))
    covdir2 <- merge(covdir, motifcts2, by=c("Sequence"))

    covdir3 <- merge(covdir2, motifdat, by=c("Category", "Sequence"))
    covdir3$exp <- covdir3$Count*covdir3$rel_prop*1.67e-06*1074
    exp <- sum(covdir3$exp)

    total <- nrow(dnmstmp)
    test <- prop.test(c(obs, exp), c(total, total))
    newrow <- data.frame(cov, dir=dir, obs=obs, exp=exp, n=total,
      propobs=test$estimate[1], propexp=test$estimate[2], pval=test$p.value)
    # testdat <- rbind(testdat, newrow)
    newrow
  }
}

motiffile <- "/net/bipolar/jedidiah/mutation/output/7bp_1000k_rates.txt"
motifdat <- read.table(motiffile, header=T, stringsAsFactors=F)
motifdat <- motifdat %>%
  mutate(Category=gsub("cpg_", "", Category2)) %>%
  mutate(Sequence=substr(Sequence, 0, 7)) %>%
  dplyr::select(Category, Sequence, rel_prop)

covdat <- read.table("/net/bipolar/jedidiah/mutation/fa_motifs.txt", header=T, stringsAsFactors=F)
covdat$Category <- gsub("cpg_", "", covdat$Category)
covs <- unique(covdat$Cov)
# covs <- covs[grepl("H3", covs)]
testdat <- data.frame()
covdir <- covdat %>%
  mutate(Dir=ifelse(Est>=0, "Up", "Down")) %>%
  group_by(Cov, Dir) %>%
  summarise(n=n())
for(i in 1:nrow(covdir)){
  cov <- covdir[i,]$Cov
  dir <- covdir[i,]$Dir
  if(covdir[i,]$n > 10){
    row <- runTest(cov, dir)
    testdat <- rbind(testdat, row)
  }
}
suppressMessages(usePackage(ggplot2))
suppressMessages(usePackage(dplyr))
suppressMessages(usePackage(tidyr))
suppressMessages(usePackage(reshape2))
suppressMessages(usePackage(RColorBrewer))
suppressMessages(usePackage(MASS))
suppressMessages(usePackage(speedglm))
suppressMessages(usePackage(boot))
suppressMessages(usePackage(devtools))
suppressMessages(usePackage(psych))

source("./R/get_functions.r")

runTest <- function(cov, dir){
  covtmp <- covdat %>% filter(Cov==cov)
  if(dir=="Up"){
    covdir <- covtmp %>% filter(Est>0)
  } else {
    covdir <- covtmp %>% filter(Est<0)
  }

  dnmstmp <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covdir$Category, "_", covdir$Sequence),]
  if(nrow(dnmstmp)>=5){
    if(cov=="GC"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_gc"
      dnmstmp$GC <- gcCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/output/3bp_10k/full_bin.txt")
      dnmstmp$inside <- ifelse(dnmstmp$GC>=0.55, 1, 0)
    } else if(cov=="TIME"){
      dnmstmp$TIME <- repCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/lymph_rep_time.txt")
      if(dir=="Down"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/late_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME<=-1.25, 1, 0)
      } else if(dir=="Up"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/early_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME>=1.25, 1, 0)
      }
    } else if(cov=="RR"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_rr"
      dnmstmp$RR <- rcrCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/recomb_rate.bed")
      dnmstmp$inside <- ifelse(dnmstmp$RR>=2, 1, 0)
    } else if(cov=="DHS"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/DHS"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="CpGI"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/cpg_islands_sorted"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="LAMIN"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/lamin_B1_LADS2"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else {
      covbase <- paste0("/net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov)
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    }

    obs <- sum(dnmstmp$inside)

    seqs <- unlist(c(covdir$Sequence, lapply(covdir$Sequence, revcomp)))
    write.table(seqs, "/net/bipolar/jedidiah/mutation/seqs.txt", col.names=F, row.names=F, quote=F, sep="\t")

    grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqs.txt ", covbase, ".fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
    system(grepcmd)

    motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

    names(motifcts) <- c("Count", "SEQ")
    motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
    motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
      motifcts$SEQ, motifcts$REVSEQ)
      # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
      # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
    motifcts2 <- motifcts %>%
      group_by(Sequence) %>%
      summarise(Count=sum(Count))
    covdir2 <- merge(covdir, motifcts2, by=c("Sequence"))

    covdir3 <- merge(covdir2, motifdat, by=c("Category", "Sequence"))
    covdir3$exp <- covdir3$Count*covdir3$rel_prop*1.67e-06*1074
    exp <- sum(covdir3$exp)

    total <- nrow(dnmstmp)
    test <- prop.test(c(obs, exp), c(total, total))
    newrow <- data.frame(cov, dir=dir, obs=obs, exp=exp, n=total,
      propobs=test$estimate[1], propexp=test$estimate[2], pval=test$p.value)
    # testdat <- rbind(testdat, newrow)
    newrow
  }
}

motiffile <- "/net/bipolar/jedidiah/mutation/output/7bp_1000k_rates.txt"
motifdat <- read.table(motiffile, header=T, stringsAsFactors=F)
motifdat <- motifdat %>%
  mutate(Category=gsub("cpg_", "", Category2)) %>%
  mutate(Sequence=substr(Sequence, 0, 7)) %>%
  dplyr::select(Category, Sequence, rel_prop)

covdat <- read.table("/net/bipolar/jedidiah/mutation/fa_motifs.txt", header=T, stringsAsFactors=F)
covdat$Category <- gsub("cpg_", "", covdat$Category)
covs <- unique(covdat$Cov)
# covs <- covs[grepl("H3", covs)]
testdat <- data.frame()
covdir <- covdat %>%
  mutate(Dir=ifelse(Est>=0, "Up", "Down")) %>%
  group_by(Cov, Dir) %>%
  summarise(n=n())
for(i in 1:nrow(covdir)){
  cov <- covdir[i,]$Cov
  dir <- covdir[i,]$Dir
  if(covdir[i,]$n > 10){
    row <- runTest(cov, dir)
    testdat <- rbind(testdat, row)
  }
}
suppressMessages(usePackage(ggplot2))
suppressMessages(usePackage(dplyr))
suppressMessages(usePackage(tidyr))
suppressMessages(usePackage(reshape2))
suppressMessages(usePackage(RColorBrewer))
suppressMessages(usePackage(MASS))
suppressMessages(usePackage(speedglm))
suppressMessages(usePackage(boot))
suppressMessages(usePackage(devtools))
suppressMessages(usePackage(psych))

source("./R/get_functions.r")

runTest <- function(cov, dir){
  covtmp <- covdat %>% filter(Cov==cov)
  if(dir=="Up"){
    covdir <- covtmp %>% filter(Est>0)
  } else {
    covdir <- covtmp %>% filter(Est<0)
  }

  dnmstmp <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covdir$Category, "_", covdir$Sequence),]
  if(nrow(dnmstmpup)>=5){
    if(cov=="GC"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_gc"
      dnmstmp$GC <- gcCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/output/3bp_10k/full_bin.txt")
      dnmstmp$inside <- ifelse(dnmstmp$GC>=0.55, 1, 0)
    } else if(cov=="TIME"){
      dnmstmp$TIME <- repCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/lymph_rep_time.txt")
      if(dir=="Down"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/late_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME<=-1.25, 1, 0)
      } else if(dir=="Up"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/early_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME>=1.25, 1, 0)
      }
    } else if(cov=="RR"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_rr"
      dnmstmp$RR <- rcrCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/recomb_rate.bed")
      dnmstmp$inside <- ifelse(dnmstmp$RR>=2, 1, 0)
    } else if(cov=="DHS"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/DHS"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="CpGI"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/cpg_islands_sorted"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="LAMIN"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/lamin_B1_LADS2"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else {
      covbase <- paste0("/net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov)
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    }

    obs <- sum(dnmstmp$inside)

    seqs <- unlist(c(covdir$Sequence, lapply(covdir$Sequence, revcomp)))
    write.table(seqs, "/net/bipolar/jedidiah/mutation/seqs.txt", col.names=F, row.names=F, quote=F, sep="\t")

    grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqs.txt ", covbase, ".fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
    system(grepcmd)

    motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

    names(motifcts) <- c("Count", "SEQ")
    motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
    motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
      motifcts$SEQ, motifcts$REVSEQ)
      # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
      # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
    motifcts2 <- motifcts %>%
      group_by(Sequence) %>%
      summarise(Count=sum(Count))
    covdir2 <- merge(covdir, motifcts2, by=c("Sequence"))

    covdir3 <- merge(covdir2, motifdat, by=c("Category", "Sequence"))
    covdir3$exp <- covdir3$Count*covdir3$rel_prop*1.67e-06*1074
    exp <- sum(covdir3$exp)

    total <- nrow(dnmstmp)
    test <- prop.test(c(obs, exp), c(total, total))
    newrow <- data.frame(cov, dir=dir, obs=obs, exp=exp, n=total,
      propobs=test$estimate[1], propexp=test$estimate[2], pval=test$p.value)
    # testdat <- rbind(testdat, newrow)
    newrow
  }
}

motiffile <- "/net/bipolar/jedidiah/mutation/output/7bp_1000k_rates.txt"
motifdat <- read.table(motiffile, header=T, stringsAsFactors=F)
motifdat <- motifdat %>%
  mutate(Category=gsub("cpg_", "", Category2)) %>%
  mutate(Sequence=substr(Sequence, 0, 7)) %>%
  dplyr::select(Category, Sequence, rel_prop)

covdat <- read.table("/net/bipolar/jedidiah/mutation/fa_motifs.txt", header=T, stringsAsFactors=F)
covdat$Category <- gsub("cpg_", "", covdat$Category)
covs <- unique(covdat$Cov)
# covs <- covs[grepl("H3", covs)]
testdat <- data.frame()
covdir <- covdat %>%
  mutate(Dir=ifelse(Est>=0, "Up", "Down")) %>%
  group_by(Cov, Dir) %>%
  summarise(n=n())
for(i in 1:nrow(covdir)){
  cov <- covdir[i,]$Cov
  dir <- covdir[i,]$Dir
  if(covdir[i,]$n > 10){
    row <- runTest(cov, dir)
    testdat <- rbind(testdat, row)
  }
}
#' Create an SBATCH option
#'
#' @param key The key for the sbatch option.
#'
#' @return A function that takes a single argument representing
#' the value for the \code{key}.
sbatch_opt <- function(key) {
    return(function(value) {
        return(paste0("--", key, "=", value))
    })
}



#' A list of sbatch options.
#'
#' The value of each item in the list is a string or a function
#' which takes a string as a parameter, using \code{sbatch_opt}.
#'
#' @export
sbatch_opts <- list (
    begin = sbatch_opt("begin"),
    cpus_per_task = sbatch_opt("cpus-per-task"),
    mail_type = sbatch_opt("mail-type"),
    mail_user = sbatch_opt("mail-user"),
    memory = sbatch_opt("mem"),
    nodes = sbatch_opt("nodes"),
    ouput = sbatch_opt("ouput"),
    time = sbatch_opt("time")
)
source("./R/get_functions.r")

runTest <- function(cov, dir){
  covtmp <- covdat %>% filter(Cov==cov)
  if(dir=="Up"){
    covdir <- covtmp %>% filter(Est>0)
  } else {
    covdir <- covtmp %>% filter(Est<0)
  }

  dnmstmp <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covdir$Category, "_", covdir$Sequence),]
  if(nrow(dnmstmpup)>=5){
    if(cov=="GC"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_gc"
      dnmstmp$GC <- gcCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/output/3bp_10k/full_bin.txt")
      dnmstmp$inside <- ifelse(dnmstmp$GC>=0.55, 1, 0)
    } else if(cov=="TIME"){
      dnmstmp$TIME <- repCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/lymph_rep_time.txt")
      if(dir=="Down"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/late_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME<=-1.25, 1, 0)
      } else if(dir=="Up"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/early_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME>=1.25, 1, 0)
      }
    } else if(cov=="RR"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_rr"
      dnmstmp$RR <- rcrCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/recomb_rate.bed")
      dnmstmp$inside <- ifelse(dnmstmp$RR>=2, 1, 0)
    } else if(cov=="DHS"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/DHS"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="CpGI"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/cpg_islands_sorted"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="LAMIN"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/lamin_B1_LADS2"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else {
      covbase <- paste0("/net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov)
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    }

    obs <- sum(dnmstmp$inside)

    seqs <- unlist(c(covdir$Sequence, lapply(covdir$Sequence, revcomp)))
    write.table(seqs, "/net/bipolar/jedidiah/mutation/seqs.txt", col.names=F, row.names=F, quote=F, sep="\t")

    grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqs.txt ", covbase, ".fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
    system(grepcmd)

    motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

    names(motifcts) <- c("Count", "SEQ")
    motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
    motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
      motifcts$SEQ, motifcts$REVSEQ)
      # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
      # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
    motifcts2 <- motifcts %>%
      group_by(Sequence) %>%
      summarise(Count=sum(Count))
    covdir2 <- merge(covdir, motifcts2, by=c("Sequence"))

    covdir3 <- merge(covdir2, motifdat, by=c("Category", "Sequence"))
    covdir3$exp <- covdir3$Count*covdir3$rel_prop*1.67e-06*1074
    exp <- sum(covdir3$exp)

    total <- nrow(dnmstmp)
    test <- prop.test(c(obs, exp), c(total, total))
    newrow <- data.frame(cov, dir=dir, obs=obs, exp=exp, n=total,
      propobs=test$estimate[1], propexp=test$estimate[2], pval=test$p.value)
    # testdat <- rbind(testdat, newrow)
    newrow
  }
}

motiffile <- "/net/bipolar/jedidiah/mutation/output/7bp_1000k_rates.txt"
motifdat <- read.table(motiffile, header=T, stringsAsFactors=F)
motifdat <- motifdat %>%
  mutate(Category=gsub("cpg_", "", Category2)) %>%
  mutate(Sequence=substr(Sequence, 0, 7)) %>%
  dplyr::select(Category, Sequence, rel_prop)

covdat <- read.table("/net/bipolar/jedidiah/mutation/fa_motifs.txt", header=T, stringsAsFactors=F)
covdat$Category <- gsub("cpg_", "", covdat$Category)
covs <- unique(covdat$Cov)
# covs <- covs[grepl("H3", covs)]
testdat <- data.frame()
covdir <- covdat %>%
  mutate(Dir=ifelse(Est>=0, "Up", "Down")) %>%
  group_by(Cov, Dir) %>%
  summarise(n=n())
for(i in 1:nrow(covdir)){
  cov <- covdir[i,]$Cov
  dir <- covdir[i,]$Dir
  if(covdir[i,]$n > 10){
    row <- runTest(cov, dir)
    testdat <- rbind(testdat, row)
  }
}
source("./get_functions.r")

runTest <- function(cov, dir){
  covtmp <- covdat %>% filter(Cov==cov)
  if(dir=="Up"){
    covdir <- covtmp %>% filter(Est>0)
  } else {
    covdir <- covtmp %>% filter(Est<0)
  }

  dnmstmp <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covdir$Category, "_", covdir$Sequence),]
  if(nrow(dnmstmpup)>=5){
    if(cov=="GC"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_gc"
      dnmstmp$GC <- gcCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/output/3bp_10k/full_bin.txt")
      dnmstmp$inside <- ifelse(dnmstmp$GC>=0.55, 1, 0)
    } else if(cov=="TIME"){
      dnmstmp$TIME <- repCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/lymph_rep_time.txt")
      if(dir=="Down"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/late_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME<=-1.25, 1, 0)
      } else if(dir=="Up"){
        covbase <- "/net/bipolar/jedidiah/mutation/reference_data/early_rt"
        dnmstmp$inside <- ifelse(dnmstmp$TIME>=1.25, 1, 0)
      }
    } else if(cov=="RR"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/high_rr"
      dnmstmp$RR <- rcrCol(dnmstmp,
        "/net/bipolar/jedidiah/mutation/reference_data/recomb_rate.bed")
      dnmstmp$inside <- ifelse(dnmstmp$RR>=2, 1, 0)
    } else if(cov=="DHS"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/DHS"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="CpGI"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/cpg_islands_sorted"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else if(cov=="LAMIN"){
      covbase <- "/net/bipolar/jedidiah/mutation/reference_data/lamin_B1_LADS2"
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    } else {
      covbase <- paste0("/net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov)
      covbed <- paste0(covbase, ".bed")
      dnmstmp$inside <- binaryCol(dnmstmp, covbed)
    }

    obs <- sum(dnmstmp$inside)

    seqs <- unlist(c(covdir$Sequence, lapply(covdir$Sequence, revcomp)))
    write.table(seqs, "/net/bipolar/jedidiah/mutation/seqs.txt", col.names=F, row.names=F, quote=F, sep="\t")

    grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqs.txt ", covbase, ".fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
    system(grepcmd)

    motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

    names(motifcts) <- c("Count", "SEQ")
    motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
    motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
      motifcts$SEQ, motifcts$REVSEQ)
      # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
      # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
    motifcts2 <- motifcts %>%
      group_by(Sequence) %>%
      summarise(Count=sum(Count))
    covdir2 <- merge(covdir, motifcts2, by=c("Sequence"))

    covdir3 <- merge(covdir2, motifdat, by=c("Category", "Sequence"))
    covdir3$exp <- covdir3$Count*covdir3$rel_prop*1.67e-06*1074
    exp <- sum(covdir3$exp)

    total <- nrow(dnmstmp)
    test <- prop.test(c(obs, exp), c(total, total))
    newrow <- data.frame(cov, dir=dir, obs=obs, exp=exp, n=total,
      propobs=test$estimate[1], propexp=test$estimate[2], pval=test$p.value)
    # testdat <- rbind(testdat, newrow)
    newrow
  }
}

motiffile <- "/net/bipolar/jedidiah/mutation/output/7bp_1000k_rates.txt"
motifdat <- read.table(motiffile, header=T, stringsAsFactors=F)
motifdat <- motifdat %>%
  mutate(Category=gsub("cpg_", "", Category2)) %>%
  mutate(Sequence=substr(Sequence, 0, 7)) %>%
  dplyr::select(Category, Sequence, rel_prop)

covdat <- read.table("/net/bipolar/jedidiah/mutation/fa_motifs.txt", header=T, stringsAsFactors=F)
covdat$Category <- gsub("cpg_", "", covdat$Category)
covs <- unique(covdat$Cov)
# covs <- covs[grepl("H3", covs)]
testdat <- data.frame()
covdir <- covdat %>%
  mutate(Dir=ifelse(Est>=0, "Up", "Down")) %>%
  group_by(Cov, Dir) %>%
  summarise(n=n())
for(i in 1:nrow(covdir)){
  cov <- covdir[i,]$Cov
  dir <- covdir[i,]$Dir
  if(covdir[i,]$n > 10){
    row <- runTest(cov, dir)
    testdat <- rbind(testdat, row)
  }
}
motiffile <- "/net/bipolar/jedidiah/mutation/output/7bp_1000k_rates.txt"
motifdat <- read.table(motiffile, header=T, stringsAsFactors=F)
motifdat <- motifdat %>%
  mutate(Category=gsub("cpg_", "", Category2)) %>%
  mutate(Sequence=substr(Sequence, 0, 7)) %>%
  dplyr::select(Category, Sequence, rel_prop)

covdat <- read.table("/net/bipolar/jedidiah/mutation/fa_motifs.txt", header=T, stringsAsFactors=F)
# covdat$Category <- gsub("cpg_", "", covdat$Category)
covs <- unique(covdat$Cov)
covs <- covs[grepl("H3", covs)]
testdat <- data.frame()
for(i in 1:length(covs)){
# for(i in 1:2){
  cov <- covs[i]
  covtmp <- covdat %>% filter(Cov==cov)
  covup <- covtmp %>% filter(Est > 0)
  covdown <- covtmp %>% filter(Est < 0)

  dnmstmpup <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covup$Category, "_", covup$Sequence),]
  dnmstmpdown <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covdown$Category, "_", covdown$Sequence),]

  # fastacmd <- paste0("bash bedtools getfasta -fi /net/bipolar/jedidiah/mutation/reference_data/human_g1k_v37.fasta -bed <(sed \'s/chr//g\' /net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov, ".bed | sed /^X/d | sed /^Y/d) -fo /net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov, ".fa")
  # system(fastacmd)

  covfile <- paste0("/net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov, ".bed")
  covbed <- read.table(covfile, header=F)
  covsum <- covbed %>%
    filter(!grepl("X|Y", V1)) %>%
    mutate(length=V3-V2) %>%
    summarise(total=sum(length), prop=total/3e9)

  if(nrow(dnmstmpup)>=5){
    dnmstmpup$inside <- binaryCol(dnmstmpup, covfile)

    upobs <- sum(dnmstmpup$inside)
    # upexp <- covsum$prop*nrow(dnmstmpup)

    seqsup <- unlist(c(covup$Sequence, lapply(covup$Sequence, revcomp)))
    write.table(seqsup, "/net/bipolar/jedidiah/mutation/seqsup.txt", col.names=F, row.names=F, quote=F, sep="\t")

    grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqsup.txt /net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov, ".fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
    system(grepcmd)

    motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

    names(motifcts) <- c("Count", "SEQ")
    motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
    motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
      motifcts$SEQ, motifcts$REVSEQ)
      # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
      # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
    motifcts2 <- motifcts %>%
      group_by(Sequence) %>%
      summarise(Count=sum(Count))
    covup2 <- merge(covup, motifcts2, by=c("Sequence"))

    covup3 <- merge(covup2, motifdat, by=c("Category", "Sequence"))
    covup3$exp <- covup3$Count*covup3$rel_prop*1.67e-06*1074
    upexp <- sum(covup3$exp)

    uptotal <- nrow(dnmstmpup)
    uptest <- prop.test(c(upobs, upexp), c(uptotal, uptotal))
    uprow <- data.frame(cov, dir="up", obs=upobs, exp=upexp, n=uptotal,
      propobs=uptest$estimate[1], propexp=uptest$estimate[2], pval=uptest$p.value)
    testdat <- rbind(testdat, uprow)
  }

  if(nrow(dnmstmpdown)>=5){
    dnmstmpdown$inside <- binaryCol(dnmstmpdown, covfile)

    downobs <- sum(dnmstmpdown$inside)
    seqsdown <- unlist(c(covdown$Sequence, lapply(covdown$Sequence, revcomp)))
    write.table(seqsdown, "/net/bipolar/jedidiah/mutation/seqsdown.txt", col.names=F, row.names=F, quote=F, sep="\t")

    grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqsdown.txt /net/bipolar/jedidiah/mutation/reference_data/histone_marks/broad/sort.E062-", cov, ".fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
    system(grepcmd)

    motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

    names(motifcts) <- c("Count", "SEQ")
    motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
    motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
      motifcts$SEQ, motifcts$REVSEQ)
      # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
      # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
    motifcts2 <- motifcts %>%
      group_by(Sequence) %>%
      summarise(Count=sum(Count))
    covdown2 <- merge(covdown, motifcts2, by=c("Sequence"))

    covdown3 <- merge(covdown2, motifdat, by=c("Category", "Sequence"))
    covdown3$exp <- covdown3$Count*covdown3$rel_prop*1.67e-06*1074
    downexp <- sum(covdown3$exp)

    downtotal <- nrow(dnmstmpdown)
    downtest <- prop.test(c(downobs, downexp), c(downtotal, downtotal))
    downrow <- data.frame(cov, dir="down", obs=downobs, exp=downexp, n=downtotal,
      propobs=downtest$estimate[1], propexp=downtest$estimate[2], pval=downtest$p.value)
    testdat <- rbind(testdat, downrow)
  }
}

# Repeat with CpGI
cov <- "CpGI"
covtmp <- covdat %>% filter(Cov==cov)
covup <- covtmp %>% filter(Est > 0)
covdown <- covtmp %>% filter(Est < 0)

dnmstmpup <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in% paste0(covup$Category, "_", covup$Sequence),]
dnmstmpdown <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in% paste0(covdown$Category, "_", covdown$Sequence),]

covfile <- paste0("/net/bipolar/jedidiah/mutation/reference_data/cpg_islands_sorted.bed")
covbed <- read.table(covfile, header=F)
covsum <- covbed %>%
  filter(!grepl("X|Y", V1)) %>%
  mutate(length=V4) %>%
  summarise(total=sum(length), prop=total/3e9)

if(nrow(dnmstmpup)>=5){
  dnmstmpup$inside <- binaryCol(dnmstmpup, covfile)

  upobs <- sum(dnmstmpup$inside)
  seqsup <- unlist(c(covup$Sequence, lapply(covup$Sequence, revcomp)))
  write.table(seqsup, "/net/bipolar/jedidiah/mutation/seqsup.txt", col.names=F, row.names=F, quote=F, sep="\t")

  grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqsup.txt /net/bipolar/jedidiah/mutation/reference_data/cpg_islands_sorted.fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
  system(grepcmd)

  motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

  names(motifcts) <- c("Count", "SEQ")
  motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
  motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
    motifcts$SEQ, motifcts$REVSEQ)
    # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
    # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
  motifcts2 <- motifcts %>%
    group_by(Sequence) %>%
    summarise(Count=sum(Count))
  covup2 <- merge(covup, motifcts2, by=c("Sequence"))

  covup3 <- merge(covup2, motifdat, by=c("Category", "Sequence"))
  covup3$exp <- covup3$Count*covup3$rel_prop*1.67e-06*1074
  upexp <- sum(covup3$exp)
  uptotal <- nrow(dnmstmpup)
  uptest <- prop.test(c(upobs, upexp), c(uptotal, uptotal))
  uprow <- data.frame(cov, dir="up", obs=upobs, exp=upexp, n=uptotal,
    propobs=uptest$estimate[1], propexp=uptest$estimate[2], pval=uptest$p.value)
  testdat <- rbind(testdat, uprow)
}

if(nrow(dnmstmpdown)>=5){
  dnmstmpdown$inside <- binaryCol(dnmstmpdown, covfile)

  downobs <- sum(dnmstmpdown$inside)
  seqsdown <- unlist(c(covdown$Sequence, lapply(covdown$Sequence, revcomp)))
  write.table(seqsdown, "/net/bipolar/jedidiah/mutation/seqsdown.txt", col.names=F, row.names=F, quote=F, sep="\t")

  grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqsdown.txt /net/bipolar/jedidiah/mutation/reference_data/cpg_islands_sorted.fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
  system(grepcmd)

  motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

  names(motifcts) <- c("Count", "SEQ")
  motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
  motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
    motifcts$SEQ, motifcts$REVSEQ)
    # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
    # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
  motifcts2 <- motifcts %>%
    group_by(Sequence) %>%
    summarise(Count=sum(Count))
  covdown2 <- merge(covdown, motifcts2, by=c("Sequence"))

  covdown3 <- merge(covdown2, motifdat, by=c("Category", "Sequence"))
  covdown3$exp <- covdown3$Count*covdown3$rel_prop*1.67e-06*1074
  downexp <- sum(covdown3$exp)
  downtotal <- nrow(dnmstmpdown)
  downtest <- prop.test(c(downobs, downexp), c(downtotal, downtotal))
  downrow <- data.frame(cov, dir="down", obs=downobs, exp=downexp, n=downtotal,
    propobs=downtest$estimate[1], propexp=downtest$estimate[2], pval=downtest$p.value)
  testdat <- rbind(testdat, downrow)
}

# Repeat with DHS
cov <- "DHS"
covtmp <- covdat %>% filter(Cov==cov)
covup <- covtmp %>% filter(Est > 0)
covdown <- covtmp %>% filter(Est < 0)

dnmstmpup <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in% paste0(covup$Category, "_", covup$Sequence),]
dnmstmpdown <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in% paste0(covdown$Category, "_", covdown$Sequence),]

covfile <- paste0("/net/bipolar/jedidiah/mutation/reference_data/DHS.bed")
covbed <- read.table(covfile, header=F)
covsum <- covbed %>%
  filter(!grepl("X|Y", V1)) %>%
  mutate(length=V3-V2) %>%
  summarise(total=sum(length), prop=total/3e9)

if(nrow(dnmstmpup)>=5){
  dnmstmpup$inside <- binaryCol(dnmstmpup, covfile)

  upobs <- sum(dnmstmpup$inside)
  seqsup <- unlist(c(covup$Sequence, lapply(covup$Sequence, revcomp)))
  write.table(seqsup, "/net/bipolar/jedidiah/mutation/seqsup.txt", col.names=F, row.names=F, quote=F, sep="\t")

  grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqsup.txt /net/bipolar/jedidiah/mutation/reference_data/DHS.fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
  system(grepcmd)

  motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

  names(motifcts) <- c("Count", "SEQ")
  motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
  motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
    motifcts$SEQ, motifcts$REVSEQ)
    # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
    # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
  motifcts2 <- motifcts %>%
    group_by(Sequence) %>%
    summarise(Count=sum(Count))
  covup2 <- merge(covup, motifcts2, by=c("Sequence"))

  covup3 <- merge(covup2, motifdat, by=c("Category", "Sequence"))
  covup3$exp <- covup3$Count*covup3$rel_prop*1.67e-06*1074
  upexp <- sum(covup3$exp)
  uptotal <- nrow(dnmstmpup)
  uptest <- prop.test(c(upobs, upexp), c(uptotal, uptotal))
  uprow <- data.frame(cov, dir="up", obs=upobs, exp=upexp, n=uptotal,
    propobs=uptest$estimate[1], propexp=uptest$estimate[2], pval=uptest$p.value)
  testdat <- rbind(testdat, uprow)
}

if(nrow(dnmstmpdown)>=5){
  dnmstmpdown$inside <- binaryCol(dnmstmpdown, covfile)

  downobs <- sum(dnmstmpdown$inside)
  seqsdown <- unlist(c(covdown$Sequence, lapply(covdown$Sequence, revcomp)))
  write.table(seqsdown, "/net/bipolar/jedidiah/mutation/seqsdown.txt", col.names=F, row.names=F, quote=F, sep="\t")

  grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqsdown.txt /net/bipolar/jedidiah/mutation/reference_data/DHS.fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
  system(grepcmd)

  motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

  names(motifcts) <- c("Count", "SEQ")
  motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
  motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
    motifcts$SEQ, motifcts$REVSEQ)
    # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
    # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
  motifcts2 <- motifcts %>%
    group_by(Sequence) %>%
    summarise(Count=sum(Count))
  covdown2 <- merge(covdown, motifcts2, by=c("Sequence"))

  covdown3 <- merge(covdown2, motifdat, by=c("Category", "Sequence"))
  covdown3$exp <- covdown3$Count*covdown3$rel_prop*1.67e-06*1074
  downexp <- sum(covdown3$exp)
  downtotal <- nrow(dnmstmpdown)
  downtest <- prop.test(c(downobs, downexp), c(downtotal, downtotal))
  downrow <- data.frame(cov, dir="down", obs=downobs, exp=downexp, n=downtotal,
    propobs=downtest$estimate[1], propexp=downtest$estimate[2], pval=downtest$p.value)
  testdat <- rbind(testdat, downrow)
}

# Repeat with LAD
cov <- "LAMIN"
covtmp <- covdat %>% filter(Cov==cov)
covup <- covtmp %>% filter(Est > 0)
covdown <- covtmp %>% filter(Est < 0)

dnmstmpup <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in% paste0(covup$Category, "_", covup$Sequence),]
dnmstmpdown <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in% paste0(covdown$Category, "_", covdown$Sequence),]

covfile <- paste0("/net/bipolar/jedidiah/mutation/reference_data/lamin_B1_LADS2.bed")
covbed <- read.table(covfile, header=F)
covsum <- covbed %>%
  filter(!grepl("X|Y", V1)) %>%
  mutate(length=V3-V2) %>%
  summarise(total=sum(length), prop=total/3e9)

if(nrow(dnmstmpup)>=5){
  dnmstmpup$inside <- binaryCol(dnmstmpup, covfile)

  upobs <- sum(dnmstmpup$inside)
  seqsup <- unlist(c(covup$Sequence, lapply(covup$Sequence, revcomp)))
  write.table(seqsup, "/net/bipolar/jedidiah/mutation/seqsup.txt", col.names=F, row.names=F, quote=F, sep="\t")

  grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqsup.txt /net/bipolar/jedidiah/mutation/reference_data/lamin_B1_LADS2.fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
  system(grepcmd)

  motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

  names(motifcts) <- c("Count", "SEQ")
  motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
  motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
    motifcts$SEQ, motifcts$REVSEQ)
    # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
    # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
  motifcts2 <- motifcts %>%
    group_by(Sequence) %>%
    summarise(Count=sum(Count))
  covup2 <- merge(covup, motifcts2, by=c("Sequence"))

  covup3 <- merge(covup2, motifdat, by=c("Category", "Sequence"))
  covup3$exp <- covup3$Count*covup3$rel_prop*1.67e-06*1074
  upexp <- sum(covup3$exp)
  uptotal <- nrow(dnmstmpup)
  uptest <- prop.test(c(upobs, upexp), c(uptotal, uptotal))
  uprow <- data.frame(cov, dir="up", obs=upobs, exp=upexp, n=uptotal,
    propobs=uptest$estimate[1], propexp=uptest$estimate[2], pval=uptest$p.value)
  testdat <- rbind(testdat, uprow)
}

if(nrow(dnmstmpdown)>=5){
  dnmstmpdown$inside <- binaryCol(dnmstmpdown, covfile)

  downobs <- sum(dnmstmpdown$inside)
  seqsdown <- unlist(c(covdown$Sequence, lapply(covdown$Sequence, revcomp)))
  write.table(seqsdown, "/net/bipolar/jedidiah/mutation/seqsdown.txt", col.names=F, row.names=F, quote=F, sep="\t")

  grepcmd <- paste0("grep -o -Ff /net/bipolar/jedidiah/mutation/seqsdown.txt /net/bipolar/jedidiah/mutation/reference_data/lamin_B1_LADS2.fa | sort | uniq -c > /net/bipolar/jedidiah/mutation/testcounts.txt")
  system(grepcmd)

  motifcts <- read.table("/net/bipolar/jedidiah/mutation/testcounts.txt", header=F, stringsAsFactors=F)

  names(motifcts) <- c("Count", "SEQ")
  motifcts$REVSEQ <- unlist(lapply(motifcts$SEQ, revcomp))
  motifcts$Sequence <- ifelse(substr(motifcts$SEQ,4,4) %in% c("A", "C"),
    motifcts$SEQ, motifcts$REVSEQ)
    # paste0(motifcts$SEQ, "(", motifcts$REVSEQ, ")"),
    # paste0(motifcts$REVSEQ, "(", motifcts$SEQ, ")"))
  motifcts2 <- motifcts %>%
    group_by(Sequence) %>%
    summarise(Count=sum(Count))
  covdown2 <- merge(covdown, motifcts2, by=c("Sequence"))

  covdown3 <- merge(covdown2, motifdat, by=c("Category", "Sequence"))
  covdown3$exp <- covdown3$Count*covdown3$rel_prop*1.67e-06*1074
  downexp <- sum(covdown3$exp)
  downtotal <- nrow(dnmstmpdown)
  downtest <- prop.test(c(downobs, downexp), c(downtotal, downtotal))
  downrow <- data.frame(cov, dir="down", obs=downobs, exp=downexp, n=downtotal,
    propobs=downtest$estimate[1], propexp=downtest$estimate[2], pval=downtest$p.value)
  testdat <- rbind(testdat, downrow)
}

# recombination rate
{
  cov <- "RR"
  covtmp <- covdat %>% filter(Cov==cov)
  covup <- covtmp %>% filter(Est > 0)
  covdown <- covtmp %>% filter(Est < 0)

  dnmstmpup <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covup$Category, "_", covup$Sequence),]
  dnmstmpupinv <- chrpfdnm[!(paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covup$Category, "_", covup$Sequence)),]

  dnmstmpup$RR <- rcrCol(dnmstmpup,
    "/net/bipolar/jedidiah/mutation/reference_data/recomb_rate.bed")

  dnmstmpupinv$RR <- rcrCol(dnmstmpupinv,
    "/net/bipolar/jedidiah/mutation/reference_data/recomb_rate.bed")
  rcruptest <- t.test(dnmstmpup$RR, dnmstmpupinv$RR)
}

# replication timing
{
  cov <- "TIME"
  covtmp <- covdat %>% filter(Cov==cov)
  covup <- covtmp %>% filter(Est > 0)
  covdown <- covtmp %>% filter(Est < 0)

  dnmstmpup <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covup$Category, "_", covup$Sequence),]
  dnmstmpupinv <- chrpfdnm[!(paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covup$Category, "_", covup$Sequence)),]

  dnmstmpup$TIME <- repCol(dnmstmpup,
    "/net/bipolar/jedidiah/mutation/reference_data/lymph_rep_time.txt")

  dnmstmpupinv$TIME <- repCol(dnmstmpupinv,
    "/net/bipolar/jedidiah/mutation/reference_data/lymph_rep_time.txt")

  reptimeuptest <- t.test(dnmstmpup$TIME, dnmstmpupinv$TIME)

  dnmstmpdown <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covdown$Category, "_", covdown$Sequence),]
  dnmstmpdowninv <- chrpfdnm[!(paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covdown$Category, "_", covdown$Sequence)),]

  dnmstmpdown$TIME <- repCol(dnmstmpdown,
    "/net/bipolar/jedidiah/mutation/reference_data/lymph_rep_time.txt")

  dnmstmpdowninv$TIME <- repCol(dnmstmpdowninv,
    "/net/bipolar/jedidiah/mutation/reference_data/lymph_rep_time.txt")

  reptimedowntest <- t.test(dnmstmpdown$TIME, dnmstmpdowninv$TIME)
}

# gc content
{
  cov <- "GC"
  covtmp <- covdat %>% filter(Cov==cov)
  covup <- covtmp %>% filter(Est > 0)
  covdown <- covtmp %>% filter(Est < 0)

  dnmstmpup <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covup$Category, "_", covup$Sequence),]
  dnmstmpupinv <- chrpfdnm[!(paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covup$Category, "_", covup$Sequence)),]

  dnmstmpup$GC <- gcCol(dnmstmpup,
    "/net/bipolar/jedidiah/mutation/output/3bp_10k/full_bin.txt")

  dnmstmpupinv$GC <- gcCol(dnmstmpupinv,
    "/net/bipolar/jedidiah/mutation/output/3bp_10k/full_bin.txt")

  gcuptest <- t.test(dnmstmpup$GC, dnmstmpupinv$GC)

  dnmstmpdown <- chrpfdnm[paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covdown$Category, "_", covdown$Sequence),]
  dnmstmpdowninv <- chrpfdnm[!(paste0(chrpfdnm$Category.x, "_", chrpfdnm$Sequence) %in%
    paste0(covdown$Category, "_", covdown$Sequence)),]

  dnmstmpdown$GC <- gcCol(dnmstmpdown,
    "/net/bipolar/jedidiah/mutation/output/3bp_10k/full_bin.txt")

  dnmstmpdowninv$GC <- gcCol(dnmstmpdowninv,
    "/net/bipolar/jedidiah/mutation/output/3bp_10k/full_bin.txt")

  gcdowntest <- t.test(dnmstmpdown$GC, dnmstmpdowninv$GC)
}
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:
    filename <- 'Multiple_parameters'
    min.tx = 45
    K.values = c(2,4,6,8)
    MW = c(1,3,5)
    WT = c(0,0.3,0.6,1)
    blind = FALSE
    minimum_threshold = 0.3
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/Tanimoto_data.RData")
load("./RData/interactions_source.RData")
suppressMessages(load("./RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
# Format interaction catalogue to fit this table format
    S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
    S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
    }

# setting up the analyses for multiple communities
# Data for communities on which to test the algorithm
    Cm <- unique(interactions_sources[, 'source'])
    communities <- vector("list", length(Cm))
    names(communities) <- Cm

    # Taxa list per community to predict
        for(i in 1:length(communities)) {
            Ci <- which(interactions_sources[, 'source'] == Cm[i])
            S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

            if(length(which(!S1 %in% S0_catalog)) > 0) {
                print('Taxa in C[i] are not all included in taxa list S0')
                break
            }

            communities[[i]] <- S1
        }

# Substracting GloBI interactions for this portion
    Cm.lg <- numeric()
    for(i in 1:length(communities)) {
        Cm.lg <- c(Cm.lg,length(communities[[i]]))
    }

    to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

    Cm <- Cm[-to.delete]
    for(i in rev(to.delete)) {
        communities[[i]] <- NULL
    }
    names(communities) <- Cm

# Setting up lists to store the results
    wt.init <- wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
    wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
    for(i in rev(wt.remove)) {
        similarity.matrices[[i]] <- NULL
    }

    sim.wt <- names(similarity.matrices)
    Tanimoto_analysis <- vector("list",length(sim.wt))
    names(Tanimoto_analysis) <- sim.wt
    for(i in 1:length(sim.wt)) {
        Tanimoto_analysis[[i]] <- vector("list", length(Cm))
        names(Tanimoto_analysis[[i]]) <- Cm
    }

# List to store results of multiple K values
K <- vector("list", length(K.values))
for(i in 1:length(K.values)) {
    K[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- K
names(Tanimoto_analysis) <- K.values
remove(K)

min.wt <- vector("list", length(MW))
for(i in 1:length(MW)) {
    min.wt[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- min.wt
names(Tanimoto_analysis) <- MW
remove(min.wt)

file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
save(x = Tanimoto_analysis, file = file.to.save)

init.time <- Sys.time()
for(n in 1:length(MW)) {
    mw <- MW[n]
    for(m in 1:length(K.values)) {

        # Tanimoto analysis with different weights for different communities
            # Parameters:
                Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
            #   wt  Weight of traits in similarity measurement
            #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
            #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

            # Output:
            #   A vector of sets of resources for each taxon

            for(i in 1:length(WT)){ #1st loop for all types of wt values
                wt <- WT[i]
                pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                for(j in 1:length(Cm)) { #2nd loop for all C[i]
                    S1 <- communities[[j]]
                    S0 <- S0_catalog
                    similarity.matrix <- similarity.matrices[[i]]

                    # Two choices here:
                    #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                    #   2. The analysis takes into account preexisting information already contained in the catalogue

                    # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                    if(blind == TRUE) {
                        for(k in 1:length(S1)) {
                          S0[S1[k], 'resource'] <- ""
                          S0[S1[k], 'non-resource'] <- ""
                        }

                    # 2. Preexisting information kept to inform algorithm
                    } else { # blind == FALSE

                        interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                        # Only modifying those that are loosing data from the catalogue, less time
                            to.change <- numeric()
                            for(k in 1:length(S1)) {
                                to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                            }
                            to.change <- unique(to.change)

                        # Modifying sets of resources and non-resources for taxa in S1
                            interactions <- interactions[to.change, ]
                            rownames(interactions) <- seq(1,nrow(interactions))
                            resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                      resource = interactions[, 'resource'],
                                                                      inter_type = interactions[, 'inter'])

                        # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                            for(k in 1:nrow(resource_set)) {
                              S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                              S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                            }
                        remove(interactions, resource_set, to.change)
                    } #if blind or not blind

                    # Recalculate similarity
                        similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                            S1 = S1,
                                                                            wt = wt,
                                                                            similarity.matrix = similarity.matrix)

                    # Predicting interactions
                        Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                Kr = Kr,
                                                                                S0 = S0,
                                                                                S1 = S1,
                                                                                MW = mw,
                                                                                similarity.matrix = similarity.matrix,
                                                                                minimum_threshold = minimum_threshold)

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(S0, S1, similarity.matrix)
                    setTxtProgressBar(pb, j)
                }#2nd loop for all C[i]

                save(x = Tanimoto_analysis, file = file.to.save)
                remove(wt)

            }#1st loop for all types of wt values
            close(pb)
    }#m
}#n
print(Sys.time() - init.time)

# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf("./Article/Catalog_vs_predictions.pdf",width=7,height=7)
# Plots
par(mfrow=c(2,2))
# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 1.09)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000088","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
            axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
            # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
            points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
        } #i

        ## Add legend
        if(j == 12) {
            legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        }
} #j
dev.off()

save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))
#' SlurmSettings R6 object.
#'
#' An interface to SBATCH settings.
#'
#' @export
SlurmSettings <- R6::R6Class("SlurmSettings",
    public = list(
        nodes = NA,
        cpus_per_task = NA,
        time = NA,
        memory = NA,
        mail_to = NA,
        mail_type = NA,
        initialize = function(nodes = 1, cpus_per_task = 12,
                              time = "00:30:00", memory = "16g",
                              mail_to = NA, mail_type = "all") {
            self$nodes <- nodes
            self$cpus_per_task <- cpus_per_task
            self$time <- time
            self$memory <- memory

            if (!is.na(self$mail_to) && !is.na(self$mail_type)) {
                self$mail_to <- mail_to
                self$mail_type <- mail_type
            }
        },
        sbatch_comments = function() {
            sb <- "#SBATCH --"
            sb_nodes <- paste0(sb, "nodes=", self$nodes)
            sb_cpus_per_task <- paste0(sb, "cpus-per-task=",
                                       self$cpus_per_task)
            sb_time <- paste0(sb, "time=", self$time)
            sb_memory <- paste0(sb, "mem=", self$memory)

            comments <- paste(sb_nodes, sb_cpus_per_task, sb_time,
                              sb_memory, "#SBATCH -o R_job.o%j", sep = "\n")

            if (!is.na(self$mail_to)) {
                sb_mail_to <- paste0(sb, "mail-user=", self$mail_to)
                sb_mail_type <- paste0(sb, "mail-type=", self$mail_type)

                comments <- paste(comments, sb_mail_type, sb_mail_to, sep = "\n")
            }

            return(commments)
        }
    )
)
#' SlurmSettings R6 object.
#'
#' An interface to SBATCH settings.
#'
#' @export
SlurmSettings <- R6::R6Class("SlurmSettings",
    public = list(
        nodes = NA,
        cpus_per_task = NA,
        time = NA,
        memory = NA,
        initialize = function(nodes = 1, cpus_per_task = 12,
                              time = "00:30:00", memory = "16g") {
            self$nodes <- nodes
            self$cpus_per_task <- cpus_per_task
            self$time <- time
            self$memory <- memory
        },
        sbatch_comments = function() {
            sb <- "#SBATCH --"
            sb_nodes <- paste0(sb, "nodes=", self$nodes)
            sb_cpus_per_task <- paste0(sb, "cpus-per-task=",
                                       self$cpus_per_task)
            sb_time <- paste0(sb, "time=", self$time)
            sb_memory <- paste0(sb, "mem=", self$memory)
            return(paste(sb_nodes, sb_cpus_per_task, sb_time,
                         sb_memory, "#SBATCH -o R_job.o%j", sep = "\n"))
        }
    )
)
## Author(s): Kalle von Feilitzen, Fredric J & Martin Hjelmare

# Gain calculation script
# Run with "Rscript path/to/script/gain.r path/to/working/dir/
# path/to/histogram-csv-filebase path/to/initialgains/csv-file"
# from linux command line.
# Repeat for each well.

# Gain calculation script
setwd(commandArgs(TRUE)[1])
filebase <- commandArgs(TRUE)[2]
# Initial gain values used
initialgains <- read.csv(commandArgs(TRUE)[3])$gain
gain <- list()
bins <- list()
gains <- list()

green <- 11;    # 11 images
blue <- 18;     # 7 images
yellow <- 25;   # 7 images
red <- 32;      # 7 images
channel <- vector()
channel_name <- vector()
channel <- append(channel, rep(green, green-length(channel)))
channel_name <- append(channel_name, rep('green', green-length(channel_name)))
channel <- append(channel, rep(blue, blue-length(channel)))
channel_name <- append(channel_name, rep('blue', blue-length(channel_name)))
channel <- append(channel, rep(yellow, yellow-length(channel)))
channel_name <- append(channel_name, rep('yellow', yellow-length(channel_name)))
channel <- append(channel, rep(red, red-length(channel)))
channel_name <- append(channel_name, rep('red', red-length(channel_name)))
channels <- unique(channel)


for (i in 1:(length(channels))) {
	bins[[i]] <- vector()
	gains[[i]] <- vector()
}

# Create curve and function for each individual well
for (i in 1:32) {
	# Read histogram CSV file
	csvfile <- paste(filebase, "C", sprintf("%02d", i-1), ".ome.csv", sep="")
	csv <- read.csv(csvfile)
	csv1 <- csv[csv$count>0 & csv$bin>0,]
	bin1 <- csv1$bin
	count1 <- csv1$count
	# Only use values in interval 10-100
	binmax <- tail(csv$bin, n=1)
	csv2 <- csv[csv$count <= 100 & csv$count >= 10 & csv$bin < binmax,]
	bin2 <- csv2$bin
	count2 <- csv2$count
	# Plot values
	test <- 0
	png(filename=paste(filebase, "C", sprintf("%02d", i-1), ".ome.png", sep = ""))
	if (length(bin1) > 0) {
		plot(count1, bin1, log="xy")
	}
	# Fit curve
	sink("/dev/null")	# Suppress output
	curv <- tryCatch(nls(bin2 ~ A*count2^B, start=list(A = 1000, B=-1), trace=T),
									 warning=function(e) NULL,
									 error=function(e) NULL)
	sink()
	if (!is.null(curv)) {
		# Plot curve
		lines(count2, fitted.values(curv), lwd=2, col="green")
		# Find function and save gain value
		func <- function(val, A=coef(curv)[1], B=coef(curv)[2]) {A*val^B}
		chn <- which(channels==channel[i])
		bins[[chn]] <- append(bins[[chn]], func(2))	# 2 is close to 0 but safer
		gains[[chn]] <- append(gains[[chn]], initialgains[i])
	}
	dev.off()
}

# Create curve and function for each channel (multiple wells)
for (i in 1:(length(channels))) {
	bins_c <- bins[[i]]
	gains_c <- gains[[i]]
	png(filename=paste(filebase,
										 channel_name[channels[i]],
										 "_gain.png",
										 sep = ""))
	if (length(bins_c) >= 3) {
		plot(bins_c, gains_c)
		# Remove values not making an upward trend and above bin=600 (Martin Hjelmare)
		point.connected <- 0
		point.start <- 1
		point.end <- 1
		for (m in 1:(length(bins_c)-1)) {
			for (n in (m+1):length(bins_c)) {
				if(bins_c[n] <= 600 & bins_c[n] >= bins_c[n-1]) {
					if((n-m+1) > point.connected) {
						point.connected <- n-m+1
						point.start <- m
						point.end <- n
					}
				}
				else {
					break
				}
			}
		}
		bins_c <- bins_c[point.start:point.end]
		gains_c <- gains_c[point.start:point.end]
	}
	gain[[i]] <- round(initialgains[channels[i]])
	if (length(bins_c) >= 3) {
		# Fit curve
		sink("/dev/null")	# Suppress output
		curv2 <- tryCatch(nls(gains_c ~ C*bins_c^D,
													start=list(C = 1, D=1),
													trace=T),
											warning=function(e) NULL,
											error=function(e) NULL)
		sink()
		# Find function
		if (!is.null(curv2)) {
			func2 <- function(val, A=coef(curv2)[1], B=coef(curv2)[2]) {A*val^B}
			lines(bins_c, fitted.values(curv2), lwd=2, col="green")
			abline(v=binmax)
			gain[[i]] <- round(min(func2(binmax), gain[[i]]))
		}
	}
	dev.off()
}
cat(paste(gain[[1]], gain[[2]], gain[[3]], gain[[4]]))
#' SlurmSettings R6 object.
#'
#' An interface to SBATCH settings.
#'
#' @export
SlurmSettings <- R6::R6Class("SlurmSettings")
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", basename(main_file), "'"), "], source)")
            loading <- paste("sapply(list.files('./.objects', full.names = TRUE),
                             function(file) { load(file, env = .GlobalEnv) })")
            running_main <- "main()"

            cat(sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

# Flatten input directory
mv -r ./input .

main_file=$(basename $1)

R CMD BATCH ./sources/$main_file

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources', full.names = TRUE)[!(list.files('./sources')) %in%",
                              paste0("'", basename(main_file), "'"), "], source)")
            loading <- paste("sapply(list.files('./.objects'), load)")
            running_main <- "main()"

            cat(sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

# Flatten input directory
mv -r ./input .

main_file=$(basename $1)

R CMD BATCH ./sources/$main_file

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources')[!(",
                              paste0("'", main_file, "'"),
                              "%in% list.files('./sources'))], source)")
            loading <- paste("sapply(list.files('./.objects'), load)")
            running_main <- "main()"

            cat(sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

# Flatten input directory
mv -r ./input .

main_file=$(basename $1)

R CMD BATCH ./sources/$main_file

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources')[!(",
                              paste0("'", main_file, "'"),
                              "%in% list.files('./sources'))], source)")
            loading <- paste("sapply(list.files('./.objects'), load)")
            running_main <- "main()"

            cat(sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

# Flatten input directory
mv -r ./input .

R CMD BATCH ./sources/$1

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            name <- paste0("job_", private$rand_alphanumeric())
            dir <- paste(getwd(), dir, name, sep = "/")
            self$dir <- dir

            for (sub_dir in c("/input", "/output", "/sources", "/.objects")) {
                dir.create(paste0(dir, sub_dir), recursive = TRUE,
                           showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (!is.na(value)) {
                obj_dir <- paste0(self$dir, "/.objects")
                rdata <- paste0(name, ".Rdata")
                save(value, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        add_source = function(file) {
            if (file.exists(file)) {
                source_dir <- paste0(self$dir, "/sources")
                system(paste("cp -r", file, source_dir))
            } else {
                stop("Source file does not exist.")
            }
        },
        add_input = function(file) {
            if (file.exists(file)) {
                input_dir <- paste0(self$dir, "/input")
                system(paste("cp -r", file, input_dir))
            } else {
                stop("Source file does not exist.")
            }
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            name <- paste0("job_", private$rand_alphanumeric())
            dir <- paste(getwd(), dir, name, sep = "/")
            self$dir <- dir

            for (sub_dir in c("/input", "/output", "/sources", "/.objects")) {
                dir.create(paste0(dir, sub_dir), recursive = TRUE,
                           showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            if (!is.na(value)) {
                obj_dir <- paste0(self$dir, "/.objects")
                rdata <- paste0(name, ".Rdata")
                save(value, file = paste(obj_dir, rdata, sep = "/"))
            } else {
                stop("Object must have an non NA value.")
            }
        },
        add_source = function(file) {
            if (file.exists(file)) {
                source_dir <- paste0(self$dir, "/sources")
                system(paste("cp", file, source_dir))
            } else {
                stop("Source file does not exist.")
            }
        },
        add_input = function(file) {
            if (file.exists(file)) {
                input_dir <- paste0(self$dir, "/input")
                system(paste("cp", file, input_dir))
            } else {
                stop("Source file does not exist.")
            }
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources')[!(",
                              paste0("'", main_file, "'"),
                              "%in% list.files('./sources'))], source)")
            loading <- paste("sapply(list.files('./.objects'), load)")
            running_main <- "main()"

            cat(sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

R CMD BATCH ./source/$1

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("#!/bin/bash\nsbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources')[!(",
                              paste0("'", main_file, "'"),
                              "%in% list.files('./sources'))], source)")
            loading <- paste("sapply(list.files('./.objects'), load)")
            running_main <- "main()"

            cat(sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

R CMD BATCH ./source/$1

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("sbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in c(self$source_files, self$main_file)) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })

            script <- SlurmBashScript$new(container, self$main_file)
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            testthat::source_file(self$main_file, e)

            for (file in self$source_files) {
                testthat::source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$cat_main_file_magic(container$dir, main_file)
            private$write_slurm_script(container$dir)
            private$write_submit_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        cat_main_file_magic = function(dir, main_file) {
            file <- paste(dir, "sources", basename(main_file), sep = "/")
            sourcing <- paste("sapply(list.files('./sources')[!(",
                              paste0("'", main_file, "'"),
                              "%in% list.files('./sources'))], source)")
            loading <- paste("sapply(list.files('./.objects'), load)")
            running_main <- "main()"

            cat(sourcing, loading, running_main, file = file, append = TRUE, sep = "\n")
        },
        write_slurm_script = function(dir) {
            contents <- "
#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./sources ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

R CMD BATCH ./source/$1

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("sbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in c(self$source_files, self$main_file)) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })

            script <- SlurmBashScript$new(container, main_file)
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(self$main_file, e)

            for (file in self$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = c("*")) {
            private$write_slurm_script(container$dir)
            private$write_slurm_script(container$dir, main_file, copy_back)
        }
    ),
    private = list(
        write_slurm_script = function(dir) {
            contents <- "
#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./source ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

R CMD BATCH $1

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        },
        write_submit_script = function(dir, main_file, copy_back) {
            contents <- paste("sbatch ./.static.slurm", main_file, copy_back)
            write(contents, file = paste(dir, "submit.sh", sep = "/"))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in c(self$source_files, self$main_file)) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(self$main_file, e)

            for (file in self$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript",
    public = list(
        initialize = function(container, main_file, copy_back = "*") {
            private$write_slurm_script(container$dir)
        }
    ),
    private = list(
        write_slurm_script = function(dir) {
            contents <- "
#!/bin/bash
#SBATCH --nodes=1
#SBATCH --cpus-per-task=12
#SBATCH --time=0:10:00
#SBATCH --mem=16g
#SBATCH -o R_job.o%j


# copy necessary files over
cp -r ./source ./input ./.objects $PFSDIR
cd $PFSDIR

module load hpc-ods
module load pandoc

R CMD BATCH $1

for i in ${@:2}
do
cp -r $i $SLURM_SUBMIT_DIR/output
done

cp -r './$1out' $SLURM_SUBMIT_DIR/output"

            write(contents, file = paste(dir, ".static.slurm", sep = "/"))
        }
    )
)
#' SlurmBashScript R6 object.
#'
#' Generates the necessary bash script to submit through
#' the `sbatch` command.
SlurmBashScript <- R6::R6Class("SlurmBashScript")
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in self$source_files) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(self$main_file, e)

            for (file in self$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        container = NULL,
        params = list(),
        main_file = NULL,
        input_files = list(),
        source_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                self$main_file <- main_file

                self$source_files <- source_files

                private$base_dir <- container_location
                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in self$source_files) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }

                self$container <- container
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })
        }
    ),
    private = list(
        globals = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(self$main_file, e)

            for (file in self$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        container = NULL,
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in private$source_files) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }

                self$container <- container
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        container = NULL,
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        add_input_files = function(files) {
            for (file in c(files)) {
                if (!file.exists(file)) {
                    warning("Input file does not exist.")
                }
            }

            input_files <- c(input_files, files)
        },
        create = function() {
            container <- SlurmContainer$new(private$base_dir)

            tryCatch({
                for (name in names(self$params)) {
                    container$add_object(name, self$params[[name]])
                }

                for (file in private$source_files) {
                    container$add_source(file)
                }

                for (file in self$input_files) {
                    container$add_input(file)
                }

                self$container <- container
            }, error = function(e) {
                system(paste("rm -rf", container$dir))
                stop(e)
            })
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        container = NULL,
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        add_input_files = function(files) {
            for (file in c(files)) {
                if (!file.exists(file)) {
                    warning("Input file does not exist.")
                }
            }

            input_files <- c(input_files, files)
        },
        create = function() {
            container <- SlurmContainer$new(container_location)

            for (name in names(self$params)) {
                container$add_object(name, self$params[[name]])
            }

            for (file in private$source_files) {
                container$add_source(file)
            }

            for (file in self$input_files) {
                container$add_input(file)
            }

            self$container <- container
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        container = NULL,
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()

                self$container <- SlurmContainer$new(container_location)
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        add_input_files = function(files) {
            for (file in c(files)) {
                if (!file.exists(file)) {
                    warning("Input file does not exist.")
                }
            }

            input_files <- c(input_files, files)
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            for (name in names(self$params)) {
                self$container$add_object(name, self$params[[name]])
            }

            for (file in private$source_files) {
                self$container$add_source(file)
            }

            for (file in self$input_files) {
                self$container$add_input(file)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            name <- paste0("job_", private$rand_alphanumeric())
            dir <- paste(getwd(), dir, name, sep = "/")
            self$dir <- dir

            for (sub_dir in c("/input", "/ouput", "/sources", "/.objects")) {
                dir.create(paste0(dir, sub_dir), recursive = TRUE,
                           showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            obj_dir <- paste0(self$dir, "/.objects")
            rdata <- paste0(name, ".Rdata")
            save(value, paste(obj_dir, rdata, sep = "/"))
        },
        add_source = function(file) {
            if (file.exists(file)) {
                source_dir <- paste0(self$dir, "/source")
                system(paste("cp", file, source_dir))
            } else {
                warning("Source file does not exist.")
            }
        },
        add_input = function(file) {
            if (file.exists(file)) {
                input_dir <- paste0(self$dir, "/input")
                system(paste("cp", file, input_dir))
            } else {
                warning("Source file does not exist.")
            }
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        container = NULL,
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()

                self$container <- SlurmContainer$new(container_location)
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        add_input_files = function(files) {
            for (file in c(files)) {
                if (!file.exists(file)) {
                    warning("Input file does not exist.")
                }
            }

            input_files <- c(input_files, files)
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            for (name in names(self$params)) {
                self$container$add_object(name, self$params[[name]])
            }

            # Copy source files to sources directory
            for (file in private$source_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/sources"))
                system(cmd)
            }

            # Copy input files to input directory
            for (file in self$input_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/input"))
                system(cmd)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            name <- paste0("job_", private$rand_alphanumeric())
            dir <- paste(getwd(), dir, name, sep = "/")
            self$dir <- dir

            for (sub_dir in c("/input", "/ouput", "/sources", "/.objects")) {
                dir.create(paste0(dir, sub_dir), recursive = TRUE,
                           showWarnings = FALSE)
            }
        },
        add_object = function(name, value) {
            obj_dir <- paste0(self$dir, "/.objects")
            rdata <- paste0(name, ".Rdata")
            save(value, paste(obj_dir, rdata, sep = "/"))
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        container = NULL,
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()

                self$container <- SlurmContainer$new(container_location)
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        add_input_files = function(files) {
            for (file in c(files)) {
                if (!file.exists(file)) {
                    warning("Input file does not exist.")
                }
            }

            input_files <- c(input_files, files)
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            objects_dir <- paste(private$base_dir, ".objects", sep = "/")

            for (param in names(self$params)) {
                value <- self$params[[param]]
                rdata <- paste(objects_dir, paste0(param, ".RData"), sep = "/")
                save(value, file = rdata)
            }

            # Copy source files to sources directory
            for (file in private$source_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/sources"))
                system(cmd)
            }

            # Copy input files to input directory
            for (file in self$input_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/input"))
                system(cmd)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            name <- paste0("job_", private$rand_alphanumeric())
            dir <- paste(getwd(), dir, name, sep = "/")
            self$dir <- dir

            for (sub_dir in c("/input", "/ouput", "/sources", "/.objects")) {
                dir.create(paste0(dir, sub_dir), recursive = TRUE,
                           showWarnings = FALSE)
            }
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        add_input_files = function(files) {
            for (file in c(files)) {
                if (!file.exists(file)) {
                    warning("Input file does not exist.")
                }
            }

            input_files <- c(input_files, files)
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            private$generate_container()
            objects_dir <- paste(private$base_dir, ".objects", sep = "/")

            for (param in names(self$params)) {
                value <- self$params[[param]]
                rdata <- paste(objects_dir, paste0(param, ".RData"), sep = "/")
                save(value, file = rdata)
            }

            # Copy source files to sources directory
            for (file in private$source_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/sources"))
                system(cmd)
            }

            # Copy input files to input directory
            for (file in self$input_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/input"))
                system(cmd)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        },
        generate_container = function() {
            private$base_dir <- paste0(private$base_dir, "/job")
            bd <- paste0(private$base_dir, "/")
            dir.create(paste0(bd, "input"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "output"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "sources"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, ".objects"), recursive = TRUE, showWarnings = FALSE)

        }
    )
)
#' SlurmContainer R6 object.
#'
#' A slurm container is simply a directory with a specific
#' structure, particulary it has a submit.slurm script at the
#' top level.
SlurmContainer <- R6::R6Class("SlurmContainer",
    public = list(
        dir = NULL,
        initialize = function(dir = ".") {
            name <- paste0("job_", private$rand_alphanumeric())
            dir <- paste(dir, name, sep = "/")

            for (sub_dir in c("/input", "/ouput", "/sources", "/.objects")) {
                dir.create(paste0(dir, sub_dir), recursive = TRUE,
                           showWarnings = FALSE)
            }
        }
    ),
    private = list(
        rand_alphanumeric = function(len = 3) {
            population <- c(rep(0:9, each = 5), LETTERS, letters)
            samp <- sample(population, len, replace = TRUE)
            return(paste(samp, collapse = ''))
        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        input_files = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        warning("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        add_input_files = function(files) {
            for (file in c(files)) {
                if (!file.exists(file)) {
                    warning("Input file does not exist.")
                }
            }

            input_files <- c(input_files, files)
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            private$generate_container()
            objects_dir <- paste(private$base_dir, ".objects", sep = "/")

            for (param in names(self$params)) {
                value <- self$params[[param]]
                rdata <- paste(objects_dir, paste0(param, ".RData"), sep = "/")
                save(value, file = rdata)
            }

            # Copy source files to sources directory
            for (file in private$source_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/sources"))
                system(cmd)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        },
        generate_container = function() {
            private$base_dir <- paste0(private$base_dir, "/job")
            bd <- paste0(private$base_dir, "/")
            dir.create(paste0(bd, "input"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "output"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "sources"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, ".objects"), recursive = TRUE, showWarnings = FALSE)

        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file

                for (file in source_files) {
                    if (!file.exists(file)) {
                        stop("Source file does not exist.")
                    }
                }

                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            private$generate_container()
            objects_dir <- paste(private$base_dir, ".objects", sep = "/")

            for (param in names(self$params)) {
                value <- self$params[[param]]
                rdata <- paste(objects_dir, paste0(param, ".RData"), sep = "/")
                save(value, file = rdata)
            }

            # Copy source files to sources directory
            for (file in private$source_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/sources"))
                system(cmd)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        },
        generate_container = function() {
            private$base_dir <- paste0(private$base_dir, "/job")
            bd <- paste0(private$base_dir, "/")
            dir.create(paste0(bd, "input"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "output"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "sources"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, ".objects"), recursive = TRUE, showWarnings = FALSE)

        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file
                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            private$generate_container()
            objects_dir <- paste(private$base_dir, ".objects", sep = "/")

            for (param in names(self$params)) {
                value <- self$params[[param]]
                rdata <- paste(objects_dir, paste0(param, ".RData"), sep = "/")
                save(value, file = rdata)
            }

            # Copy source files to sources directory
            for (file in private$source_files) {
                cmd <- paste("cp -r", file, paste0(private$base_dir, "/sources"))
                system(cmd)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        },
        generate_container = function() {
            private$base_dir <- paste0(private$base_dir, "/job")
            bd <- paste0(private$base_dir, "/")
            dir.create(paste0(bd, "input"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "output"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "sources"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, ".objects"), recursive = TRUE, showWarnings = FALSE)

        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        params = list(),
        initialize = function(main_file, container_location = ".", source_files = list()) {
            if (!missing(main_file)) {
                private$main_file <- main_file
                private$source_files <- source_files
                private$base_dir <- container_location

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        },
        create = function() {
            for (param in names(self$params)) {
                if (is.na(self$params[[param]])) {
                    message(paste0("`", param, "` "), appendLF = FALSE)
                    stop("is NA. Must be specified.")
                }
            }

            private$generate_container()
            objects_dir <- paste(private$base_dir, ".objects", sep = "/")

            for (param in names(self$params)) {
                value <- self$params[[param]]
                rdata <- paste(objects_dir, paste0(param, ".RData"), sep = "/")
                save(value, file = rdata)
            }
        }
    ),
    private = list(
        globals = list(),
        main_file = NULL,
        source_files = list(),
        base_dir = ".",
        find_globals = function() {
            e <- new.env()
            source_file(private$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        },
        generate_container = function() {
            private$base_dir <- paste0(private$base_dir, "/job")
            bd <- paste0(private$base_dir, "/")
            dir.create(paste0(bd, "input"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, "output"), recursive = TRUE, showWarnings = FALSE)
            dir.create(paste0(bd, ".objects"), recursive = TRUE, showWarnings = FALSE)

        }
    )
)
#' SlurmJob R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        main_file = NULL,
        params = list(),
        initialize = function(main_file, source_files = list()) {
            if (!missing(main_file)) {
                self$main_file <- main_file
                private$source_files <- source_files

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        }
    ),
    private = list(
        globals = list(),
        source_files = list(),
        find_globals = function() {
            e <- new.env()
            source_file(self$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify:"))
                message(globals)
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            # Set the values of all gobals to NA
            global_list <- list()

            for (global in globals) {
                global_list[[global]] <- NA
            }

            private$globals = global_list
            self$params = global_list
        }
    )
)
#' NOAARequest R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        main_file = NULL,
        params = list(),
        initialize = function(main_file, source_files = list()) {
            if (!missing(main_file)) {
                self$main_file <- main_file
                private$source_files = source_files

                private$find_globals()
            } else {
                stop("A file containing a main() function must be provided.")
            }
        }
    ),
    private = list(
        globals = list(),
        source_files = list(),
        find_globals = function() {
            e <- new.env()
            source_file(self$main_file, e)

            for (file in private$source_files) {
                source_file(file, e)
            }

            globals <- codetools::findGlobals(e$main)

            # Filter known `findGlobals` errors
            known_errors <- c("{", "}", "::")
            globals <- globals[!(globals %in% known_errors)]

            # Filter all functions in loaded packages
            for (package in (.packages())) {
                package <- paste0("package:", package)
                exports <- names(as.list(as.environment(package)))
                globals <- globals[!(globals %in% exports)]
            }

            # Filter functions and variables in source files
            globals <- globals[!(globals %in% names(as.list(e)))]

            nglobals <- length(globals)

            if (nglobals > 0) {
                message(paste("Found", nglobals, "parameter to specify."))
                message("Access these variables in the `params` property.")
                message("If new source files are added, `params` will be updated.")
            }

            private$globals = globals
            self$params = globals
        }
    )
)
#' NOAARequest R6 object.
#'
#' An interface to SLURM bash scripts and their submissions.
SlurmJob <- R6::R6Class("SlurmJob",
    public = list(
        main_file = NULL,
        initialize = function(main_file) {
            if (!missing(main_file)) {
                self$main_file <- main_file
            } else {
                stop("A file containing a main() function must be provided.")
            }
        }
    )
)
# Given a campaign finance report ID number from the FEC's website, will download that data, analyze it, and save it as CSVs.
# Consists of two functions: fecgrabber() and fecanalyzer().
# fecgrabber() takes as input a title and an ID.
# It will download the specified report, and clean it up.
# The title should be descriptive and precise, such as "LewisQ1". It should not include any characters such as spaces, dashes or periods that could confuse either R or your file system.
# The ID number can be obtained from the Filings page on a candidate's FEC page, under the View/Download column. It is the numeric part of a string such as "FEC-1061533" — so, in this case, the ID would be 1061533.
# Sample function call: fecgrabber("LewisQ1",1061533)
# It will create a folder in your working directory with a name equal to the title you called the function with, and in it create two CSVs: full data for receipts (1) and expenses (2).
# It then calls fecanalyzer() using the output.
# fecanalyzer() takes as input a title, a table with receipts data and a table with expenditures data. 
# Will be run automatically as part of fecgrabber(). Can also be called manually, in which case the receipts and expenditures data should be specified by reference to data frames in R. It does not include any read.csv() calls to load from the disk; this will have to be done manually.
# fecanalyzer() will output in the console quick overall fundraising summary numbers, but these are incidental to this script. The script is designed to do more in-depth analysis; for basic summary data see the FEC's summaries.
# It will also create a folder in your working directory with a name equal to the title you called the function with, if this doesn't already exist, and in it create six CSVs: Fundraising summarized by (1) states, (2) cities, (3) occupation and (4) employer, and expenses summarized by (5) purpose and (6) recipient.
# FEC reports often contain lots of unclean artifacts — typos, unusual methods of recording data, etc. This won't catch that stuff, so always check your outputs. If you catch issues, you can fix them manually and then call fecanalyzer() to re-run the analysis on the clean data.
# This code drops all contributions from "Actblue", a conduit PAC that often shows up as double entries in FEC reports. If your data should not exclude Actblue, comment out line 47.
# Code by David H. Montgomery for the Pioneer Press.

library(RCurl)
library(dplyr)

fecgrabber <- function(title,id) {
    tmp <- read.table( # Load the FEC file from the web
        textConnection(
            getURL(
                paste0("http://docquery.fec.gov/dcdev/posted/",id,".fec")
            )
        ),
        sep = "\034",
        quote = "\"",
        skip = 2, # Skip the useless header lines
        fill = TRUE, # Fill in blank cells to avoid tons of errors
        stringsAsFactors= FALSE,
        colClasses = c(rep("character",20),"numeric","numeric",rep("character",3))
    )
    tmp$V20 <- as.Date(tmp$V20,"%Y%m%d") # Convert dates from character to date format
    receipts <- subset(tmp, grepl("SA", V1)) # Extract receipt data to a new data frame
    expenses <- subset(tmp, grepl("SB", V1)) # Extract expenses data to a new data frame
    
    # Process Receipts table
    
    receipts <- receipts[,c(1,6:9,13:18,20:25)] # Drop unneeded receipts columns
    colnames(receipts) <- c("Code","Type","Name","Lastname","Firstname","Address","PO Box","City","State","ZIP","Elex","Date","Contrib","To Date","Memo","Employer","Job") # Label receipts columns
    receipts <- receipts[receipts$Code != "SA13A",] # Drop self-funding
    for (i in 1:nrow(receipts)) { if(receipts[i,3] == "") {receipts[i,3] <- paste0(receipts[i,4],", ",receipts[i,5]) }} # Fill in full names
    for (i in 1:nrow(receipts)) { if(receipts[i,7] != "") {receipts[i,6] <- paste(receipts[i,6],receipts[i,7]) }} # Fill in full addresses
    receipts <- receipts[,-c(4,5,7)] # Drop newly superfluous columns
    receipts <- receipts[receipts$Name != "Actblue",] # Remove ActBlue contributions
    
    # Process Expenses table
    
    expenses <- expenses[,c(1,6:9,13:18,20:21,23)] # Drop unneeded expenses columns
    colnames(expenses) <- c("Code","Type","Name","Lastname","Firstname","Address","PO Box","City","State","ZIP","Elex","Date","Amount","Expense") # Label expenses columns
    for (i in 1:nrow(expenses)) { if(expenses[i,3] == "") {expenses[i,3] <- paste0(expenses[i,4],", ",expenses[i,5]) }} # Fill in full names
    for (i in 1:nrow(expenses)) { if(expenses[i,7] != "") {expenses[i,6] <- paste(expenses[i,6],expenses[i,7]) }} # Fill in full addresses
    expenses <- expenses[,-c(4,5,7)] # Drop newly superfluous columns

	# Save contents to disk.
	if (!dir.exists(title)) {dir.create(title)} # If it doesn't exist, create a directory named after the specified title.
	setwd(title) # Move to the new directory
	# Save the receipts and expenses tables as CSVs
	write.csv(receipts,paste0(title,"receipts.csv"), row.names =F)
	write.csv(expenses,paste0(title,"expenses.csv"), row.names = F)
	setwd("..") # Return to the original working directory.
	fecanalyzer(title,receipts,expenses) # Call the supporting function fecanalyzer() with the outputs from fecgrabber().
}
		
	
# Supporting function that takes data frames as formatted by fecgrabber() and extracts some interesting information from them.

# The top states of origin for donations in the report.
fecanalyzer <- function(title, raised, spent) {	
	a <- raised %>% group_by(State) %>% summarise(Total = sum(Contrib)) %>% arrange(desc(Total))
	a$Percent <- a$Total / sum(a$Total, na.rm=T) # Calculate each state's donations as a percent of the total donations.

	# The top cities of origin for donations in the report.	
	b <- raised %>% group_by(City, State) %>% na.omit() %>% summarise(Total = sum(Contrib))
	b <- arrange(as.data.frame(b),desc(Total)) # Do the sorting a little differently because the cities sort wasn't working the way the other calls did.
	b$Percent <- b$Total / sum(b$Total, na.rm=T) # Calculate each city's donations as a percent of the total donations.
	
	# The top occupations listed by donors in the report.
	c <- raised %>% group_by(Job) %>% summarise(Total = sum(Contrib)) %>% arrange(desc(Total))
	c$Percent <- c$Total / sum(c$Total, na.rm=T) # Calculate each job's donations as a percent of the total donations.
	
	# The top employers listed by donors in the report.
	d <- raised %>% group_by(Employer) %>% summarise(Total = sum(Contrib)) %>% arrange(desc(Total))
	d$Percent <- d$Total / sum(d$Total, na.rm=T) # Calculate each employer's donations as a percent of the total donations.
	
	# The top types of expense in the report.
	e <- spent %>% group_by(Expense) %>% summarise(Total = sum(Amount)) %>% arrange(desc(Total))
	e$Percent <- e$Total / sum(e$Total, na.rm=T) # Calculate each expense type as a percent of the total expenses.

	# The top recipients of expenses in the report.
	f <- spent %>% group_by(Name) %>% summarise(Total = sum(Amount)) %>% arrange(desc(Total))
	f$Percent <- f$Total / sum(f$Total, na.rm=T) # Calculate each expense recipient as a percent of the total expenses.

	
	if (!dir.exists(title)) {dir.create(title)} # If it doesn't exist, create a directory named after the specified title.
	setwd(title) # Move to the directory in question
	# Save the six data frames just calcualted as CSVs, with filenames based on your title.
	write.csv(a,paste0(title,"-in-states.csv"), row.names =F)
	write.csv(b,paste0(title,"-in-cities.csv"), row.names =F)
	write.csv(c,paste0(title,"-in-jobs.csv"), row.names =F)
	write.csv(d,paste0(title,"-in-employers.csv"), row.names =F)
	write.csv(e,paste0(title,"-out-expenses.csv"), row.names =F)
	write.csv(f,paste0(title,"-out-recipients.csv"), row.names =F)
	setwd("..") # Return to the original working directory.
	
	# Create a new global variable, called [title].fec: a list containing the six data frames, so you can call them in R for quick analysis.
	assign(paste0(title,".fec"),list("Top States" = a,"Top Cities" = b,"Top Jobs" = c,"Top Employers" = d, "Top Expenses" = e, "Top Recipients" = f), envir = .GlobalEnv) 
	rm(a,b,c,d,e,f) # Clean up the old data frames.
	
	# Print basic summary data into the console.
	print(paste0("Total raised: $",sum(raised$Contrib, na.rm=T)))
	print(paste0("Total spent: $",sum(spent$Amount, na.rm=T)))
}#' Remove points from a scatter plot where density is really high
#' @param x x-coordinates vector
#' @param y y-coordinates vector
#' @param resolution number of partitions for the x and y-dimensions.
#' @param max.per.cell maximum number of points per x-y partition.
#' @return index into the points that omits points from x-y partitions
#' so that each has at most \code{max.per.cell} points.
scatter.thinning <- function(x,y,resolution=100,max.per.cell=100) {
    x.cell <- floor((resolution-1)*(x - min(x,na.rm=T))/diff(range(x,na.rm=T))) + 1
    y.cell <- floor((resolution-1)*(y - min(y,na.rm=T))/diff(range(y,na.rm=T))) + 1
    z.cell <- x.cell * resolution + y.cell
    frequency.table <- table(z.cell)
    frequency <- rep(0,max(z.cell, na.rm=T))
    frequency[as.integer(names(frequency.table))] <- frequency.table
    f.cell <- frequency[z.cell]
    
    big.cells <- length(which(frequency > max.per.cell))
    sort(c(which(f.cell <= max.per.cell),
           sample(which(f.cell > max.per.cell),
                  size=big.cells * max.per.cell, replace=F)),
         decreasing=F)
}

#' QQ plot for EWAS
#'
#' @param ewas.object Return object from \code{\link{meffil.ewas()}}.
#' @param sig.threshold P-value threshold for significance (Default: 1e-7).
#' @param sig.color Color for points corresponding to significant tests (Default: "red").
#' @param title Title for the plot (Default: "QQ plot").
#' @param xlab Label for the x-axis (Default: -log_10(expected p-values)).
#' @param ylab Label for the y-axis (Default: -log_10(observed p-values)).
#' @param lambda.method Method for calculating genomic inflation lambda.
#' Valid values are "median" or "regression" (Default: "median").
#' @return List of \code{\link{ggplot}} for each analysis in \code{ewas.object}.
#' @export
meffil.ewas.qq.plot <- function(ewas.object,
                                sig.threshold=1e-7,
                                sig.color="red",
                                title="QQ plot",
                                xlab=bquote(-log[10]("expected p-values")),
                                ylab=bquote(-log[10]("observed p-values")),
                                lambda.method="median") {
    stopifnot(is.ewas.object(ewas.object))
    
    sapply(names(ewas.object$analyses), function(name) {
        p.values <- sort(ewas.object$analyses[[name]]$table$p.value, decreasing=T)
        stats <- data.frame(is.sig=p.values < sig.threshold,
                            expected=-log(sort(ppoints(p.values),decreasing=T),10),
                            observed=-log(p.values, 10))
        lambda <- qq.lambda(p.values[which(p.values > sig.threshold)],
                            method=lambda.method)

        label.x <- min(stats$expected) + diff(range(stats$expected))*0.1
        label.y <- min(stats$expected) + diff(range(stats$observed))*0.9

        lambda.label <- paste("lambda == ", format(lambda$estimate,digits=3),
                              "%+-%", format(lambda$se, digits=3),
                              "~(", lambda.method, ")", sep="")

        selection.idx <- scatter.thinning(stats$observed, stats$expected,
                                          resolution=100, max.per.cell=100)

        lim <- range(c(0, stats$expected, stats$observed))
        sig.threshold <- format(sig.threshold, digits=3)
        
        (ggplot(stats[selection.idx,], aes(x=expected, y=observed)) + 
         geom_abline(intercept = 0, slope = 1, colour="black") +              
         geom_point(aes(colour=factor(sign(is.sig)))) +
         scale_colour_manual(values=c("black", "red"),
                             name="Significant",
                             breaks=c("0","1"),
                             labels=c(paste("p-value >", sig.threshold),
                                 paste("p-value <", sig.threshold))) +
         annotate(geom="text", x=label.x, y=label.y, hjust=0,
                  label=lambda.label,
                  parse=T) +
         xlim(lim) + ylim(lim) + 
         xlab(xlab) + ylab(ylab) +
         coord_fixed() +
         ggtitle(paste(title, ": ", name, sep="")))
     }, simplify=F)     
}

qq.lambda <- function(p.values, method="median", B=100) {
    stopifnot(method %in% c("median","regression"))
    p.values <- na.omit(p.values)
    observed <- qchisq(p.values, df=1, lower.tail = FALSE)
    observed <- sort(observed)
    expected <- qchisq(ppoints(length(observed)), df=1, lower.tail=FALSE)
    expected <- sort(expected)

    lambda <- se <- NA
    if (method == "median")  {
        lambda <- median(observed)/qchisq(0.5, df=1)
        boot.medians <- sapply(1:B, function(i) median(sample(observed, replace=T)))
        se <- sd(boot.medians/qchisq(0.5,df=1))
    } else if (method == "regression") {
        coef.table <- summary(lm(observed ~ 0 + expected))$coeff
        lambda <- coef.table["expected","Estimate"]
        se <- coef.table["expected", "Std. Error"]
    }
    list(method=method, estimate=lambda, se=se)
}

#' Manhattan plot for EWAS
#'
#' @param ewas.object Return object from \code{\link{meffil.ewas()}}.
#' @param sig.threshold P-value threshold for significance (Default: 1e-7).
#' @param title Title for the plot (Default: "Manhattan plot").
#' @return \code{\link{ggplot}} showing the Manhattan plot. 
#' @export
meffil.ewas.manhattan.plot <- function(ewas.object, sig.threshold=1e-7,
                                       title="Manhattan plot") {
    stopifnot(is.ewas.object(ewas.object))
    
    chromosomes <- paste("chr", c(1:22, "X","Y"), sep="")
    sapply(names(ewas.object$analyses), function(name) {
        stats <- ewas.object$analyses[[name]]$table
        stats$chromosome <- factor(as.character(stats$chromosome), levels=chromosomes)
        stats$chr.colour <- 0
        stats$chr.colour[stats$chromosomes %in% chromosomes[seq(1,length(chromosomes),2)]] <- 1
        stats$stat <- -log(stats$p.value,10) * sign(stats$coefficient)

        stats <- stats[order(stats$stat, decreasing=T),]

        chromosome.lengths <- sapply(chromosomes, function(chromosome)
                                     max(stats$position[which(stats$chromosome == chromosome)]))
        chromosome.lengths <- as.numeric(chromosome.lengths)
        chromosome.starts <- c(1,cumsum(chromosome.lengths)+1)
        names(chromosome.starts) <- c(chromosomes, "NA")
        stats$global <- stats$position + chromosome.starts[stats$chromosome] - 1

        selection.idx <- scatter.thinning(stats$global, stats$stat,
                                          resolution=100, max.per.cell=100)
        
        (ggplot(stats[selection.idx,], aes(x=position, y=stat)) +
         geom_point(aes(colour=chr.colour)) +
         facet_grid(. ~ chromosome, space="free_x", scales="free_x") +
         theme(strip.text.x = element_text(angle = 90)) +
         guides(colour=FALSE) +
         labs(x="Position",
              y=bquote(-log[10]("p-value") * sign(beta))) +             
         geom_hline(yintercept=log(sig.threshold,10), colour="red") +
         geom_hline(yintercept=-log(sig.threshold,10), colour="red") +
         theme(axis.text.x = element_blank(), axis.ticks.x = element_blank()) +
         ggtitle(paste(title, ": ", name, sep=""))) 
    }, simplify=F)        
}


#' Scatter plots for a CpG site in an EWAS
#'
#' @param ewas.object Return object from \code{\link{meffil.ewas()}}.
#' @param cpg CpG site to plot.
#' @param title Title of the plot (Default: \code{cpg}).
#' @param beta Matrix of methylation levels used to create the \code{ewas.object}.
#' @param \code{\link{ggplot}} object showing the scatterplots of DNA methylation vs the variable of interest
#' in the EWAS.  Each plot corresponds to a covariate set.
#' Methylation levels are in fact residuals from fitting a model with DNA methylation and the covariates.
#' 
#' @export
meffil.ewas.cpg.plot <- function(ewas.object, cpg, beta, title=cpg) {
    stopifnot(is.ewas.object(ewas.object))
    stopifnot(is.matrix(beta) && cpg %in% rownames(beta))
    
    variable <- ewas.object$variable
    
    lapply(names(ewas.object$analyses), function(name) {
        ewas <- ewas.object$analyses[[name]]        

        if (!all(rownames(ewas$design) %in% colnames(beta)))
            stop("EWAS samples do not match those in the beta argument (methylation matrix)")
        methylation <- beta[cpg,rownames(ewas$design)]

        covariates <- subset(data.frame(ewas$design), select=c(-variable,-intercept))
        if (ncol(covariates) == 0)
            covariates <- NULL
        cpg.plot(methylation, variable, covariates, title=paste(name, ": ", title, sep=""))
    })
}

cpg.plot <- function(methylation, variable, covariates=NULL, title="") {
    ## remove missing values
    idx <- which(!is.na(methylation) & !is.na(variable))
    if (length(idx) < 3) {
        warning("Not enough data points to plot CpG methylation.")
        return(NULL)
    }
    methylation <- methylation[idx]
    variable <- variable[idx]
    
    ## linear model fit
    if (is.null(covariates)) {
        fit <- lm(methylation ~ variable)
        base <- lm(methylation ~ 1)
    }
    else {
        covariates <- covariates[idx,,drop=F]
        fit <- lm(methylation ~ variable + ., data=covariates)
        base <- lm(methylation ~ ., data=covariates)
    }
    p.value.lm <- anova(fit,base)[2,"Pr(>F)"]

    stats.desc <- paste("variable\np[lm]= ", format(p.value.lm, digits=3), sep="")
                        
    has.betareg <- all(c("lmtest", "betareg") %in% rownames(installed.packages()))
    if (has.betareg) {
        require("betareg")
        require("lmtest")
        ## beta regression model fit
        if (is.null(covariates)) {
            fit <- betareg(methylation ~ variable)
            base <- betareg(methylation ~ 1)
        }
        else {
            fit <- betareg(methylation ~ variable + ., data=covariates)
            base <- betareg(methylation ~ ., data=covariates)
        }
        p.value.beta <- lrtest(fit, base)[2,"Pr(>Chisq)"]

        stats.desc <- paste(stats.desc, "; p[beta] = ", format(p.value.beta, digits=3), sep="")
    }
    if (!is.null(covariates))
        methylation <- residuals(base)

    ## plot
    data <- data.frame(methylation=methylation, variable=variable)
    if (is.factor(variable) || length(unique(variable)) <= 20) {
        data$variable <- as.factor(data$variable)
        p <- (ggplot(data, aes(x=variable, y=methylation)) +
              geom_boxplot())
    } else {
        p <- (ggplot(data, aes(x=variable, y=methylation)) +
              geom_point() + geom_smooth(method=lm))
    }

    (p + ggtitle(title) +
     xlab(stats.desc) + ylab("DNA methylation"))
}
##predefined_condition_begin
# setwd("h:/temp")  
#   
# data<-read.table("Z:/Shared/Labs/Brown,J/tiger/20160509_brown_3436/star_genetable/result/B3436_gene.count",row.names=1, header=T, check.names=F)
# 
# taskName<-'B3436'
# showLabelInPCA<-1
# showDEGeneCluster<-0
# pvalue<-0.05
# foldChange<-2
# minMedianInGroup<-5
# addCountOne<-0
# 
# comparisons=list(
#   "CAPTISOL_vs_FED" = c("CAPTISOL_vs_FED.design", "FED", "CAPTISOL")
# ) 
#
##predefined_condition_end

library("DESeq2")
library("heatmap3")
library("lattice")
library("reshape")
library("ggplot2")
library("grid")
library("scales")
library("reshape2")
library("VennDiagram")

##Solving node stack overflow problem start###
#when there are too many genes, drawing dendrogram may failed due to node stack overflow,
#It could be solved by forcing stats:::plotNode to be run as interpreted code rather then byte-compiled code via a nasty hack.
#http://stackoverflow.com/questions/16559250/error-in-heatmap-2-gplots/25877485#25877485

# Convert a byte-compiled function to an interpreted-code function 
unByteCode <- function(fun)
{
  FUN <- eval(parse(text=deparse(fun)))
  environment(FUN) <- environment(fun)
  FUN
}

# Replace function definition inside of a locked environment **HACK** 
assignEdgewise <- function(name, env, value)
{
  unlockBinding(name, env=env)
  assign( name, envir=env, value=value)
  lockBinding(name, env=env)
  invisible(value)
}

# Replace byte-compiled function in a locked environment with an interpreted-code
# function
unByteCodeAssign <- function(fun)
{
  name <- gsub('^.*::+','', deparse(substitute(fun)))
  FUN <- unByteCode(fun)
  retval <- assignEdgewise(name=name,
                           env=environment(FUN),
                           value=FUN
  )
  invisible(retval)
}

# Use the above functions to convert stats:::plotNode to interpreted-code:
unByteCodeAssign(stats:::plotNode)

# Now raise the interpreted code recursion limit (you may need to adjust this,
#  decreasing if it uses to much memory, increasing if you get a recursion depth error ).
options(expressions=5e4)

##Solving node stack overflow problem end###

hmcols <- colorRampPalette(c("green", "black", "red"))(256)

drawHCA<-function(prefix, rldselect, ispaired, designData, conditionColors, gnames){
  htfile<-paste0(prefix, "_DESeq2-vsd-heatmap.png")
  cat("saving HCA to ", htfile, "\n")
  genecount<-nrow(rldselect)
  if(genecount > 2){
    png(filename=htfile, width=3000, height =3000, res=300)
    cexCol = max(1.0, 0.2 + 1/log10(ncol(rldselect)))
    if(ispaired){
      htColors<-rainbow(length(unique(designData$Paired)))
      gsColors<-as.matrix(data.frame(Group=conditionColors, Sample=htColors[designData$Paired]))
    }else{
      gsColors = conditionColors;
    }
    heatmap3(rldselect, 
             col = hmcols, 
             ColSideColors = gsColors, 
             margins=c(12,5), 
             scale="r", 
             dist=dist, 
             labRow=NA,
             main=paste0("Hierarchical Cluster Using ", genecount, " Genes"),  
             cexCol=cexCol, 
             useRaster=FALSE,
             legendfun=function() showLegend(legend=paste0("Group ", gnames), col=c("red","blue"),cex=1.0,x="center"))
    dev.off()
  }
}

drawPCA<-function(prefix, rldmatrix, showLabelInPCA, designData, conditionColors){
  #filename<-paste0(prefix, "_DESeq2-vsd-pca.png")
  filename<-paste0(prefix, "_DESeq2-vsd-pca.pdf")
  genecount<-nrow(rldmatrix)
  if(genecount > 2){
    cat("saving PCA to ", filename, "\n")
    #png(filename=filename, width=3000, height=3000, res=300) # 10 X 10 inches
    pdf(filename, width=10, height=10)
    pca<-prcomp(t(rldmatrix))
    supca<-summary(pca)$importance
    pcadata<-data.frame(pca$x)
    pcalabs=paste0(colnames(pcadata), "(", round(supca[2,] * 100), "%)")
    pcadata["sample"]<-row.names(pcadata)
    
    if(showLabelInPCA){
      g <- ggplot(pcadata, aes(x=PC1, y=PC2, label=sample)) + 
        geom_text(vjust=-0.6, size=4) +
        geom_point(col=conditionColors, size=4) + 
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) +
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) + 
        xlab(pcalabs[1]) + ylab(pcalabs[2])
    }else{
      g <- ggplot(pcadata, aes(x=PC1, y=PC2)) + 
        geom_point(col=conditionColors, size=4) + 
        labs(color = "Group") +
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) + 
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) +
        xlab(pcalabs[1]) + ylab(pcalabs[2]) + 
        theme(legend.position="top")
    }
    
    print(g)
    dev.off()
  }
}

#for volcano plot
reverselog_trans <- function(base = exp(1)) {
  trans <- function(x) -log(x, base)
  inv <- function(x) base^(-x)
  trans_new(paste0("reverselog-", format(base)), trans, inv, 
            log_breaks(base = base), 
            domain = c(1e-100, Inf))
}

data<-data[,colnames(data) != "Feature_length"]
colClass<-sapply(data, class)
countNotNumIndex<-which(colClass!="numeric" & colClass!="integer")
if (length(countNotNumIndex)==0) {
  index<-1;
  indecies<-c()
} else {
  index<-max(countNotNumIndex)+1
  indecies<-c(1:(index-1))
}

countData<-data[,c(index:ncol(data))]
countData[is.na(countData)] <- 0
countData<-round(countData)

if(addCountOne){
  countData<-countData+1
}

comparisonNames=names(comparisons)
comparisonName=comparisonNames[1]

dir.create("details", showWarnings = FALSE)

pairedspearman<-list()
resultAllOut<-data
resultAllOutVar<-c("log2FoldChange","pvalue","padj")
for(comparisonName in comparisonNames){
  str(comparisonName)
  designFile=comparisons[[comparisonName]][1]
  gnames=comparisons[[comparisonName]][2:3]
  designData<-read.table(designFile, sep="\t", header=T)
  designData$Condition<-factor(designData$Condition, levels=gnames)
  
  if(ncol(designData) >= 3){
    cat("Data with covariances!\n")
  }else{
    cat("Data without covariances!\n")
  }
  if (any(colnames(designData)=="Paired")) {
	  ispaired<-TRUE
	  cat("Paired Data!\n")
  }else{
	  ispaired<-FALSE
	  cat("Not Paired Data!\n")
  }
  temp<-apply(designData,2,function(x) length(unique(x)))
  if (any(temp==1)) {
	  cat(paste0("Factors with only 1 level in design matrix: ",colnames(designData)[which(temp==1)],"\n"))
	  cat("They will be removed")
	  cat("\n")
	  designData<-designData[,which(temp!=1)]
  }
  temp<-apply(designData[,-1,drop=F],2,rank)
  if (length(unique(rowSums(temp)))==1 | identical(temp[,1],temp[,-1])) {
	  cat(paste0("The model matrix is not full rank, so the model cannot be fit as specified"))
	  cat("\n")
	  cat("Only Condition variable will be kept.")
	  cat("\n")
	  designData<-designData[,which(colnames(designData)%in% c("Sample","Condition"))]
  }
  
  comparisonData<-countData[,colnames(countData) %in% as.character(designData$Sample),drop=F]
  if(ncol(comparisonData) != nrow(designData)){
	message=paste0("Data not matched, there are ", nrow(designData), " samples in design file ", designFile, " but ", ncol(comparisonData), " samples in data ")
	warning(message)
	writeLines(message,paste0(comparisonName,".error"))
	next
  }
  comparisonData<-comparisonData[,as.character(designData$Sample)]
  
  prefix<-comparisonName
  curdata<-data
  if(minMedianInGroup > 0){
    conds<-unique(designData$Condition)
    data1<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[1]]]
    data2<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[2]]]
    med1<-apply(data1, 1, median) >= minMedianInGroup
    med2<-apply(data2, 1, median) >= minMedianInGroup
    med<-med1 | med2
    comparisonData<-comparisonData[med,]
    cat(nrow(comparisonData), " genes with minimum median count in group larger or equals than ", minMedianInGroup, "\n")
    
    if (nrow(comparisonData)==0) {
		message=paste0("Error: 0 Genes can be used in DESeq2 analysis in comparison ",comparisonName," \n")
		warning(message)
		writeLines(message,paste0(comparisonName,".error"))
      next;
    }
    
    prefix<-paste0(comparisonName, "_min", minMedianInGroup)
    curdata<-data[med,]
  }
  
  if(ispaired){
    pairedSamples = unique(designData$Paired)
    
    spcorr<-unlist(lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      cor(comparisonData[,samples[1]],comparisonData[,samples[2]],method="spearman")
    }))
    
    
    sptable<-data.frame(Name=pairedSamples, Spcorr=spcorr)
    write.csv(sptable, file=paste0(prefix, "_Spearman.csv"), row.names=FALSE)
    
    lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      log2c1<-log2(comparisonData[,samples[1]]+1)
      log2c2<-log2(comparisonData[,samples[2]]+1)
      png(paste0("details/", prefix, "_Spearman_", pairedSamples[x], ".png"), width=2000, height=2000, res=300)
      plot(log2c1, log2c2, xlab=paste0(samples[1], " [log2(Count + 1)]"), ylab=paste0(samples[2], " [log2(Count + 1)]"))
      text(3,15,paste0("SpearmanCorr=", sprintf("%0.3f", spcorr[x])))
      dev.off()
    })
    
    pairedspearman[[comparisonName]]<-spcorr
  }
  
  notEmptyData<-apply(comparisonData, 1, max) > 0
  comparisonData<-comparisonData[notEmptyData,]
  curdata<-curdata[notEmptyData,]
  
  if(ispaired){
    colnames(comparisonData)<-unlist(lapply(c(1:ncol(comparisonData)), function(i){paste0(designData$Paired[i], "_", colnames(comparisonData)[i])}))
  }
  rownames(designData)<-colnames(comparisonData)
  conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
  
  write.csv(comparisonData, file=paste0(prefix, ".csv"))
  
  #some basic graph
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                             colData = designData,
                             design = ~1)
  
  colnames(dds)<-colnames(comparisonData)
  
  #draw density graph
  rldmatrix<-as.matrix(log2(counts(dds,normalized=FALSE) + 1))
  rsdata<-melt(rldmatrix)
  colnames(rsdata)<-c("Gene", "Sample", "log2Count")
  png(filename=paste0(prefix, "_DESeq2-log2-density.png"), width=4000, height=3000, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  width=max(4000, ncol(rldmatrix) * 40 + 1000)
  height=max(3000, ncol(rldmatrix) * 40)
  png(filename=paste0(prefix, "_DESeq2-log2-density-individual.png"), width=width, height=height, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + facet_wrap(~Sample, scales = "free") + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  
  #varianceStabilizingTransformation
  
  allDesignData<-designData
  allComparisonData<-comparisonData
  
  excludedSample<-c()
  zeronumbers<-apply(comparisonData, 2, function(x){sum(x==0)})
  zeronumbers<-names(zeronumbers[order(zeronumbers)])
  percent10<-max(1, round(length(zeronumbers) * 0.1))
  
  removed<-0
  
  excludedCountFile<-paste0(prefix, "_DESeq2-exclude-count.csv")
  excludedDesignFile<-paste0(prefix, "_DESeq2-exclude-design.csv")
  if(file.exists(excludedCountFile)){
    file.remove(excludedCountFile)
  }
  if(file.exists(excludedDesignFile)){
    file.remove(excludedDesignFile)
  }
  
  fitType<-"parametric"
  while(1){
    #varianceStabilizingTransformation
    vsdres<-try(vsd <- varianceStabilizingTransformation(dds, blind=TRUE,fitType=fitType))
    if(class(vsdres) == "try-error" && grepl("every gene contains at least one zero", vsdres[1])){
      removed<-removed+1
      keptNumber<-length(zeronumbers) - percent10 * removed
      keptSample<-zeronumbers[1:keptNumber]
      excludedSample<-zeronumbers[(keptNumber+1):length(zeronumbers)]
      
      comparisonData<-comparisonData[, colnames(comparisonData) %in% keptSample]
      designData<-designData[rownames(designData) %in% keptSample,]
      dds=DESeqDataSetFromMatrix(countData = comparisonData,
                                 colData = designData,
                                 design = ~1)
      
      colnames(dds)<-colnames(comparisonData)
    } else if (class(vsdres) == "try-error" && grepl("newsplit: out of vertex space", vsdres[1])) {
		message=paste0("Warning: varianceStabilizingTransformation function can't run. fitType was set to local to try again")
		warning(message)
		fitType<-"mean"
		writeLines(message,paste0(comparisonName,".error"))
	} else{
      conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
      break
    }
  }
  if (nrow(comparisonData)<=1) {
	  message=paste0("Error: All genes in ",comparisonName," has at least one 0 value. Can't do DESeq2.")
	  warning(message)
	  writeLines(message,paste0(comparisonName,".error"))
	  next;
  }
  
  if(length(excludedSample) > 0){
    excludedCountData<-allComparisonData[,colnames(allComparisonData) %in% excludedSample]
    write.csv(file=excludedCountFile, excludedCountData)
    excludedDesignData<-allDesignData[rownames(allDesignData) %in% excludedSample,]
    write.csv(file=excludedDesignFile, excludedDesignData)
  }
  
  assayvsd<-assay(vsd)
  write.csv(assayvsd, file=paste0(prefix, "_DESeq2-vsd.csv"))
  
  vsdiqr<-apply(assayvsd, 1, IQR)
  assayvsd<-assayvsd[order(vsdiqr, decreasing=T),]
  
  rldmatrix=as.matrix(assayvsd)
  
  #draw pca graph
  drawPCA(paste0(prefix,"_geneAll"), rldmatrix, showLabelInPCA, designData, conditionColors)
  
  #draw heatmap
  #drawHCA(paste0(prefix,"_gene500"), rldmatrix[1:min(500, nrow(rldmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  drawHCA(paste0(prefix,"_geneAll"), rldmatrix, ispaired, designData, conditionColors, gnames)
  
  #different expression analysis
  designFormula=as.formula(paste0("~",paste0(c(colnames(designData)[-c(1:2)],"Condition"),collapse="+")))
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                               colData = designData,
                               design = designFormula)
  
  dds <- DESeq(dds,fitType=fitType)
  res<-results(dds,cooksCutoff=FALSE)
  
  cat("DESeq2 finished.\n")
  
  select<-(!is.na(res$padj)) & (res$padj<pvalue) & ((res$log2FoldChange >= log2(foldChange)) | (res$log2FoldChange <= -log2(foldChange)))
  
  if(length(indecies) > 0){
    inddata<-curdata[,indecies,drop=F]
    tbb<-cbind(inddata, comparisonData, res)
  }else{
    tbb<-cbind(comparisonData, res)
  }
  tbb$FoldChange<-2^tbb$log2FoldChange
  tbbselect<-tbb[select,,drop=F]
  tbbAllOut<-as.data.frame(tbb[,resultAllOutVar,drop=F])
  tbbAllOut$Significant<-select
  colnames(tbbAllOut)<-paste0(colnames(tbbAllOut)," (",comparisonName,")")
  resultAllOut<-cbind(resultAllOut,tbbAllOut[row.names(resultAllOut),])

  tbb<-tbb[order(tbb$padj),,drop=F]
  write.csv(as.data.frame(tbb),paste0(prefix, "_DESeq2.csv"))
  
  tbbselect<-tbbselect[order(tbbselect$padj),,drop=F]
  write.csv(as.data.frame(tbbselect),paste0(prefix, "_DESeq2_sig.csv"))
  
  if("Feature_gene_name" %in% colnames(tbb)){
    write.table(tbb[,c("Feature_gene_name", "stat"),drop=F],paste0(prefix, "_DESeq2_GSEA.rnk"),row.names=F,col.names=F,sep="\t", quote=F)
    write.table(tbbselect[,c("Feature_gene_name"),drop=F], paste0(prefix, "_DESeq2_sig_genename.txt"),row.names=F,col.names=F,sep="\t", quote=F)
  }

  if(showDEGeneCluster){
    siggenes<-rownames(rldmatrix) %in% rownames(tbbselect)
    
    nonDEmatrix<-rldmatrix[!siggenes,,drop=F]
    DEmatrix<-rldmatrix[siggenes,,drop=F]
    
    drawPCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, ispaired, designData, conditionColors, gnames)
    
    drawPCA(paste0(prefix,"_geneDE"),DEmatrix , showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneDE"),DEmatrix , ispaired, designData, conditionColors, gnames)
    #drawHCA(paste0(prefix,"_gene500NotDE"), nonDEmatrix[1:min(500, nrow(nonDEmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  }
  
  #Top 25 Significant genes barplot
  sigDiffNumber<-nrow(tbbselect)
  if (sigDiffNumber>0) {
    if (sigDiffNumber>25) {
      print(paste0("More than 25 genes were significant. Only the top 25 genes will be used in barplot"))
      diffResultSig<-tbbselect[order(tbbselect$padj)[1:25],]
    } else {
      diffResultSig<-tbbselect
    }
    if("Feature_gene_name" %in% colnames(diffResultSig)){
      diffResultSig$Name<-as.character(diffResultSig$Feature_gene_name)
    }else{
      diffResultSig$Name<-sapply(strsplit(row.names(diffResultSig),";"),function(x) x[1])
    }
    diffResultSig$Name <- factor(diffResultSig$Name, levels=diffResultSig$Name[order(diffResultSig$log2FoldChange)])
    diffResultSig<-as.data.frame(diffResultSig)
    
    png(filename=paste0(prefix, "_DESeq2_sig_barplot.png"), width=3000, height=3000, res=300)
    #	  pdf(paste0(prefix,"_DESeq2_sig_barplot.pdf"))
    p<-ggplot(diffResultSig,aes(x=Name,y=log2FoldChange,order=log2FoldChange))+geom_bar(stat="identity")+
      coord_flip()+
      #			geom_abline(slope=0,intercept=1,colour="red",linetype = 2)+
      scale_y_continuous(name=bquote(log[2]~Fold~Change))+
      theme(axis.text = element_text(colour = "black"))
    print(p)
    dev.off()
  } else {
    print(paste0("No gene with adjusted p value less than ",pvalue," and fold change larger than ",foldChange))
  }
  
  #volcano plot
  changeColours<-c(grey="grey",blue="blue",red="red")
  diffResult<-as.data.frame(tbb)
  diffResult$log10BaseMean<-log10(diffResult$baseMean)
  diffResult$colour<-"grey"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange>=log2(foldChange))]<-"red"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange<=-log2(foldChange))]<-"blue"
  png(filename=paste0(prefix, "_DESeq2_volcanoPlot.png"), width=3000, height=3000, res=300)
  #  pdf(paste0(prefix,"_DESeq2_volcanoPlot.pdf"))
  p<-ggplot(diffResult,aes(x=log2FoldChange,y=padj))+
    geom_point(aes(size=log10BaseMean,colour=colour))+
    scale_color_manual(values=changeColours,guide = FALSE)+
    scale_y_continuous(trans=reverselog_trans(10),name=bquote(Adjusted~p~value))+
    scale_x_continuous(name=bquote(log[2]~Fold~Change))+
    geom_hline(yintercept = 1,colour="grey",linetype = "dotted")+
    geom_vline(xintercept = 0,colour="grey",linetype = "dotted")+
    guides(size=guide_legend(title=bquote(log[10]~Base~Mean)))+
    theme_bw()+
    scale_size(range = c(3, 7))+
    theme(axis.text = element_text(colour = "black",size=30),
			axis.title = element_text(size=30),
			legend.text= element_text(size=30),
			legend.title= element_text(size=30))
  print(p)
  dev.off()
}

#write a file with all information
write.csv(resultAllOut,paste0(taskName, "_DESeq2.csv"))

if(length(pairedspearman) > 0){
  #draw pca graph
  filename<-ifelse(minMedianInGroup > 0, paste0("spearman_min", minMedianInGroup, ".png"), "spearman.png")
  png(filename=filename, width=1000 * length(pairedspearman), height=2000, res=300)
  boxplot(pairedspearman)
  dev.off()
}

#Venn for all significant genes
allSigNameList<-list()
allSigDirectionList<-list()
for(comparisonName in comparisonNames){
	if (minMedianInGroup > 0) {
		prefix<-paste0(comparisonName, "_min", minMedianInGroup)
	} else {
		prefix<-comparisonName
	}
	sigFile<-paste0(prefix, "_DESeq2_sig.csv")
	if (file.exists(sigFile)) {
		sigTable<-read.csv(sigFile,header=TRUE,as.is=TRUE)
		if (nrow(sigTable)>0) {
			allSigNameList[[comparisonName]]<-sigTable[,1]
			allSigDirectionList[[comparisonName]]<-sign(sigTable$log2FoldChange)
		} else {
			warning(paste0("No significant genes in ",comparisonName))
#		allSigNameList[[comparisonName]]<-""
		}
	}
}

#Do venn if length between 2-5
if (length(allSigNameList)>=2 & length(allSigNameList)<=5) {
	venn.diagram1<-function (x, filename, height = 3000, width = 3000, resolution = 500, 
			units = "px", compression = "lzw", na = "stop", main = NULL, 
			sub = NULL, main.pos = c(0.5, 1.05), main.fontface = "plain", 
			main.fontfamily = "serif", main.col = "black", main.cex = 1, 
			main.just = c(0.5, 1), sub.pos = c(0.5, 1.05), sub.fontface = "plain", 
			sub.fontfamily = "serif", sub.col = "black", sub.cex = 1, 
			sub.just = c(0.5, 1), category.names = names(x), force.unique = TRUE,
			fill=NA,
			...) 
	{
		if (is.na(fill)) {
			if (length(x)==5) {
				fill = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3")
			} else if (length(x)==4) {
				fill = c("dodgerblue", "goldenrod1",  "seagreen3", "orchid3")
			} else if (length(x)==3) {
				fill = c("dodgerblue", "goldenrod1", "seagreen3")
			} else if (length(x)==2) {
				fill = c("dodgerblue", "goldenrod1")
			}
		}
		if (force.unique) {
			for (i in 1:length(x)) {
				x[[i]] <- unique(x[[i]])
			}
		}
		if ("none" == na) {
			x <- x
		}
		else if ("stop" == na) {
			for (i in 1:length(x)) {
				if (any(is.na(x[[i]]))) {
					stop("NAs in dataset", call. = FALSE)
				}
			}
		}
		else if ("remove" == na) {
			for (i in 1:length(x)) {
				x[[i]] <- x[[i]][!is.na(x[[i]])]
			}
		}
		else {
			stop("Invalid na option: valid options are \"none\", \"stop\", and \"remove\"")
		}
		if (0 == length(x) | length(x) > 5) {
			stop("Incorrect number of elements.", call. = FALSE)
		}
		if (1 == length(x)) {
			list.names <- category.names
			if (is.null(list.names)) {
				list.names <- ""
			}
			grob.list <- VennDiagram::draw.single.venn(area = length(x[[1]]), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else if (2 == length(x)) {
			grob.list <- VennDiagram::draw.pairwise.venn(area1 = length(x[[1]]), 
					area2 = length(x[[2]]), cross.area = length(intersect(x[[1]], 
									x[[2]])), category = category.names, ind = FALSE, 
					fill=fill,
					...)
		}
		else if (3 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			list.names <- category.names
			nab <- intersect(A, B)
			nbc <- intersect(B, C)
			nac <- intersect(A, C)
			nabc <- intersect(nab, C)
			grob.list <- VennDiagram::draw.triple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), n12 = length(nab), 
					n23 = length(nbc), n13 = length(nac), n123 = length(nabc), 
					category = list.names, ind = FALSE, list.order = 1:3, 
					fill=fill,
					...)
		}
		else if (4 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n34 <- intersect(C, D)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n134 <- intersect(n13, D)
			n234 <- intersect(n23, D)
			n1234 <- intersect(n123, D)
			grob.list <- VennDiagram::draw.quad.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					n12 = length(n12), n13 = length(n13), n14 = length(n14), 
					n23 = length(n23), n24 = length(n24), n34 = length(n34), 
					n123 = length(n123), n124 = length(n124), n134 = length(n134), 
					n234 = length(n234), n1234 = length(n1234), category = list.names, 
					ind = FALSE, fill=fill,...)
		}
		else if (5 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			E <- x[[5]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n15 <- intersect(A, E)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n25 <- intersect(B, E)
			n34 <- intersect(C, D)
			n35 <- intersect(C, E)
			n45 <- intersect(D, E)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n125 <- intersect(n12, E)
			n134 <- intersect(n13, D)
			n135 <- intersect(n13, E)
			n145 <- intersect(n14, E)
			n234 <- intersect(n23, D)
			n235 <- intersect(n23, E)
			n245 <- intersect(n24, E)
			n345 <- intersect(n34, E)
			n1234 <- intersect(n123, D)
			n1235 <- intersect(n123, E)
			n1245 <- intersect(n124, E)
			n1345 <- intersect(n134, E)
			n2345 <- intersect(n234, E)
			n12345 <- intersect(n1234, E)
			grob.list <- VennDiagram::draw.quintuple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					area5 = length(E), n12 = length(n12), n13 = length(n13), 
					n14 = length(n14), n15 = length(n15), n23 = length(n23), 
					n24 = length(n24), n25 = length(n25), n34 = length(n34), 
					n35 = length(n35), n45 = length(n45), n123 = length(n123), 
					n124 = length(n124), n125 = length(n125), n134 = length(n134), 
					n135 = length(n135), n145 = length(n145), n234 = length(n234), 
					n235 = length(n235), n245 = length(n245), n345 = length(n345), 
					n1234 = length(n1234), n1235 = length(n1235), n1245 = length(n1245), 
					n1345 = length(n1345), n2345 = length(n2345), n12345 = length(n12345), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else {
			stop("Invalid size of input object")
		}
		if (!is.null(sub)) {
			grob.list <- add.title(gList = grob.list, x = sub, pos = sub.pos, 
					fontface = sub.fontface, fontfamily = sub.fontfamily, 
					col = sub.col, cex = sub.cex)
		}
		if (!is.null(main)) {
			grob.list <- add.title(gList = grob.list, x = main, pos = main.pos, 
					fontface = main.fontface, fontfamily = main.fontfamily, 
					col = main.col, cex = main.cex)
		}
		grid.newpage()
		grid.draw(grob.list)
		return(1)
#	return(grob.list)
	}
	png(paste0(taskName,"_significantVenn.png"),res=300,height=2000,width=2000)
	venn.diagram1(allSigNameList)
	dev.off()
}
#Do heatmap significant genes if length larger or equal than 2
if (length(allSigNameList)>=2) {
	temp<-cbind(unlist(allSigNameList),unlist(allSigDirectionList))
	colnames(temp)<-c("Gene","Direction")
	temp<-cbind(temp,comparisonName=rep(names(allSigNameList),sapply(allSigNameList,length)))
	temp<-data.frame(temp)
	dataForFigure<-temp
	#geting dataForFigure order in figure
	temp$Direction<-as.integer(as.character(temp$Direction))
	temp<-acast(temp, Gene~comparisonName ,value.var="Direction")
	temp<-temp[do.call(order, data.frame(temp)),]
	maxNameChr<-max(nchar(row.names(temp)))
	if (maxNameChr>70) {
		row.names(temp)<-substr(row.names(temp),0,70)
		dataForFigure$Gene<-substr(dataForFigure$Gene,0,70)
		warning(paste0("The gene names were too long (",maxNameChr,"). Only first 70 letters were kept."))
	}
	dataForFigure$Gene<-factor(dataForFigure$Gene,levels=row.names(temp))
	
	width=max(2500, 60 * length(unique(dataForFigure$comparisonName)))
	height=max(2000, 40 * length(unique(dataForFigure$Gene)))
	png(paste0(taskName,"_significantHeatmap.png"),res=300,height=height,width=width)
	g<-ggplot(dataForFigure, aes(comparisonName, Gene))+
			geom_tile(aes(fill=Direction), color="white") +
			scale_fill_manual(values=c("light green", "red")) +
			theme(axis.text.x = element_text(angle=90, vjust=0.5, size=11, hjust=0.5, face="bold"),
					axis.text.y = element_text(size=11, face="bold")) +
			coord_equal()
	print(g)
	dev.off()
}


#readFile = "CR_Y_TBX5_peaks.broadPeak.bed.reads" 
#singlePdf = 0 
#inputFile = "CR_Y_TBX5_peaks.broadPeak.bed.depth" 
#outputFile = "" 
#facet<-0
#drawLine<-1

library("reshape2")
library("ggplot2")

data<-read.table(inputFile, sep="\t", header=T, stringsAsFactors = F)

if(exists("readFile")){
  sampleReads<-read.table(readFile, sep="\t", header=T, row.names=1, as.is = T)
  totalReads<-sampleReads[, 1]
  names(totalReads)<-rownames(sampleReads)
  for(sample in rownames(sampleReads)){
    data[,sample] = data[,sample] * 1000000 / totalReads[sample]
  }
}

if(exists("cnvrFile")){
  cnvr<-read.table(cnvrFile, sep="\t", header=T, stringsAsFactors = F, row.names=4)
  refs<-rownames(sampleReads)[! rownames(sampleReads) %in% colnames(cnvr)]
  
  colors<-c("green", "darkblue", "lightblue", "black", colorRampPalette(c("yellow", "red"))(11))
  names(colors)<-c("REF","CN0", "CN1", "CN2", "CN3", "CN4", "CN5", "CN6", "CN7", "CN8", "CN16", "CN32", "CN64")
  
  #no_sig<-c("CN1","CN2","CN3","REF")
  no_sig<-c("CN2","REF")
}

files<-unique(data$File)

if(singlePdf){
  pdf(outputFile, onefile = T)
}

x<-files[2]
for(x in files){
  cat(x, "\n")
  
  if(exists("cnvrFile")){
    tmpcnv<-cnvr[x, c(4:ncol(cnvr))]
    tmpcnv[,refs] <- "REF"
    tmpcnv<-t(tmpcnv)
    
    curcnv<-as.character(tmpcnv[,1])
    names(curcnv) <- row.names(tmpcnv)
    
    if(length(curcnv[! (curcnv %in% no_sig)]) == 0){
      next
    }
  }
  
  curdata<-data[data$File==x,]
  
  title<-paste0(x, " (", curdata$Chr[1], ":", min(curdata$Position),"-",max(curdata$Position),")")
  
  mdata<-melt(curdata, id=c("Chr", "Position", "File"))
  colnames(mdata)<-c("Chr", "Position", "File", "Sample", "Depth")
  
  if(facet){
    height=max(2000, 400+800 * length(unique(mdata$Sample)))
    if(exists("cnvrFile")){
      mdata$Color<-as.character(curcnv[as.character(mdata$Sample)])
      g<-ggplot(mdata, aes(x=Position, y=Depth))
      if(drawLine){
        g <- g + geom_line(aes(color = Color), size=0.8)
      }else{
        g <- g + geom_point(aes(color = Color), size=0.8)
      }
      g<-g + scale_colour_manual(name="CNV", values = colors)
    }else{
      g<-ggplot(mdata, aes(x=Position, y=Depth))
      if(drawLine){
        g<-g+geom_line(aes(color = Sample), size=0.8, show.legend = F)
      }else{
        g<-g+geom_point(aes(color = Sample), size=0.8, show.legend = F)
      }
    }
    g <- g + xlab(unique(data$chr)) + 
      ylab("Reads per million total reads") +
      ggtitle(x) +
      facet_wrap( ~ Sample, ncol=1) +
      theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
  }
  else{
    height=2000
    if(exists("cnvrFile")){
      mdata$Color<-as.character(curcnv[as.character(mdata$Sample)])
      g<-ggplot(mdata, aes(x=Position, y=Depth, group=Sample))
      if(drawLine){
        g <- g + geom_line(aes(color = Color), size=0.8)
      }else{
        g <- g + geom_point(aes(color = Color), size=0.8)
      }
      g<-g+scale_colour_manual(name="CNV", values = colors)
    }else{
      g<-ggplot(mdata, aes(x=Position, y=Depth, group=Sample))
      if(drawLine){
        g <- g + geom_line(aes(color = Sample), size=0.8, show.legend = T)
      }else{
        g <- g + geom_point(aes(color = Sample), size=0.8, show.legend = T)
      }
    }
    
    g <- g + xlab(data$chr[1]) + 
      ylab("Reads per million total reads") +
      ggtitle(title) +
      theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))
  }
  if(singlePdf){
    print(g)
  }else{
    png(paste0(x, ".png"), width=2000, height=height, res=300)
    print(g)
    dev.off()
  }
}

if(singlePdf){
  dev.off()
}
#################################################################################
### CALIBRATION CHECKING SCRIPT
### The goal here is to take a DIMA that contains calibration data, grab those data, and serve up information on how the observers compare on the major calibration indicators
### A lot of things are defined as values before they're called so that this can be altered as needed and to add hooks for a Shiny implementation
## Reporting out on the following indicators
## LPI : Foliar Cover, Bare Soil, Litter, Basal Cover, Rock Fragments, Vegetation Heights (by woody/herbaceous and height classes)
## Gap Intercept : Gap counts and proprtion of plot in gaps (by size classes)
#################################################################################

#################################################################################
### BASIC CONFIGURATION #########################################################
#################################################################################
## Getting the packages
require(RODBC)
require(dplyr)

# Filepath to find the DIMA
path.read <- "C:/Users/username/Documents/Projects/"
# DIMA filename
name.dima <- "training__calibration_DIMA_4.1.mdb"
# Filepath to write out the .csv of calibration results
path.write <- "C:/Users/username/Documents/Projects/"
# Filename for the .csv that you want to write out the results in
filename.output <- "calibration_results.csv"
#################################################################################

#################################################################################
### SETTING CALIBRATION TOLERANCES ##############################################
#################################################################################
## In the end, we need everyone to be within tolerances, which is ±5% from the mean for anything reported in percentages and ±2 on the species counts
## I'm still defining them as values in a list in case we want to let people set different tolerances eventually

## Initialize the tolerances list
tolerances <- list()

## LPI tolerances
# These four are the tolerance for (maximum observed percent on plot - minimum observed percent on plot)
tolerances$lpi$foliar.percent.range <- 10
tolerances$lpi$baresoil.percent.range <- 10
tolerances$lpi$basalcover.percent.range <- 10
tolerances$lpi$rockfragments.percent.range <- 10
# These four are maximum tolerance in abs(individual's observed percentage - mean plot percentage)
tolerances$lpi$foliar.percent <- tolerances$lpi$foliar.percent.range/2
tolerances$lpi$baresoil.percent <- tolerances$lpi$baresoil.percent.range/2
tolerances$lpi$basalcover.percent <- tolerances$lpi$basalcover.percent.range/2
tolerances$lpi$rockfragments.percent <- tolerances$lpi$rockfragments.percent.range/2
# Tolerance for (maximum observed count within a height class - minimum observed count within a height class)
tolerances$lpi$heights.count.range <- 4
# Tolerance for abs(individual's observed count within a height class - mean observed count on plot within a height class)
tolerances$lpi$heights.count <- tolerances$lpi$heights.count.range/2
# The breaking points in cm for the height classes. The upper bound is inclusive on each, e.g. <=50, >50 & <=200, >200
tolerances$lpi$heights.breaks <- c(50, 200, 500)



## Gap tolerances
tolerances$gaps$gap.pct.range <- 10
tolerances$gaps$gap.percent <- tolerances$gaps$gap.pct.range/2
## The breaking points in cm for the gap classes. For the first gap class, the check is inclusive, e.g. >= 25 & <=50
## For other gaps, the check is inclusive on the high end, e.g. >50 & <=100
## For the largest gap class, the upper limit is unbound, e.g. >200
tolerances$gaps$gap.breaks <- c(25, 50, 100, 200)
# gap.count is currently unused
tolerances$gaps$gap.count <- 2
#################################################################################


#################################################################################
### PULLING THE DATA FROM A DATABASE ############################################
#################################################################################
## Specify the DIMA filepath
dima.location <- paste(path.read, name.dima, sep = "/")

## Initialize our queries list
queries <- list()

## SQL query for getting a table of all LPI hits by layer with recorder, observer,, heights and species for heights by woody and herbaceous, point location on line,
## point number on line, line, plot, site, and date
queries$lpi <- "SELECT joinSitePlotLine.SiteID, joinSitePlotLine.PlotID, joinSitePlotLine.PlotKey, joinSitePlotLine.LineID, tblLPIHeader.FormDate, tblLPIHeader.Observer, tblLPIHeader.Recorder, tblLPIDetail.PointLoc, tblLPIDetail.PointNbr, tblLPIDetail.TopCanopy, tblLPIDetail.Lower1, tblLPIDetail.Lower2, tblLPIDetail.Lower3, tblLPIDetail.Lower4, tblLPIDetail.SoilSurface, tblLPIDetail.HeightWoody, tblLPIDetail.SpeciesWoody, tblLPIDetail.HeightHerbaceous, tblLPIDetail.SpeciesHerbaceous
FROM joinSitePlotLine INNER JOIN (tblLPIHeader LEFT JOIN tblLPIDetail ON tblLPIHeader.RecKey = tblLPIDetail.RecKey) ON joinSitePlotLine.LineKey = tblLPIHeader.LineKey;"

## SQL query for getting a table of gaps with observer, recorder, line, plot,site, and date
queries$gaps <- "SELECT joinSitePlotLine.SiteID, joinSitePlotLine.PlotID, joinSitePlotLine.PlotKey, joinSitePlotLine.LineID, tblGapHeader.FormDate, tblGapHeader.Observer, tblGapHeader.Recorder, tblGapDetail.Gap, tblGapHeader.LineLengthAmount
FROM joinSitePlotLine INNER JOIN (tblGapHeader INNER JOIN tblGapDetail ON tblGapHeader.RecKey = tblGapDetail.RecKey) ON joinSitePlotLine.LineKey = tblGapHeader.LineKey;"


## Let's get some tables extracted from the specified DIMA!
## Initialize the lists to keep all our data frames in
lpi <- list()
gaps <- list()

## Note that I'm using the function odbcConnectAccess2007() because I have 64-bit R and 64-bit Access installed. If your Access install is 32-bit, use odbcConnectAccess() in 32-bit R
## I also never trust factored fields to work with functions that I want to use, so I avoid them in the first place
## This is just connecting to the database and running the SQL queries then storing the results
lpi$raw <- odbcConnectAccess2007(dima.location) %>% sqlQuery(., queries$lpi, stringsAsFactors = F)
gaps$raw <- odbcConnectAccess2007(dima.location) %>% sqlQuery(., queries$gaps, stringsAsFactors = F)
odbcCloseAll()

## The line length is in meters, but we need cm, so we'll quickly do that
gaps$raw$LineLengthAmount <- gaps$raw$LineLengthAmount*100

## We also want the plot keys to be strings, not numeric values
lpi$raw$PlotKey <- as.character(lpi$raw$PlotKey)
gaps$raw$PlotKey <- as.character(gaps$raw$PlotKey)

## We'll set up some objects we can use to populate options in the Shiny tool that maybe will one day be built
sites.plots <- rbind(gaps$raw[,c("SiteID", "PlotID", "PlotKey")], lpi$raw[,c("SiteID", "PlotID", "PlotKey")]) %>% unique()
observers.all <- c(gaps$raw$Observer, lpi$raw$Observer) %>% unique()

## If you want to see your options for the calibration PlotKey, Plot-, and SiteID, use this
# sites.plots %>% View()

## Where's the calibration data? Specify the SiteID and the PlotID, although all we really need is the key
## This was originally—naively—written to use a combination of the Site- and PlotIDs on a one-at-a-time basis
## We've moved onto a loop that'll look at all the plots in a database using the plotkeys that were found
calibration.SiteID <- "Canyonlands Calibration"
calibration.PlotID <- "Calibration: NWDO"
## Humans struggle with reliably typing out a plot key, so let's just extract it based on the friendlier Site- and PlotIDs
calibration.PlotKey <- sites.plots$PlotKey[sites.plots$SiteID == calibration.SiteID & sites.plots$PlotID == calibration.PlotID]
#################################################################################


#################################################################################
### KICKING OFF THE LOOP THAT'LL ITERATE THROUGH ALL PLOTS ######################
#################################################################################
## For general purposes, we need to make a final data table that has calibration information for every plot
## in the database instead of just one at a time. So, we'll loop through each of the plot keys in turn and
## mash together the results from the data associated to each key.
## Obviously, the conclusion to this needs to come at the end of all the calibration work, so if you comment this
## out make sure you also comment out that section

## This is predicated on the assumption that the database contains only calibration plots. If there's just one calibration
## plot, just make sure it's set up above. If you have multiple calibration plots, let this do its thing and then
## just filter/subset at the end of it all. Your life will be much better for it.

for (n in seq_along(sites.plots$PlotKey)){
  calibration.PlotKey <- sites.plots$PlotKey[n]
  
## I'm aware that this is slow and inelegant, but the script was written assuming a single plot and this is much easier
## than working to rewrite to do calculations without looping and it's not that much data, really
#################################################################################
  
  
  
#################################################################################
### CALIBRATION CHECKING FOR LPI ################################################
#################################################################################
## The indicators being evaluated are Foliar Cover, Bare Soil, Litter, Basal Cover, Rock Fragments, Vegetation Heights (by woody/herbaceous and height classes)
## This is currently set up so that it'll work regardless of how many lines were read

## Create a data frame of just the LPI data from the calibration plot so we can get to work looking at it
## This first line is from the dark times when we didn't use plot keys
# lpi$calibration.raw <- lpi$raw %>% subset(SiteID == calibration.SiteID) %>% subset(PlotID == calibration.PlotID)
lpi$calibration.raw <- lpi$raw %>% subset(PlotKey == calibration.PlotKey)
## Add in some extra variables so we can calculate the indicators relatively painlessly. Normally I wouldn't do this, but summarize() is fighting me and this should make it possible
## First up is to add a 1 to all observations where the top canopy hit isn't a "None" so that we can find the sum to know how many foliar hits there were
lpi$calibration.raw$foliar.cover[lpi$calibration.raw$TopCanopy != "None"] <- 1
## Likewise, do the same sort of thing to all the points where there's a species code at the soil surface, which here is just anywhere where a standard non-vegetative code was not found
surface.codes <- c("S", "LC", "M", "D", "W", "CY", "EL", "R", "GR", "CB", "ST", "BY", "BR")
lpi$calibration.raw$basal.cover[!(lpi$calibration.raw$SoilSurface %in% surface.codes)] <- 1
## And a variable for if the last hit was a rock of some sort that wasn't bedrock because that's not a "rock fragment"
lpi$calibration.raw$rock.fragments[lpi$calibration.raw$SoilSurface %in% surface.codes[8:12]] <- 1
## One for bare ground. Assume it's true and then invalidate it wherever the surface code isn't S or CY, the top code isn't None, or there's anything in Lower1:Lower4. Clunky, but effective
lpi$calibration.raw$bare.soil <- 1
lpi$calibration.raw$bare.soil[!(lpi$calibration.raw$SoilSurface %in% c("S", "CY"))] <- 0
lpi$calibration.raw$bare.soil[lpi$calibration.raw$TopCanopy != "None"] <- 0
lpi$calibration.raw$bare.soil[lpi$calibration.raw$Lower1 != ""] <- 0
lpi$calibration.raw$bare.soil[lpi$calibration.raw$Lower2 != ""] <- 0
lpi$calibration.raw$bare.soil[lpi$calibration.raw$Lower3 != ""] <- 0
lpi$calibration.raw$bare.soil[lpi$calibration.raw$Lower4 != ""] <- 0

## The NAs were a complete nightmare to deal with, so I turned them into -1s. After this next bit I'll turn them back
lpi$calibration.raw$HeightWoody[is.na(lpi$calibration.raw$HeightWoody)] <- -1
lpi$calibration.raw$HeightHerbaceous[is.na(lpi$calibration.raw$HeightHerbaceous)] <- -1

## Adding in the height classes for woody and herbaceous.
for (n in seq_along(tolerances$lpi$heights.breaks)){
  ## For the first loop, we're checking for plants shorter than or equal to the first height break
  if (n == min(seq_along(tolerances$lpi$heights.breaks))){
    # That !is.na() wrapped around the logical statement is because for some reason it was returning a vector of TRUE and NA instead of TRUE and FALSE
    lpi$calibration.raw[lpi$calibration.raw$HeightWoody <= tolerances$lpi$heights.breaks[n] &
                           lpi$calibration.raw$HeightWoody > 0,
                        paste0("woody.0.", tolerances$lpi$heights.breaks[n])] <- 1
    lpi$calibration.raw[lpi$calibration.raw$HeightHerbaceous <= tolerances$lpi$heights.breaks[n] &
                          lpi$calibration.raw$HeightHerbaceous > 0,
                        paste0("herbaceous.0.", tolerances$lpi$heights.breaks[n])] <- 1
  ## The last loop will just look for anything larger than the last height break
  } else if (n == max(seq_along(tolerances$lpi$heights.breaks))){
    lpi$calibration.raw[lpi$calibration.raw$HeightWoody > tolerances$lpi$heights.breaks[n-1] &
                          lpi$calibration.raw$HeightWoody <= tolerances$lpi$heights.breaks[n] &
                          lpi$calibration.raw$HeightWoody > 0,
                        paste0("woody.", tolerances$lpi$heights.breaks[n-1]+1, ".", tolerances$lpi$heights.breaks[n])] <- 1
    lpi$calibration.raw[lpi$calibration.raw$HeightHerbaceous > tolerances$lpi$heights.breaks[n-1] &
                          lpi$calibration.raw$Heightherbaceous <= tolerances$lpi$heights.breaks[n],
                        paste0("herbaceous.", tolerances$lpi$heights.breaks[n-1]+1, ".", tolerances$lpi$heights.breaks[n])] <- 1
    lpi$calibration.raw[lpi$calibration.raw$HeightWoody > tolerances$lpi$heights.breaks[n] &
                          lpi$calibration.raw$HeightWoody > 0,
                        paste0("woody.", tolerances$lpi$heights.breaks[n] + 1)] <- 1
    lpi$calibration.raw[lpi$calibration.raw$HeightHerbaceous > tolerances$lpi$heights.breaks[n],
                        paste0("herbaceous.", tolerances$lpi$heights.breaks[n] + 1)] <- 1
  ## All other loops will find plants greater than the previous height break AND shorter than or equal to the current one
  } else {
    lpi$calibration.raw[lpi$calibration.raw$HeightWoody > tolerances$lpi$heights.breaks[n-1] &
                          lpi$calibration.raw$HeightWoody <= tolerances$lpi$heights.breaks[n] &
                          lpi$calibration.raw$HeightWoody > 0,
                        paste0("woody.", tolerances$lpi$heights.breaks[n-1]+1, ".", tolerances$lpi$heights.breaks[n])] <- 1
    lpi$calibration.raw[lpi$calibration.raw$HeightHerbaceous > tolerances$lpi$heights.breaks[n-1] &
                          lpi$calibration.raw$Heightherbaceous <= tolerances$lpi$heights.breaks[n],
                        paste0("herbaceous.", tolerances$lpi$heights.breaks[n-1]+1, ".", tolerances$lpi$heights.breaks[n])] <- 1
  }
}

## Restoring the NAs so that we can tell that there weren't values there
lpi$calibration.raw$HeightWoody[lpi$calibration.raw$HeightWoody == -1] <- NA
lpi$calibration.raw$HeightHerbaceous[lpi$calibration.raw$HeightHerbaceous == -1] <- NA

## Storing the column names we just generated for future reference
tolerances$lpi$heights.classes <- tail(colnames(lpi$calibration.raw), (length(tolerances$lpi$heights.breaks) + 1)*2)


## Taking those raw data and converting them into the various indicators we want for each observer, specifically: percent total foliar cover, percent bare soil, percent basal cover, percent rock fragments,
## and the woody and herbaceous heights by height classes
lpi$calibration <- lpi$calibration.raw %>% group_by(Observer, SiteID, PlotID, PlotKey) %>%
  summarize(records.lpi = n(),
            foliar.hits = sum(foliar.cover, na.rm = T),
            basal.hits = sum(basal.cover, na.rm = T),
            rock.frag.hits = sum(rock.fragments, na.rm = T),
            bare.soil.hits = sum(bare.soil, na.rm = T))

for (n in seq_along(tolerances$lpi$heights.classes)){
  lpi$calibration <- lpi$calibration.raw %>% group_by(Observer, SiteID, PlotID, PlotKey) %>%
    summarize_(paste0("sum(", tolerances$lpi$heights.classes[n], ", na.rm = T)")) %>%
    merge(y = ., x = lpi$calibration, all = T)
  colnames(lpi$calibration)[length(colnames(lpi$calibration))] <- paste0(tolerances$lpi$heights.classes[n], ".count")
}

## Calculating percentages for the appropriate indicators
lpi$calibration <- lpi$calibration %>% mutate(foliar.cover.pct = 100*(foliar.hits/records.lpi),
                                              basal.cover.pct = 100*(basal.hits/records.lpi),
                                              rock.fragments.pct = 100*(rock.frag.hits/records.lpi),
                                              bare.soil.pct = 100*(bare.soil.hits/records.lpi))

## Now to add in the min and max for each indicator
lpi$calibration <- lpi$calibration %>% mutate(foliar.cover.pct.min = min(foliar.cover.pct),
                                              basal.cover.pct.min = min(basal.cover.pct),
                                              rock.fragments.pct.min = min(rock.fragments.pct),
                                              bare.soil.pct.min = min(bare.soil.pct),
                                              foliar.cover.pct.max = max(foliar.cover.pct),
                                              basal.cover.pct.max = max(basal.cover.pct),
                                              rock.fragments.pct.max = max(rock.fragments.pct),
                                              bare.soil.pct.max = max(bare.soil.pct))

for (n in seq_along(tolerances$lpi$heights.classes)){
  lpi$calibration <- lpi$calibration %>% mutate_(paste0("min(",tolerances$lpi$heights.classes[n],".count)"),
                                                 paste0("max(",tolerances$lpi$heights.classes[n],".count)"),
                                                 paste0("max(",tolerances$lpi$heights.classes[n],".count) - min(",tolerances$lpi$heights.classes[n],".count)"))
  colnames(lpi$calibration)[tail(seq_along(colnames(lpi$calibration)), 3)] <- c(paste0(tolerances$lpi$heights.classes[n], ".count.min"),
                                                                                paste0(tolerances$lpi$heights.classes[n], ".count.max"),
                                                                                paste0(tolerances$lpi$heights.classes[n], ".count.range"))
}


## And now to add the calibrated-or-not logical values!
lpi$calibration$foliar.cover.calibrated <- (lpi$calibration$foliar.cover.pct.max - lpi$calibration$foliar.cover.pct.min) <= tolerances$lpi$foliar.percent.range
lpi$calibration$basal.cover.calibrated <- (lpi$calibration$basal.cover.pct.max - lpi$calibration$basal.cover.pct.min) <= tolerances$lpi$basalcover.percent.range
lpi$calibration$bare.soil.calibrated <- (lpi$calibration$bare.soil.pct.max - lpi$calibration$bare.soil.pct.min) <= tolerances$lpi$baresoil.percent.range
lpi$calibration$rock.fragments.calibrated <- (lpi$calibration$rock.fragments.pct.max - lpi$calibration$rock.fragments.pct.min) <= tolerances$lpi$rockfragments.percent.range

for (n in seq_along(tolerances$lpi$heights.classes)){
  lpi$calibration[,paste0(tolerances$lpi$heights.classes[n], ".calibrated")] <- lpi$calibration[, paste0(tolerances$lpi$heights.classes[n], ".count.range")] <= tolerances$lpi$heights.count.range
}
#################################################################################

#################################################################################
### CALIBRATION CHECKING FOR GAPS ###############################################
#################################################################################
## The indicator being evaluated percentage of line[s] in gaps of of size classes defined by the values in tolerances$gaps$gap.breaks.
## Additionally, the gap count for each size class is included
## This is currently set up so that it'll work regardless of how many lines were read or number of gap classes

## Subset to just the data from the calibration plot
## This used to use a combination of Site- and PlotID, but much more reasonably, if less readably, now uses plot keys
# gaps$calibration.raw <- gaps$raw %>% subset(SiteID == calibration.SiteID) %>% subset(PlotID == calibration.PlotID)
## It also omits all rows with NA values, so just be aware
gaps$calibration.raw <- gaps$raw %>% subset(PlotKey == calibration.PlotKey) %>% na.omit()

## Writing in variables to keep track of what size class these belong to
## These are generalized so that no matter what the gap breaks are or how many size classes they result in, you should get the appropriate
## number of columns with intelligible names
for (n in seq_along(tolerances$gaps$gap.breaks)){
  # This evaluates for the first gap class, which is inclusive of the lower bounding cm value and the upper
  if (n == min(seq_along(tolerances$gaps$gap.breaks))){
    # This is the standard situation for the smallest gap class, but it only applies if there's more than one gap class
    if (length(tolerances$gaps$gap.breaks) > 1){
      # This creates a column with the name of "gap.[lowerbound].[upperbound]" and writes a 1 into it in every row where the size of the gap is both >= the lowest bound and <= the next break
      gaps$calibration.raw[gaps$calibration.raw$Gap >= tolerances$gaps$gap.breaks[n] & gaps$calibration.raw$Gap <= tolerances$gaps$gap.breaks[n+1], paste("gap", tolerances$gaps$gap.breaks[n], tolerances$gaps$gap.breaks[n+1], sep = ".")] <- 1
      # Otherwise, if for some reason there's only one size class, this will handle that situation
    } else {
      gaps$calibration.raw[gaps$calibration.raw$Gap >= tolerances$gaps$gap.breaks[n], paste("gap", tolerances$gaps$gap.breaks[n], sep = ".")] <- 1
    }
    # This evaluates the largest gap class, which has no upper bound on size and is not inclusive on the lower bound
  } else if (n == max(seq_along(tolerances$gaps$gap.breaks))){
    gaps$calibration.raw[gaps$calibration.raw$Gap > tolerances$gaps$gap.breaks[n], paste("gap", tolerances$gaps$gap.breaks[n] + 1, sep = ".")] <- 1
    # This evaluates all other gap classes, which are inclusive only on the upper bound   
  } else {
    gaps$calibration.raw[gaps$calibration.raw$Gap > tolerances$gaps$gap.breaks[n] & gaps$calibration.raw$Gap <= tolerances$gaps$gap.breaks[n+1], paste("gap", tolerances$gaps$gap.breaks[n], tolerances$gaps$gap.breaks[n+1] + 1, sep = ".")] <- 1
  }
}

## Just going to store the resulting gap classes' column names for future reference. They're the only ones with "gap." in them at this point
## Basically every loop after this takes advantage of this vector because it's so useful
tolerances$gaps$gap.classes <- colnames(gaps$calibration.raw)[grep("gap.", colnames(gaps$calibration.raw))]

## Counting gaps and finding their sums. This was the quick-and-dirty solution where I just filtered by the classes and kept merging them into the same calibration data frame
for (n in seq_along(tolerances$gaps$gap.classes)){
  ## As ever, we want to do something different on the first pass because we're creating gaps.calibration here, but with later passes we'll merge
  if (n == min(seq_along(tolerances$gaps$gap.classes))){
    ## Step one is to group the data by an observer on the plot
    gaps$calibration <- gaps$calibration.raw %>% group_by(Observer, SiteID, PlotID, PlotKey) %>%
      ## Then we use filter_() to get only the rows where the currently-being-evaluated gap class was recorded
      ## I guess that filter_() lets us pass strings as arguments whereas filter() doesn't, so we can create a string of "[column name] == 1"
      ## to use as our evaluations statement
      filter_(paste0(tolerances$gaps$gap.classes[n], "==", 1)) %>%
      ## Finish off with summarizing the number of gaps and the sum of the gaps' lengths in that size class, with appropriate but still ambiguously-named columns
      summarize(count = n(), cm.sum = sum(Gap, na.rm = T))
    ## Renaming those columns because doing it inside the summarize() was too hard to implement. Frankly this isn't much easier, but at least it works
    ## The grep() is looking for a column that exactly matches the string provided. "^" indicates that that's the start of the string and "$" is the end
    ## so "^count$" will only return the index of "count" but not "counts" or "account"
    colnames(gaps$calibration)[grep("^count$", colnames(gaps$calibration))] <- paste0(tolerances$gaps$gap.classes[n], ".count")
    colnames(gaps$calibration)[grep("^cm.sum$", colnames(gaps$calibration))] <- paste0(tolerances$gaps$gap.classes[n], ".cm.sum")
    ## And on any subsequent passes, we do the same thing, but merge in so as to not overwrite
  } else {
    gaps$calibration <- gaps$calibration.raw %>% group_by(Observer, SiteID, PlotID, PlotKey) %>%
      filter_(paste0(tolerances$gaps$gap.classes[n], "==", 1)) %>%
      summarize(count = n(), cm.sum = sum(Gap, na.rm = T)) %>%
      ## The only difference from above is that this line merges because gaps$calibration already has data in it
      merge (x = ., y = gaps$calibration, all = T)
    colnames(gaps$calibration)[grep("^count$", colnames(gaps$calibration))] <- paste0(tolerances$gaps$gap.classes[n], ".count")
    colnames(gaps$calibration)[grep("^cm.sum$", colnames(gaps$calibration))] <- paste0(tolerances$gaps$gap.classes[n], ".cm.sum")
  }
}

## Adding in the line lengths on a per-observer basis in case they maybe read different lengths even though they shouldn't
gaps$calibration <- gaps$calibration.raw %>% group_by(Observer, SiteID, PlotID, PlotKey) %>% summarize(length.total.cm = first(LineLengthAmount)) %>% merge (x = ., y = gaps$calibration, all = T)

## We've got NAs, but those are really 0s because this data frame is restricted to observers who completed gap forms, so let's change them
gaps$calibration <- gaps$calibration %>% replace(., is.na(.), 0)

## We need the minimum and maximum gap counts and percent in each gap class
for (n in seq_along(tolerances$gaps$gap.classes)){
  gaps$calibration[,paste0(tolerances$gaps$gap.classes[n], ".pct.max")] <- 100*max(gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".cm.sum")]/gaps$calibration$length.total.cm)
  gaps$calibration[,paste0(tolerances$gaps$gap.classes[n], ".pct.min")] <- 100*min(gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".cm.sum")]/gaps$calibration$length.total.cm)
  gaps$calibration[,paste0(tolerances$gaps$gap.classes[n], ".count.max")] <- max(gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".count")])
  gaps$calibration[,paste0(tolerances$gaps$gap.classes[n], ".count.min")] <- min(gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".count")])
}

## Now we'll add the percent of length and the mean percent of length in each gap class and mean count
for (n in seq_along(tolerances$gaps$gap.classes)){
  gaps$calibration <-  gaps$calibration %>% mutate_(paste0("100*(", tolerances$gaps$gap.classes[n], ".cm.sum/length.total.cm)"),
                                                    paste0("100*(mean(", tolerances$gaps$gap.classes[n], ".cm.sum, na.rm = T)/length.total.cm)"),
                                                    paste0(" mean(", tolerances$gaps$gap.classes[n], ".count, na.rm = T)")
  )
  ## So, I can't be bothered to fight naming mutate_() columns anymore. This takes the last three column names in the data frame
  ## using the tail() function to get the indices for them in the vector from colnames() and uses those to rename them with the same paste0()
  ## results that I couldn't get working in the mutate_()
  colnames(gaps$calibration)[tail(seq_along(colnames(gaps$calibration)), 3)] <- c(paste0(tolerances$gaps$gap.classes[n], ".pct"), paste0(tolerances$gaps$gap.classes[n], ".pct.mean"), paste0(tolerances$gaps$gap.classes[n], ".count.mean"))
}

## Final step is to decide if they're calibrated or not.
for (n in seq_along(tolerances$gaps$gap.classes)){
  gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".pct.calibrated")] <- (gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".pct.max")] - gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".pct.min")]) <= tolerances$gaps$gap.pct.range
  gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".count.calibrated")] <- (gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".count.max")] - gaps$calibration[, paste0(tolerances$gaps$gap.classes[n], ".count.min")]) <= tolerances$gaps$gap.count
}
#################################################################################

#################################################################################
### CONCLUDING THE LOOP THAT'LL ITERATE THROUGH ALL PLOTS #######################
#################################################################################
## And now we wrap up the loop set in motion above. This will result in a single data frame output that contains all the calibration
## information for each observer by plot.

## On the first trip through the loop, it just creates calibration.results
  if (n < 2){
    calibration.results <- merge(lpi$calibration, gaps$calibration, all = T)
    ## On subsequent loops, the calibration.results data frame exists, so the new plot's results are just appended to avoid overwriting
  } else {
    calibration.results <- merge(lpi$calibration, gaps$calibration, all = T) %>% rbind(., calibration.results)
  }
}

#################################################################################


#################################################################################
### COMBINING AND WRITING CALIBRATION RESULTS ###################################
#################################################################################
### COMBINING AND WRITING CALIBRATION RESULTS
## So, now there're two data frames—one for LPI and one for gaps—but we want them combined and written out
## This needs to be uncommented to combine things if you aren't using the whole-database loop!
## calibration.results <- merge(lpi$calibration, gaps$calibration, all = T)
write.csv(calibration.results, paste(path.write, filename.output, sep = "/"))

#################################################################################
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
filename = 'similarity_cons_res_blind'
similarity_cons_res <- tanimoto_analysis(min.tx = 45,
                                        K.values = 8,
                                        MW = 1,
                                        WT =  c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1),
                                        minimum_threshold = 0.3,
                                        filename = filename)

# Catalog vs predictions
load("./RData/interactions_source.RData")
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = similarity_cons_res, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = similarity_cons_res, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = similarity_cons_res)

#Figure
filename = 'Similarity_cons_res'
pdf(paste('./Article/',filename,'.pdf',sep=''),width=7,height=7)

# Plots
par(mfrow=c(2,2))
# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 1.09)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(similarity_cons_res[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000088","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
            axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
            # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
            points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
        } #i

        ## Add legend
        if(j == 12) {
            legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        }
} #j
dev.off()
no.extension <- function(filename) { 
  if (substr(filename, nchar(filename), nchar(filename))==".") { 
    return(substr(filename, 1, nchar(filename)-1)) 
  } else { 
    no.extension(substr(filename, 1, nchar(filename)-1)) 
  } 
}


extract.ages <- function(file = NULL, replicates = 1, cutoff = NULL, random = TRUE){

if (is.null(file)) 
    stop("you must enter a filename or a character string\n")

rnd <- random
q <- cutoff
dat1 <- read.table(file, header=T, stringsAsFactors=F, row.names=NULL, sep="\t", strip.white=T)
fname <- no.extension(basename(file))
outfile <- paste(dirname(file), "/", fname, "_PyRate.py", sep="")

dat1[,1] <- gsub("[[:blank:]]{1,}","_", dat1[,1])

if (replicates > 1){
	rnd <- TRUE
}

if (any(is.na(dat1[,1:4]))){
	stop("the input file contains missing data in species names, status or ages)\n")
}

if (!is.null(q)){
		dat <- dat1[!(dat1[,4] - dat1[,3] >= q),]
	} else { 
		dat <- dat1 
}

if (length(dat) == 5){
	colnames(dat) <- c("Species", "Status", "min_age", "max_age", "trait")	
	} else {
	colnames(dat) <- c("Species", "Status", "min_age", "max_age")
}

dat$new_age <- "NA"
splist <- unique(dat[,c(1,2)])[order(unique(dat[,c(1,2)][,1])),]


if (any(is.element(splist$Species[splist$Status == "extant"], splist$Species[splist$Status == "extinct"]))){
	print(intersect(splist$Species[splist$Status == "extant"], splist$Species[splist$Status == "extinct"]))
	stop("at least one species is listed as both extinct and extant\n")
}

cat("#!/usr/bin/env python", "from numpy import * ", "",  file=outfile, sep="\n")

for (j in 1:replicates){
	times <- list()
	cat ("\nreplicate", j)
	
	dat[dat$min_age == 0,3] <- 0.001
	
	if (any(dat[,4] < dat[,3])){
		cat("\nWarning: the min age is older than the max age for at least one record\n")
		cat ("\nlines:",1+as.numeric(which(dat[,4] < dat[,3])),sep=" ")
	}
	
	if (isTRUE(rnd)){
			dat$new_age <- round(runif(length(dat[,1]), min=apply(dat[,3:4],FUN=min,1), max=apply(dat[,3:4],FUN=max,1)), digits=6)
		} else {
			for (i in 1:length(dat[,1])){
				dat$new_age[i] <- mean(c(dat[i,3], dat[i,4]))
			}				
		}

	dat2 <- subset(dat, select=c("Species","new_age"))
	taxa <- sort(unique(dat2$Species))

	for (n in 1:length(taxa)){
		times[[n]] <- dat2$new_age[dat2$Species == taxa[n]]
		if (toupper(splist$Status[splist$Species == taxa[n]]) == toupper("extant")){
			times[[n]] <- append(times[[n]], "0", after=length(times[[n]]))
		}
	}

	dat3 <- matrix(data=NA, nrow=length(times), ncol=max(sapply(times, length)))
	rownames(dat3) <- taxa

	for (p in 1:length(times)){
		dat3[p,1:length(times[[p]])] <- times[[p]]
	}

	cat(noquote(sprintf("\ndata_%s=[", j)), file=outfile, append=TRUE)

	for (n in 1:(length(taxa)-1)){
		rec <- paste(dat3[n,!is.na(dat3[n,])], collapse=",")
		cat(noquote(sprintf("array([%s]),", rec)), file=outfile, append=TRUE, sep="\n")
	}

	n <- n+1
	rec <- paste(dat3[n,!is.na(dat3[n,])], collapse=",")
	cat(noquote(sprintf("array([%s])", rec)), file=outfile, append=TRUE, sep="\n")

	cat("]", "", file=outfile, append=TRUE, sep="\n")
}


data_sets <- ""
names <- ""

if (replicates > 1){
	for (j in 1:(replicates-1)) {
		data_sets <- paste(data_sets, noquote(sprintf("data_%s,", j)))
		names <- paste(names, noquote(sprintf(" '%s_%s',", fname,j)))
		}

	data_sets <- paste(data_sets, noquote(sprintf("data_%s", j+1)))
	names <- paste(names, noquote(sprintf(" '%s_%s',", fname,j+1)))
} else {
	data_sets <- "data_1"
	names <- noquote(sprintf(" '%s_1'", fname))	
}

cat(noquote(sprintf("d=[%s]", data_sets)), noquote(sprintf("names=[%s]", names)), "def get_data(i): return d[i]", "def get_out_name(i): return  names[i]", file=outfile, append=TRUE, sep="\n")


tax_names <- paste(taxa, collapse="','")
cat(noquote(sprintf("taxa_names=['%s']", tax_names)), "def get_taxa_names(): return taxa_names", file=outfile, append=TRUE, sep="\n")


if ("trait" %in% colnames(dat)){
	datBM <- dat[,1]
	splist$Trait <- NA
	for (n in 1:length(splist[,1])){
		splist$Trait[n] <- mean(dat$trait[datBM == splist[n,1]], na.rm=T)
	}
	s1 <- "\ntrait1=array(["
	BM <- gsub("NaN|NA", "nan", toString(splist$Trait))
	s2 <- "])\ntraits=[trait1]\ndef get_continuous(i): return traits[i]"
	STR <- paste(s1,BM,s2)
	cat(STR, file=outfile, append=TRUE, sep="\n")
}

splistout <- paste(dirname(file), "/", fname, "_SpeciesList.txt", sep="")
lookup <- as.data.frame(taxa)
lookup$status  <- "extinct"

write.table(splist, file=splistout, sep="\t", row.names=F, quote=F)
cat("\n\nPyRate input file was saved in: ", sprintf("%s", outfile), "\n\n")

}


fit.prior <- function(file = NULL, lineage = "root_age"){

require(fitdistrplus)

if (is.null(file)){
    stop("You must enter a valid filename.\n")
	}

dat <- read.table(file, header=T, stringsAsFactors=F, row.names=NULL, sep="\t")
fname <- no.extension(basename(file))
outfile <- paste(dirname(file), "/", lineage, "_Prior.txt", sep="")

lineage2 <- paste(lineage,"_TS", sep="")
if (!is.element(lineage2, colnames(dat))){
	stop("Lineage not found, please check your input.\n")
	}

time <- dat[,which(names(dat) == lineage2)]
time2 <- time-(min(time)-0.01)
gamm <- fitdist(time2, distr="gamma", method = "mle")$estimate 

cat("Lineage: ", lineage, "; Shape: ", gamm[1], "; Scale: ", 1/gamm[2], "; Offset: ", min(time), sep="", file=outfile, append=FALSE)
}
                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
#        list12 <- stocklistperiod[period, 2][[1]]
#        for (i in 1:max) {
#            print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
#        }
        for (i in 1:max) {
            id <- list11$id[i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
            }
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), rise, list11$id[[i]]))
        }
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, mynames, topbottom, periodtext, maindate, olddate, days) {
    dev.new()
    colours <- rainbow(topbottom)
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE, col = colours[i], pch = i)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o", lty = i, col = colours[i], pch = i)
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(mynames[1]))
        legend(1, g_range[2], mynames, cex=0.8, lty=1:6, pch=1:25, col=colours) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (type == pricetype) {
        return (df$price)
    }
    if (type == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    normalize <- 0
    if (length(ids) > 1) {
        if (periodtext == "price") {
            normalize <- 1
        }
        if (periodtext == "index") {
            normalize <- 1
        }
    }
    
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, pricetype)
        perioddata[["text"]] <- pairs
        perioddatamap[["price"]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, indextype)
        perioddata[["text"]] <- pairs
        perioddatamap[["index"]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    dayset <- list()
    ls <- list()
    mynames <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        if (normalize == 1) {
                            str("minmax")
                            str(l)
                            mymin <- abs(min(l))
                            mymax <- abs(max(l))
                            if (mymin > mymax) {
                                mymax <- mymin
                            }
                            for (j in 1:length(l)) {
                                l[j] <- l[j] * 100 / mymax;
                            }
                            str(l)
                        }
                        
                        dayset <- append(dayset, bigretl[[2]])
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        mynames[c] <- df$name
                    }
                }
            }
        }
    }
    daynames <- names(dayset)
    olddate <- min(daynames)
    newdate <- max(daynames)
    displaychart(ls, mynames, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
#        list12 <- stocklistperiod[period, 2][[1]]
#        for (i in 1:max) {
#            print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
#        }
        for (i in 1:max) {
            id <- list11$id[i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
            }
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), rise, list11$id[[i]]))
        }
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, mynames, topbottom, periodtext, maindate, olddate, days) {
    dev.new()
    colours <- rainbow(topbottom)
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE, col = colours[i], pch = i)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o", lty = i, col = colours[i], pch = i)
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(mynames[1]))
        legend(1, g_range[2], mynames, cex=0.8, lty=1:6, pch=1:25, col=colours) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (type == pricetype) {
        return (df$price)
    }
    if (type == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    normalize <- 0
    if (length(ids) > 0) {
        if (periodtext == "price") {
            normalize <- 1
        }
        if (periodtext == "index") {
            normalize <- 1
        }
    }
    
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, pricetype)
        perioddata[["text"]] <- pairs
        perioddatamap[["price"]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, indextype)
        perioddata[["text"]] <- pairs
        perioddatamap[["index"]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    dayset <- list()
    ls <- list()
    mynames <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        if (normalize == 1) {
                            str("minmax")
                            str(l)
                            mymin <- abs(min(l))
                            mymax <- abs(max(l))
                            if (mymin > mymax) {
                                mymax <- mymin
                            }
                            for (j in 1:length(l)) {
                                l[j] <- l[j] * 100 / mymax;
                            }
                            str(l)
                        }
                        
                        dayset <- append(dayset, bigretl[[2]])
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        mynames[c] <- df$name
                    }
                }
            }
        }
    }
    daynames <- names(dayset)
    olddate <- min(daynames)
    newdate <- max(daynames)
    displaychart(ls, mynames, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

#setwd("/scratch/cqs/shengq1/dnaseq/2110/cnmops/result")
#sample_names <- c(
#"2110_JP_01"
#,"2110_JP_02"
#,"2110_JP_03"
#,"2110_JP_04"
#,"2110_JP_05"
#,"2110_JP_06"
#,"2110_JP_07"
#,"2110_JP_08"
#,"2110_JP_09"
#,"2110_JP_10"
#,"2110_JP_11"
#,"2110_JP_12"
#,"2110_JP_13"
#,"2110_JP_14"
#,"2110_JP_15"
#,"2110_JP_16"
#)
#bam_files <- c(
#"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-1_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-2_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-3_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-4_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-5_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-6_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-7_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-8_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-9_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-10_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-11_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-12_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-13_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-14_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-15_realigned_recal_rmdup.sorted.bam"
#,"/scratch/cqs/shengq1/dnaseq/2110/bwa_markdup/2110-JP-16_realigned_recal_rmdup.sorted.bam"
#)
#hasbed<-1
#bedfile<-"/scratch/cqs/lij17/cnv/SureSelect_XT_Human_All_Exon_V4_withoutchr_withoutY_lite.bed"
#prefix<-"2110"
#callfile<-"2110.call"
#pairmode<-"paired"
#parallel<-8
#refnames<-c()

if(hasbed){
  segments <- read.table(bedfile, sep="\t", as.is=TRUE, header=T)
  gr <- GRanges(segments[,1], IRanges(segments[,2], segments[,3]))
  gr <- reduce(gr)
  sort(gr, ignore.strand=TRUE)
}    

library(cn.mops)
library(DNAcopy)
resfile<-paste0(prefix, "_resCNMOPS.cnmops.Rdata")

if(length(refnames) > 0){
  insample<-sample_names %in% refnames
  REFNames<-sample_names[insample]
  REFFiles<-bam_files[insample]
  SAMNames<-sample_names[!insample]
  SAMFiles<-bam_files[!insample]
  if(hasbed){
    segfile<-paste0(prefix, "_getSegmentReadCountsFromBAM_ref.Rdata")
    if(file.exists(segfile)){
      load(segfile)
    }else{
      refdata <- getSegmentReadCountsFromBAM(REFFiles, GR=gr, sampleNames=REFNames, mode=pairmode, parallel=parallel)
      samdata <- getSegmentReadCountsFromBAM(SAMFiles, GR=gr, sampleNames=SAMNames, mode=pairmode, parallel=parallel)
      save(refdata, samdata, file=segfile)
    }
  }else{
    countfile<-paste0(prefix, "_getReadCountsFromBAM_ref.Rdata")
    if(file.exists(countfile)){
      load(countfile)
    }else{
      refdata <- getReadCountsFromBAM(REFFiles, sampleNames=REFNames, mode=pairmode, parallel=parallel)
      samdata <- getReadCountsFromBAM(SAMFiles, sampleNames=SAMNames, mode=pairmode, parallel=parallel)
      save(refdata, samdata, file=countfile)
    }
  }
  resCNMOPS<-referencecn.mops(cases=samdata, 
                              controls=refdata, 
                              upperThreshold=0.5, 
                              lowerThreshold=-0.5,
                              segAlgorithm="fast")
  resCNMOPS<-calcIntegerCopyNumbers(resCNMOPS)
}else{
  if(hasbed){
    segfile<-paste0(prefix, "_getSegmentReadCountsFromBAM.Rdata")
    if(file.exists(segfile)){
      load(segfile)
    }else{
      x <- getSegmentReadCountsFromBAM(bam_files, GR=gr, sampleNames=sample_names, mode=pairmode, parallel=parallel)
      save(refx, samx, file=segfile)
    }
    resCNMOPS<-exomecn.mops(x, upperThreshold=0.5, lowerThreshold=-0.5)
    resCNMOPS<-calcIntegerCopyNumbers(resCNMOPS)
  }else{
    countfile<-paste0(prefix, "_getReadCountsFromBAM.Rdata")
    if(file.exists(countfile)){
      load(countfile)
    }else{
      x <- getReadCountsFromBAM(bam_files, sampleNames=sample_names, mode=pairmode)
      save(x, file=countfile)
    }
    resCNMOPS <- cn.mops(x) 
    resCNMOPS <- calcIntegerCopyNumbers(resCNMOPS)
  }
}

#load(resfile)
save(resCNMOPS, file=resfile)

d<-as.data.frame(cnvs(resCNMOPS))
d[,"type"]<-apply(d,1,function(x){
  if(as.numeric(x["median"]) < 0){
    return ("DELETION")
  }else{
    return ("DUPLICATION")
  }
})

# locus<-data.frame(Title=paste0(d$sampleName, " ~ ", d$seqnames, ":", d$start, "-", d$end, " ~ ", d$type),
#                   Filename=paste0(d$sampleName, "_", d$seqnames, "_", d$start, "_", d$end, ".png"))

d<-d[order(d[,"sampleName"], as.numeric(d[,"seqnames"]), as.numeric(d[,"start"])),]
write.table(d, file=callfile,sep="\t",col.names=T,row.names=F,quote=F)

locus<-d[,c("seqnames", "start", "end")]
locus$name<-paste0(d$seqnames, "_", d$start, "_", d$end, "_", d$CN, "_", d$sampleName)
locus<-locus[order(d$seqnames, d$start),]
write.table(locus, file=paste0(prefix, ".call.bed"), sep="\t", col.names=F, row.names=F,quote=F)

cnvr<- data.frame(seqnames=seqnames(resCNMOPS@cnvr),
                  starts=start(resCNMOPS@cnvr)-1,
                  ends=end(resCNMOPS@cnvr),
                  file=paste(seqnames(resCNMOPS@cnvr), start(resCNMOPS@cnvr)-1, end(resCNMOPS@cnvr), sep="_") )
cnvr<-data.frame(cbind(cnvr, elementMetadata(resCNMOPS@cnvr)))
write.table(file=paste0(prefix, ".cnvr.tsv"), cnvr, sep="\t" ,row.names=F, quote=F)

# dir.create("images", showWarnings = FALSE)
# 
# index<-9
# for(index in c(1:nrow(locus))){
#   png(filename=paste0("images/", locus$Filename[index]), width=2000, height=2000, res=300)
#   plot(resCNMOPS, which=index, toFile=TRUE)
#   grid.text(locus$Title[index], y=0.98)
#   dev.off()
# }
                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
#        list12 <- stocklistperiod[period, 2][[1]]
#        for (i in 1:max) {
#            print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
#        }
        for (i in 1:max) {
            id <- list11$id[i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
            }
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), rise, list11$id[[i]]))
        }
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, mynames, topbottom, periodtext, maindate, olddate, days) {
    dev.new()
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(mynames[1]))
        legend(1, g_range[2], mynames, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (type == pricetype) {
        return (df$price)
    }
    if (type == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    normalize <- 0
    if (length(ids) > 0) {
        if (periodtext == "price") {
            normalize <- 1
        }
        if (periodtext == "index") {
            normalize <- 1
        }
    }
    
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, pricetype)
        perioddata[["text"]] <- pairs
        perioddatamap[["price"]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, indextype)
        perioddata[["text"]] <- pairs
        perioddatamap[["index"]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    dayset <- list()
    ls <- list()
    mynames <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        if (normalize == 1) {
                            str("minmax")
                            str(l)
                            mymin <- abs(min(l))
                            mymax <- abs(max(l))
                            if (mymin > mymax) {
                                mymax <- mymin
                            }
                            for (j in 1:length(l)) {
                                l[j] <- l[j] * 100 / mymax;
                            }
                            str(l)
                        }
                        
                        dayset <- append(dayset, bigretl[[2]])
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        mynames[c] <- df$name
                    }
                }
            }
        }
    }
    daynames <- names(dayset)
    olddate <- min(daynames)
    newdate <- max(daynames)
    displaychart(ls, mynames, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

# The functions require rchart-helper.R preloaded

# getQ2TimelapsePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getQ2TimelapsePlot = function(data, names, colors, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    dateFactors = list()
    for (i in 1:length(data)) {
        dateFactors[[i]] = as.factor(data[[i]]$date)
        boxplot = boxplot(data[[i]]$x ~ dateFactors[[i]],
                          data=data.frame(dateFactors[[i]], data[[i]]$x), plot=FALSE)
        stats = setNames(as.data.frame(boxplot$stats), nm=NULL)

        # Timpstamp in miliseconds
        unixTimestamps =
            1000 * as.numeric(as.POSIXct(sort(unique(data[[i]]$date)),
                                         origin="1970-01-01"))
        statsMedian = rbind(setNames(unixTimestamps, nm=NULL), stats[3,])
        statsQ2 = rbind(setNames(unixTimestamps, nm=NULL), stats[c(2, 4),])

        series[[2 * (i - 1) + 1]] =
            list(name=names[i], data=statsMedian, zIndex=1, color=colors[i],
                 marker=list(fillColor="white", lineWidth=2, lineColor=colors[i]))
        series[[2 * i]] = list(name="50th quartile", data=statsQ2, zIndex=0,
                 type="arearange", color=colors[i], lineWidth=0, linkedTo=":previous", fillOpacity=0.3)
    }

    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=list(text=yLabel), min=0)
    chart$set(series=series)
    return(chart)
}

# Helper for creating histogram
getBinItemList = function(data, businesses, interval=100) {
    binItemList = c()
    currentBin = interval
    maxBin = max(data$count) + interval
    while (currentBin < maxBin) {
        items = filter(data, currentBin - interval <= count & count < currentBin)
        binItemList = c(binItemList,
                        paste("< ", currentBin, "<br>",
                              paste(items$name, collapse="<br>, ")))
        currentBin = currentBin + interval
    }
    return(binItemList)
}

# getStackedHistogram
# data[[]]$x
getStackedHistogram = function(data, names, xLabel, interval=100, logScale=FALSE, logBase=exp(1), normalize=FALSE, colors = c("#7cb5ec", "#000000")) {
    series = list()
    plotLines = list()
    for (i in 1:length(data)){
        x = data[[i]]$x

        plotLines[[i * 2 - 1]] =
            list(color=colors[i],
                 value=mean(x),
                 width=2,
                 label=list(text="mean", style=list(color=colors[i]), verticalAlign="middle"))
        plotLines[[i * 2]] =
            list(color=colors[i],
                 value=median(x),
                 dashStyle="dash",
                 width=2,
                 label=list(text="median", style=list(color=colors[i]), verticalAlign="middle"))

        maxBin = max(data[[i]]$x)
        actualInterval = interval

        if (logScale) {
            x = log(x + 1, base=logBase)
            maxBin = log(maxBin + 1, base=logBase)
            actualInterval = log(interval, base=logBase)
        }
        histogram = hist(x, breaks=seq(0, maxBin + actualInterval, actualInterval), plot=FALSE)
        histNames = getBinItemList(data[[i]], interval=actualInterval)

        nBins = min(length(histogram$breaks), length(histogram$counts))
        counts = histogram$counts[1:nBins]
        if (normalize) {
            counts = counts / nrow(data[[i]])
        }
        bins = getValues(
            histogram$breaks[1:nBins],
            counts,
            name=histNames)
        series[[i]] = list(name=names[i], data=bins)
    }
   
    chart <- Highcharts$new()
    chart$chart(type="column")
    chart$plotOptions(
        column="{ grouping: false, pointPadding: 0, borderWidth: 0, groupPadding: 0, shadow: false}")
    chart$xAxis(title=paste("{text: '", xLabel, "'}", sep=""),
                plotLines=plotLines)
    yLabel = "frequency"
    if (normalize) {
        yLabel = paste(yLabel, "(normalized)")
    }
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""))
    chart$set(series=series)
    return(chart)
}

# getTimelapseLinePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getTimelapseLinePlot = function(data, names, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    for (i in 1:length(data)){
        timelapseValues = getTimelapseValues(
            as.POSIXlt(strptime(as.character(data[[i]]$date), "%Y-%m-%d", tz=timezone)),
            data[[i]]$x)
        series[[i]] = list(name=names[i], data=timelapseValues)
    }


    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""), gridLineColor="#FFFFFF")
    chart$set(series=series)
    return(chart)
}
                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
#        list12 <- stocklistperiod[period, 2][[1]]
#        for (i in 1:max) {
#            print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
#        }
        for (i in 1:max) {
            id <- list11$id[i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
            }
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), rise, list11$id[[i]]))
        }
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, mynames, topbottom, periodtext, maindate, olddate, days) {
    dev.new()
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(mynames[1]))
        legend(1, g_range[2], mynames, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (type == pricetype) {
        return (df$price)
    }
    if (type == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    normalize <- 0
    if (length(ids) > 0) {
        if (periodtext == "price") {
            normalize <- 1
        }
        if (periodtext == "index") {
            normalize <- 1
        }
    }
    
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, pricetype)
        perioddata[["text"]] <- pairs
        perioddatamap[["price"]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, indextype)
        perioddata[["text"]] <- pairs
        perioddatamap[["index"]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    ls <- list()
    mynames <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        if (normalize == 1) {
                            str("minmax")
                            str(l)
                            mymin <- abs(min(l))
                            mymax <- abs(max(l))
                            if (mymin > mymax) {
                                mymax <- mymin
                            }
                            for (j in 1:length(l)) {
                                l[j] <- l[j] * 100 / mymax;
                            }
                            str(l)
                        }
                        
                        dayset <- bigretl[[2]]
                        daynames <- names(dayset)
                        olddate <- min(daynames)
                        newdate <- max(daynames)
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        mynames[c] <- df$name
                    }
                }
            }
        }
    }
    displaychart(ls, mynames, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max, days) {
    list1 <- stocklistperiod
    for (j in 1:days) {
        list2 <- list()
        if (j < days) {
            list2 <- periodmaps[period, j][[1]]
        }

        list11 <- stocklistperiod[period, j][[1]]
#        list12 <- stocklistperiod[period, 2][[1]]
#        for (i in 1:max) {
#            print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
#        }
        for (i in 1:max) {
            id <- list11$id[i]
            rise <- 0
            if (j < days) {
                rise <- list2[[id]]
            }
            print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), rise, list11$id[[i]]))
        }
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom, days)
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, periodtext, maindate, olddate, days) {
    dev.new()
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (type == pricetype) {
        return (df$price)
    }
    if (type == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    normalize <- 0
    if (length(ids) > 0) {
        if (periodtext == "price") {
            normalize <- 1
        }
        if (periodtext == "index") {
            normalize <- 1
        }
    }
    
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, pricetype)
        perioddata[["text"]] <- pairs
        perioddatamap[["price"]] <- perioddata
        }
        {
        perioddata <- list()
        pairs[[paste(1, market)]] <- list(market, indextype)
        perioddata[["text"]] <- pairs
        perioddatamap[["index"]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    ls <- list()
    names <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        if (normalize == 1) {
                            str("minmax")
                            str(l)
                            mymin <- abs(min(l))
                            mymax <- abs(max(l))
                            if (mymin > mymax) {
                                mymax <- mymin
                            }
                            for (j in 1:length(l)) {
                                l[j] <- l[j] * 100 / mymax;
                            }
                            str(l)
                        }
                        
                        dayset <- bigretl[[2]]
                        daynames <- names(dayset)
                        olddate <- min(daynames)
                        newdate <- max(daynames)
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        names[c] <- df$name
                    }
                }
            }
        }
    }
    displaychart(ls, names, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

REBOL [
    System: "REBOL [R3] Language Interpreter and Run-time Environment"
    Title: "REBOL 3 Mezzanine: File Related"
    Rights: {
        Copyright 2012 REBOL Technologies
        REBOL is a trademark of REBOL Technologies
    }
    License: {
        Licensed under the Apache License, Version 2.0
        See: http://www.apache.org/licenses/LICENSE-2.0
    }
]

clean-path: func [
    "Returns new directory path with //, . and .. processed."
    file [file! url! string!]
    /only "Do not prepend current directory"
    /dir "Add a trailing / if missing"
    /local out cnt f
][
    case [
        any [only not file? file] [file: copy file]
        #"/" = first file [
            ++ file
            out: next what-dir
            while [
                all [
                    #"/" = first file
                    f: find/tail out #"/"
                ]
            ][
                ++ file
                out: f
            ]
            file: append clear out file
        ]
        true [file: append what-dir file]
    ]

    if all [dir not dir? file] [append file #"/"]

    out: make type-of file length file ; same datatype
    cnt: 0 ; back dir counter

    parse reverse file [
        some [
            ;pp: (?? pp)
            "../" (++ cnt)
            | "./"
            | #"/" (if any [not file? file #"/" <> last out] [append out #"/"])
            | copy f [to #"/" | to end] (
                either cnt > 0 [
                    -- cnt
                ][
                    unless find ["" "." ".."] to string! f [append out f]
                ]
            )
        ]
    ]

    if all [#"/" = last out #"/" <> last file] [remove back tail out]
    reverse out
]

input: function [
    {Inputs a string from the console. New-line character is removed.}
;   /hide "Mask input with a * character"
][
    if any [
        not port? system/ports/input
        not open? system/ports/input
    ][
        system/ports/input: open [scheme: 'console]
    ]
    line: to-string read system/ports/input
    trim/with line newline
    line
]

ask: func [
    "Ask the user for input."
    question [any-series!] "Prompt to user"
    /hide "mask input with *"
][
    prin question
    trim either hide [input/hide] [input]
]

confirm: func [
    "Confirms a user choice."
    question [any-series!] "Prompt to user"
    /with choices [string! block!]
    /local response
][
    if all [block? choices 2 < length choices] [
        cause-error 'script 'invalid-arg mold choices
    ]
    response: ask question
    unless with [choices: [["y" "yes"] ["n" "no"]]]
    case [ ; returned
        empty? choices [true]
        string? choices [if find/match response choices [true]]
        2 > length choices [if find/match response first choices [true]]
        find first choices response [true]
        find second choices response [false]
    ]
]

list-dir: func [
    "Print contents of a directory (ls)."
    'path [<end> file! word! path! string!]
        "Accepts %file, :variables, and just words (as dirs)"
    /l "Line of info format"
    /f "Files only"
    /d "Dirs only"
;   /t "Time order"
    /r "Recursive"
    /i indent
    /local files save-dir info
][
    save-dir: what-dir

    unless file? save-dir [
        fail ["No directory listing protocol registered for" save-dir]
    ]

    switch type-of :path [
        _ [] ; Stay here
        :file! [change-dir path]
        :string! [change-dir to-rebol-file path]
        :word! :path! [change-dir to-file path]
    ]

    if r [l: true]
    unless l [l: make string! 62] ; approx width
    indent: any [:indent ""]
    files: attempt [read %./]
    if not files [print ["Not found:" :path] change-dir save-dir exit]
    for-each file files [
        if any [
            all [f dir? file]
            all [d not dir? file]
        ][continue]
        either string? l [
            append l file
            append/dup l #" " 15 - remainder length l 15
            if greater? length l 60 [print l clear l]
        ][
            info: get query file
            change info second split-path info/1
            printf [indent 16 -8 #" " 24 #" " 6] info
            if all [r dir? file] [
                list-dir/l/r/i :file join indent "    "
            ]
        ]
    ]
    if all [string? l not empty? l] [print l]
    change-dir save-dir
    exit
]

undirize: func [
    {Returns a copy of the path with any trailing "/" removed.}
    path [file! string! url!]
][
    path: copy path
    if #"/" = last path [clear back tail path]
    path
]

in-dir: func [
    "Evaluate a block while in a directory."
    dir [file!] "Directory to change to (changed back after)"
    block [block!] "Block to evaluate"
    /local old-dir
] [
    old-dir: what-dir
    change-dir dir
    also do block change-dir old-dir
] ; You don't want the block to be done if the change-dir fails, for safety.

to-relative-file: func [
    "Returns the relative portion of a file if in a subdirectory, or the original if not."
    file [file! string!] "File to check (local if string!)"
    /no-copy "Don't copy, just reference"
    /as-rebol "Convert to REBOL-style filename if not"
    /as-local "Convert to local-style filename if not"
] [
    either string? file [ ; Local file
        ; Note: to-local-file drops trailing / in R2, not in R3
        ; if tmp: find/match file to-local-file what-dir [file: next tmp]
        file: any [find/match file to-local-file what-dir  file]
        if as-rebol [file: to-rebol-file file  no-copy: true]
    ] [
        file: any [find/match file what-dir  file]
        if as-local [file: to-local-file file  no-copy: true]
    ]
    unless no-copy [file: copy file]
    file
]
#' Calibrate oli images to TM images
#'
#' Calibrate oli images to TM images using linear regression
#' @param oliwrs2dir character. oli WRS-2 scene directory path
#' @param tmwrs2dir character. TM WRS-2 scene directory path
#' @import raster
#' @export


olical_single = function(oli_file, tm_file, overwrite=F){
  
  get_intersection = function(files){
    int = intersect(extent(raster(files[1])),extent(raster(files[2])))
    if(length(files) >= 3){for(i in 3:length(files))int = intersect(extent(raster(files[i])), int)}
    return(int)
  }
  
  predict_oli_index = function(tbl, outsampfile){  
    
    #create a multivariable linear model
    model = rlm(refsamp ~ b2samp + b3samp + b4samp + b5samp + b6samp + b7samp, data=tbl) #
    
    tbl$singlepred = round(predict(model))
    write.csv(tbl, outsampfile, row.names=F)
    
    #plot the regression
    r = cor(tbl$refsamp, tbl$singlepred)
    coef = rlm(tbl$refsamp ~ tbl$singlepred)
    
    pngout = sub("samp.csv", "plot.png",outsampfile)
    png(pngout,width=700, height=700)
    title = paste(tbl$index[1],"linear regression: slope =",paste(signif(coef$coefficients[2], digits=3),",",sep=""),
                  "y Intercept =",paste(round(coef$coefficients[1], digits=3),",",sep=""),
                  "r =",signif(r, digits=3))
    plot(x=tbl$singlepred,y=tbl$refsamp,
         main=title,
         xlab=paste(tbl$oli_img[1],tbl$index[1]),
         ylab=paste(tbl$ref_img[1],tbl$index[1]))
    abline(coef = coef$coefficients, col="red")  
    dev.off()
    
    #return the information
    coef_tbl = data.frame(rbind(model$coefficients))
    cnames = c("yint","b2c","b3c","b4c","b5c","b6c","b7c")
    colnames(coef_tbl) = cnames
    tbls = list(coef_tbl,tbl)
    return(tbls)
  }

  #define the filenames
  oli_sr_file = oli_file
  oli_mask_file = sub("l8sr.tif", "cloudmask.tif", oli_sr_file)
  ref_tc_file = tm_file
  ref_tca_file = sub("tc", "tca", ref_tc_file)
  ref_mask_file = sub("tc", "cloudmask", ref_tc_file)
  
  #make new directory
  dname = dirname(oli_sr_file)
  oliimgid = substr(basename(oli_sr_file),1,16)
  outdir = file.path(substr(dname,1,nchar(dname)-12),"calibration", oliimgid)  #-5
  dir.create(outdir, showWarnings = F, recursive=T)
  
  #check to see if single cal has already been run
  files = list.files(outdir)
  thesefiles = c("tca_cal_plot.png","tcb_cal_plot.png","tcg_cal_plot.png","tcw_cal_plot.png",
                 "tca_cal_samp.csv","tcb_cal_samp.csv","tcg_cal_samp.csv","tcw_cal_samp.csv")
  results = rep(NA,length(thesefiles))
  for(i in 1:length(results)){
    test = grep(thesefiles[i], files)
    results[i] = length(test) > 0
  }
  if(all(results) == T & overwrite == F){return(0)}
  
  
  #load files as raster
  oli_sr_img = brick(oli_sr_file)
  oli_mask_img = raster(oli_mask_file)
  ref_tc_img = brick(ref_tc_file)
  ref_tca_img  = raster(ref_tca_file)
  ref_mask_img = raster(ref_mask_file)
  
  #align the extents
  extent(oli_sr_img)  = alignExtent(oli_sr_img, ref_tc_img, snap="near")
  extent(oli_mask_img) = alignExtent(oli_mask_img, ref_tc_img, snap="near")
  extent(ref_tc_img)   = alignExtent(ref_tc_img, ref_tc_img, snap="near")
  extent(ref_tca_img)  = alignExtent(ref_tca_img, ref_tc_img, snap="near")
  extent(ref_mask_img) = alignExtent(ref_mask_img, ref_tc_img, snap="near")
  
  #crop the images to their intersection
  int = get_intersection(c(oli_mask_file,ref_mask_file))
  oli_b5_img = crop(subset(oli_sr_img,5),int)
  ref_tca_img = crop(ref_tca_img,int)
  oli_mask_img = crop(oli_mask_img,int)
  ref_mask_img = crop(ref_mask_img,int)
  
  #make a composite mask

  oli_mask_v = as.vector(oli_mask_img)
  ref_mask_v = as.vector(ref_mask_img)

  mask = oli_mask_v*ref_mask_v #make composite mask
  oli_mask_v = ref_mask_v = 0 # save memory
  
  #load oli and etm+ bands
  oli_b5_v = as.vector(oli_b5_img)
  ref_tca_v = as.vector(ref_tca_img)
  
  dif = oli_b5_v - ref_tca_v #find the difference
  oli_b5_v = ref_tca_v = 0 #save memory
  nas = which(mask == 0) #find the bads in the mask
  dif[nas] = NA #set the bads in the dif to NA so they are not included in the calc of mean and stdev
  stdv = sd(dif, na.rm=T) #get stdev of difference
  center = mean(dif, na.rm=T) #get the mean difference
  dif = dif < (center+stdv*2) & dif > (center-stdv*2) #find the pixels that are not that different
    
  
  goods = which(dif == 1)
  if(length(goods) < 20000){return(0)}
  
  #random sample
  samp = sample(1:length(goods), 20000)
  samp = goods[samp]
  sampxy = xyFromCell(oli_mask_img, samp)
  
  #save memory
  mask = 0
  
  #extract the sample pixels from the bands
  olisamp = extract(subset(oli_sr_img, 2:7), sampxy)
  tcsamp = extract(ref_tc_img, sampxy)
  tcasamp = extract(ref_tca_img, sampxy)
  
  #make sure the values are good for running regression on (diversity)
  unib2samp = length(unique(olisamp[,1]))
  unib3samp = length(unique(olisamp[,2]))
  unib4samp = length(unique(olisamp[,3]))
  unib5samp = length(unique(olisamp[,4]))
  unib6samp = length(unique(olisamp[,5]))
  unib7samp = length(unique(olisamp[,6]))
  
  unitcbsamp = length(unique(tcsamp[,1]))
  unitcgsamp = length(unique(tcsamp[,2]))
  unitcwsamp = length(unique(tcsamp[,3]))
  unitcasamp = length(unique(tcasamp))
  
  
  if(unib2samp < 15 | unib3samp < 15 | unib4samp < 15 | unib5samp < 15 | unib6samp < 15 | 
     unib7samp < 15 | unitcbsamp < 15 | unitcgsamp < 15 | unitcwsamp < 15 | unitcasamp < 15){return()}
  
  olibname = basename(oli_sr_file)
  refbname = basename(ref_tc_file)
  refabname = basename(ref_tca_file)
  
  tcb_tbl = data.frame(olibname,refbname,"tcb",sampxy,tcsamp[,1],olisamp)
  tcg_tbl = data.frame(olibname,refbname,"tcg",sampxy,tcsamp[,2],olisamp)
  tcw_tbl = data.frame(olibname,refbname,"tcw",sampxy,tcsamp[,3],olisamp)
  tca_tbl = data.frame(olibname,refabname,"tca",sampxy,tcasamp,olisamp)
  
  tcb_tbl = tcb_tbl[complete.cases(tcb_tbl),]
  tcg_tbl = tcg_tbl[complete.cases(tcg_tbl),]
  tcw_tbl = tcw_tbl[complete.cases(tcw_tbl),]
  tca_tbl = tca_tbl[complete.cases(tca_tbl),]
  
  cnames = c("oli_img","ref_img","index","x","y","refsamp","b2samp","b3samp","b4samp","b5samp","b6samp","b7samp") 
  colnames(tcb_tbl) = cnames
  colnames(tcg_tbl) = cnames
  colnames(tcw_tbl) = cnames
  colnames(tca_tbl) = cnames
  
  #predict the indices
  #TCB
  outsampfile = file.path(outdir,paste(oliimgid,"_tcb_cal_samp.csv",sep=""))
  model = predict_oli_index(tcb_tbl, outsampfile)
  bcoef = model[[1]]
  bsamp = model[[2]]
  br = cor(bsamp$refsamp, bsamp$singlepred)
  
  #TCG
  outsampfile = file.path(outdir,paste(oliimgid,"_tcg_cal_samp.csv",sep=""))
  model = predict_oli_index(tcg_tbl, outsampfile)
  gcoef = model[[1]]
  gsamp = model[[2]]
  gr = cor(gsamp$refsamp, gsamp$singlepred)
  
  #TCW
  outsampfile = file.path(outdir,paste(oliimgid,"_tcw_cal_samp.csv",sep=""))
  model = predict_oli_index(tcw_tbl, outsampfile)
  wcoef = model[[1]]
  wsamp = model[[2]]
  wr = cor(wsamp$refsamp, wsamp$singlepred)
  
  #TCA
  outsampfile = file.path(outdir,paste(oliimgid,"_tca_cal_samp.csv",sep=""))
  model = predict_oli_index(tca_tbl, outsampfile)
  acoef = model[[1]]
  asamp = model[[2]]
  ar = cor(asamp$refsamp, asamp$singlepred)
  
  #write out the coef files
  tcbinfo = data.frame(oli_file=olibname, ref_file=refbname, index="tcb", bcoef, r=br)
  tcginfo = data.frame(oli_file=olibname, ref_file=refbname, index="tcg", gcoef, r=gr)
  tcwinfo = data.frame(oli_file=olibname, ref_file=refbname, index="tcw", wcoef, r=wr)
  tcainfo = data.frame(oli_file=olibname, ref_file=refabname, index="tca", acoef, r=ar)
  
  tcbcoefoutfile = file.path(outdir,paste(oliimgid,"_tcb_cal_coef.csv",sep=""))
  tcgcoefoutfile = file.path(outdir,paste(oliimgid,"_tcg_cal_coef.csv",sep=""))
  tcwcoefoutfile = file.path(outdir,paste(oliimgid,"_tcw_cal_coef.csv",sep=""))
  tcacoefoutfile = file.path(outdir,paste(oliimgid,"_tca_cal_coef.csv",sep=""))
  
  write.csv(tcbinfo, tcbcoefoutfile, row.names=F)
  write.csv(tcginfo, tcgcoefoutfile, row.names=F)
  write.csv(tcwinfo, tcwcoefoutfile, row.names=F)
  write.csv(tcainfo, tcacoefoutfile, row.names=F)
}
#' Calibrate OLI images to TM images
#'
#' Calibrate OLI images to TM images using linear regression
#' @param oliwrs2dir character. oli WRS-2 scene directory path
#' @param tmwrs2dir character. TM WRS-2 scene directory path
#' @param cores numeric. Number of cores to process with options: 1 or 2
#' @export


olical = function(oliwrs2dir, tmwrs2dir, cores=2, overwrite=overwrite){  
  
  olifiles = list.files(oliwrs2dir, "l8sr.tif", recursive=T, full.names=T)
  tmfiles = list.files(tmwrs2dir, "tc.tif", recursive=T, full.names=T)
  
  #pull out oli and tm year
  olibase = basename(olifiles)
  oliyears = substr(olibase, 10, 13)
  tmbase = basename(tmfiles)   
  tmyears = substr(tmbase, 10, 13)
  tmyearday = as.numeric(substr(tmbase, 10, 16))
  
  #get overlapping oli/etm+ years
  oliuni = unique(oliyears)
  notintm = oliuni %in% tmyears
  if(sum(notintm) < 2){stop("There is not at least one year of overlapping images between OLI and ETM+ to calibrate on")}
  theseoli = which(oliyears %in% tmyears == T)
  olifilessub = olifiles[theseoli]
  olibase = olibase[theseoli]
  oliyears = oliyears[theseoli]
  oliyearday = as.numeric(substr(olibase, 10, 16))
  
  len = length(olifilessub)
  match = data.frame(oli=olifilessub, etm=NA, stringsAsFactors=FALSE)
  for(i in 1:len){
    closest = order(abs(oliyearday[i]-tmyearday))[1]
    match$etm[i] = tmfiles[closest]
  }
  
  #do single pair modeling
  print("...single image pair modeling")
  if(cores==2){
    cl = makeCluster(cores)
    registerDoParallel(cl)
    cfun <- function(a, b) NULL
    o = foreach(i=1:len, .combine="cfun",.packages="LandsatLinkr") %dopar% olical_single(match$oli[i], match$etm[i], overwrite=overwrite) #
    stopCluster(cl)
  } else {for(i in 1:len){olical_single(match$oli[i], match$etm[i], overwrite=overwrite)}}
  
  #do aggregated modeling
  caldir = file.path(oliwrs2dir,"calibration")
  print("...aggregate image pair modeling")
  cal_oli_tc_aggregate_model(caldir,overwrite=overwrite)
  
  #predict tc and tca from aggregate model
  calagdir = file.path(caldir,"aggregate_model")
  bcoef = as.numeric(read.csv(file.path(calagdir,"tcb_cal_aggregate_coef.csv"))[1,3:8])
  gcoef = as.numeric(read.csv(file.path(calagdir,"tcg_cal_aggregate_coef.csv"))[1,3:8])
  wcoef = as.numeric(read.csv(file.path(calagdir,"tcw_cal_aggregate_coef.csv"))[1,3:8])
  
  print("...applying model to all oli images")
  for(i in 1:len){olisr2tc(olifiles[i],bcoef,gcoef,wcoef,"apply",overwrite=overwrite)}
}
#' Calibrate OLI images to TM images
#'
#' Calibrate OLI images to TM images using linear regression
#' @param oliwrs2dir character. oli WRS-2 scene directory path
#' @param tmwrs2dir character. TM WRS-2 scene directory path
#' @param cores numeric. Number of cores to process with options: 1 or 2
#' @export


olical = function(oliwrs2dir, tmwrs2dir, cores=2, overwrite=overwrite){  
  
  olifiles = list.files(oliwrs2dir, "l8sr.tif", recursive=T, full.names=T)
  tmfiles = list.files(tmwrs2dir, "tc.tif", recursive=T, full.names=T)
  
  #pull out oli and tm year
  olibase = basename(olifiles)
  oliyears = substr(olibase, 10, 13)
  tmbase = basename(tmfiles)   
  tmyears = substr(tmbase, 10, 13)
  tmyearday = as.numeric(substr(tmbase, 10, 16))
  
  #get overlapping oli/etm+ years
  oliuni = unique(oliyears)
  notintm = oliuni %in% tmyears
  if(sum(notintm) < 2){stop("There are not at least three years of overlaping images between OLI and ETM+")}
  theseoli = which(oliyears %in% tmyears == T)
  olifilessub = olifiles[theseoli]
  olibase = olibase[theseoli]
  oliyears = oliyears[theseoli]
  oliyearday = as.numeric(substr(olibase, 10, 16))
  
  len = length(olifilessub)
  match = data.frame(oli=olifilessub, etm=NA, stringsAsFactors=FALSE)
  for(i in 1:len){
    closest = order(abs(oliyearday[i]-tmyearday))[1]
    match$etm[i] = tmfiles[closest]
  }
  
  #do single pair modeling
  print("...single image pair modeling")
  if(cores==2){
    cl = makeCluster(cores)
    registerDoParallel(cl)
    cfun <- function(a, b) NULL
    o = foreach(i=1:len, .combine="cfun",.packages="LandsatLinkr") %dopar% olical_single(match$oli[i], match$etm[i], overwrite=overwrite) #
    stopCluster(cl)
  } else {for(i in 1:len){olical_single(match$oli[i], match$etm[i], overwrite=overwrite)}}
  
  #do aggregated modeling
  caldir = file.path(oliwrs2dir,"calibration")
  print("...aggregate image pair modeling")
  cal_oli_tc_aggregate_model(caldir,overwrite=overwrite)
  
  #predict tc and tca from aggregate model
  calagdir = file.path(caldir,"aggregate_model")
  bcoef = as.numeric(read.csv(file.path(calagdir,"tcb_cal_aggregate_coef.csv"))[1,3:8])
  gcoef = as.numeric(read.csv(file.path(calagdir,"tcg_cal_aggregate_coef.csv"))[1,3:8])
  wcoef = as.numeric(read.csv(file.path(calagdir,"tcw_cal_aggregate_coef.csv"))[1,3:8])
  
  print("...applying model to all oli images")
  for(i in 1:len){olisr2tc(olifiles[i],bcoef,gcoef,wcoef,"apply",overwrite=overwrite)}
}
#' Calibrate MSS images to TM images
#'
#' Calibrate MSS images to TM images using linear regression
#' @param msswrs2dir character. MSS WRS-2 scene directory path
#' @param tmwrs2dir character. TM WRS-2 scene directory path
#' @import raster
#' @export


msscal_single = function(mss_file, tm_file){
  
  get_intersection = function(files){
    int = intersect(extent(raster(files[1])),extent(raster(files[2])))
    if(length(files) >= 3){for(i in 3:length(files))int = intersect(extent(raster(files[i])), int)}
    return(int)
  }
  
  predict_mss_index = function(tbl, outsampfile){  
    #create a multivariable linear model
    model = rlm(refsamp ~ b1samp + b2samp + b3samp + b4samp, data=tbl) #tbl replaced final 1/22/2016
    
    tbl$singlepred = round(predict(model))
    write.csv(tbl, outsampfile, row.names=F)
    
    #plot the regression
    r = cor(tbl$refsamp, tbl$singlepred)
    coef = rlm(tbl$refsamp ~ tbl$singlepred)
    
    pngout = sub("samp.csv", "plot.png",outsampfile)
    png(pngout,width=700, height=700)
    title = paste(tbl$index[1],"linear regression: slope =",paste(signif(coef$coefficients[2], digits=3),",",sep=""),
                  "y Intercept =",paste(round(coef$coefficients[1], digits=3),",",sep=""),
                  "r =",signif(r, digits=3))
    plot(x=tbl$singlepred,y=tbl$refsamp, #tbl replaced final 1/22/2016
         main=title,
         xlab=paste(tbl$mss_img[1],tbl$index[1]),
         ylab=paste(tbl$ref_img[1],tbl$index[1]))   
    abline(coef = coef$coefficients, col="red")  
    dev.off()
    
    coef_tbl = data.frame(rbind(model$coefficients))
    cnames = c("yint","b1c","b2c","b3c","b4c")
    colnames(coef_tbl) = cnames
    tbls = list(coef_tbl,tbl)
    return(tbls)
  }
  
  #define the filenames
  mss_sr_file = mss_file
  mss_mask_file = sub("dos_sr_30m.tif", "cloudmask_30m.tif", mss_sr_file)
  ref_tc_file = tm_file
  ref_tca_file = sub("tc", "tca", ref_tc_file)
  ref_mask_file = sub("tc", "cloudmask", ref_tc_file)
  
  #make new directory
  dname = dirname(mss_sr_file)
  mssimgid = substr(basename(mss_sr_file),1,16)
  outdir = file.path(substr(dname,1,nchar(dname)-12),"calibration", mssimgid)  #-5
  dir.create(outdir, showWarnings = F, recursive=T)
  
  #load files as raster
  mss_sr_img = brick(mss_sr_file)
  mss_mask_img = raster(mss_mask_file)
  ref_tc_img = brick(ref_tc_file)
  ref_tca_img  = raster(ref_tca_file)
  ref_mask_img = raster(ref_mask_file)
  
  #align the extents
  extent(mss_sr_img)  = alignExtent(mss_sr_img, ref_tc_img, snap="near")
  extent(mss_mask_img) = alignExtent(mss_mask_img, ref_tc_img, snap="near")
  extent(ref_tc_img)   = alignExtent(ref_tc_img, ref_tc_img, snap="near")
  extent(ref_tca_img)  = alignExtent(ref_tca_img, ref_tc_img, snap="near")
  extent(ref_mask_img) = alignExtent(ref_mask_img, ref_tc_img, snap="near")
  
  #crop the images to their intersection
  int = get_intersection(c(mss_sr_file,mss_mask_file,ref_tc_file,ref_tca_file,ref_mask_file))
  mss_sr_img = crop(mss_sr_img,int)
  mss_mask_img = crop(mss_mask_img,int)
  ref_tc_img = crop(ref_tc_img,int)
  ref_tca_img = crop(ref_tca_img,int)
  ref_mask_img = crop(ref_mask_img,int)
  
  #make a composite mask
  mss_mask_v = as.vector(mss_mask_img)
  ref_mask_v = as.vector(ref_mask_img)
  mask = mss_mask_v*ref_mask_v
  mss_mask_v = ref_mask_v = 0 # save memory
  
  goods = which(mask == 1)
  if(length(goods) < 20000){return()}
  
  #random sample
  samp = sample(1:length(goods), 20000)
  samp = goods[samp]
  sampxy = xyFromCell(mss_mask_img, samp) #added on 1/22/2016
  
  #save memory
  mask = 0
  
  msssamp = extract(mss_sr_img, sampxy)
  tcsamp = extract(ref_tc_img, sampxy)
  tcasamp = extract(ref_tca_img, sampxy)
  
  #make sure the values are good for running regression on (diversity)
  unib1samp = length(unique(msssamp[,1]))
  unib2samp = length(unique(msssamp[,2]))
  unib3samp = length(unique(msssamp[,3]))
  unib4samp = length(unique(msssamp[,4]))
  
  unitcbsamp = length(unique(tcsamp[,1]))
  unitcgsamp = length(unique(tcsamp[,2]))
  unitcwsamp = length(unique(tcsamp[,3]))
  unitcasamp = length(unique(tcasamp))
  
  
  #if(unib1samp < 15 | unib2samp < 15 | unib3samp < 15 | unib4samp < 15 ){return()}
  if(unib1samp < 15 | unib2samp < 15 | unib3samp < 15 | unib4samp < 15 |
     unitcbsamp < 15 | unitcgsamp < 15 | unitcwsamp < 15 | unitcasamp < 15){return()}
  
  mssbname = basename(mss_sr_file)
  refbname = basename(ref_tc_file)
  refabname = basename(ref_tca_file)
  
  tcb_tbl = data.frame(mssbname,refbname,"tcb",sampxy,tcsamp[,1],msssamp)
  tcg_tbl = data.frame(mssbname,refbname,"tcg",sampxy,tcsamp[,2],msssamp)
  tcw_tbl = data.frame(mssbname,refbname,"tcw",sampxy,tcsamp[,3],msssamp)
  tca_tbl = data.frame(mssbname,refabname,"tca",sampxy,tcasamp,msssamp)
  
  tcb_tbl = tcb_tbl[complete.cases(tcb_tbl),]
  tcg_tbl = tcg_tbl[complete.cases(tcg_tbl),]
  tcw_tbl = tcw_tbl[complete.cases(tcw_tbl),]
  tca_tbl = tca_tbl[complete.cases(tca_tbl),]
  
  cnames = c("mss_img","ref_img","index","x","y","refsamp","b1samp","b2samp","b3samp","b4samp") 
  colnames(tcb_tbl) = cnames
  colnames(tcg_tbl) = cnames
  colnames(tcw_tbl) = cnames
  colnames(tca_tbl) = cnames
  
  outsampfile = file.path(outdir,paste(mssimgid,"_tcb_cal_samp.csv",sep=""))
  model = predict_mss_index(tcb_tbl, outsampfile)
  bcoef = model[[1]]
  bsamp = model[[2]]
  br = cor(bsamp$refsamp, bsamp$singlepred)
  
  outsampfile = file.path(outdir,paste(mssimgid,"_tcg_cal_samp.csv",sep=""))
  model = predict_mss_index(tcg_tbl, outsampfile)
  gcoef = model[[1]]
  gsamp = model[[2]]
  gr = cor(gsamp$refsamp, gsamp$singlepred)
  
  outsampfile = file.path(outdir,paste(mssimgid,"_tcw_cal_samp.csv",sep=""))
  model = predict_mss_index(tcw_tbl, outsampfile)
  wcoef = model[[1]]
  wsamp = model[[2]]
  wr = cor(wsamp$refsamp, wsamp$singlepred)
  
  #TCA
  outsampfile = file.path(outdir,paste(mssimgid,"_tca_cal_samp.csv",sep=""))
  model = predict_mss_index(tca_tbl, outsampfile)
  acoef = model[[1]]
  asamp = model[[2]]
  ar = cor(asamp$refsamp, asamp$singlepred)
  
  tcbinfo = data.frame(mss_file=mssbname, ref_file=refbname, index="tcb", bcoef, r=br)
  tcginfo = data.frame(mss_file=mssbname, ref_file=refbname, index="tcg", gcoef, r=gr)
  tcwinfo = data.frame(mss_file=mssbname, ref_file=refbname, index="tcw", wcoef, r=wr)
  tcainfo = data.frame(mss_file=mssbname, ref_file=refabname, index="tca", acoef, r=ar)
  
  tcbcoefoutfile = file.path(outdir,paste(mssimgid,"_tcb_cal_coef.csv",sep=""))
  tcgcoefoutfile = file.path(outdir,paste(mssimgid,"_tcg_cal_coef.csv",sep=""))
  tcwcoefoutfile = file.path(outdir,paste(mssimgid,"_tcw_cal_coef.csv",sep=""))
  tcacoefoutfile = file.path(outdir,paste(mssimgid,"_tca_cal_coef.csv",sep=""))
  
  write.csv(tcbinfo, tcbcoefoutfile, row.names=F)
  write.csv(tcginfo, tcgcoefoutfile, row.names=F)
  write.csv(tcwinfo, tcwcoefoutfile, row.names=F)
  write.csv(tcainfo, tcacoefoutfile, row.names=F)
}
#' Composite images 
#'
#' Composite images
#' @param msswrs1dir character. list of mss wrs1 directory paths
#' @param msswrs2dir character. list of mss wrs2 directory paths
#' @param tmwrs2dir character. list of tm wrs2 directory path
#' @param index character. spectral index to make composites for. options: "tca", "tcb", "tcg", "tcw"
#' @param outdir character. path to output directory
#' @param runname character. unique name for the composite set
#' @param useareafile character. path to usearea file
#' @param doyears ??? what years to composite
#' @param order character. how to order the images options "sensor_and_doy" and "doy"
#' @param overlap character. how to deal with overlapping images. options: "mean"
#' @import raster
#' @import gdalUtils
#' @import plyr
#' @export


mixel = function(msswrs1dir,msswrs2dir,tmwrs2dir,oliwrs2dir,index,outdir,runname,useareafile,doyears="all",order="none",overlap="mean",startday,endday,yearadj=0){
  
  mixel_find = function(files, refimg){
    info = matrix(ncol = 4, nrow=length(files))
    print("Getting image extents")
    for(i in 1:length(files)){ 
      print(i)
      img = raster(files[i])
      ext = extent(img)
      info[i,1] = ext@xmin
      info[i,2] = ext@xmax
      info[i,3] = ext@ymin
      info[i,4] = ext@ymax
    }
    
    text = extent(raster(refimg))  
    these = which(info[,3] < text@ymax & info[,4] > text@ymin & info[,2] > text@xmin & info[,1] < text@xmax) 
    goods = files[these]
    return(goods)
  }
  
  mixel_mask = function(imgfile, useareafile, index){ #search,
    print(paste("...cloud masking:",basename(imgfile)))
    if(index == "tca" | index == "tcb"){band=1}
    if(index == "tcg"){band=2}
    if(index == "tcw"){band=3}
    
    sensor = substr(basename(imgfile), 1,2)
    if(sensor == "LM"){maskbit = "_cloudmask_30m.tif"} else {maskbit = "_cloudmask.tif"}
    
    maskfile = file.path(dirname(imgfile), paste(substr(basename(imgfile),1,16),maskbit,sep=""))
    img = raster(imgfile, band=band)
    mask = raster(maskfile)
    NAvalue(mask) = 0 #make 0 in the mask
    refimg = raster(useareafile)
    
    imgex = alignExtent(img, refimg, snap="near")
    maskex = alignExtent(mask, refimg, snap="near")
    extent(img) = imgex
    extent(mask) = maskex
    
    overlap = intersect(img, mask)
    mask = crop(mask, overlap)
    img = crop(img, overlap)
    
    img = img*mask
    return(img)
  }
  
  change_envi_to_bsq = function(file){
    envifilename = sub("bsq","envi",file)
    envixmlfile = paste(envifilename,".aux.xml",sep="")
    bsqxmlfile = sub("envi","bsq",envixmlfile)
    file.rename(envifilename,file)
    file.rename(envixmlfile,bsqxmlfile)
  }
  
  mixel_composite = function(outdir, imginfosub, runname, index, order, useareafile, overlap, yearadj){

    #outdir= mssdir 
    #imginfosub = mssdf

    uniyears = sort(unique(imginfosub$compyear))
    
    #for all the unique year make a composite
    for(i in 1:length(uniyears)){
      print(paste("working on year:", uniyears[i]))
      these = which(imginfosub$compyear == uniyears[i])
      theseimgs = imginfosub$file[these]

      if(order == "none"){theseimgs = theseimgs}

      len = length(theseimgs)
      #mask all the images in a year
      for(m in 1:len){
        mergeit = ifelse(m == 1, "r1", paste(mergeit,",r",m, sep=""))
        dothis = paste("r",m,"=mixel_mask(theseimgs[",m,"], useareafile, index)", sep="") 
        eval(parse(text=dothis))
      }
      
      #select a mosaic method
      if(overlap == "order"){mergeit = paste("newimg = merge(",mergeit,")", sep="")} else
      if(overlap == "mean"){mergeit = paste("newimg = mosaic(",mergeit,",fun=mean,na.rm=T)", sep="")} else
      if(overlap == "median"){mergeit = paste("newimg = mosaic(",mergeit,",fun=median,na.rm=T)", sep="")} else
      if(overlap == "max"){mergeit = paste("newimg = mosaic(",mergeit,",fun=max,na.rm=T)", sep="")} else
      if(overlap == "min"){mergeit = paste("newimg = mosaic(",mergeit,",fun=min,na.rm=T)", sep="")}
      
      #run the merge function
      print(paste("...merging files using ", overlap, ":",sep=""))
      for(h in 1:len){print(paste("......",basename(theseimgs[h]),sep=""))}
      if(len == 1){newimg = r1} else {eval(parse(text=mergeit))} #only run merge it if there are multiple files to merge
      
      #name the new file
      yearlabel = as.character(as.numeric(uniyears[i])+yearadj)
      newbase = paste(yearlabel,"_",runname,"_",index,"_composite.bsq", sep="")
      outimgfile = file.path(outdir,newbase)
      outtxtfile = sub("composite.bsq", "composite_img_list.csv", outimgfile)
      theseimgs = data.frame(theseimgs)
      colnames(theseimgs) = "File"
      write.csv(theseimgs, file=outtxtfile, row.names = F)
      
      #load in the usearea file and crop/extend the new image to it
      refimg = raster(useareafile)
      newimg = round(crop(newimg, refimg))
      newimg = extend(newimg, refimg, value=NA)

      #set NA values to 0 for use
      refimg = refimg != 0 # set all values not equal to 0 to 1 and 0 to 0 - NA can still be in there, it will be set to 0 in the final img
      refimg = refimg * newimg #set all 0's in the usearea file to 0 in the img file - if NA are in the usearea file, they will be transfered to img and then set to 0 in the final img
      newimg[is.na(newimg)] = 0 #set all NA to 0

      #write out the new image
      projection(newimg) = set_projection(files[1])
      writeRaster(newimg, outimgfile, format="ENVI", datatype = "INT2S",overwrite=T)
      change_envi_to_bsq(outimgfile)
    
      #clean the temp directory      
      delete_temp_files()
    }
  }
  
  delete_temp_files = function(){
    tempdir = dirname(rasterTmpFile())
    tempfiles = list.files(tempdir,full.names=T)
    unlink(tempfiles)
  }
  
  find_files = function(dir, search){
    if(length(which(is.na(dir) == T)) > 0){return(vector())} else{
      imgdir = normalizePath(file.path(dir,"images"),winslash="/")
      files = vector()
      for(i in 1:length(imgdir)){
        print(paste("finding files in: ",imgdir))
        files = c(files,list.files(imgdir[i], search, recursive=T, full.names=T))
      }
      if(length(files)==0){stop(
          paste("There were no tasselled cap files found in this directory: ",imgdir[i],".
          Make sure that you provided the correct scene head directory path and that all processing
          steps up to compositing have been completed. MSS directories should contain
          files with the extension 'tc_30m.tif' and 'tca_30m.tif', and TM/ETM+ and OLI 'tc.tif' and 'tca.tif'.
          A valid scene head directory path should look like this mock example: 'C:/mock/landsat/wrs2/045030'.
          The program will then append 'images' to the path and search recursively in that directory. If
          you wish to continue without this directory, re-run the compositing call and don't add this directory.",sep="")
        )
      } else{
        return(files)
      }
    }
  }
  
  combine_overlapping_senors = function(ref_files, dep_files){
    thesetm = which(basename(ref_files) %in% basename(dep_files))
    ref_files_sort = sort(ref_files[thesetm])
    thesemss = which(basename(dep_files) %in% basename(ref_files))
    dep_files_sort = sort(dep_files[thesemss])
    len = length(dep_files_sort)
    if(len > 0){
      for(i in 1:len){
        print(paste("...",i,"/",len,sep=""))
        depimg= raster(dep_files_sort[i])
        refimg= raster(ref_files_sort[i])
        NAvalue(depimg) = 0
        NAvalue(refimg) = 0
        newimg = mosaic(depimg,refimg, fun="mean", na.rm=T)
        newimg[is.na(newimg)] = 0
        projection(newimg) = set_projection(files[1])
        
        outimgfile = file.path(outdir,basename(dep_files_sort[i]))
        writeRaster(newimg, outimgfile, format="ENVI", datatype = "INT2S",overwrite=T)
        change_envi_to_bsq(outimgfile)
        
        delete_temp_files()
      }
    }
  }
  
  
  pixel_level_offset = function(ref_files, dep_files, outdir, sensor, projfile, runname){
    
    #find overlapping years
    theseref = which(basename(ref_files) %in% basename(dep_files))
    thesedep = which(basename(dep_files) %in% basename(ref_files))
    lendep = length(thesedep)
    lenref = length(theseref)
    if(lenref == 0 | lendep == 0 | lenref != lendep){return()} # get out if there are no matching files - no overlap
    
    print(paste("calculating pixel-level offset for: ",sensor," composites",sep=""))
    
    #sort the files to make sure they are in the same order
    ref_files_sort = sort(ref_files[theseref])
    dep_files_sort = sort(dep_files[thesedep])
    
    #find the mean pixel-wise difference between dependent and reference images
    for(i in 1:lendep){
      print(paste("...",basename(dep_files_sort[i]),sep=""))
      refimg = raster(ref_files_sort[i])
      depimg = raster(dep_files_sort[i])
      NAvalue(refimg) = 0
      NAvalue(depimg) = 0
      
      dif = refimg - depimg #get the difference 
      denom = !is.na(dif) #get the cells that are not NA after difference
      dif[is.na(dif)] = 0 #set the difference NA values to 0
      
      #make the sum difference and denominator layers
      if(i == 1){ #if i is one then start the layers
        difsum = dif
        denomsum = denom
      } else{ #else sum the layers
        difsum = sum(difsum, dif, na.rm=T)
        denomsum = sum(denomsum, denom, na.rm=T)
      }
    }
    print("...calculating mean pixel-level offset")
    meandiforig = round(difsum/denomsum) #mean the mean for the time series
    meandiforig[is.na(meandiforig)] = 0 #make division by 0 set to 0 instead of NA - there will be no correction for these pixels

    #figure out parts of file names
    if(sensor == "mss"){offsetdir = file.path(outdir,"mss_offset");deprunname="lm"; refrunname="lt"; meandiffilebname = "mss_mean_dif.bsq"}
    if(sensor == "oli"){offsetdir = file.path(outdir,"oli_offset");deprunname="lc"; refrunname="le"; meandiffilebname = "oli_mean_dif.bsq"}
    
    #write out the mean pixel-wise difference file
    dir.create(offsetdir, recursive=T, showWarnings=F)
    projection(meandiforig) = set_projection(projfile)
    meandiffile = file.path(offsetdir,meandiffilebname)
    writeRaster(meandiforig, meandiffile, format="ENVI", datatype = "INT2S",overwrite=T)
    change_envi_to_bsq(meandiffile)
    
    #write out the frequency file
    projection(denomsum) = set_projection(projfile)
    denomsumfile = file.path(dirname(meandiffile),"overlap_frequency.bsq")
    writeRaster(denomsum, denomsumfile, format="ENVI", datatype="INT2S",overwrite=T)
    change_envi_to_bsq(denomsumfile)
    
    #move files around
    for(i in 1:lendep){
      from_dep_files = list.files(dirname(dep_files_sort[1]),substr(basename(dep_files_sort[i]),1,4), full.names = T)
      from_ref_files = list.files(dirname(ref_files_sort[1]),substr(basename(ref_files_sort[i]),1,4), full.names = T)
      to_dep_files = file.path(offsetdir,sub(paste("_",runname,"_",sep=""),paste("_",deprunname,"_",sep=""),basename(from_dep_files)))
      to_ref_files = file.path(offsetdir,sub(paste("_",runname,"_",sep=""),paste("_",refrunname,"_",sep=""),basename(from_ref_files)))
      
      file.copy(from_dep_files, to_dep_files)
      file.copy(from_ref_files, to_ref_files)
    }
    
    #adjust the dep images
    print("...adjusting images by mean pixel-level offset:")
    for(i in 1:length(dep_files)){
      print(paste("......",basename(dep_files[i]),sep=""))
      img = raster(dep_files[i])
      NAvalue(img) = 0
      
      meandiforig = raster(meandiffile) #need to load this each time because delete_temp_files() gets called at the end of each loop - if this file is big it is held in the temp directory and will be deleted
      img = img + meandiforig
      img[is.na(img)] = 0
      
      #write out the new image
      projection(img) = set_projection(projfile)
      
      #delete the old .bsq files - keep the "img_list.csv" files
      allfiles = list.files(dirname(dep_files[i]),substr(basename(dep_files[i]),1,nchar(basename(dep_files[i]))-4),full.names=T)
      allfiles = grep("img_list.csv", allfiles, invert=T, value=T) #keep the "img_list.csv" files
      unlink(allfiles)
      writeRaster(img, dep_files[i], format="ENVI", datatype="INT2S",overwrite=T)
      change_envi_to_bsq(dep_files[i])
      
      delete_temp_files()
    }
  }
  
  #check for leap year
  leapyear = function(year){
    return(((year %% 4 == 0) & (year %% 100 != 0)) | (year %% 400 == 0))
  }
  
  #create decimal year day
  decyearday = function(year,day){
    num = ifelse(leapyear(year) == T, 366, 365)
    return(year+day/num)
  }
  
  #create decimal day
  decday = function(day){
    num = ifelse(day == 366, 366, 365)
    return(day/num)
  }

  #########################################################################
  #########################################################################
  #########################################################################
  print(paste("working on index:",index))
  
  #create some search terms depending on index
  if(index == "tca"){msssearch="tca_30m.tif$"; tmsearch="tca.tif$"; olisearch="tca.tif$"}
  if(index == "tcb"){msssearch="tc_30m.tif$"; tmsearch="tc.tif$"; olisearch="tc.tif$"}
  if(index == "tcg"){msssearch="tc_30m.tif$"; tmsearch="tc.tif$"; olisearch="tc.tif$"}
  if(index == "tcw"){msssearch="tc_30m.tif$"; tmsearch="tc.tif$"; olisearch="tc.tif$"}
  
  #find the files
  msswrs1files = find_files(msswrs1dir, msssearch)
  msswrs2files = find_files(msswrs2dir, msssearch)
  tmwrs2files = find_files(tmwrs2dir, tmsearch)
  oliwrs2files = find_files(oliwrs2dir, olisearch)
  
  #put all the files together in a vector and check to make sure the files intersect the useareafile, if not they will be excluded
  files = c(msswrs1files,msswrs2files,tmwrs2files,oliwrs2files)
  
  #find files that intersect the usearea file
  files = mixel_find(files, useareafile)
  if(length(files)==0){stop("There were no files in the given directories that intersect the provided 'usearea file'.
                            Make sure that you provided the correct file, checked that it actually overlaps the scenes you 
                            specified for compositing, and that the projection is the same as the images.")}
  
  
  #create a table with info on the files
  imginfo = data.frame(file = as.character(files))
  imginfo$file = as.character(imginfo$file)
  bname = basename(imginfo$file)
  imginfo$year = substr(bname, 10, 13)
  imginfo$day = substr(bname, 14,16)
  imginfo$sensor = substr(bname, 1,2)
  imginfo$compyear = imginfo$decdate = NA
  for(i in 1:nrow(imginfo)){imginfo$decdate[i] = decyearday(as.numeric(imginfo$year[i]),as.numeric(imginfo$day[i]))}
  
  #figure out the dec year day range that is good
  #uniyears = as.numeric(sort(unique(imginfo$year)))
  uniyears = 1972:as.numeric(format(Sys.Date(),'%Y'))
  
  if(doyears != "all"){uniyears = uniyears[match(doyears,uniyears)]}

  decstart = decday(startday)
  decend = decday(endday)
  dif = ifelse(decstart > decend, (1-decstart)+decend, decend - decstart)
  start = uniyears+decstart
  end = start+dif
  yearsdf = data.frame(uniyears,start,end)
  
  #figure out which images are in the composite date range, get rif of ones that aren't
  for(i in 1:nrow(yearsdf)){
    these = which(imginfo$decdate >= yearsdf$start[i] & imginfo$decdate <= yearsdf$end[i])
    imginfo$compyear[these] = yearsdf$uniyears[i]
  }
  imginfo = na.omit(imginfo)
  if(nrow(imginfo)==0){stop("There were no files in the given directories that intersect the provided start and end year-of-day bounds.
                            Make sure that you provided the correct limits and check that there are actually image files that intersect 
                            the specified date range.")}
  
  
  #make composites
  mssdir = file.path(outdir,"mss")
  tmdir = file.path(outdir,"tm")
  olidir = file.path(outdir,"oli")
  
  #pull out files by sensor
  mssdf = imginfo[imginfo$sensor == "LM",]
  tmetmdf = imginfo[imginfo$sensor == "LT" | imginfo$sensor == "LE",]
  olidf = imginfo[imginfo$sensor == "LC",]
  
  #create annual composites for all sensors
  if(nrow(mssdf) != 0){
    dir.create(mssdir, recursive=T, showWarnings=F)
    mixel_composite(mssdir, mssdf, runname=runname,index=index, order=order, useareafile=useareafile, overlap=overlap, yearadj=yearadj)
  }
  if(nrow(tmetmdf) != 0){
    dir.create(tmdir, recursive=T, showWarnings=F)
    mixel_composite(tmdir, tmetmdf, runname=runname,index=index, order=order, useareafile=useareafile, overlap=overlap, yearadj=yearadj)
  }
  if(nrow(olidf) != 0){
    dir.create(olidir, recursive=T, showWarnings=F)
    mixel_composite(olidir, olidf, runname=runname,index=index, order=order, useareafile=useareafile, overlap=overlap, yearadj=yearadj)
  }
  
  #deal with the overlapping composites
  msscompfiles = list.files(mssdir, ".bsq$", recursive=T, full.names=T)
  tmcompfiles = list.files(tmdir, ".bsq$", recursive=T, full.names=T)
  olicompfiles = list.files(olidir, ".bsq$", recursive=T, full.names=T)
  
  pixel_level_offset(ref_files=tmcompfiles, dep_files=msscompfiles, outdir=outdir, sensor="mss", projfile=files[1], runname=runname)
  pixel_level_offset(ref_files=tmcompfiles, dep_files=olicompfiles, outdir=outdir, sensor="oli", projfile=files[1], runname=runname)
  
  
  print("dealing with any temporally overlapping MSS/TM composites")
  combine_overlapping_senors(tmcompfiles, msscompfiles)
  
  print("dealing with any temporally overlapping ETM+/OLI composites")
  combine_overlapping_senors(tmcompfiles, olicompfiles)
  
  
  #rename files
  print("directory and file organization/cleaning")
  imglists = list.files(outdir, paste(runname,"_",index,"_composite_img_list.csv",sep=""), recursive=T, full.names=T)
  imglistyears = substr(basename(imglists),1,4)
  uniimglistyears = unique(imglistyears)
  for(i in 1:length(uniimglistyears)){
    outname = file.path(outdir,paste(uniimglistyears[i],"_",runname,"_",index,"_composite_img_list.csv", sep=""))
    theseones = which(imglistyears %in% uniimglistyears[i])
    if(length(theseones) == 1){file.rename(imglists[i], outname)}
    if(length(theseones) == 2){
      data1 = read.csv(imglists[theseones[1]])
      data2 = read.csv(imglists[theseones[2]])
      mergedlists = as.data.frame(rbind(data1,data2)$File)
      colnames(mergedlists) = "File"
      write.csv(mergedlists, outname, row.names = F)
    }
  }
  
  #move files
  msstmolifiles = c(msscompfiles, tmcompfiles, olicompfiles)
  finalfiles = file.path(outdir, basename(msstmolifiles))
  for(i in 1:length(finalfiles)){
    check = file.exists(finalfiles[i])
    if(check == F){
      year = substr(basename(finalfiles[i]), 1, 4)
      files = list.files(dirname(msstmolifiles[i]), year, full.names=T)
      file.rename(files, file.path(outdir, basename(files)))
    }
  }
  
  #clean up
  unlink(c(mssdir,tmdir,olidir), recursive=T)
  
  #make the final stack
  print("making final annual composite stack")
  bname = paste(runname,"_",index,"_composite_stack.bsq", sep="")
  bands = sort(list.files(outdir, "composite.bsq$", full.names=T))
  fullnametif = file.path(outdir,bname)
  fullnamevrt = change_extension("bsq", "vrt", fullnametif)
  gdalbuildvrt(gdalfile=bands, output.vrt = fullnamevrt, separate=T) #, tr=c(reso,reso)
  gdal_translate(src_dataset=fullnamevrt, dst_dataset=fullnametif, of = "ENVI") #, co="INTERLEAVE=BAND"
  unlink(fullnamevrt)
}


#' Calibrate MSS imagery to TM and make cloud-free composites 
#'
#' Calibrate MSS imagery to TM and make cloud-free composites   
#' @param msswrs1dir character. mss wrs1 directory path
#' @param msswrs2dir character. mss wrs2 directory path
#' @param tmwrs2dir character. tm wrs2 directory path
#' @param index character. spectral index to make composites for. options: "tca", "tcb", "tcg", "tcw"
#' @param outdir character. path to output directory
#' @param runname character. unique name for the composite set
#' @param useareafile character. path to usearea file
#' @param doyears ??? what years to composite
#' @param order character. how to order the images options "sensor_and_doy", "doy", and "none"
#' @param overlap character. how to deal with overlapping images. options: "mean"
#' @param cores numeric. Number of cores to process with options: 1 or 2
#' @param process numeric. integer or vector specifying which processes to run: 1=msscal, 2=mixel
#' @import foreach
#' @import doParallel
#' @export


calibrate_and_composite = function(msswrs1dir,msswrs2dir,tmwrs2dir,oliwrs2dir,index,outdir,runname,useareafile,doyears="all",order="none",overlap="mean", cores=2, process, overwrite=F ,startday, endday, yearadj){
  
  #msscal
  if(1 %in% process ==T){
    #resample MSS
    print("Resampling MSS reflectance and cloudmask images")
    msswrs1srfiles = list.files(msswrs1dir, "dos_sr.tif", recursive=T, full.names=T)
    msswrs1cloudfiles = list.files(msswrs1dir, "cloudmask.tif", recursive=T, full.names=T)
    msswrs2srfiles = list.files(msswrs2dir, "dos_sr.tif", recursive=T, full.names=T)
    msswrs2cloudfiles = list.files(msswrs2dir, "cloudmask.tif", recursive=T, full.names=T)
    files = c(msswrs1srfiles,msswrs1cloudfiles,msswrs2srfiles,msswrs2cloudfiles)
    #cores=2
    if(cores == 2){
      print("...in parallel")
      cl = makeCluster(cores)
      registerDoParallel(cl)
      o = foreach(i=1:length(files), .combine="c",.packages="LandsatLinkr") %dopar% resample(files[i], overwrite=F) #hardwired to not overwrite
      stopCluster(cl)
    } else {for(i in 1:length(files)){o = resample(files[i], overwrite=F)}} #hardwired to not overwrite
    
    
    print("Running msscal")
    t=proc.time()
    msscal(msswrs1dir, msswrs2dir, tmwrs2dir, cores=cores)
    print(proc.time()-t)
  }
  
  #olical
  if(2 %in% process ==T){
    print("Running olical")
    t=proc.time()
    olical(oliwrs2dir, tmwrs2dir, cores=cores, overwrite=overwrite)
    print(proc.time()-t)
  }

  #mixel
  if(3 %in% process ==T){
    print("Running mixel")
    t=proc.time()
    if(index == "all"){
      index = c("tca", "tcb", "tcg", "tcw")
      outdir = c(file.path(outdir,"tca"),file.path(outdir,"tcb"),file.path(outdir,"tcg"),file.path(outdir,"tcw"))
      for(i in 1:length(index)){mixel(msswrs1dir,msswrs2dir,tmwrs2dir,oliwrs2dir,index[i],outdir[i],runname,useareafile,doyears="all",order="none",overlap=overlap, startday=startday, endday=endday, yearadj=yearadj)} #overlap="mean"
    } else {
      outdir = file.path(outdir,index)
      mixel(msswrs1dir,msswrs2dir,tmwrs2dir,oliwrs2dir,index,outdir,runname,useareafile,doyears="all",order="none",overlap=overlap, startday=startday, endday=endday, yearadj=yearadj) #overlap="mean"
    }
    print(proc.time()-t)
  }  
}##predefined_condition_begin
# setwd("h:/temp")  
#   
# data<-read.table("Z:/Shared/Labs/Brown,J/tiger/20160509_brown_3436/star_genetable/result/B3436_gene.count",row.names=1, header=T, check.names=F)
# 
# taskName<-'B3436'
# showLabelInPCA<-1
# showDEGeneCluster<-0
# pvalue<-0.05
# foldChange<-2
# minMedianInGroup<-5
# addCountOne<-0
# 
# comparisons=list(
#   "CAPTISOL_vs_FED" = c("CAPTISOL_vs_FED.design", "FED", "CAPTISOL")
# ) 
#
##predefined_condition_end

library("DESeq2")
library("heatmap3")
library("lattice")
library("reshape")
library("ggplot2")
library("grid")
library("scales")
library("reshape2")
library("VennDiagram")

##Solving node stack overflow problem start###
#when there are too many genes, drawing dendrogram may failed due to node stack overflow,
#It could be solved by forcing stats:::plotNode to be run as interpreted code rather then byte-compiled code via a nasty hack.
#http://stackoverflow.com/questions/16559250/error-in-heatmap-2-gplots/25877485#25877485

# Convert a byte-compiled function to an interpreted-code function 
unByteCode <- function(fun)
{
  FUN <- eval(parse(text=deparse(fun)))
  environment(FUN) <- environment(fun)
  FUN
}

# Replace function definition inside of a locked environment **HACK** 
assignEdgewise <- function(name, env, value)
{
  unlockBinding(name, env=env)
  assign( name, envir=env, value=value)
  lockBinding(name, env=env)
  invisible(value)
}

# Replace byte-compiled function in a locked environment with an interpreted-code
# function
unByteCodeAssign <- function(fun)
{
  name <- gsub('^.*::+','', deparse(substitute(fun)))
  FUN <- unByteCode(fun)
  retval <- assignEdgewise(name=name,
                           env=environment(FUN),
                           value=FUN
  )
  invisible(retval)
}

# Use the above functions to convert stats:::plotNode to interpreted-code:
unByteCodeAssign(stats:::plotNode)

# Now raise the interpreted code recursion limit (you may need to adjust this,
#  decreasing if it uses to much memory, increasing if you get a recursion depth error ).
options(expressions=5e4)

##Solving node stack overflow problem end###

hmcols <- colorRampPalette(c("green", "black", "red"))(256)

drawHCA<-function(prefix, rldselect, ispaired, designData, conditionColors, gnames){
  htfile<-paste0(prefix, "_DESeq2-vsd-heatmap.png")
  cat("saving HCA to ", htfile, "\n")
  genecount<-nrow(rldselect)
  if(genecount > 2){
    png(filename=htfile, width=3000, height =3000, res=300)
    cexCol = max(1.0, 0.2 + 1/log10(ncol(rldselect)))
    if(ispaired){
      htColors<-rainbow(length(unique(designData$Paired)))
      gsColors<-as.matrix(data.frame(Group=conditionColors, Sample=htColors[designData$Paired]))
    }else{
      gsColors = conditionColors;
    }
    heatmap3(rldselect, 
             col = hmcols, 
             ColSideColors = gsColors, 
             margins=c(12,5), 
             scale="r", 
             dist=dist, 
             labRow=NA,
             main=paste0("Hierarchical Cluster Using ", genecount, " Genes"),  
             cexCol=cexCol, 
             useRaster=FALSE,
             legendfun=function() showLegend(legend=paste0("Group ", gnames), col=c("red","blue"),cex=1.0,x="center"))
    dev.off()
  }
}

drawPCA<-function(prefix, rldmatrix, showLabelInPCA, designData, conditionColors){
  #filename<-paste0(prefix, "_DESeq2-vsd-pca.png")
  filename<-paste0(prefix, "_DESeq2-vsd-pca.pdf")
  genecount<-nrow(rldmatrix)
  if(genecount > 2){
    cat("saving PCA to ", filename, "\n")
    #png(filename=filename, width=3000, height=3000, res=300) # 10 X 10 inches
    pdf(filename, width=10, height=10)
    pca<-prcomp(t(rldmatrix))
    supca<-summary(pca)$importance
    pcadata<-data.frame(pca$x)
    pcalabs=paste0(colnames(pcadata), "(", round(supca[2,] * 100), "%)")
    pcadata["sample"]<-row.names(pcadata)
    
    if(showLabelInPCA){
      g <- ggplot(pcadata, aes(x=PC1, y=PC2, label=sample)) + 
        geom_text(vjust=-0.6, size=4) +
        geom_point(col=conditionColors, size=4) + 
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) +
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) + 
        xlab(pcalabs[1]) + ylab(pcalabs[2])
    }else{
      g <- ggplot(pcadata, aes(x=PC1, y=PC2)) + 
        geom_point(col=conditionColors, size=4) + 
        labs(color = "Group") +
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) + 
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) +
        xlab(pcalabs[1]) + ylab(pcalabs[2]) + 
        theme(legend.position="top")
    }
    
    print(g)
    dev.off()
  }
}

#for volcano plot
reverselog_trans <- function(base = exp(1)) {
  trans <- function(x) -log(x, base)
  inv <- function(x) base^(-x)
  trans_new(paste0("reverselog-", format(base)), trans, inv, 
            log_breaks(base = base), 
            domain = c(1e-100, Inf))
}

data<-data[,colnames(data) != "Feature_length"]
colClass<-sapply(data, class)
countNotNumIndex<-which(colClass!="numeric" & colClass!="integer")
if (length(countNotNumIndex)==0) {
  index<-1;
  indecies<-c()
} else {
  index<-max(countNotNumIndex)+1
  indecies<-c(1:(index-1))
}

countData<-data[,c(index:ncol(data))]
countData[is.na(countData)] <- 0
countData<-round(countData)

if(addCountOne){
  countData<-countData+1
}

comparisonNames=names(comparisons)
comparisonName=comparisonNames[1]

dir.create("details", showWarnings = FALSE)

pairedspearman<-list()
resultAllOut<-data
resultAllOutVar<-c("log2FoldChange","pvalue","padj")
for(comparisonName in comparisonNames){
  str(comparisonName)
  designFile=comparisons[[comparisonName]][1]
  gnames=comparisons[[comparisonName]][2:3]
  designData<-read.table(designFile, sep="\t", header=T)
  designData$Condition<-factor(designData$Condition, levels=gnames)
  
  if(ncol(designData) >= 3){
    cat("Data with covariances!\n")
  }else{
    cat("Data without covariances!\n")
  }
  if (any(colnames(designData)=="Paired")) {
	  ispaired<-TRUE
	  cat("Paired Data!\n")
  }else{
	  ispaired<-FALSE
	  cat("Not Paired Data!\n")
  }
  temp<-apply(designData,2,function(x) length(unique(x)))
  if (any(temp==1)) {
	  cat(paste0("Factors with only 1 level in design matrix: ",colnames(designData)[which(temp==1)],"\n"))
	  cat("They will be removed")
	  cat("\n")
	  designData<-designData[,which(temp!=1)]
  }
  temp<-apply(designData[,-1,drop=F],2,rank)
  if (length(unique(rowSums(temp)))==1 | identical(temp[,1],temp[,-1])) {
	  cat(paste0("The model matrix is not full rank, so the model cannot be fit as specified"))
	  cat("\n")
	  cat("Only Condition variable will be kept.")
	  cat("\n")
	  designData<-designData[,which(colnames(designData)%in% c("Sample","Condition"))]
  }
  
  comparisonData<-countData[,colnames(countData) %in% as.character(designData$Sample),drop=F]
  if(ncol(comparisonData) != nrow(designData)){
	message=paste0("Data not matched, there are ", nrow(designData), " samples in design file ", designFile, " but ", ncol(comparisonData), " samples in data ")
	warning(message)
	writeLines(message,paste0(comparisonName,".error"))
	next
  }
  comparisonData<-comparisonData[,as.character(designData$Sample)]
  
  prefix<-comparisonName
  curdata<-data
  if(minMedianInGroup > 0){
    conds<-unique(designData$Condition)
    data1<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[1]]]
    data2<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[2]]]
    med1<-apply(data1, 1, median) >= minMedianInGroup
    med2<-apply(data2, 1, median) >= minMedianInGroup
    med<-med1 | med2
    comparisonData<-comparisonData[med,]
    cat(nrow(comparisonData), " genes with minimum median count in group larger or equals than ", minMedianInGroup, "\n")
    
    if (nrow(comparisonData)==0) {
		message=paste0("Error: 0 Genes can be used in DESeq2 analysis in comparison ",comparisonName," \n")
		warning(message)
		writeLines(message,paste0(comparisonName,".error"))
      next;
    }
    
    prefix<-paste0(comparisonName, "_min", minMedianInGroup)
    curdata<-data[med,]
  }
  
  if(ispaired){
    pairedSamples = unique(designData$Paired)
    
    spcorr<-unlist(lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      cor(comparisonData[,samples[1]],comparisonData[,samples[2]],method="spearman")
    }))
    
    
    sptable<-data.frame(Name=pairedSamples, Spcorr=spcorr)
    write.csv(sptable, file=paste0(prefix, "_Spearman.csv"), row.names=FALSE)
    
    lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      log2c1<-log2(comparisonData[,samples[1]]+1)
      log2c2<-log2(comparisonData[,samples[2]]+1)
      png(paste0("details/", prefix, "_Spearman_", pairedSamples[x], ".png"), width=2000, height=2000, res=300)
      plot(log2c1, log2c2, xlab=paste0(samples[1], " [log2(Count + 1)]"), ylab=paste0(samples[2], " [log2(Count + 1)]"))
      text(3,15,paste0("SpearmanCorr=", sprintf("%0.3f", spcorr[x])))
      dev.off()
    })
    
    pairedspearman[[comparisonName]]<-spcorr
  }
  
  notEmptyData<-apply(comparisonData, 1, max) > 0
  comparisonData<-comparisonData[notEmptyData,]
  curdata<-curdata[notEmptyData,]
  
  if(ispaired){
    colnames(comparisonData)<-unlist(lapply(c(1:ncol(comparisonData)), function(i){paste0(designData$Paired[i], "_", colnames(comparisonData)[i])}))
  }
  rownames(designData)<-colnames(comparisonData)
  conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
  
  write.csv(comparisonData, file=paste0(prefix, ".csv"))
  
  #some basic graph
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                             colData = designData,
                             design = ~1)
  
  colnames(dds)<-colnames(comparisonData)
  
  #draw density graph
  rldmatrix<-as.matrix(log2(counts(dds,normalized=FALSE) + 1))
  rsdata<-melt(rldmatrix)
  colnames(rsdata)<-c("Gene", "Sample", "log2Count")
  png(filename=paste0(prefix, "_DESeq2-log2-density.png"), width=4000, height=3000, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  width=max(4000, ncol(rldmatrix) * 40 + 1000)
  height=max(3000, ncol(rldmatrix) * 40)
  png(filename=paste0(prefix, "_DESeq2-log2-density-individual.png"), width=width, height=height, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + facet_wrap(~Sample, scales = "free") + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  
  #varianceStabilizingTransformation
  
  allDesignData<-designData
  allComparisonData<-comparisonData
  
  excludedSample<-c()
  zeronumbers<-apply(comparisonData, 2, function(x){sum(x==0)})
  zeronumbers<-names(zeronumbers[order(zeronumbers)])
  percent10<-max(1, round(length(zeronumbers) * 0.1))
  
  removed<-0
  
  excludedCountFile<-paste0(prefix, "_DESeq2-exclude-count.csv")
  excludedDesignFile<-paste0(prefix, "_DESeq2-exclude-design.csv")
  if(file.exists(excludedCountFile)){
    file.remove(excludedCountFile)
  }
  if(file.exists(excludedDesignFile)){
    file.remove(excludedDesignFile)
  }
  
  fitType<-"parametric"
  while(1){
    #varianceStabilizingTransformation
    vsdres<-try(vsd <- varianceStabilizingTransformation(dds, blind=TRUE,fitType=fitType))
    if(class(vsdres) == "try-error" && grepl("every gene contains at least one zero", vsdres[1])){
      removed<-removed+1
      keptNumber<-length(zeronumbers) - percent10 * removed
      keptSample<-zeronumbers[1:keptNumber]
      excludedSample<-zeronumbers[(keptNumber+1):length(zeronumbers)]
      
      comparisonData<-comparisonData[, colnames(comparisonData) %in% keptSample]
      designData<-designData[rownames(designData) %in% keptSample,]
      dds=DESeqDataSetFromMatrix(countData = comparisonData,
                                 colData = designData,
                                 design = ~1)
      
      colnames(dds)<-colnames(comparisonData)
    } else if (class(vsdres) == "try-error" && grepl("newsplit: out of vertex space", vsdres[1])) {
		message=paste0("Warning: varianceStabilizingTransformation function can't run. fitType was set to local to try again")
		warning(message)
		fitType<-"mean"
		writeLines(message,paste0(comparisonName,".error"))
	} else{
      conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
      break
    }
  }
  if (nrow(comparisonData)<=1) {
	  message=paste0("Error: All genes in ",comparisonName," has at least one 0 value. Can't do DESeq2.")
	  warning(message)
	  writeLines(message,paste0(comparisonName,".error"))
	  next;
  }
  
  if(length(excludedSample) > 0){
    excludedCountData<-allComparisonData[,colnames(allComparisonData) %in% excludedSample]
    write.csv(file=excludedCountFile, excludedCountData)
    excludedDesignData<-allDesignData[rownames(allDesignData) %in% excludedSample,]
    write.csv(file=excludedDesignFile, excludedDesignData)
  }
  
  assayvsd<-assay(vsd)
  write.csv(assayvsd, file=paste0(prefix, "_DESeq2-vsd.csv"))
  
  vsdiqr<-apply(assayvsd, 1, IQR)
  assayvsd<-assayvsd[order(vsdiqr, decreasing=T),]
  
  rldmatrix=as.matrix(assayvsd)
  
  #draw pca graph
  drawPCA(paste0(prefix,"_geneAll"), rldmatrix, showLabelInPCA, designData, conditionColors)
  
  #draw heatmap
  #drawHCA(paste0(prefix,"_gene500"), rldmatrix[1:min(500, nrow(rldmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  drawHCA(paste0(prefix,"_geneAll"), rldmatrix, ispaired, designData, conditionColors, gnames)
  
  #different expression analysis
  designFormula=as.formula(paste0("~",paste0(c(colnames(designData)[-c(1:2)],"Condition"),collapse="+")))
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                               colData = designData,
                               design = designFormula)
  
  dds <- DESeq(dds,fitType=fitType)
  res<-results(dds,cooksCutoff=FALSE)
  
  cat("DESeq2 finished.\n")
  
  select<-(!is.na(res$padj)) & (res$padj<pvalue) & ((res$log2FoldChange >= log2(foldChange)) | (res$log2FoldChange <= -log2(foldChange)))
  
  if(length(indecies) > 0){
    inddata<-curdata[,indecies,drop=F]
    tbb<-cbind(inddata, comparisonData, res)
  }else{
    tbb<-cbind(comparisonData, res)
  }
  tbb$FoldChange<-2^tbb$log2FoldChange
  tbbselect<-tbb[select,,drop=F]
  tbbAllOut<-as.data.frame(tbb[,resultAllOutVar,drop=F])
  tbbAllOut$Significant<-select
  colnames(tbbAllOut)<-paste0(colnames(tbbAllOut)," (",comparisonName,")")
  resultAllOut<-cbind(resultAllOut,tbbAllOut[row.names(resultAllOut),])

  tbb<-tbb[order(tbb$padj),,drop=F]
  write.csv(as.data.frame(tbb),paste0(prefix, "_DESeq2.csv"))

  if("Feature_gene_name" %in% colnames(tbb)){
    gsea<-tbb[,c("Feature_gene_name", "stat"),drop=F]
    write.table(gsea,paste0(prefix, "_DESeq2_GSEA.rnk"),row.names=F,col.names=F,sep="\t", quote=F)
  }

  tbbselect<-tbbselect[order(tbbselect$padj),,drop=F]
  write.csv(as.data.frame(tbbselect),paste0(prefix, "_DESeq2_sig.csv"))
  
  if(showDEGeneCluster){
    siggenes<-rownames(rldmatrix) %in% rownames(tbbselect)
    
    nonDEmatrix<-rldmatrix[!siggenes,,drop=F]
    DEmatrix<-rldmatrix[siggenes,,drop=F]
    
    drawPCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, ispaired, designData, conditionColors, gnames)
    
    drawPCA(paste0(prefix,"_geneDE"),DEmatrix , showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneDE"),DEmatrix , ispaired, designData, conditionColors, gnames)
    #drawHCA(paste0(prefix,"_gene500NotDE"), nonDEmatrix[1:min(500, nrow(nonDEmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  }
  
  #Top 25 Significant genes barplot
  sigDiffNumber<-nrow(tbbselect)
  if (sigDiffNumber>0) {
    if (sigDiffNumber>25) {
      print(paste0("More than 25 genes were significant. Only the top 25 genes will be used in barplot"))
      diffResultSig<-tbbselect[order(tbbselect$padj)[1:25],]
    } else {
      diffResultSig<-tbbselect
    }
    if("Feature_gene_name" %in% colnames(diffResultSig)){
      diffResultSig$Name<-as.character(diffResultSig$Feature_gene_name)
    }else{
      diffResultSig$Name<-sapply(strsplit(row.names(diffResultSig),";"),function(x) x[1])
    }
    diffResultSig$Name <- factor(diffResultSig$Name, levels=diffResultSig$Name[order(diffResultSig$log2FoldChange)])
    diffResultSig<-as.data.frame(diffResultSig)
    
    png(filename=paste0(prefix, "_DESeq2_sig_barplot.png"), width=3000, height=3000, res=300)
    #	  pdf(paste0(prefix,"_DESeq2_sig_barplot.pdf"))
    p<-ggplot(diffResultSig,aes(x=Name,y=log2FoldChange,order=log2FoldChange))+geom_bar(stat="identity")+
      coord_flip()+
      #			geom_abline(slope=0,intercept=1,colour="red",linetype = 2)+
      scale_y_continuous(name=bquote(log[2]~Fold~Change))+
      theme(axis.text = element_text(colour = "black"))
    print(p)
    dev.off()
  } else {
    print(paste0("No gene with adjusted p value less than ",pvalue," and fold change larger than ",foldChange))
  }
  
  #volcano plot
  changeColours<-c(grey="grey",blue="blue",red="red")
  diffResult<-as.data.frame(tbb)
  diffResult$log10BaseMean<-log10(diffResult$baseMean)
  diffResult$colour<-"grey"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange>=log2(foldChange))]<-"red"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange<=-log2(foldChange))]<-"blue"
  png(filename=paste0(prefix, "_DESeq2_volcanoPlot.png"), width=3000, height=3000, res=300)
  #  pdf(paste0(prefix,"_DESeq2_volcanoPlot.pdf"))
  p<-ggplot(diffResult,aes(x=log2FoldChange,y=padj))+
    geom_point(aes(size=log10BaseMean,colour=colour))+
    scale_color_manual(values=changeColours,guide = FALSE)+
    scale_y_continuous(trans=reverselog_trans(10),name=bquote(Adjusted~p~value))+
    scale_x_continuous(name=bquote(log[2]~Fold~Change))+
    geom_hline(yintercept = 1,colour="grey",linetype = "dotted")+
    geom_vline(xintercept = 0,colour="grey",linetype = "dotted")+
    guides(size=guide_legend(title=bquote(log[10]~Base~Mean)))+
    theme_bw()+
    scale_size(range = c(3, 7))+
    theme(axis.text = element_text(colour = "black",size=30),
			axis.title = element_text(size=30),
			legend.text= element_text(size=30),
			legend.title= element_text(size=30))
  print(p)
  dev.off()
}

#write a file with all information
write.csv(resultAllOut,paste0(taskName, "_DESeq2.csv"))

if(length(pairedspearman) > 0){
  #draw pca graph
  filename<-ifelse(minMedianInGroup > 0, paste0("spearman_min", minMedianInGroup, ".png"), "spearman.png")
  png(filename=filename, width=1000 * length(pairedspearman), height=2000, res=300)
  boxplot(pairedspearman)
  dev.off()
}

#Venn for all significant genes
allSigNameList<-list()
allSigDirectionList<-list()
for(comparisonName in comparisonNames){
	if (minMedianInGroup > 0) {
		prefix<-paste0(comparisonName, "_min", minMedianInGroup)
	} else {
		prefix<-comparisonName
	}
	sigFile<-paste0(prefix, "_DESeq2_sig.csv")
	if (file.exists(sigFile)) {
		sigTable<-read.csv(sigFile,header=TRUE,as.is=TRUE)
		if (nrow(sigTable)>0) {
			allSigNameList[[comparisonName]]<-sigTable[,1]
			allSigDirectionList[[comparisonName]]<-sign(sigTable$log2FoldChange)
		} else {
			warning(paste0("No significant genes in ",comparisonName))
#		allSigNameList[[comparisonName]]<-""
		}
	}
}

#Do venn if length between 2-5
if (length(allSigNameList)>=2 & length(allSigNameList)<=5) {
	venn.diagram1<-function (x, filename, height = 3000, width = 3000, resolution = 500, 
			units = "px", compression = "lzw", na = "stop", main = NULL, 
			sub = NULL, main.pos = c(0.5, 1.05), main.fontface = "plain", 
			main.fontfamily = "serif", main.col = "black", main.cex = 1, 
			main.just = c(0.5, 1), sub.pos = c(0.5, 1.05), sub.fontface = "plain", 
			sub.fontfamily = "serif", sub.col = "black", sub.cex = 1, 
			sub.just = c(0.5, 1), category.names = names(x), force.unique = TRUE,
			fill=NA,
			...) 
	{
		if (is.na(fill)) {
			if (length(x)==5) {
				fill = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3")
			} else if (length(x)==4) {
				fill = c("dodgerblue", "goldenrod1",  "seagreen3", "orchid3")
			} else if (length(x)==3) {
				fill = c("dodgerblue", "goldenrod1", "seagreen3")
			} else if (length(x)==2) {
				fill = c("dodgerblue", "goldenrod1")
			}
		}
		if (force.unique) {
			for (i in 1:length(x)) {
				x[[i]] <- unique(x[[i]])
			}
		}
		if ("none" == na) {
			x <- x
		}
		else if ("stop" == na) {
			for (i in 1:length(x)) {
				if (any(is.na(x[[i]]))) {
					stop("NAs in dataset", call. = FALSE)
				}
			}
		}
		else if ("remove" == na) {
			for (i in 1:length(x)) {
				x[[i]] <- x[[i]][!is.na(x[[i]])]
			}
		}
		else {
			stop("Invalid na option: valid options are \"none\", \"stop\", and \"remove\"")
		}
		if (0 == length(x) | length(x) > 5) {
			stop("Incorrect number of elements.", call. = FALSE)
		}
		if (1 == length(x)) {
			list.names <- category.names
			if (is.null(list.names)) {
				list.names <- ""
			}
			grob.list <- VennDiagram::draw.single.venn(area = length(x[[1]]), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else if (2 == length(x)) {
			grob.list <- VennDiagram::draw.pairwise.venn(area1 = length(x[[1]]), 
					area2 = length(x[[2]]), cross.area = length(intersect(x[[1]], 
									x[[2]])), category = category.names, ind = FALSE, 
					fill=fill,
					...)
		}
		else if (3 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			list.names <- category.names
			nab <- intersect(A, B)
			nbc <- intersect(B, C)
			nac <- intersect(A, C)
			nabc <- intersect(nab, C)
			grob.list <- VennDiagram::draw.triple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), n12 = length(nab), 
					n23 = length(nbc), n13 = length(nac), n123 = length(nabc), 
					category = list.names, ind = FALSE, list.order = 1:3, 
					fill=fill,
					...)
		}
		else if (4 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n34 <- intersect(C, D)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n134 <- intersect(n13, D)
			n234 <- intersect(n23, D)
			n1234 <- intersect(n123, D)
			grob.list <- VennDiagram::draw.quad.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					n12 = length(n12), n13 = length(n13), n14 = length(n14), 
					n23 = length(n23), n24 = length(n24), n34 = length(n34), 
					n123 = length(n123), n124 = length(n124), n134 = length(n134), 
					n234 = length(n234), n1234 = length(n1234), category = list.names, 
					ind = FALSE, fill=fill,...)
		}
		else if (5 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			E <- x[[5]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n15 <- intersect(A, E)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n25 <- intersect(B, E)
			n34 <- intersect(C, D)
			n35 <- intersect(C, E)
			n45 <- intersect(D, E)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n125 <- intersect(n12, E)
			n134 <- intersect(n13, D)
			n135 <- intersect(n13, E)
			n145 <- intersect(n14, E)
			n234 <- intersect(n23, D)
			n235 <- intersect(n23, E)
			n245 <- intersect(n24, E)
			n345 <- intersect(n34, E)
			n1234 <- intersect(n123, D)
			n1235 <- intersect(n123, E)
			n1245 <- intersect(n124, E)
			n1345 <- intersect(n134, E)
			n2345 <- intersect(n234, E)
			n12345 <- intersect(n1234, E)
			grob.list <- VennDiagram::draw.quintuple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					area5 = length(E), n12 = length(n12), n13 = length(n13), 
					n14 = length(n14), n15 = length(n15), n23 = length(n23), 
					n24 = length(n24), n25 = length(n25), n34 = length(n34), 
					n35 = length(n35), n45 = length(n45), n123 = length(n123), 
					n124 = length(n124), n125 = length(n125), n134 = length(n134), 
					n135 = length(n135), n145 = length(n145), n234 = length(n234), 
					n235 = length(n235), n245 = length(n245), n345 = length(n345), 
					n1234 = length(n1234), n1235 = length(n1235), n1245 = length(n1245), 
					n1345 = length(n1345), n2345 = length(n2345), n12345 = length(n12345), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else {
			stop("Invalid size of input object")
		}
		if (!is.null(sub)) {
			grob.list <- add.title(gList = grob.list, x = sub, pos = sub.pos, 
					fontface = sub.fontface, fontfamily = sub.fontfamily, 
					col = sub.col, cex = sub.cex)
		}
		if (!is.null(main)) {
			grob.list <- add.title(gList = grob.list, x = main, pos = main.pos, 
					fontface = main.fontface, fontfamily = main.fontfamily, 
					col = main.col, cex = main.cex)
		}
		grid.newpage()
		grid.draw(grob.list)
		return(1)
#	return(grob.list)
	}
	png(paste0(taskName,"_significantVenn.png"),res=300,height=2000,width=2000)
	venn.diagram1(allSigNameList)
	dev.off()
}
#Do heatmap significant genes if length larger or equal than 2
if (length(allSigNameList)>=2) {
	temp<-cbind(unlist(allSigNameList),unlist(allSigDirectionList))
	colnames(temp)<-c("Gene","Direction")
	temp<-cbind(temp,comparisonName=rep(names(allSigNameList),sapply(allSigNameList,length)))
	temp<-data.frame(temp)
	dataForFigure<-temp
	#geting dataForFigure order in figure
	temp$Direction<-as.integer(as.character(temp$Direction))
	temp<-acast(temp, Gene~comparisonName ,value.var="Direction")
	temp<-temp[do.call(order, data.frame(temp)),]
	maxNameChr<-max(nchar(row.names(temp)))
	if (maxNameChr>70) {
		row.names(temp)<-substr(row.names(temp),0,70)
		dataForFigure$Gene<-substr(dataForFigure$Gene,0,70)
		warning(paste0("The gene names were too long (",maxNameChr,"). Only first 70 letters were kept."))
	}
	dataForFigure$Gene<-factor(dataForFigure$Gene,levels=row.names(temp))
	
	width=max(2500, 60 * length(unique(dataForFigure$comparisonName)))
	height=max(2000, 40 * length(unique(dataForFigure$Gene)))
	png(paste0(taskName,"_significantHeatmap.png"),res=300,height=height,width=width)
	g<-ggplot(dataForFigure, aes(comparisonName, Gene))+
			geom_tile(aes(fill=Direction), color="white") +
			scale_fill_manual(values=c("light green", "red")) +
			theme(axis.text.x = element_text(angle=90, vjust=0.5, size=11, hjust=0.5, face="bold"),
					axis.text.y = element_text(size=11, face="bold")) +
			coord_equal()
	print(g)
	dev.off()
}


print.data.frame = function (x, ..., digits = NULL, quote = FALSE, right = TRUE,
                             row.names = TRUE)
{
    if (! isTRUE(all.equal(rownames(x), as.character(seq_len(nrow(x))))))
        x = tibble::rownames_to_column(x)
    print(dplyr::tbl_df(x))
}
##predefined_condition_begin
# setwd("h:/temp")  
#   
# data<-read.table("Z:/Shared/Labs/Brown,J/tiger/20160509_brown_3436/star_genetable/result/B3436_gene.count",row.names=1, header=T, check.names=F)
# 
# taskName<-'B3436'
# showLabelInPCA<-1
# showDEGeneCluster<-0
# pvalue<-0.05
# foldChange<-2
# minMedianInGroup<-5
# addCountOne<-0
# 
# comparisons=list(
#   "CAPTISOL_vs_FED" = c("CAPTISOL_vs_FED.design", "FED", "CAPTISOL")
# ) 
#
##predefined_condition_end

library("DESeq2")
library("heatmap3")
library("lattice")
library("reshape")
library("ggplot2")
library("grid")
library("scales")
library("reshape2")
library("VennDiagram")

##Solving node stack overflow problem start###
#when there are too many genes, drawing dendrogram may failed due to node stack overflow,
#It could be solved by forcing stats:::plotNode to be run as interpreted code rather then byte-compiled code via a nasty hack.
#http://stackoverflow.com/questions/16559250/error-in-heatmap-2-gplots/25877485#25877485

# Convert a byte-compiled function to an interpreted-code function 
unByteCode <- function(fun)
{
  FUN <- eval(parse(text=deparse(fun)))
  environment(FUN) <- environment(fun)
  FUN
}

# Replace function definition inside of a locked environment **HACK** 
assignEdgewise <- function(name, env, value)
{
  unlockBinding(name, env=env)
  assign( name, envir=env, value=value)
  lockBinding(name, env=env)
  invisible(value)
}

# Replace byte-compiled function in a locked environment with an interpreted-code
# function
unByteCodeAssign <- function(fun)
{
  name <- gsub('^.*::+','', deparse(substitute(fun)))
  FUN <- unByteCode(fun)
  retval <- assignEdgewise(name=name,
                           env=environment(FUN),
                           value=FUN
  )
  invisible(retval)
}

# Use the above functions to convert stats:::plotNode to interpreted-code:
unByteCodeAssign(stats:::plotNode)

# Now raise the interpreted code recursion limit (you may need to adjust this,
#  decreasing if it uses to much memory, increasing if you get a recursion depth error ).
options(expressions=5e4)

##Solving node stack overflow problem end###

hmcols <- colorRampPalette(c("green", "black", "red"))(256)

drawHCA<-function(prefix, rldselect, ispaired, designData, conditionColors, gnames){
  htfile<-paste0(prefix, "_DESeq2-vsd-heatmap.png")
  cat("saving HCA to ", htfile, "\n")
  genecount<-nrow(rldselect)
  if(genecount > 2){
    png(filename=htfile, width=3000, height =3000, res=300)
    cexCol = max(1.0, 0.2 + 1/log10(ncol(rldselect)))
    if(ispaired){
      htColors<-rainbow(length(unique(designData$Paired)))
      gsColors<-as.matrix(data.frame(Group=conditionColors, Sample=htColors[designData$Paired]))
    }else{
      gsColors = conditionColors;
    }
    heatmap3(rldselect, 
             col = hmcols, 
             ColSideColors = gsColors, 
             margins=c(12,5), 
             scale="r", 
             dist=dist, 
             labRow=NA,
             main=paste0("Hierarchical Cluster Using ", genecount, " Genes"),  
             cexCol=cexCol, 
             useRaster=FALSE,
             legendfun=function() showLegend(legend=paste0("Group ", gnames), col=c("red","blue"),cex=1.0,x="center"))
    dev.off()
  }
}

drawPCA<-function(prefix, rldmatrix, showLabelInPCA, designData, conditionColors){
  #filename<-paste0(prefix, "_DESeq2-vsd-pca.png")
  filename<-paste0(prefix, "_DESeq2-vsd-pca.pdf")
  genecount<-nrow(rldmatrix)
  if(genecount > 2){
    cat("saving PCA to ", filename, "\n")
    #png(filename=filename, width=3000, height=3000, res=300) # 10 X 10 inches
    pdf(filename, width=10, height=10)
    pca<-prcomp(t(rldmatrix))
    supca<-summary(pca)$importance
    pcadata<-data.frame(pca$x)
    pcalabs=paste0(colnames(pcadata), "(", round(supca[2,] * 100), "%)")
    pcadata["sample"]<-row.names(pcadata)
    
    if(showLabelInPCA){
      g <- ggplot(pcadata, aes(x=PC1, y=PC2, label=sample)) + 
        geom_text(vjust=-0.6, size=4) +
        geom_point(col=conditionColors, size=4) + 
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) +
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) + 
        xlab(pcalabs[1]) + ylab(pcalabs[2])
    }else{
      g <- ggplot(pcadata, aes(x=PC1, y=PC2)) + 
        geom_point(col=conditionColors, size=4) + 
        labs(color = "Group") +
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) + 
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) +
        xlab(pcalabs[1]) + ylab(pcalabs[2]) + 
        theme(legend.position="top")
    }
    
    print(g)
    dev.off()
  }
}

#for volcano plot
reverselog_trans <- function(base = exp(1)) {
  trans <- function(x) -log(x, base)
  inv <- function(x) base^(-x)
  trans_new(paste0("reverselog-", format(base)), trans, inv, 
            log_breaks(base = base), 
            domain = c(1e-100, Inf))
}

isDataNumeric = unlist(lapply(data[1,], function(x){is.numeric(x)}))
if (any(isDataNumeric)) {
  index = 1
  while(!all(isDataNumeric[index:ncol(data)])){
    index = index + 1
  }
} else {
  cat("Error: No numeric data found for DESeq2 \n")
  quit(save="yes")
}

if(index > 1){
  indecies<-c(1:(index-1))
}else{
  indecies<-c()
}
countData<-data[,c(index:ncol(data))]

countData[is.na(countData)] <- 0

if(addCountOne){
  countData<-round(countData)+1
}

comparisonNames=names(comparisons)
comparisonName=comparisonNames[1]

dir.create("details", showWarnings = FALSE)

pairedspearman<-list()
resultAllOut<-data
resultAllOutVar<-c("log2FoldChange","pvalue","padj")
for(comparisonName in comparisonNames){
  str(comparisonName)
  designFile=comparisons[[comparisonName]][1]
  gnames=comparisons[[comparisonName]][2:3]
  designData<-read.table(designFile, sep="\t", header=T)
  designData$Condition<-factor(designData$Condition, levels=gnames)
  
  if(ncol(designData) >= 3){
    cat("Data with covariances!\n")
  }else{
    cat("Data without covariances!\n")
  }
  if (any(colnames(designData)=="Paired")) {
	  ispaired<-TRUE
	  cat("Paired Data!\n")
  }else{
	  ispaired<-FALSE
	  cat("Not Paired Data!\n")
  }
  temp<-apply(designData,2,function(x) length(unique(x)))
  if (any(temp==1)) {
	  cat(paste0("Factors with only 1 level in design matrix: ",colnames(designData)[which(temp==1)],"\n"))
	  cat("They will be removed")
	  cat("\n")
	  designData<-designData[,which(temp!=1)]
  }
  temp<-apply(designData[,-1,drop=F],2,rank)
  if (length(unique(rowSums(temp)))==1 | identical(temp[,1],temp[,-1])) {
	  cat(paste0("The model matrix is not full rank, so the model cannot be fit as specified"))
	  cat("\n")
	  cat("Only Condition variable will be kept.")
	  cat("\n")
	  designData<-designData[,which(colnames(designData)%in% c("Sample","Condition"))]
  }
  
  comparisonData<-countData[,colnames(countData) %in% as.character(designData$Sample),drop=F]
  if(ncol(comparisonData) != nrow(designData)){
	message=paste0("Data not matched, there are ", nrow(designData), " samples in design file ", designFile, " but ", ncol(comparisonData), " samples in data ")
	warning(message)
	writeLines(message,paste0(comparisonName,".error"))
	next
  }
  comparisonData<-comparisonData[,as.character(designData$Sample)]
  
  prefix<-comparisonName
  curdata<-data
  if(minMedianInGroup > 0){
    conds<-unique(designData$Condition)
    data1<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[1]]]
    data2<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[2]]]
    med1<-apply(data1, 1, median) >= minMedianInGroup
    med2<-apply(data2, 1, median) >= minMedianInGroup
    med<-med1 | med2
    comparisonData<-comparisonData[med,]
    cat(nrow(comparisonData), " genes with minimum median count in group larger or equals than ", minMedianInGroup, "\n")
    
    if (nrow(comparisonData)==0) {
		message=paste0("Error: 0 Genes can be used in DESeq2 analysis in comparison ",comparisonName," \n")
		warning(message)
		writeLines(message,paste0(comparisonName,".error"))
      next;
    }
    
    prefix<-paste0(comparisonName, "_min", minMedianInGroup)
    curdata<-data[med,]
  }
  
  if(ispaired){
    pairedSamples = unique(designData$Paired)
    
    spcorr<-unlist(lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      cor(comparisonData[,samples[1]],comparisonData[,samples[2]],method="spearman")
    }))
    
    
    sptable<-data.frame(Name=pairedSamples, Spcorr=spcorr)
    write.csv(sptable, file=paste0(prefix, "_Spearman.csv"), row.names=FALSE)
    
    lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      log2c1<-log2(comparisonData[,samples[1]]+1)
      log2c2<-log2(comparisonData[,samples[2]]+1)
      png(paste0("details/", prefix, "_Spearman_", pairedSamples[x], ".png"), width=2000, height=2000, res=300)
      plot(log2c1, log2c2, xlab=paste0(samples[1], " [log2(Count + 1)]"), ylab=paste0(samples[2], " [log2(Count + 1)]"))
      text(3,15,paste0("SpearmanCorr=", sprintf("%0.3f", spcorr[x])))
      dev.off()
    })
    
    pairedspearman[[comparisonName]]<-spcorr
  }
  
  notEmptyData<-apply(comparisonData, 1, max) > 0
  comparisonData<-comparisonData[notEmptyData,]
  curdata<-curdata[notEmptyData,]
  
  if(ispaired){
    colnames(comparisonData)<-unlist(lapply(c(1:ncol(comparisonData)), function(i){paste0(designData$Paired[i], "_", colnames(comparisonData)[i])}))
  }
  rownames(designData)<-colnames(comparisonData)
  conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
  
  write.csv(comparisonData, file=paste0(prefix, ".csv"))
  
  #some basic graph
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                             colData = designData,
                             design = ~1)
  
  colnames(dds)<-colnames(comparisonData)
  
  #draw density graph
  rldmatrix<-as.matrix(log2(counts(dds,normalized=FALSE) + 1))
  rsdata<-melt(rldmatrix)
  colnames(rsdata)<-c("Gene", "Sample", "log2Count")
  png(filename=paste0(prefix, "_DESeq2-log2-density.png"), width=4000, height=3000, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  width=max(4000, ncol(rldmatrix) * 40 + 1000)
  height=max(3000, ncol(rldmatrix) * 40)
  png(filename=paste0(prefix, "_DESeq2-log2-density-individual.png"), width=width, height=height, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + facet_wrap(~Sample, scales = "free") + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  
  #varianceStabilizingTransformation
  
  allDesignData<-designData
  allComparisonData<-comparisonData
  
  excludedSample<-c()
  zeronumbers<-apply(comparisonData, 2, function(x){sum(x==0)})
  zeronumbers<-names(zeronumbers[order(zeronumbers)])
  percent10<-max(1, round(length(zeronumbers) * 0.1))
  
  removed<-0
  
  excludedCountFile<-paste0(prefix, "_DESeq2-exclude-count.csv")
  excludedDesignFile<-paste0(prefix, "_DESeq2-exclude-design.csv")
  if(file.exists(excludedCountFile)){
    file.remove(excludedCountFile)
  }
  if(file.exists(excludedDesignFile)){
    file.remove(excludedDesignFile)
  }
  
  fitType<-"parametric"
  while(1){
    #varianceStabilizingTransformation
    vsdres<-try(vsd <- varianceStabilizingTransformation(dds, blind=TRUE,fitType=fitType))
    if(class(vsdres) == "try-error" && grepl("every gene contains at least one zero", vsdres[1])){
      removed<-removed+1
      keptNumber<-length(zeronumbers) - percent10 * removed
      keptSample<-zeronumbers[1:keptNumber]
      excludedSample<-zeronumbers[(keptNumber+1):length(zeronumbers)]
      
      comparisonData<-comparisonData[, colnames(comparisonData) %in% keptSample]
      designData<-designData[rownames(designData) %in% keptSample,]
      dds=DESeqDataSetFromMatrix(countData = comparisonData,
                                 colData = designData,
                                 design = ~1)
      
      colnames(dds)<-colnames(comparisonData)
    } else if (class(vsdres) == "try-error" && grepl("newsplit: out of vertex space", vsdres[1])) {
		message=paste0("Warning: varianceStabilizingTransformation function can't run. fitType was set to local to try again")
		warning(message)
		fitType<-"mean"
		writeLines(message,paste0(comparisonName,".error"))
	} else{
      conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
      break
    }
  }
  if (nrow(comparisonData)<=1) {
	  message=paste0("Error: All genes in ",comparisonName," has at least one 0 value. Can't do DESeq2.")
	  warning(message)
	  writeLines(message,paste0(comparisonName,".error"))
	  next;
  }
  
  if(length(excludedSample) > 0){
    excludedCountData<-allComparisonData[,colnames(allComparisonData) %in% excludedSample]
    write.csv(file=excludedCountFile, excludedCountData)
    excludedDesignData<-allDesignData[rownames(allDesignData) %in% excludedSample,]
    write.csv(file=excludedDesignFile, excludedDesignData)
  }
  
  assayvsd<-assay(vsd)
  write.csv(assayvsd, file=paste0(prefix, "_DESeq2-vsd.csv"))
  
  vsdiqr<-apply(assayvsd, 1, IQR)
  assayvsd<-assayvsd[order(vsdiqr, decreasing=T),]
  
  rldmatrix=as.matrix(assayvsd)
  
  #draw pca graph
  drawPCA(paste0(prefix,"_geneAll"), rldmatrix, showLabelInPCA, designData, conditionColors)
  
  #draw heatmap
  #drawHCA(paste0(prefix,"_gene500"), rldmatrix[1:min(500, nrow(rldmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  drawHCA(paste0(prefix,"_geneAll"), rldmatrix, ispaired, designData, conditionColors, gnames)
  
  #different expression analysis
  designFormula=as.formula(paste0("~",paste0(c(colnames(designData)[-c(1:2)],"Condition"),collapse="+")))
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                               colData = designData,
                               design = designFormula)
  
  dds <- DESeq(dds,fitType=fitType)
  res<-results(dds,cooksCutoff=FALSE)
  
  cat("DESeq2 finished.\n")
  
  select<-(!is.na(res$padj)) & (res$padj<pvalue) & ((res$log2FoldChange >= log2(foldChange)) | (res$log2FoldChange <= -log2(foldChange)))
  
  if(length(indecies) > 0){
    inddata<-curdata[,indecies,drop=F]
    tbb<-cbind(inddata, comparisonData, res)
  }else{
    tbb<-cbind(comparisonData, res)
  }
  tbb$FoldChange<-2^tbb$log2FoldChange
  tbbselect<-tbb[select,,drop=F]
  tbbAllOut<-as.data.frame(tbb[,resultAllOutVar,drop=F])
  tbbAllOut$Significant<-select
  colnames(tbbAllOut)<-paste0(colnames(tbbAllOut)," (",comparisonName,")")
  resultAllOut<-cbind(resultAllOut,tbbAllOut[row.names(resultAllOut),])

  tbb<-tbb[order(tbb$padj),,drop=F]
  write.csv(as.data.frame(tbb),paste0(prefix, "_DESeq2.csv"))

  if("Feature_gene_name" %in% colnames(tbb)){
    gsea<-tbb[,c("Feature_gene_name", "stat"),drop=F]
    write.table(gsea,paste0(prefix, "_DESeq2_GSEA.rnk"),row.names=F,col.names=F,sep="\t")
  }

  tbbselect<-tbbselect[order(tbbselect$padj),,drop=F]
  write.csv(as.data.frame(tbbselect),paste0(prefix, "_DESeq2_sig.csv"))
  
  if(showDEGeneCluster){
    siggenes<-rownames(rldmatrix) %in% rownames(tbbselect)
    
    nonDEmatrix<-rldmatrix[!siggenes,,drop=F]
    DEmatrix<-rldmatrix[siggenes,,drop=F]
    
    drawPCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, ispaired, designData, conditionColors, gnames)
    
    drawPCA(paste0(prefix,"_geneDE"),DEmatrix , showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneDE"),DEmatrix , ispaired, designData, conditionColors, gnames)
    #drawHCA(paste0(prefix,"_gene500NotDE"), nonDEmatrix[1:min(500, nrow(nonDEmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  }
  
  #Top 25 Significant genes barplot
  sigDiffNumber<-nrow(tbbselect)
  if (sigDiffNumber>0) {
    if (sigDiffNumber>25) {
      print(paste0("More than 25 genes were significant. Only the top 25 genes will be used in barplot"))
      diffResultSig<-tbbselect[order(tbbselect$padj)[1:25],]
    } else {
      diffResultSig<-tbbselect
    }
    if("Feature_gene_name" %in% colnames(diffResultSig)){
      diffResultSig$Name<-as.character(diffResultSig$Feature_gene_name)
    }else{
      diffResultSig$Name<-sapply(strsplit(row.names(diffResultSig),";"),function(x) x[1])
    }
    diffResultSig$Name <- factor(diffResultSig$Name, levels=diffResultSig$Name[order(diffResultSig$log2FoldChange)])
    diffResultSig<-as.data.frame(diffResultSig)
    
    png(filename=paste0(prefix, "_DESeq2_sig_barplot.png"), width=3000, height=3000, res=300)
    #	  pdf(paste0(prefix,"_DESeq2_sig_barplot.pdf"))
    p<-ggplot(diffResultSig,aes(x=Name,y=log2FoldChange,order=log2FoldChange))+geom_bar(stat="identity")+
      coord_flip()+
      #			geom_abline(slope=0,intercept=1,colour="red",linetype = 2)+
      scale_y_continuous(name=bquote(log[2]~Fold~Change))+
      theme(axis.text = element_text(colour = "black"))
    print(p)
    dev.off()
  } else {
    print(paste0("No gene with adjusted p value less than ",pvalue," and fold change larger than ",foldChange))
  }
  
  #volcano plot
  changeColours<-c(grey="grey",blue="blue",red="red")
  diffResult<-as.data.frame(tbb)
  diffResult$log10BaseMean<-log10(diffResult$baseMean)
  diffResult$colour<-"grey"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange>=log2(foldChange))]<-"red"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange<=-log2(foldChange))]<-"blue"
  png(filename=paste0(prefix, "_DESeq2_volcanoPlot.png"), width=3000, height=3000, res=300)
  #  pdf(paste0(prefix,"_DESeq2_volcanoPlot.pdf"))
  p<-ggplot(diffResult,aes(x=log2FoldChange,y=padj))+
    geom_point(aes(size=log10BaseMean,colour=colour))+
    scale_color_manual(values=changeColours,guide = FALSE)+
    scale_y_continuous(trans=reverselog_trans(10),name=bquote(Adjusted~p~value))+
    scale_x_continuous(name=bquote(log[2]~Fold~Change))+
    geom_hline(yintercept = 1,colour="grey",linetype = "dotted")+
    geom_vline(xintercept = 0,colour="grey",linetype = "dotted")+
    guides(size=guide_legend(title=bquote(log[10]~Base~Mean)))+
    theme_bw()+
    scale_size(range = c(3, 7))+
    theme(axis.text = element_text(colour = "black",size=30),
			axis.title = element_text(size=30),
			legend.text= element_text(size=30),
			legend.title= element_text(size=30))
  print(p)
  dev.off()
}

#write a file with all information
write.csv(resultAllOut,paste0(taskName, "_DESeq2.csv"))

if(length(pairedspearman) > 0){
  #draw pca graph
  filename<-ifelse(minMedianInGroup > 0, paste0("spearman_min", minMedianInGroup, ".png"), "spearman.png")
  png(filename=filename, width=1000 * length(pairedspearman), height=2000, res=300)
  boxplot(pairedspearman)
  dev.off()
}

#Venn for all significant genes
allSigNameList<-list()
allSigDirectionList<-list()
for(comparisonName in comparisonNames){
	if (minMedianInGroup > 0) {
		prefix<-paste0(comparisonName, "_min", minMedianInGroup)
	} else {
		prefix<-comparisonName
	}
	sigFile<-paste0(prefix, "_DESeq2_sig.csv")
	if (file.exists(sigFile)) {
		sigTable<-read.csv(sigFile,header=TRUE,as.is=TRUE)
		if (nrow(sigTable)>0) {
			allSigNameList[[comparisonName]]<-sigTable[,1]
			allSigDirectionList[[comparisonName]]<-sign(sigTable$log2FoldChange)
		} else {
			warning(paste0("No significant genes in ",comparisonName))
#		allSigNameList[[comparisonName]]<-""
		}
	}
}

#Do venn if length between 2-5
if (length(allSigNameList)>=2 & length(allSigNameList)<=5) {
	venn.diagram1<-function (x, filename, height = 3000, width = 3000, resolution = 500, 
			units = "px", compression = "lzw", na = "stop", main = NULL, 
			sub = NULL, main.pos = c(0.5, 1.05), main.fontface = "plain", 
			main.fontfamily = "serif", main.col = "black", main.cex = 1, 
			main.just = c(0.5, 1), sub.pos = c(0.5, 1.05), sub.fontface = "plain", 
			sub.fontfamily = "serif", sub.col = "black", sub.cex = 1, 
			sub.just = c(0.5, 1), category.names = names(x), force.unique = TRUE,
			fill=NA,
			...) 
	{
		if (is.na(fill)) {
			if (length(x)==5) {
				fill = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3")
			} else if (length(x)==4) {
				fill = c("dodgerblue", "goldenrod1",  "seagreen3", "orchid3")
			} else if (length(x)==3) {
				fill = c("dodgerblue", "goldenrod1", "seagreen3")
			} else if (length(x)==2) {
				fill = c("dodgerblue", "goldenrod1")
			}
		}
		if (force.unique) {
			for (i in 1:length(x)) {
				x[[i]] <- unique(x[[i]])
			}
		}
		if ("none" == na) {
			x <- x
		}
		else if ("stop" == na) {
			for (i in 1:length(x)) {
				if (any(is.na(x[[i]]))) {
					stop("NAs in dataset", call. = FALSE)
				}
			}
		}
		else if ("remove" == na) {
			for (i in 1:length(x)) {
				x[[i]] <- x[[i]][!is.na(x[[i]])]
			}
		}
		else {
			stop("Invalid na option: valid options are \"none\", \"stop\", and \"remove\"")
		}
		if (0 == length(x) | length(x) > 5) {
			stop("Incorrect number of elements.", call. = FALSE)
		}
		if (1 == length(x)) {
			list.names <- category.names
			if (is.null(list.names)) {
				list.names <- ""
			}
			grob.list <- VennDiagram::draw.single.venn(area = length(x[[1]]), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else if (2 == length(x)) {
			grob.list <- VennDiagram::draw.pairwise.venn(area1 = length(x[[1]]), 
					area2 = length(x[[2]]), cross.area = length(intersect(x[[1]], 
									x[[2]])), category = category.names, ind = FALSE, 
					fill=fill,
					...)
		}
		else if (3 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			list.names <- category.names
			nab <- intersect(A, B)
			nbc <- intersect(B, C)
			nac <- intersect(A, C)
			nabc <- intersect(nab, C)
			grob.list <- VennDiagram::draw.triple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), n12 = length(nab), 
					n23 = length(nbc), n13 = length(nac), n123 = length(nabc), 
					category = list.names, ind = FALSE, list.order = 1:3, 
					fill=fill,
					...)
		}
		else if (4 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n34 <- intersect(C, D)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n134 <- intersect(n13, D)
			n234 <- intersect(n23, D)
			n1234 <- intersect(n123, D)
			grob.list <- VennDiagram::draw.quad.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					n12 = length(n12), n13 = length(n13), n14 = length(n14), 
					n23 = length(n23), n24 = length(n24), n34 = length(n34), 
					n123 = length(n123), n124 = length(n124), n134 = length(n134), 
					n234 = length(n234), n1234 = length(n1234), category = list.names, 
					ind = FALSE, fill=fill,...)
		}
		else if (5 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			E <- x[[5]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n15 <- intersect(A, E)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n25 <- intersect(B, E)
			n34 <- intersect(C, D)
			n35 <- intersect(C, E)
			n45 <- intersect(D, E)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n125 <- intersect(n12, E)
			n134 <- intersect(n13, D)
			n135 <- intersect(n13, E)
			n145 <- intersect(n14, E)
			n234 <- intersect(n23, D)
			n235 <- intersect(n23, E)
			n245 <- intersect(n24, E)
			n345 <- intersect(n34, E)
			n1234 <- intersect(n123, D)
			n1235 <- intersect(n123, E)
			n1245 <- intersect(n124, E)
			n1345 <- intersect(n134, E)
			n2345 <- intersect(n234, E)
			n12345 <- intersect(n1234, E)
			grob.list <- VennDiagram::draw.quintuple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					area5 = length(E), n12 = length(n12), n13 = length(n13), 
					n14 = length(n14), n15 = length(n15), n23 = length(n23), 
					n24 = length(n24), n25 = length(n25), n34 = length(n34), 
					n35 = length(n35), n45 = length(n45), n123 = length(n123), 
					n124 = length(n124), n125 = length(n125), n134 = length(n134), 
					n135 = length(n135), n145 = length(n145), n234 = length(n234), 
					n235 = length(n235), n245 = length(n245), n345 = length(n345), 
					n1234 = length(n1234), n1235 = length(n1235), n1245 = length(n1245), 
					n1345 = length(n1345), n2345 = length(n2345), n12345 = length(n12345), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else {
			stop("Invalid size of input object")
		}
		if (!is.null(sub)) {
			grob.list <- add.title(gList = grob.list, x = sub, pos = sub.pos, 
					fontface = sub.fontface, fontfamily = sub.fontfamily, 
					col = sub.col, cex = sub.cex)
		}
		if (!is.null(main)) {
			grob.list <- add.title(gList = grob.list, x = main, pos = main.pos, 
					fontface = main.fontface, fontfamily = main.fontfamily, 
					col = main.col, cex = main.cex)
		}
		grid.newpage()
		grid.draw(grob.list)
		return(1)
#	return(grob.list)
	}
	png(paste0(taskName,"_significantVenn.png"),res=300,height=2000,width=2000)
	venn.diagram1(allSigNameList)
	dev.off()
}
#Do heatmap significant genes if length larger or equal than 2
if (length(allSigNameList)>=2) {
	temp<-cbind(unlist(allSigNameList),unlist(allSigDirectionList))
	colnames(temp)<-c("Gene","Direction")
	temp<-cbind(temp,comparisonName=rep(names(allSigNameList),sapply(allSigNameList,length)))
	temp<-data.frame(temp)
	dataForFigure<-temp
	#geting dataForFigure order in figure
	temp$Direction<-as.integer(as.character(temp$Direction))
	temp<-acast(temp, Gene~comparisonName ,value.var="Direction")
	temp<-temp[do.call(order, data.frame(temp)),]
	maxNameChr<-max(nchar(row.names(temp)))
	if (maxNameChr>70) {
		row.names(temp)<-substr(row.names(temp),0,70)
		dataForFigure$Gene<-substr(dataForFigure$Gene,0,70)
		warning(paste0("The gene names were too long (",maxNameChr,"). Only first 70 letters were kept."))
	}
	dataForFigure$Gene<-factor(dataForFigure$Gene,levels=row.names(temp))
	
	width=max(2500, 60 * length(unique(dataForFigure$comparisonName)))
	height=max(2000, 40 * length(unique(dataForFigure$Gene)))
	png(paste0(taskName,"_significantHeatmap.png"),res=300,height=height,width=width)
	g<-ggplot(dataForFigure, aes(comparisonName, Gene))+
			geom_tile(aes(fill=Direction), color="white") +
			scale_fill_manual(values=c("light green", "red")) +
			theme(axis.text.x = element_text(angle=90, vjust=0.5, size=11, hjust=0.5, face="bold"),
					axis.text.y = element_text(size=11, face="bold")) +
			coord_equal()
	print(g)
	dev.off()
}


##predefined_condition_begin
# setwd("h:/temp")  
#   
# data<-read.table("Z:/Shared/Labs/Brown,J/tiger/20160509_brown_3436/star_genetable/result/B3436_gene.count",row.names=1, header=T, check.names=F)
# 
# taskName<-'B3436'
# showLabelInPCA<-1
# showDEGeneCluster<-0
# pvalue<-0.05
# foldChange<-2
# minMedianInGroup<-5
# addCountOne<-0
# 
# comparisons=list(
#   "CAPTISOL_vs_FED" = c("CAPTISOL_vs_FED.design", "FED", "CAPTISOL")
# ) 
#
##predefined_condition_end

library("DESeq2")
library("heatmap3")
library("lattice")
library("reshape")
library("ggplot2")
library("grid")
library("scales")
library("reshape2")
library("VennDiagram")

##Solving node stack overflow problem start###
#when there are too many genes, drawing dendrogram may failed due to node stack overflow,
#It could be solved by forcing stats:::plotNode to be run as interpreted code rather then byte-compiled code via a nasty hack.
#http://stackoverflow.com/questions/16559250/error-in-heatmap-2-gplots/25877485#25877485

# Convert a byte-compiled function to an interpreted-code function 
unByteCode <- function(fun)
{
  FUN <- eval(parse(text=deparse(fun)))
  environment(FUN) <- environment(fun)
  FUN
}

# Replace function definition inside of a locked environment **HACK** 
assignEdgewise <- function(name, env, value)
{
  unlockBinding(name, env=env)
  assign( name, envir=env, value=value)
  lockBinding(name, env=env)
  invisible(value)
}

# Replace byte-compiled function in a locked environment with an interpreted-code
# function
unByteCodeAssign <- function(fun)
{
  name <- gsub('^.*::+','', deparse(substitute(fun)))
  FUN <- unByteCode(fun)
  retval <- assignEdgewise(name=name,
                           env=environment(FUN),
                           value=FUN
  )
  invisible(retval)
}

# Use the above functions to convert stats:::plotNode to interpreted-code:
unByteCodeAssign(stats:::plotNode)

# Now raise the interpreted code recursion limit (you may need to adjust this,
#  decreasing if it uses to much memory, increasing if you get a recursion depth error ).
options(expressions=5e4)

##Solving node stack overflow problem end###

hmcols <- colorRampPalette(c("green", "black", "red"))(256)

drawHCA<-function(prefix, rldselect, ispaired, designData, conditionColors, gnames){
  htfile<-paste0(prefix, "_DESeq2-vsd-heatmap.png")
  cat("saving HCA to ", htfile, "\n")
  genecount<-nrow(rldselect)
  if(genecount > 2){
    png(filename=htfile, width=3000, height =3000, res=300)
    cexCol = max(1.0, 0.2 + 1/log10(ncol(rldselect)))
    if(ispaired){
      htColors<-rainbow(length(unique(designData$Paired)))
      gsColors<-as.matrix(data.frame(Group=conditionColors, Sample=htColors[designData$Paired]))
    }else{
      gsColors = conditionColors;
    }
    heatmap3(rldselect, 
             col = hmcols, 
             ColSideColors = gsColors, 
             margins=c(12,5), 
             scale="r", 
             dist=dist, 
             labRow=NA,
             main=paste0("Hierarchical Cluster Using ", genecount, " Genes"),  
             cexCol=cexCol, 
             useRaster=FALSE,
             legendfun=function() showLegend(legend=paste0("Group ", gnames), col=c("red","blue"),cex=1.0,x="center"))
    dev.off()
  }
}

drawPCA<-function(prefix, rldmatrix, showLabelInPCA, designData, conditionColors){
  #filename<-paste0(prefix, "_DESeq2-vsd-pca.png")
  filename<-paste0(prefix, "_DESeq2-vsd-pca.pdf")
  genecount<-nrow(rldmatrix)
  if(genecount > 2){
    cat("saving PCA to ", filename, "\n")
    #png(filename=filename, width=3000, height=3000, res=300) # 10 X 10 inches
    pdf(filename, width=10, height=10)
    pca<-prcomp(t(rldmatrix))
    supca<-summary(pca)$importance
    pcadata<-data.frame(pca$x)
    pcalabs=paste0(colnames(pcadata), "(", round(supca[2,] * 100), "%)")
    pcadata["sample"]<-row.names(pcadata)
    
    if(showLabelInPCA){
      g <- ggplot(pcadata, aes(x=PC1, y=PC2, label=sample)) + 
        geom_text(vjust=-0.6, size=4) +
        geom_point(col=conditionColors, size=4) + 
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) +
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) + 
        xlab(pcalabs[1]) + ylab(pcalabs[2])
    }else{
      g <- ggplot(pcadata, aes(x=PC1, y=PC2)) + 
        geom_point(col=conditionColors, size=4) + 
        labs(color = "Group") +
        scale_x_continuous(limits=c(min(pcadata$PC1) * 1.2,max(pcadata$PC1) * 1.2)) + 
        scale_y_continuous(limits=c(min(pcadata$PC2) * 1.2,max(pcadata$PC2) * 1.2)) + 
        geom_hline(aes(yintercept=0), size=.2) + 
        geom_vline(aes(xintercept=0), size=.2) +
        xlab(pcalabs[1]) + ylab(pcalabs[2]) + 
        theme(legend.position="top")
    }
    
    print(g)
    dev.off()
  }
}

#for volcano plot
reverselog_trans <- function(base = exp(1)) {
  trans <- function(x) -log(x, base)
  inv <- function(x) base^(-x)
  trans_new(paste0("reverselog-", format(base)), trans, inv, 
            log_breaks(base = base), 
            domain = c(1e-100, Inf))
}

isDataNumeric = unlist(lapply(data[1,], function(x){is.numeric(x)}))
if (any(isDataNumeric)) {
  index = 1
  while(!all(isDataNumeric[index:ncol(data)])){
    index = index + 1
  }
} else {
  cat("Error: No numeric data found for DESeq2 \n")
  quit(save="yes")
}

if(index > 1){
  indecies<-c(1:(index-1))
}else{
  indecies<-c()
}
countData<-data[,c(index:ncol(data))]

countData[is.na(countData)] <- 0

if(addCountOne){
  countData<-round(countData)+1
}

comparisonNames=names(comparisons)
comparisonName=comparisonNames[1]

dir.create("details", showWarnings = FALSE)

pairedspearman<-list()
resultAllOut<-data
resultAllOutVar<-c("log2FoldChange","pvalue","padj")
for(comparisonName in comparisonNames){
  str(comparisonName)
  designFile=comparisons[[comparisonName]][1]
  gnames=comparisons[[comparisonName]][2:3]
  designData<-read.table(designFile, sep="\t", header=T)
  designData$Condition<-factor(designData$Condition, levels=gnames)
  
  if(ncol(designData) >= 3){
    cat("Data with covariances!\n")
  }else{
    cat("Data without covariances!\n")
  }
  if (any(colnames(designData)=="Paired")) {
	  ispaired<-TRUE
	  cat("Paired Data!\n")
  }else{
	  ispaired<-FALSE
	  cat("Not Paired Data!\n")
  }
  temp<-apply(designData,2,function(x) length(unique(x)))
  if (any(temp==1)) {
	  cat(paste0("Factors with only 1 level in design matrix: ",colnames(designData)[which(temp==1)],"\n"))
	  cat("They will be removed")
	  cat("\n")
	  designData<-designData[,which(temp!=1)]
  }
  temp<-apply(designData[,-1,drop=F],2,rank)
  if (length(unique(rowSums(temp)))==1 | identical(temp[,1],temp[,-1])) {
	  cat(paste0("The model matrix is not full rank, so the model cannot be fit as specified"))
	  cat("\n")
	  cat("Only Condition variable will be kept.")
	  cat("\n")
	  designData<-designData[,which(colnames(designData)%in% c("Sample","Condition"))]
  }
  
  comparisonData<-countData[,colnames(countData) %in% as.character(designData$Sample),drop=F]
  if(ncol(comparisonData) != nrow(designData)){
	message=paste0("Data not matched, there are ", nrow(designData), " samples in design file ", designFile, " but ", ncol(comparisonData), " samples in data ")
	warning(message)
	writeLines(message,paste0(comparisonName,".error"))
	next
  }
  comparisonData<-comparisonData[,as.character(designData$Sample)]
  
  prefix<-comparisonName
  curdata<-data
  if(minMedianInGroup > 0){
    conds<-unique(designData$Condition)
    data1<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[1]]]
    data2<-comparisonData[, colnames(comparisonData) %in% designData$Sample[designData$Condition==conds[2]]]
    med1<-apply(data1, 1, median) >= minMedianInGroup
    med2<-apply(data2, 1, median) >= minMedianInGroup
    med<-med1 | med2
    comparisonData<-comparisonData[med,]
    cat(nrow(comparisonData), " genes with minimum median count in group larger or equals than ", minMedianInGroup, "\n")
    
    if (nrow(comparisonData)==0) {
		message=paste0("Error: 0 Genes can be used in DESeq2 analysis in comparison ",comparisonName," \n")
		warning(message)
		writeLines(message,paste0(comparisonName,".error"))
      next;
    }
    
    prefix<-paste0(comparisonName, "_min", minMedianInGroup)
    curdata<-data[med,]
  }
  
  if(ispaired){
    pairedSamples = unique(designData$Paired)
    
    spcorr<-unlist(lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      cor(comparisonData[,samples[1]],comparisonData[,samples[2]],method="spearman")
    }))
    
    
    sptable<-data.frame(Name=pairedSamples, Spcorr=spcorr)
    write.csv(sptable, file=paste0(prefix, "_Spearman.csv"), row.names=FALSE)
    
    lapply(c(1:length(pairedSamples)), function(x){
      samples<-designData$Sample[designData$Paired==pairedSamples[x]]
      log2c1<-log2(comparisonData[,samples[1]]+1)
      log2c2<-log2(comparisonData[,samples[2]]+1)
      png(paste0("details/", prefix, "_Spearman_", pairedSamples[x], ".png"), width=2000, height=2000, res=300)
      plot(log2c1, log2c2, xlab=paste0(samples[1], " [log2(Count + 1)]"), ylab=paste0(samples[2], " [log2(Count + 1)]"))
      text(3,15,paste0("SpearmanCorr=", sprintf("%0.3f", spcorr[x])))
      dev.off()
    })
    
    pairedspearman[[comparisonName]]<-spcorr
  }
  
  notEmptyData<-apply(comparisonData, 1, max) > 0
  comparisonData<-comparisonData[notEmptyData,]
  curdata<-curdata[notEmptyData,]
  
  if(ispaired){
    colnames(comparisonData)<-unlist(lapply(c(1:ncol(comparisonData)), function(i){paste0(designData$Paired[i], "_", colnames(comparisonData)[i])}))
  }
  rownames(designData)<-colnames(comparisonData)
  conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
  
  write.csv(comparisonData, file=paste0(prefix, ".csv"))
  
  #some basic graph
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                             colData = designData,
                             design = ~1)
  
  colnames(dds)<-colnames(comparisonData)
  
  #draw density graph
  rldmatrix<-as.matrix(log2(counts(dds,normalized=FALSE) + 1))
  rsdata<-melt(rldmatrix)
  colnames(rsdata)<-c("Gene", "Sample", "log2Count")
  png(filename=paste0(prefix, "_DESeq2-log2-density.png"), width=4000, height=3000, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  width=max(4000, ncol(rldmatrix) * 40 + 1000)
  height=max(3000, ncol(rldmatrix) * 40)
  png(filename=paste0(prefix, "_DESeq2-log2-density-individual.png"), width=width, height=height, res=300)
  g<-ggplot(rsdata) + geom_density(aes(x=log2Count, colour=Sample)) + facet_wrap(~Sample, scales = "free") + xlab("DESeq2 log2 transformed count")
  print(g)
  dev.off()
  
  
  #varianceStabilizingTransformation
  
  allDesignData<-designData
  allComparisonData<-comparisonData
  
  excludedSample<-c()
  zeronumbers<-apply(comparisonData, 2, function(x){sum(x==0)})
  zeronumbers<-names(zeronumbers[order(zeronumbers)])
  percent10<-max(1, round(length(zeronumbers) * 0.1))
  
  removed<-0
  
  excludedCountFile<-paste0(prefix, "_DESeq2-exclude-count.csv")
  excludedDesignFile<-paste0(prefix, "_DESeq2-exclude-design.csv")
  if(file.exists(excludedCountFile)){
    file.remove(excludedCountFile)
  }
  if(file.exists(excludedDesignFile)){
    file.remove(excludedDesignFile)
  }
  
  fitType<-"parametric"
  while(1){
    #varianceStabilizingTransformation
    vsdres<-try(vsd <- varianceStabilizingTransformation(dds, blind=TRUE,fitType=fitType))
    if(class(vsdres) == "try-error" && grepl("every gene contains at least one zero", vsdres[1])){
      removed<-removed+1
      keptNumber<-length(zeronumbers) - percent10 * removed
      keptSample<-zeronumbers[1:keptNumber]
      excludedSample<-zeronumbers[(keptNumber+1):length(zeronumbers)]
      
      comparisonData<-comparisonData[, colnames(comparisonData) %in% keptSample]
      designData<-designData[rownames(designData) %in% keptSample,]
      dds=DESeqDataSetFromMatrix(countData = comparisonData,
                                 colData = designData,
                                 design = ~1)
      
      colnames(dds)<-colnames(comparisonData)
    } else if (class(vsdres) == "try-error" && grepl("newsplit: out of vertex space", vsdres[1])) {
		message=paste0("Warning: varianceStabilizingTransformation function can't run. fitType was set to local to try again")
		warning(message)
		fitType<-"mean"
		writeLines(message,paste0(comparisonName,".error"))
	} else{
      conditionColors<-as.matrix(data.frame(Group=c("red", "blue")[designData$Condition]))
      break
    }
  }
  if (nrow(comparisonData)<=1) {
	  message=paste0("Error: All genes in ",comparisonName," has at least one 0 value. Can't do DESeq2.")
	  warning(message)
	  writeLines(message,paste0(comparisonName,".error"))
	  next;
  }
  
  if(length(excludedSample) > 0){
    excludedCountData<-allComparisonData[,colnames(allComparisonData) %in% excludedSample]
    write.csv(file=excludedCountFile, excludedCountData)
    excludedDesignData<-allDesignData[rownames(allDesignData) %in% excludedSample,]
    write.csv(file=excludedDesignFile, excludedDesignData)
  }
  
  assayvsd<-assay(vsd)
  write.csv(assayvsd, file=paste0(prefix, "_DESeq2-vsd.csv"))
  
  vsdiqr<-apply(assayvsd, 1, IQR)
  assayvsd<-assayvsd[order(vsdiqr, decreasing=T),]
  
  rldmatrix=as.matrix(assayvsd)
  
  #draw pca graph
  drawPCA(paste0(prefix,"_geneAll"), rldmatrix, showLabelInPCA, designData, conditionColors)
  
  #draw heatmap
  #drawHCA(paste0(prefix,"_gene500"), rldmatrix[1:min(500, nrow(rldmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  drawHCA(paste0(prefix,"_geneAll"), rldmatrix, ispaired, designData, conditionColors, gnames)
  
  #different expression analysis
  designFormula=as.formula(paste0("~",paste0(c(colnames(designData)[-c(1:2)],"Condition"),collapse="+")))
  dds=DESeqDataSetFromMatrix(countData = comparisonData,
                               colData = designData,
                               design = designFormula)
  
  dds <- DESeq(dds,fitType=fitType)
  res<-results(dds,cooksCutoff=FALSE)
  
  cat("DESeq2 finished.\n")
  
  select<-(!is.na(res$padj)) & (res$padj<pvalue) & ((res$log2FoldChange >= log2(foldChange)) | (res$log2FoldChange <= -log2(foldChange)))
  
  if(length(indecies) > 0){
    inddata<-curdata[,indecies,drop=F]
    tbb<-cbind(inddata, comparisonData, res)
  }else{
    tbb<-cbind(comparisonData, res)
  }
  tbb$FoldChange<-2^tbb$log2FoldChange
  tbbselect<-tbb[select,,drop=F]
  tbbAllOut<-as.data.frame(tbb[,resultAllOutVar,drop=F])
  tbbAllOut$Significant<-select
  colnames(tbbAllOut)<-paste0(colnames(tbbAllOut)," (",comparisonName,")")
  resultAllOut<-cbind(resultAllOut,tbbAllOut[row.names(resultAllOut),])

  tbb<-tbb[order(tbb$padj),,drop=F]
  write.csv(as.data.frame(tbb),paste0(prefix, "_DESeq2.csv"))
  
  tbbselect<-tbbselect[order(tbbselect$padj),,drop=F]
  write.csv(as.data.frame(tbbselect),paste0(prefix, "_DESeq2_sig.csv"))
  
  if(showDEGeneCluster){
    siggenes<-rownames(rldmatrix) %in% rownames(tbbselect)
    
    nonDEmatrix<-rldmatrix[!siggenes,,drop=F]
    DEmatrix<-rldmatrix[siggenes,,drop=F]
    
    drawPCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneNotDE"), nonDEmatrix, ispaired, designData, conditionColors, gnames)
    
    drawPCA(paste0(prefix,"_geneDE"),DEmatrix , showLabelInPCA, designData, conditionColors)
    drawHCA(paste0(prefix,"_geneDE"),DEmatrix , ispaired, designData, conditionColors, gnames)
    #drawHCA(paste0(prefix,"_gene500NotDE"), nonDEmatrix[1:min(500, nrow(nonDEmatrix)),,drop=F], ispaired, designData, conditionColors, gnames)
  }
  
  #Top 25 Significant genes barplot
  sigDiffNumber<-nrow(tbbselect)
  if (sigDiffNumber>0) {
    if (sigDiffNumber>25) {
      print(paste0("More than 25 genes were significant. Only the top 25 genes will be used in barplot"))
      diffResultSig<-tbbselect[order(tbbselect$padj)[1:25],]
    } else {
      diffResultSig<-tbbselect
    }
    if("Feature_gene_name" %in% colnames(diffResultSig)){
      diffResultSig$Name<-as.character(diffResultSig$Feature_gene_name)
    }else{
      diffResultSig$Name<-sapply(strsplit(row.names(diffResultSig),";"),function(x) x[1])
    }
    diffResultSig$Name <- factor(diffResultSig$Name, levels=diffResultSig$Name[order(diffResultSig$log2FoldChange)])
    diffResultSig<-as.data.frame(diffResultSig)
    
    png(filename=paste0(prefix, "_DESeq2_sig_barplot.png"), width=3000, height=3000, res=300)
    #	  pdf(paste0(prefix,"_DESeq2_sig_barplot.pdf"))
    p<-ggplot(diffResultSig,aes(x=Name,y=log2FoldChange,order=log2FoldChange))+geom_bar(stat="identity")+
      coord_flip()+
      #			geom_abline(slope=0,intercept=1,colour="red",linetype = 2)+
      scale_y_continuous(name=bquote(log[2]~Fold~Change))+
      theme(axis.text = element_text(colour = "black"))
    print(p)
    dev.off()
  } else {
    print(paste0("No gene with adjusted p value less than ",pvalue," and fold change larger than ",foldChange))
  }
  
  #volcano plot
  changeColours<-c(grey="grey",blue="blue",red="red")
  diffResult<-as.data.frame(tbb)
  diffResult$log10BaseMean<-log10(diffResult$baseMean)
  diffResult$colour<-"grey"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange>=log2(foldChange))]<-"red"
  diffResult$colour[which(diffResult$padj<=pvalue & diffResult$log2FoldChange<=-log2(foldChange))]<-"blue"
  png(filename=paste0(prefix, "_DESeq2_volcanoPlot.png"), width=3000, height=3000, res=300)
  #  pdf(paste0(prefix,"_DESeq2_volcanoPlot.pdf"))
  p<-ggplot(diffResult,aes(x=log2FoldChange,y=padj))+
    geom_point(aes(size=log10BaseMean,colour=colour))+
    scale_color_manual(values=changeColours,guide = FALSE)+
    scale_y_continuous(trans=reverselog_trans(10),name=bquote(Adjusted~p~value))+
    scale_x_continuous(name=bquote(log[2]~Fold~Change))+
    geom_hline(yintercept = 1,colour="grey",linetype = "dotted")+
    geom_vline(xintercept = 0,colour="grey",linetype = "dotted")+
    guides(size=guide_legend(title=bquote(log[10]~Base~Mean)))+
    theme_bw()+
    scale_size(range = c(3, 7))+
    theme(axis.text = element_text(colour = "black",size=30),
			axis.title = element_text(size=30),
			legend.text= element_text(size=30),
			legend.title= element_text(size=30))
  print(p)
  dev.off()
}

#write a file with all information
write.csv(resultAllOut,paste0(taskName, "_DESeq2.csv"))

if(length(pairedspearman) > 0){
  #draw pca graph
  filename<-ifelse(minMedianInGroup > 0, paste0("spearman_min", minMedianInGroup, ".png"), "spearman.png")
  png(filename=filename, width=1000 * length(pairedspearman), height=2000, res=300)
  boxplot(pairedspearman)
  dev.off()
}

#Venn for all significant genes
allSigNameList<-list()
allSigDirectionList<-list()
for(comparisonName in comparisonNames){
	if (minMedianInGroup > 0) {
		prefix<-paste0(comparisonName, "_min", minMedianInGroup)
	} else {
		prefix<-comparisonName
	}
	sigFile<-paste0(prefix, "_DESeq2_sig.csv")
	if (file.exists(sigFile)) {
		sigTable<-read.csv(sigFile,header=TRUE,as.is=TRUE)
		if (nrow(sigTable)>0) {
			allSigNameList[[comparisonName]]<-sigTable[,1]
			allSigDirectionList[[comparisonName]]<-sign(sigTable$log2FoldChange)
		} else {
			warning(paste0("No significant genes in ",comparisonName))
#		allSigNameList[[comparisonName]]<-""
		}
	}
}

#Do venn if length between 2-5
if (length(allSigNameList)>=2 & length(allSigNameList)<=5) {
	venn.diagram1<-function (x, filename, height = 3000, width = 3000, resolution = 500, 
			units = "px", compression = "lzw", na = "stop", main = NULL, 
			sub = NULL, main.pos = c(0.5, 1.05), main.fontface = "plain", 
			main.fontfamily = "serif", main.col = "black", main.cex = 1, 
			main.just = c(0.5, 1), sub.pos = c(0.5, 1.05), sub.fontface = "plain", 
			sub.fontfamily = "serif", sub.col = "black", sub.cex = 1, 
			sub.just = c(0.5, 1), category.names = names(x), force.unique = TRUE,
			fill=NA,
			...) 
	{
		if (is.na(fill)) {
			if (length(x)==5) {
				fill = c("dodgerblue", "goldenrod1", "darkorange1", "seagreen3", "orchid3")
			} else if (length(x)==4) {
				fill = c("dodgerblue", "goldenrod1",  "seagreen3", "orchid3")
			} else if (length(x)==3) {
				fill = c("dodgerblue", "goldenrod1", "seagreen3")
			} else if (length(x)==2) {
				fill = c("dodgerblue", "goldenrod1")
			}
		}
		if (force.unique) {
			for (i in 1:length(x)) {
				x[[i]] <- unique(x[[i]])
			}
		}
		if ("none" == na) {
			x <- x
		}
		else if ("stop" == na) {
			for (i in 1:length(x)) {
				if (any(is.na(x[[i]]))) {
					stop("NAs in dataset", call. = FALSE)
				}
			}
		}
		else if ("remove" == na) {
			for (i in 1:length(x)) {
				x[[i]] <- x[[i]][!is.na(x[[i]])]
			}
		}
		else {
			stop("Invalid na option: valid options are \"none\", \"stop\", and \"remove\"")
		}
		if (0 == length(x) | length(x) > 5) {
			stop("Incorrect number of elements.", call. = FALSE)
		}
		if (1 == length(x)) {
			list.names <- category.names
			if (is.null(list.names)) {
				list.names <- ""
			}
			grob.list <- VennDiagram::draw.single.venn(area = length(x[[1]]), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else if (2 == length(x)) {
			grob.list <- VennDiagram::draw.pairwise.venn(area1 = length(x[[1]]), 
					area2 = length(x[[2]]), cross.area = length(intersect(x[[1]], 
									x[[2]])), category = category.names, ind = FALSE, 
					fill=fill,
					...)
		}
		else if (3 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			list.names <- category.names
			nab <- intersect(A, B)
			nbc <- intersect(B, C)
			nac <- intersect(A, C)
			nabc <- intersect(nab, C)
			grob.list <- VennDiagram::draw.triple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), n12 = length(nab), 
					n23 = length(nbc), n13 = length(nac), n123 = length(nabc), 
					category = list.names, ind = FALSE, list.order = 1:3, 
					fill=fill,
					...)
		}
		else if (4 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n34 <- intersect(C, D)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n134 <- intersect(n13, D)
			n234 <- intersect(n23, D)
			n1234 <- intersect(n123, D)
			grob.list <- VennDiagram::draw.quad.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					n12 = length(n12), n13 = length(n13), n14 = length(n14), 
					n23 = length(n23), n24 = length(n24), n34 = length(n34), 
					n123 = length(n123), n124 = length(n124), n134 = length(n134), 
					n234 = length(n234), n1234 = length(n1234), category = list.names, 
					ind = FALSE, fill=fill,...)
		}
		else if (5 == length(x)) {
			A <- x[[1]]
			B <- x[[2]]
			C <- x[[3]]
			D <- x[[4]]
			E <- x[[5]]
			list.names <- category.names
			n12 <- intersect(A, B)
			n13 <- intersect(A, C)
			n14 <- intersect(A, D)
			n15 <- intersect(A, E)
			n23 <- intersect(B, C)
			n24 <- intersect(B, D)
			n25 <- intersect(B, E)
			n34 <- intersect(C, D)
			n35 <- intersect(C, E)
			n45 <- intersect(D, E)
			n123 <- intersect(n12, C)
			n124 <- intersect(n12, D)
			n125 <- intersect(n12, E)
			n134 <- intersect(n13, D)
			n135 <- intersect(n13, E)
			n145 <- intersect(n14, E)
			n234 <- intersect(n23, D)
			n235 <- intersect(n23, E)
			n245 <- intersect(n24, E)
			n345 <- intersect(n34, E)
			n1234 <- intersect(n123, D)
			n1235 <- intersect(n123, E)
			n1245 <- intersect(n124, E)
			n1345 <- intersect(n134, E)
			n2345 <- intersect(n234, E)
			n12345 <- intersect(n1234, E)
			grob.list <- VennDiagram::draw.quintuple.venn(area1 = length(A), 
					area2 = length(B), area3 = length(C), area4 = length(D), 
					area5 = length(E), n12 = length(n12), n13 = length(n13), 
					n14 = length(n14), n15 = length(n15), n23 = length(n23), 
					n24 = length(n24), n25 = length(n25), n34 = length(n34), 
					n35 = length(n35), n45 = length(n45), n123 = length(n123), 
					n124 = length(n124), n125 = length(n125), n134 = length(n134), 
					n135 = length(n135), n145 = length(n145), n234 = length(n234), 
					n235 = length(n235), n245 = length(n245), n345 = length(n345), 
					n1234 = length(n1234), n1235 = length(n1235), n1245 = length(n1245), 
					n1345 = length(n1345), n2345 = length(n2345), n12345 = length(n12345), 
					category = list.names, ind = FALSE,fill=fill, ...)
		}
		else {
			stop("Invalid size of input object")
		}
		if (!is.null(sub)) {
			grob.list <- add.title(gList = grob.list, x = sub, pos = sub.pos, 
					fontface = sub.fontface, fontfamily = sub.fontfamily, 
					col = sub.col, cex = sub.cex)
		}
		if (!is.null(main)) {
			grob.list <- add.title(gList = grob.list, x = main, pos = main.pos, 
					fontface = main.fontface, fontfamily = main.fontfamily, 
					col = main.col, cex = main.cex)
		}
		grid.newpage()
		grid.draw(grob.list)
		return(1)
#	return(grob.list)
	}
	png(paste0(taskName,"_significantVenn.png"),res=300,height=2000,width=2000)
	venn.diagram1(allSigNameList)
	dev.off()
}
#Do heatmap significant genes if length larger or equal than 2
if (length(allSigNameList)>=2) {
	temp<-cbind(unlist(allSigNameList),unlist(allSigDirectionList))
	colnames(temp)<-c("Gene","Direction")
	temp<-cbind(temp,comparisonName=rep(names(allSigNameList),sapply(allSigNameList,length)))
	temp<-data.frame(temp)
	dataForFigure<-temp
	#geting dataForFigure order in figure
	temp$Direction<-as.integer(as.character(temp$Direction))
	temp<-acast(temp, Gene~comparisonName ,value.var="Direction")
	temp<-temp[do.call(order, data.frame(temp)),]
	maxNameChr<-max(nchar(row.names(temp)))
	if (maxNameChr>70) {
		row.names(temp)<-substr(row.names(temp),0,70)
		dataForFigure$Gene<-substr(dataForFigure$Gene,0,70)
		warning(paste0("The gene names were too long (",maxNameChr,"). Only first 70 letters were kept."))
	}
	dataForFigure$Gene<-factor(dataForFigure$Gene,levels=row.names(temp))
	
	width=max(2500, 60 * length(unique(dataForFigure$comparisonName)))
	height=max(2000, 40 * length(unique(dataForFigure$Gene)))
	png(paste0(taskName,"_significantHeatmap.png"),res=300,height=height,width=width)
	g<-ggplot(dataForFigure, aes(comparisonName, Gene))+
			geom_tile(aes(fill=Direction), color="white") +
			scale_fill_manual(values=c("light green", "red")) +
			theme(axis.text.x = element_text(angle=90, vjust=0.5, size=11, hjust=0.5, face="bold"),
					axis.text.y = element_text(size=11, face="bold")) +
			coord_equal()
	print(g)
	dev.off()
}


                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]
    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
    }
    for (i in 1:max) {
        id <- list11$id[i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), list2[[id]], list11$id[[i]]))
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        dev.new()
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        dev.new()
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, periodtext, maindate, olddate, days) {
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (period == pricetype) {
        return (df$price)
    }
    if (period == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    ls <- list()
    names <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        dayset <- bigretl[[2]]
                        daynames <- names(dayset)
                        olddate <- min(daynames)
                        newdate <- max(daynames)
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        names[c] <- df$name
                    }
                }
            }
        }
    }
    displaychart(ls, names, 5, periodtext, newdate, olddate, days)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

allstocks <- getstocks()
allmetas <- getmetas()

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

#' Print a bp length nicely
#' 
#' \code{prettybp} returns a string representation of a base pair length with optional rounding
#' 
#' @param n base pairs
#' @param round.digits (optional) number of digits to round to. Default is 2. Set
#' to NULL to disable rounding. This value is ignored if signif.digits is not \code{NULL}.
#' @param signif.digits (optional) set this if rounding to significant digits
#' is preferred.
#' @param space Set to false to eliminate the space between the number and unit.
#' @seealso \code{\link{draw.chrom.axis}} for drawing a bp scaled x-axis 
#' @export
prettybp <- function (n, round.digits=2, signif.digits=NULL, space=TRUE) {
  if ( space ) {
    use.sep <- ' '
  } else {
    use.sep <- ''
  }
  if ( log10(mean(n)) >= 6 ) {
    if ( !is.null(signif.digits) ) {
      return ( paste(signif(n/1e6, signif.digits), 'Mb', sep=use.sep))
    } else if ( !is.null(round.digits) ) {
      return ( paste(round(n/1e6, round.digits), 'Mb', sep=use.sep))
    }
    return ( paste(n/1e6, 'Mb', sep=use.sep))
  } else if ( log10(n) >= 3) {
    if ( !is.null(signif.digits) ) {
      return ( paste(signif(n/1e3, signif.digits), 'kb', sep=use.sep))
    } else if ( !is.null(round.digits) ) {
      return ( paste(round(n/1e3, round.digits), 'kb', sep=use.sep))
    }
    return ( paste(n/1e3, 'kb', sep=use.sep))
  }
  if ( !is.null(signif.digits) ) {
    return ( paste(signif(n, signif.digits), 'bp', sep=use.sep))
  } else if ( !is.null(round.digits) ) {
    return ( paste(round(n, round.digits), 'bp', sep=use.sep))
  }
  return ( paste(n, 'bp', sep=use.sep) )
}

#' Draw a horizontal chromosome axis
#' 
#' \code{draw.chrom.axis} draws a chromosome axis with appropriate scale (Mb, kb, or bp).
#' 
#' @param start.pos Starting position on the chromosome (in bp)
#' @param end.pos Ending position on the chromosome (in bp)
#' @param ... (optional) addition options to pass to \code{text} for drawing
#' labels
#' @seealso \code{\link{draw.scale}} for drawing a color scale bar
#' @export
draw.chrom.axis <- function(start.pos, end.pos, chrom=NULL, label.chrom=TRUE,
                            label.scale=TRUE, tick.length=0.1, ...) {
  plot(0, type='n', ylim=c(-1, 1), xlim=c(start.pos, end.pos),
       axes=FALSE, bty='n', xlab='', ylab='', yaxs='i')
  
  abline(h=0, xpd=FALSE)
  
  ticks.at <- axTicks(1)
  plot.height <- par('pin')[2]
  sapply(ticks.at, function (x) { lines(c(x, x), c(-tick.length, tick.length)/plot.height)})
  text(ticks.at, rep(0, length(ticks.at)), ticks.at/1e6, pos=1, xpd=NA, ...)
  if ( label.scale ) {
    text(par('usr')[2], 0, 'Mb', pos=4, xpd=NA, ...)
  }
  if ( !is.null(chrom) && label.chrom ) {
    text(par('usr')[1], 0, chrom, pos=2, xpd=NA, ...)
  }
}


#' Assign colors to value according to a scale
#' 
#' \code{draw.scale} takes a vector of values, a color vector, and a range
#' vector and returns colors for plotting those values
#' 
#' 
#' @param x values to be plotted
#' @param scale.colors a vector of colors
#' @param scale.range range for scale (vector with 2 numeric elements)
#' @param all.inside If TRUE, out-of-range points are colored with the ends of
#' the color scale. If FALSE, they will be assigned no color (NA). 
#' @seealso \code{\link{draw.scale}} for drawing a color scale
#' @export
assign.scale.colors <- function(x, scale.colors, scale.range, all.inside=TRUE) {
  x.missing <- is.na(x)
  
  x[x.missing] <- mean(x, na.rm=TRUE)
  
  if ( missing(scale.range) ) scale.range <- range(x)
  xbins <- seq(min(scale.range), max(scale.range), length.out=length(scale.colors)+1)
  color.idx <- findInterval(x, xbins, rightmost.closed=TRUE, all.inside=all.inside)
  if ( scale.range[1] > scale.range[2] )
    color.idx <- 1+length(scale.colors)-color.idx
  
  
  x.colors <- scale.colors[color.idx]
  x.colors[x.missing | color.idx == 0 | color.idx > length(scale.colors)] <- NA
  return ( x.colors )
}




#' Draw a color scale bar
#' 
#' Adds a color scale legend to the current plot with specified colors and range.
#' 
#' 
#' @param scale.colors a vector of colors
#' @param scale.range range for scale (vector with 2 numeric elements, e.g. as returned by \code{range()})
#' @param num.labs (default 6) number of text labels to draw
#' @param pos (default topright)position for scale, either a keyword such as "top", "topleft" or a numeric vector length 2
#' @param adj controls the anchoring of the scale in respect to \code{pos}
#' @param horiz  TRUE for horizontal (default) or FALSE for vertical bar
#' @param outside TRUE to display legend within the plotting area (default) or FALSE to place it outside
#' @param size approximate length in inches
#' @param ratio ratio of scale bar width to height
#' @param tick.length number between 0 and 1, controls how long the ticks are vs the color boxes. 
#' @param scale.offset inset (outset) amount for legend that is inside (outside)
#' @param label.offset spacing between ticks and text labels
#' @param box this controls whether a black border is drawn around the colors or not.
#' @param x.shift (optional) adjust x position in units of scale width.
#' @param y.shift (optional) adjust y position in units of scale height.
#' 
#' @details This function draws a color scale bar in the current plot. Position argument
#' \code{pos} can be specified by keyword: \code{'center'}, \code{'middle'},
#' \code{'topleft'}, \code{'topright'}, \code{'top'}, \code{'bottomleft'},
#' \code{'bottomright'}, \code{'bottom'}, \code{'left'}, or \code{'right'}.
#' Alternately \code{pos} can be set by specifying a numeric vector of length 2,
#' describing the x and y locations of legend, where each is a number between 0
#' (left/bottom) and 1 (right/top). The \code{adj} argument controls the anchor
#' point for the legend itself relative to the plot. If unspecified, it will
#' match \code{pos}, if \code{outside} is \code{FALSE} (default) or \code{1-pos}
#' if \code{outside} is \code{TRUE}. This alignment is offset by \code{scale.offset}
#' so that the legend does not overlap the plot border.
#' 
#' The position can be further tweaked using the \code{x.shift} and \code{y.shift}
#' arguments. 1 will shift the legend right/up by 1 scale width/height.
#' 
#' The size and shape of the color legend are controlled by \code{size}, which
#' is the approximate length of the longer dimension in inches, and \code{ratio},
#' which is the ratio between width and height (or vice versa for vertical scale bars)
#' and should generally be > 1.
#' 
#' There are several arguments that control how the legend is drawn. The
#' \code{tick.length} (between 0 and 1) argument controls how much of the shorter
#' dimension of the legend is taken up by the color scale vs the ticks. \code{label.offset}
#' controls the spacing between the ticks and the text labels. Parameters to modify
#' text size should be set via \code{par()} prior to calling this function. Setting
#' \code{box = FALSE} will remove the black outline around the colors.
#' 
#' 
#' @seealso \code{\link{draw.chrom.axis}} for drawing x-axis 
#' @examples
#' plot(1:5, 1:5, col=gray(0:4/5), pch=15)
#' # Place a horizontal scale bar a the top, inside the plot.
#' draw.scale(gray(0:4/5), c(0, 1), pos='top')
#' # Place a vertical scale bar to the right, outside the plot.
#' draw.scale(gray(0:4/5), c(76.1, 76.92), pos='right', horiz=FALSE, outside=TRUE)
#' # Place a horizontal  scale bar at the top left, outside the plot, but
#' aligned with the left edge of the plot
#' draw.scale(gray(0:4/5), c(1, 10), pos='topleft', adj=c(0, 0), outside=TRUE)
#' @export
draw.scale <- function(scale.colors, scale.range, num.labs=min(length(scale.colors)+1, 6),
                       pos='topleft', adj=NULL, horiz=TRUE,
                       outside=FALSE, size=2, ratio=12, tick.length=0.25,
                       scale.offset=0.5, label.offset=0.1,
                       box=TRUE, x.shift=0, y.shift=0) {
  
  
  if ( outside ) {
    old.par <- par(xpd=NA)
  }
  
  # recognized keywords and corresponding positions
  pos.key <- list()
  pos.key$middle <- c(0.5, 0.5)
  pos.key$center <- c(0.5, 0.5)
  pos.key$topleft <- c(0, 1)
  pos.key$topright <- c(1, 1)
  pos.key$top <- c(0.5, 1)
  pos.key$bottomleft <- c(0, 0)
  pos.key$bottomright <- c(1, 0)
  pos.key$bottom <- c(0.5, 0)
  pos.key$left <- c(0, 0.5)
  pos.key$right <- c(1, 0.5)
  pos.key <- data.frame(pos.key, row.names=c('x', 'y'))
  
  if ( is.character(pos) ) pos <- tolower(pos)
  if ( is.character(pos) && length(pos)==1 && pos %in% names(pos.key) ) {
    pos <- pos.key[[pos]]
  }
  
  if ( !is.numeric(pos) || length(pos) != 2) {
    warning('Invalid pos Please specify a keyword or xy pair.')
    pos <- c(0, 1)
  }
  
  # If adj is not specified it is the same as pos for inside
  # opposite for outside
  if ( is.null(adj) ) {
    if ( outside )
      adj <- 1-pos
    else
      adj <- pos
  }
  
  par.usr <- par('usr')
  par.pin <- par('pin')
  
  plot.width <- par.usr[2]-par.usr[1]
  plot.height <- par.usr[4]-par.usr[3]
  
  # Calculate dimensions of scale legend
  if ( horiz ) {
    legend.width <- plot.width/par.pin[1]*size
    legend.height <- plot.height/par.pin[2]*size/ratio
  } else {
    legend.height <- plot.height/par.pin[2]*size
    legend.width <- plot.width/par.pin[1]*size/ratio
  }
  
  x1 <- par.usr[1]+pos[1]*plot.width-adj[1]*legend.width
  y1 <- par.usr[3]+pos[2]*plot.height-adj[2]*legend.height
  
  # Apply scale.offset
  if ( horiz ) {
    y1 <- y1-scale.offset*legend.height*2*(adj[2]-0.5)
    x1 <- x1-scale.offset*legend.height*plot.width/plot.height*2*(adj[1]-0.5)
  } else {
    x1 <- x1-scale.offset*legend.width*2*(adj[1]-0.5)
    y1 <- y1-scale.offset*legend.width*plot.height/plot.width*2*(adj[2]-0.5)
  }
  x2 <- x1+legend.width
  y2 <- y1+legend.height
  
  # Flip depending on orientation
  if ( horiz & adj[2] > 0.5 ) {
    tm <- y1
    y1 <- y2
    y2 <- tm
  } else if ( !horiz & adj[1] > 0.5 ) {
    tm <- x1
    x1 <- x2
    x2 <- tm
  }
  #     points(x1, y1, pch=8, col='red')
  #     rect(x1, y1, x2, y2, col='#ff6633')
  
  if ( !missing(x.shift) ) {
    x1 <- x1 + x.shift*legend.width
    x2 <- x2 + x.shift*legend.width
  }
  if ( !missing(y.shift) ) {
    y1 <- y1 + y.shift*legend.height
    y2 <- y2 + y.shift*legend.height
  }
  
  if ( horiz ) {
    x.points <- seq(x1, x2, length.out=length(scale.colors)+1)
    y.mid <- y1*tick.length+y2*(1-tick.length)
    y.text <- y2+label.offset*(y2-y1)
    # draw ticks
    x.ticks <- seq(x1, x2, length.out=num.labs)
    segments(x.ticks, rep(y1, num.labs), x.ticks, rep(y2, num.labs))
    # draw colored boxes
    sapply(1:length(scale.colors), function (i) {
      rect(x.points[i], y1, x.points[i+1], y.mid, border=scale.colors[i], col=scale.colors[i])
    })
    if ( box ) rect(x1, y1, x2, y.mid)
  } else {
    y.points <- seq(y1, y2, length.out=length(scale.colors)+1)
    x.mid <- x1*tick.length+x2*(1-tick.length)
    x.text <- x2+label.offset*(x2-x1)
    # draw ticks
    y.ticks <- seq(y1, y2, length.out=num.labs)
    segments(rep(x1, num.labs), y.ticks, rep(x2, num.labs), y.ticks)
    # draw colored boxes
    sapply(1:length(scale.colors), function (i) {
      rect(x1, y.points[i], x.mid, y.points[i+1], border=scale.colors[i], col=scale.colors[i])
    })
    if ( box ) rect(x1, y1, x.mid, y2, border='#000000')
  }
  
  
  tick.labels <- seq(scale.range[1], scale.range[2], length.out=num.labs)
  sigdig <- 0
  while ( length(unique(round(tick.labels, sigdig))) < length(tick.labels) ) sigdig <- sigdig + 1
  if ( horiz ) {
    text(x.ticks, rep(y.text, num.labs), format(round(tick.labels, sigdig)),
         adj=c(0.5, round(adj[2])))
  } else {
    text(rep(x.text, num.labs), y.ticks, format(round(tick.labels, sigdig)),
         adj=c(round(adj[1]), 0.5)) 
  }
  
  if ( outside ) {
    par(old.par)
  }
}



#' Draw a color scale bar (old version)
#' 
#' \code{draw.old.scale} adds a color scale to the corner of the current plot
#' with specified colors and range
#' 
#' 
#' Currently only a horizontal scale bar is supported. To adjust position in
#' plot coordinates use x.offset and y.offset. To adjust relative position use
#' x.shift and y.shift.
#' 
#' Keep in mind that if you shift the scale bar away from the plotting area
#' (i.e. into the margins), you may need to specify the additional parameter
#' xpd=NA which will be passed to the plotting commands and allows drawing
#' in the margins.
#' 
#' @param scale.colors a vector of colors
#' @param scale.range range for scale (vector with 2 numeric elements)
#' @param num.labs (optional) number of labels to draw
#' @param position (optional) either 'topleft' 'topright' 'bottomleft' or
#' 'bottomright'
#' @param size (optional) approximate length in inches
#' @param width.to.height (optional) ratio of scale bar width to height
#' @param x.offset (optional) adjust x position (uses \code{par('usr')} scale).
#' @param y.offset (optional) adjust y position (uses \code{par('usr')} scale).
#' @param x.shift (optional) adjust x position in units of scale width.
#' @param y.shift (optional) adjust y position in units of scale height.
#' @param ... (optional) addition options to pass to plotting commands for
#' drawing labels, lines and shapes
#' 
#' @seealso \code{\link{draw.chrom.axis}} for drawing x-axis 
#' @export
draw.old.scale <- function(scale.colors, scale.range, num.labs=6,
                           position='topleft', size=3, width.to.height=20,
                           x.offset, y.offset, x.shift, y.shift, ...) {
  par.usr <- par('usr')
  par.pin <- par('pin')
  
  if ( substr(position, 1, 3) == 'top' ) {
    y1 <- par.usr[4]
    y2 <- par.usr[4] - (par.usr[4]-par.usr[3])/(par.pin[2])*size/width.to.height
    top <- TRUE
  } else {
    y1 <- par.usr[3]
    y2 <- par.usr[3] + (par.usr[4]-par.usr[3])/(par.pin[2])*size/width.to.height
    top <- FALSE
  }
  
  if ( substr(position, 7-3*top, 11-3*top) == 'left' ) {
    x1 <- par.usr[1]
    x2 <- par.usr[1] + (par.usr[2]-par.usr[1])/(par.pin[1])*size
  } else {
    x2 <- par.usr[2]
    x1 <- par.usr[2] - (par.usr[2]-par.usr[1])/(par.pin[1])*size
  }
  
  if ( missing(x.offset) ) x.offset <- 0
  if ( missing(y.offset) ) y.offset <- 0
  
  if ( !missing(x.shift) ) {
    x.offset <- x.offset + x.shift*(x2-x1)
  }
  
  if ( !missing(y.shift) ) {
    y.offset <- y.offset + y.shift*(y2-y1)
  }
  
  y1 <- y1 + y.offset
  y2 <- y2 + y.offset
  x1 <- x1 + x.offset
  x2 <- x2 + x.offset
  
  x.points <- seq(x1+(x2-x1)*0.1, x1+(x2-x1)*0.9, length.out=length(scale.colors)+1)
  y.mid <- y1+(y2-y1)/2
  
  
  
  x.ticks <- seq(x1+(x2-x1)*0.1, x1+(x2-x1)*0.9, length.out=num.labs)
  arrows(x.ticks, rep(y1, num.labs), x.ticks, rep(y2, num.labs), length=0, ...)
  
  if ( substr(position, 1, 3) == 'top' ) {
    label.pos = 1
  } else {
    label.pos = 3
  }
  
  sapply(1:length(scale.colors), function (i) {
    x1 <- x.points[i]
    x2 <- x.points[i+1]
    polygon(c(x1, x1, x2, x2), c(y1, y.mid, y.mid, y1), border=scale.colors[i], col=scale.colors[i], ...)
  })
  
  
  tick.labels <- seq(scale.range[1], scale.range[2], length.out=num.labs)
  sigdig <- 1
  while ( length(unique(signif(tick.labels, sigdig))) < length(tick.labels) ) sigdig <- sigdig + 1
  
  text(x.ticks, rep(y2, num.labs), signif(tick.labels, sigdig),
       pos=label.pos, offset=0.25, ...)
  
}

#' @export
center.out.order <- function(n) {
  if ( n <= 2 )
    return (1:n)
  if ( n %% 2 == 1 ) {
    odd <- seq(1, n, 2)
    even <- seq((n-1), 2, -2)
  } else {
    odd <- seq(1, (n-1), 2)
    even <- seq(n, 2, -2)
  }
  return ( order(c(even, odd)) )
}

#' Calculate a range with margins (padding)
#' 
#' @export
mrange <- function(x, m=0.1) {
  if ( length(x) < 2 || length(unique(x)) < 2 ) {
    warning('expected x with at least 2 unique values.\n')
    return ( x )
  }
  if ( length(x) > 2 ) {
    x <- range(x)
  }
  
  dx <- diff(x)
  x[1] <- x[1] - m*dx
  x[2] <- x[2] + m*dx
  
  return ( x )
}


#' Calculate offsets for plotting y ~ x scatter plots where y is continuous and x is categorical
#' 
#' 
#' @examples
#' rx <- ceiling(runif(250, 0, 5))
#' ry <- rnorm(250, 0, 100)+runif(5, 0, 2000)[rx]
#' offset <- splitter(ry, rx)
#' plot(offset+as.numeric(rx), ry, pch=20, col=rainbow(5)[rx])
#' @export
#' @export
splitter <- function (y, x=NULL, rad=.025, scale=TRUE) {
  zx <- rep(0, length(y))
  if ( length(y) < 2 ) return (zx)
  
  if ( !is.null(x) ) {
    if ( length(unique(x)) > length(x)/2 ) warning('x does not appear to be categorical')
    
    
    if ( scale )
      z <- (y-min(y))/diff(range(y))
    
    subs <- tapply(z, x, splitter, rad=rad, scale=FALSE, simplify=FALSE)
    subidx <- tapply(1:length(y), x)
    
    for ( s in 1:length(subs) ) {
      zx[subidx==s] <- subs[[s]]*length(subs)/2
    }
    return (zx)
  }
  
  y.order <- order(y)
  z <- y[y.order]
  if ( scale )
    z <- (z-min(z))/diff(range(z))
  
  for  ( i in 2:length(z) ) {
    
    dz <- z[i]-z[1:(i-1)]
    if ( any(dz < rad) ) {
      nbs <- (1:(i-1))[dz < rad]
      nbd <- sqrt((z[nbs]-z[i])^2+(zx[nbs]-zx[i])^2)
      if ( any(nbd < rad) ) {
        dz <- z[i]-z[nbs]
        ax <- sin(acos(dz/rad))*rad*1.01
        if ( mean(zx[nbs]) < 0 )
          nbx <- zx[nbs]+ax
        else
          nbx <-  zx[nbs]-ax
        
        for ( j in order(abs(nbx)) ) {
          zx[i] <- nbx[j]
          nbd <- sqrt((z[nbs]-z[i])^2+(zx[nbs]-zx[i])^2)
          if ( all(nbd >= rad) ) {
            break
          }
        }
        
        if ( any(nbd < rad) )
          cat('!')
        
      }
      
      
      zx[1:i] <- zx[1:i]-mean(zx[1:i])
    }
  }
  zx[y.order] <- zx
  return (zx)
}















#' Integer data binning
#' 
#' Sometimes with integer data which is not uniformly distributed, a linear
#' color scale is not ideal. The function \code{bin.ints} converts an integer
#' vector into a factor vector where each level corresponds to a range of
#' integers and the elements of x are evenly distributed (as much as possible)
#' across the factor levels.
#' 
#' This is a convenience function that makesuse of \code{find.bins} and
#' \code{label.bins}.
#' 
#' @param x data to be binned
#' @param num.bins number of bins to aim for
#'   
#'   
#' @return
#' \code{bin.ints} returns an ordered factor vector with appropriately
#' labeled levels.
#' @examples
#' x <- rpois(100, 10)
#' x.bin <- bin.ints(x)
#' 
#' 
#' @seealso \code{\link{find.bins}} for determining bin breakpoints
#' @seealso \code{\link{label.bins}} for bin labels suitable for a legend
#' @export
bin.ints <- function(x, num.bins=10) {
  bps <- find.bins(x, num.bins)
  xbin <- findInterval(x, bps)
  binlab <- label.bins(x, xbin)
  factor(xbin, labels=binlab, ordered=TRUE)
}



#' Find breakpoints for binning numeric values
#' 
#' @param x data to be binned
#' @param num.bins number of bins to aim for
#'   
#' @examples
#' x <- rpois(100, 10)
#' bins <- find.bins(x)
#' x.bin <- findInterval(x, bins)
#' 
#' 
#' @seealso \code{\link{label.bins}} for bin labels suitable for a legend
#' @seealso \code{\link{bin.ints}} for generating a factor with labels
#' @export
find.bins <- function(x, num.bins=10) {
  bins <- NULL
  x.table <- table(x)
  names(x.table) <- NULL
  x.levels <- sort(unique(x))
  x.levels <- (x.levels + c(x.levels[-1], 1+max(x)))/2
  
  i <- 1
  while ( length(bins) < (num.bins-1)  & i <= length(x.table)) {
    if ( sum(x.table[1:i])/sum(x.table) > 1/(num.bins-length(bins)) ) {
      i <- max(1, i - 1)
      bins <- c(bins, x.levels[i])
      x.table <- x.table[-(1:i)]
      x.levels <- x.levels[-(1:i)]
      i <- 1
    } else {
      i <- i + 1
    }
  }
  bins <- c(bins, max(x)+1)
  return (bins)
}


#' Label bins generated by \code{find.bins()}
#' 
#' @param x data to be binned
#' @param bin binned data
#' @param greedy (default TRUE) whether to include in labels values of x which
#' may not appear in the data. e.g. instead of \code{0, 1, 2-3, 5-6} we return
#' \code{0, 1, 2-4, 5-6}
#' 
#' @examples
#' x <- rpois(100, 10)
#' bins <- find.bins(x)
#' x.bin <- findInterval(x, bins)
#' bin.labels <- label.bins(x, x.bin)
#' 
#' @seealso \code{\link{find.bins}} for determining bin breakpoints
#' @seealso \code{\link{bin.ints}} for generating a factor with labels
#' @export
label.bins <- function(x, bins, greedy=TRUE) {
  if ( missing(bins)  ) {
    x.bins <- find.bins(x)
    bins <- findInterval(x, x.bins)
  } else if ( length(bins) == 1 && is.numeric(bins) ) {
    x.bins <- find.bins(x, bins)
    bins <- findInterval(x, x.bins)
  } else if  ( length(bins) != length(x) ) {
    stop('x and bins must have same length.')
  }
  
  x.ranges <- simplify2array(tapply(x, bins, range))
  
  if ( greedy && min(diff(sort(unique(x)))) >= 1 )
    x.ranges[2, -ncol(x.ranges)] <- x.ranges[1, -1]-1
  
  apply(x.ranges, 2, function (r) 
    if (diff(r)) paste0(r[1], if (r[2]==max(x)) '+' else paste0('-', r[2])) else r[1]
  )
}





#' @export
gw.snp.pos <- function(chromosome, position, spacing=0.1) {
  chr.order <- gtools::mixedsort(unique(chromosome))
  snp.order <- order(match(chromosome, chr.order), position)
  
  co <- match(chromosome[snp.order], chr.order)
  po <- position[snp.order]
  
  chr.ranges <- do.call(rbind, tapply(po, co, range))
  rownames(chr.ranges) <- chr.order
  chr.sizes <- apply(chr.ranges, 1, diff)
  space <- mean(chr.sizes)*spacing
  chr.bounds <- unname(cumsum(c(0, chr.sizes+spacing)))
  
  chr.offsets <- chr.bounds[1:nrow(chr.ranges)] - chr.ranges[, 1]
  
  gwpos <- unname(chr.offsets[co] + po)
  gwpos[snp.order] <- gwpos
  
  attr(gwpos, 'chr.names') <- chr.order
  attr(gwpos, 'chr.bounds') <- chr.bounds
  
  class(gwpos) <- 'gwpos'
  
  return (gwpos)
}

#' @export
`[.gwpos` <- function(x, i, ...) {
  attrs <- attributes(x)
  out <- unclass(x)
  out <- out[i]
  attributes(out) <- attrs
  out
}

#' @export
gwaxis <- function(names, bounds, ax=1) {
  midpts <- (bounds[-1] + bounds[-length(bounds)])/2
  axis(ax, bounds, labels=FALSE)
  axis(ax, midpts, labels=names, lwd=0)
}

#' @export
plot.gwpos <- function (x, y=NULL, xlab=NULL, ylab=NULL, xaxt=NULL, ...) {
  
  if ( missing(xlab) ) xlab <- deparse(substitute(x))
  if ( missing(ylab) ) ylab <- deparse(substitute(y))
  
  plot.default(x, y, xlab=xlab, ylab=ylab, xaxt='n', ...)
  if ( missing(xaxt) || xaxt != 'n')
    gwaxis(attr(x, 'chr.names'), attr(x, 'chr.bounds'))
}
# This file is part of sb_pipe.
#
# sb_pipe is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# sb_pipe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with sb_pipe.  If not, see <http://www.gnu.org/licenses/>.
#
#
# Object: Plots and statistics for parameter estimation
#
# $Revision: 3.0 $
# $Author: Piero Dalle Pezze $
# $Date: 2016-07-01 14:14:32 $


library(ggplot2)
# library(scales)
source(file.path(SB_PIPE, 'sb_pipe','utils','R','sb_pipe_ggplot2_themes.r'))
source(file.path(SB_PIPE, 'sb_pipe','utils','R','plots.r'))





# m = number of model parameters
# n = number of data points
# p = significance level
compute_fratio_threshold <- function(m, n, p=0.05) {
  1 + (m/(n-m)) * qf(1.0-p, df1=m, df2=n-m)
}


# return the left value confidence interval
leftCI <- function(cut_dataset, full_dataset, chisquare_col_idx, param_col_idx, chisquare_conf_level) {
   # retrieve the minimum parameter value for cut_dataset
    min_ci <- min(cut_dataset[[param_col_idx]])    
    # retrieve the Chi^2 of the parameters with value smaller than the minimum value retrieved from the cut_dataset, within the full dataset. 
    # ...[min95, )  (we are retrieving those ...)
    lt_min_chisquares <- full_dataset[full_dataset[,param_col_idx] < min_ci, chisquare_col_idx] 
    if(min(lt_min_chisquares) < chisquare_conf_level) 
      min_ci <- "inf"
    min_ci
}


# return the right value confidence interval
rightCI <- function(cut_dataset, full_dataset, chisquare_col_idx, param_col_idx, chisquare_conf_level) {
   # retrieve the minimum parameter value for cut_dataset
    max_ci <- max(cut_dataset[[param_col_idx]])    
    # retrieve the Chi^2 of the parameters with value greater than the maximum value retrieved from the cut_dataset, within the full dataset. 
    # (, max95]...  (we are retrieving those ...)
    gt_max_chisquares <- full_dataset[full_dataset[,param_col_idx] > max_ci, chisquare_col_idx] 
    if(min(gt_max_chisquares) < chisquare_conf_level) 
      max_ci <- "inf"
    max_ci
}


plot_fits <- function(my_array) {
  iters <- c()
  j <- 0
  k <- 0
  for(i in 1:length(my_array)) {
    if(k < my_array[i]) {
      j <- 0
    }
    iters <- c(iters, j)
    j <- j+1    
    k <- my_array[i]   
  }
  df <- data.frame(Iter=iters, Chi2=my_array)
  scatterplot_log10(df, "Iter", "Chi2")
}


# rename columns
replace_colnames <- function(dfCols) {
  dfCols <- gsub("ObjectiveValue", "Chi2", dfCols)
  dfCols <- gsub("Values.", "", dfCols)
  dfCols <- gsub("..InitialValue.", "", dfCols)
}



plot_parameter_correlations <- function(df, dfCols, plots_dir, plot_filename_prefix, chi2_col_idx, logspace=TRUE) {
  fileout <- ""
  for (i in seq(chi2_col_idx+1,length(dfCols))) { 
    for (j in seq(i, length(dfCols))) {
      if(i==j) {
	fileout <- file.path(plots_dir, paste(plot_filename_prefix, dfCols[i], ".png", sep=""))
	g <- histogramplot(df[i])
	if(logspace) {
	  g <- g + xlab(paste("log10(",dfCols[i],")",sep=""))
	}
      } else {
	fileout <- file.path(plots_dir, paste(plot_filename_prefix, dfCols[i], "_", dfCols[j], ".png", sep=""))
	g <- scatterplot_w_colour(df, colnames(df)[i], colnames(df)[j], colnames(df)[chi2_col_idx]) +
        theme(legend.key.height = unit(0.5, "in"))
	if(logspace) {
	  g <- g + xlab(paste("log10(",dfCols[i],")",sep="")) + ylab(paste("log10(",dfCols[j],")",sep=""))
	}        
      }
      ggsave(fileout, dpi=300, width=8, height=6)
    }    
  }
}




all_fits_analysis <- function(model, filenamein, plots_dir, data_point_num, fileout_approx_ple_stats, fileout_conf_levels, plot_2d_66_95cl_corr=FALSE, logspace=TRUE) {
  
  data_point_num <- as.numeric(data_point_num)
  if(data_point_num <= 0.0) {
    error("data_point_num is non positive.")
    return
  }
  
  df = read.csv(filenamein, head=TRUE, dec=".", sep="\t")
  
  if(logspace) {
    # Transform the parameter space to a log10 parameter space. 
    # The column for the Chi^2 score is maintained instead. 
    df[,-1] <- log10(df[,-1])
  }
    
  dfCols <- replace_colnames(colnames(df))
  colnames(df) <- dfCols
  
  parameter_num = length(colnames(df)) - 1
  chisquare_at_conf_level_99 <- 0  
  chisquare_at_conf_level_95 <- 0    
  chisquare_at_conf_level_66 <- 0   
  if(length(dfCols) > 1) {
    chisquare_at_conf_level_99 <- min(df[,1]) * compute_fratio_threshold(parameter_num, data_point_num, .01) 
    chisquare_at_conf_level_95 <- min(df[,1]) * compute_fratio_threshold(parameter_num, data_point_num, .05) 
    chisquare_at_conf_level_66 <- min(df[,1]) * compute_fratio_threshold(parameter_num, data_point_num, .33)   
  }

  # select the rows with chi^2 smaller than our max threshold
  df99 <- df[df[,1] <= chisquare_at_conf_level_99, ]  
  df95 <- df[df[,1] <= chisquare_at_conf_level_95, ]
  df66 <- df95[df95[,1] <= chisquare_at_conf_level_66, ]  
  
  # Set my ggplot theme here
  theme_set(basic_theme(36))
 
  # save the chisquare vs iteration
  g <- plot_fits(df[,1])
  ggsave(file.path(plots_dir, paste(model, "_chi2_vs_iters.png", sep="")), dpi=300)
    
  min_chisquare <- min(df95[[1]])  
  fileoutPLE <- sink(fileout_conf_levels)
  cat(paste("Min_Chi2", "Param_Num", "Data_Points_Num", "Chi2_Conf_Level_95", "Fits_Num_95", "Chi2_Conf_Level_66", "Fits_Num_95\n", sep="\t"))
  cat(paste(min_chisquare, parameter_num, data_point_num, chisquare_at_conf_level_95, nrow(df95), chisquare_at_conf_level_66, nrow(df66), sep="\t"), append=TRUE)
  sink() 

  fileoutPLE <- sink(fileout_approx_ple_stats)
  cat(paste("Parameter", "Value", "CI_95_left", "CI_95_right", "CI_66_left", "CI_66_right\n", sep="\t"), append=TRUE)      
  for (i in seq(2,length(dfCols))) {
    # extract statistics  
    fileout <- file.path(plots_dir, paste(model, "_approx_ple_", dfCols[i], ".png", sep=""))
    g <- scatterplot_ple(df95, colnames(df95)[i], colnames(df95)[1], 
			 chisquare_at_conf_level_66, chisquare_at_conf_level_95) + 
         theme(legend.key.height = unit(0.5, "in"))
    if(logspace) {
      g <- g + xlab(paste("log10(",dfCols[i],")",sep=""))
    }         
         
    ggsave(fileout, dpi=300)
  
    # retrieve a parameter value associated to the minimum Chi^2
    par_value <- sample(df95[df95[,1] <= min_chisquare, i], 1)    
    # retrieve the confidence intervals
    min_ci_95 <- leftCI(df95, df99, 1, i, chisquare_at_conf_level_95)
    max_ci_95 <- rightCI(df95, df99, 1, i, chisquare_at_conf_level_95)    
    min_ci_66 <- leftCI(df66, df95, 1, i, chisquare_at_conf_level_66)
    max_ci_66 <- rightCI(df66, df95, 1, i, chisquare_at_conf_level_66)
    # save the result
    cat(paste(colnames(df95)[i], par_value, min_ci_95, max_ci_95, min_ci_66, max_ci_66, sep="\t"), append=TRUE)
    cat("\n", append=TRUE)    
  }
  sink()
  
  
  # plot parameter correlations using the 66% and 95% confidence level data sets
  if(plot_2d_66_95cl_corr) {
    plot_parameter_correlations(df66[order(-df66[,1]),], dfCols, plots_dir, paste(model, "_ci66_fits_", sep=""), 1, logspace)
    plot_parameter_correlations(df95[order(-df95[,1]),], dfCols, plots_dir, paste(model, "_ci95_fits_", sep=""), 1, logspace)
    #plot_parameter_correlations(df, dfCols, plots_dir, paste(model, "_all_fits_", sep=""), 1, logspace)
  }
  
}





final_fits_analysis <- function(model, filenamein, plots_dir, best_fits_percent, logspace=TRUE) {
  
  best_fits_percent <- as.numeric(best_fits_percent)
  if(best_fits_percent <= 0.0 || best_fits_percent > 100.0) {
    warning("best_fits_percent is not in (0, 100]. Now set to 100")
    best_fits_percent = 100
  }
  
  df = read.csv(filenamein, head=TRUE,sep="\t")
  
  if(logspace) {
    # Transform the parameter space to a log10 parameter space. 
    # The 2nd column containing the Chi^2 score is maintained 
    # as well as the 1st containing the parameter estimation name. 
    df[,c(-1,-2)] <- log10(df[,c(-1,-2)])
  }
    
  dfCols <- replace_colnames(colnames(df))
  colnames(df) <- dfCols
  
  # Calculate the number of rows to extract.
  selected_rows <- nrow(df)*best_fits_percent/100
  # sort by Chi^2 (descending) so that the low Chi^2 parameter tuples 
  # (which are the most important) are plotted in front. 
  # Then extract the tail from the data frame. 
  df <- df[order(-df[,2]),]
  df <- tail(df, selected_rows)
  
  # Set my ggplot theme here
  theme_set(basic_theme(36))
  
  plot_parameter_correlations(df, dfCols, plots_dir, paste(model, "_best_fits_", sep=""), 2, logspace)
  
}


                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, tableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                #cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, tableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]
    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
    }
    for (i in 1:max) {
        id <- list11$id[i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), list2[[id]], list11$id[[i]]))
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

myperiodtextslist <- function(myperiodtexts, periodtexts) {
    retlist <- myperiodtexts
    if (is.null(myperiodtexts)) {
        retlist <- periodtexts
    }
    if (!is.list(myperiodtexts)) {
        retlist <- list(myperiodtexts)
    }
    return(retlist)
}

gettopgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        dev.new()
        gettopchart(market, days, topbottom, stocklistperiod, period)
    }
}

devoffs <- function() {
    devs <- dev.list()
    for (i in 1:length(devs)) {
        dev.off(devs[i])
    }
}

getbottomgraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
        dev.new()
        getbottomchart(market, days, topbottom, stocklistperiod, period)
    }
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
}

getrisinggraph <- function(market, mydate, days, tableintervaldays, topbottom, myperiodtexts) {
    periodtexts <- getperiodtexts(market)
    myperiodtexts <- myperiodtextslist(myperiodtexts, periodtexts)
    for (i in 1:length(myperiodtexts)) {
        periodtext <- myperiodtexts[i]
        period <- match(periodtext, periodtexts)
                                        #    cat("perind ", period)
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        alist <- getlistanddiff(datedstocklists, listid, listdate, days, tableintervaldays)
        periodmaps <- alist[[1]]
        stocklistperiod <- alist[[2]]
        rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #    str("riserise")
                                        #    str(names(rise[[1]]))
        risetopids <- head(names(rise[[1]]))
        maindate <- "new"
        olddate <- "old"
        getchart(market, days, stocklistperiod, period, risetopids)
                                        #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    }
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate, days)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, periodtext, maindate, olddate, days) {
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (period == pricetype) {
        return (df$price)
    }
    if (period == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, days, tableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:days) {
        index <- index - tableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, days, tableintervaldays, ids, periodtext) {
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, days, tableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    ls <- list()
    names <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        dayset <- bigretl[[2]]
                        daynames <- names(dayset)
                        olddate <- min(daynames)
                        newdate <- max(daynames)
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        names[c] <- df$name
                    }
                }
            }
        }
    }
    displaychart(ls, names, 5, periodtext, newdate, olddate)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

# not used

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

# not used

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

if (!exists("mymarketid")) {
    mymarketid <- "morncat"
}

if (!exists("mydate")) {
    mydate <- NULL
}

allstocks <- getstocks()
allmetas <- getmetas()
#mymeta <- getmarketmeta(allmetas, marketid)
#data_3 <- getstockmarket(allstocks, marketid)

#for (i in 1:nrow(data_3)) {
                                        #print(data_3[i,"date"])
                                        #return()
#}

                                        #for (i in data_3) {
                                        #print(i["date"])
                                        #return
                                        #}

#listid2 <- splitid(data_3)
#listdate2 <- splitdate(data_3)
#listdate <- split(data_3, data_3$date)
#listid <- split(data_3, data_3$id)

                                        #l <- listdate[[104]]
#if (!exists("days")) {
#    days <- 10
#}
#if (!exists("topbottom")) {
#    topbottom <- 5
#}
#count <- days
#if (!exists("mytableintervaldays")) {
#    mytableintervaldays <- 5
#}
                                        #date <- "2016-05-02"

#datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)

#if (!exists("period")) {
#    period <- 3
#}

                                        #alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
                                        #periodmaps <- alist[[1]]
                                        #stocklistperiod <- alist[[2]]
                                        #mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
                                        #mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)

                                        #gettopchart(days, topbottom, stocklistperiod, period)
                                        #getbottomchart(days, topbottom, stocklistperiod, period)
                                        #rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #risetopids <- head(names(rise[[1]]))

#getcontentgraph(date, ids, "1y")

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, mytableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, mytableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]
    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
    }
    for (i in 1:max) {
        id <- list11$id[i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), list2[[id]], list11$id[[i]]))
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

gettopgraph <- function(market, mydate, days, topbottom, periodtext) {
    periodtexts <- getperiodtexts(market)
    period <- match(periodtext, periodtexts)
#    cat("perind ", period)
    stocks <- getstockmarket(allstocks, market)
    listdate <- split(stocks, stocks$date)
    datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
    alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
    periodmaps <- alist[[1]]
    stocklistperiod <- alist[[2]]
    mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
    gettopchart(market, days, topbottom, stocklistperiod, period)
}

getbottomgraph <- function(market, mydate, days, topbottom, periodtext) {
    periodtexts <- getperiodtexts(market)
    period <- match(periodtext, periodtexts)
#    cat("perind ", period)
    stocks <- getstockmarket(allstocks, market)
    listdate <- split(stocks, stocks$date)
    datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
    alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
    periodmaps <- alist[[1]]
    stocklistperiod <- alist[[2]]
    mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
    getbottomchart(market, days, topbottom, stocklistperiod, period)
}

gettopchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getbottomchart <- function(market, days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getrisinggraph <- function(market, mydate, days, topbottom, periodtext) {
    periodtexts <- getperiodtexts(market)
    period <- match(periodtext, periodtexts)
#    cat("perind ", period)
    stocks <- getstockmarket(allstocks, market)
    listdate <- split(stocks, stocks$date)
    datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
    alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
    periodmaps <- alist[[1]]
    stocklistperiod <- alist[[2]]
    rise <- getrising(days, periodmaps, stocklistperiod, period)
#    str("riserise")
#    str(names(rise[[1]]))
    risetopids <- head(names(rise[[1]]))
    maindate <- "new"
    olddate <- "old"
    getchart(market, days, stocklistperiod, period, risetopids)
    #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getchart <- function(market, days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(market, period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, periodtext, maindate, olddate) {
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(market, period) {
    periodtext <- period
    if (period >= 0) {
        mymeta <- getmarketmeta(allmetas, market)
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (period == pricetype) {
        return (df$price)
    }
    if (period == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, mytableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:count) {
        index <- index - mytableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, ids, periodtext) {
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    ls <- list()
    names <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        dayset <- bigretl[[2]]
                        daynames <- names(dayset)
                        olddate <- min(daynames)
                        newdate <- max(daynames)
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        names[c] <- df$name
                    }
                }
            }
        }
    }
    displaychart(ls, names, 5, periodtext, newdate, olddate)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

# not used

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

# not used

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

if (!exists("mymarketid")) {
    mymarketid <- "morncat"
}

if (!exists("mydate")) {
    mydate <- NULL
}

allstocks <- getstocks()
allmetas <- getmetas()
#mymeta <- getmarketmeta(allmetas, marketid)
#data_3 <- getstockmarket(allstocks, marketid)

#for (i in 1:nrow(data_3)) {
                                        #print(data_3[i,"date"])
                                        #return()
#}

                                        #for (i in data_3) {
                                        #print(i["date"])
                                        #return
                                        #}

#listid2 <- splitid(data_3)
#listdate2 <- splitdate(data_3)
#listdate <- split(data_3, data_3$date)
#listid <- split(data_3, data_3$id)

                                        #l <- listdate[[104]]
if (!exists("days")) {
    days <- 10
}
if (!exists("topbottom")) {
    topbottom <- 5
}
count <- days
if (!exists("mytableintervaldays")) {
    mytableintervaldays <- 5
}
                                        #date <- "2016-05-02"

#datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)

if (!exists("period")) {
    period <- 3
}

                                        #alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
                                        #periodmaps <- alist[[1]]
                                        #stocklistperiod <- alist[[2]]
                                        #mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
                                        #mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)

                                        #gettopchart(days, topbottom, stocklistperiod, period)
                                        #getbottomchart(days, topbottom, stocklistperiod, period)
                                        #rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #risetopids <- head(names(rise[[1]]))

#getcontentgraph(date, ids, "1y")

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------

similarity_cons_res <- tanimoto_analysis(min.tx = 45,
                                        K.values = 8,
                                        MW = 1,
                                        WT =  c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1),
                                        minimum_threshold = 0.3,
                                        filename = 'similarity_cons_res')

# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf(paste('./Article/',filename,'.pdf',sep=''),width=7,height=7)

# Plots
par(mfrow=c(2,2))
# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 1.09)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000088","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
            axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
            # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
            points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
        } #i

        ## Add legend
        if(j == 12) {
            legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        }
} #j
dev.off()

save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))
tanimoto_analysis <- function(min.tx, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, blind = FALSE) {
    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon
                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog

                        if(similarity == 'both') { # For similarity matrices already evaluated
                            similarity.consumer <- similarity.consumers[[i]]
                            similarity.resource <- similarity.resources[[i]]
                        } else if(similarity == 'consumer') {
                            similarity.consumer <- similarity.consumers[[i]]
                        } else if (similarity == 'resource') {
                            similarity.resource <- similarity.resources[[i]]
                        }

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                              S0[S1[k], 'consumer'] <- ""
                              S0[S1[k], 'non-consumer'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                                consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                        resource = interactions[, 'resource'],
                                                                        inter_type = interactions[, 'inter'])


                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                  S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                  S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.consumer,
                                                                                taxa = 'consumer')

                            similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.resource,
                                                                                taxa = 'resource')

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.consumer = similarity.consumer,
                                                                                    similarity.resource = similarity.resource,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.matrix)
                        iteration <- iteration + 1
                        setTxtProgressBar(pb, iteration)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values

        }#m
    }#n
    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
tanimoto_analysis <- function(min.tx, K.values, MW, WT, minimum_threshold, similarity = 'both', filename, blind = FALSE) {
    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------
    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon
                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog

                        if(similarity == 'both') { # For similarity matrices already evaluated
                            similarity.consumer <- similarity.consumers[[i]]
                            similarity.resource <- similarity.resources[[i]]
                        } else if(similarity == 'consumer') {
                            similarity.consumer <- similarity.consumers[[i]]
                        } else if (similarity == 'resource') {
                            similarity.resource <- similarity.resources[[i]]
                        }

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                              S0[S1[k], 'consumer'] <- ""
                              S0[S1[k], 'non-consumer'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                                consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                        resource = interactions[, 'resource'],
                                                                        inter_type = interactions[, 'inter'])


                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                  S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                  S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.consumer,
                                                                                taxa = 'consumer')

                            similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.resource,
                                                                                taxa = 'resource')

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.consumer = similarity.consumer,
                                                                                    similarity.resource = similarity.resource,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.matrix)
                        iteration <- iteration + 1
                        setTxtProgressBar(pb, iteration)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values

        }#m
    }#n
    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))

    return(Tanimoto_analysis)
}
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------

similarity_cons_res <- tanimoto_analysis(min.tx = 45,
                                        K.values = 8,
                                        MW = 1,
                                        WT = seq(0,1,by=0.1),
                                        minimum_threshold = 0.3,
                                        filename = 'similarity_cons_res')

# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf("./Article/Catalog_vs_predictions.pdf",width=7,height=7)
# Plots
par(mfrow=c(2,2))
# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 1.09)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000088","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
            axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
            # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
            points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
        } #i

        ## Add legend
        if(j == 12) {
            legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        }
} #j
dev.off()

save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))
                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, mytableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, mydate) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (mydate == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, mytableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]
    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
    }
    for (i in 1:max) {
        id <- list11$id[i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), list2[[id]], list11$id[[i]]))
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

gettopgraph <- function(market, mydate, days, topbottom, periodtext) {
    periodtexts <- getperiodtexts(market)
    period <- match(periodtext, periodtexts)
#    cat("perind ", period)
    stocks <- getstockmarket(allstocks, market)
    listdate <- split(stocks, stocks$date)
    datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
    alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
    periodmaps <- alist[[1]]
    stocklistperiod <- alist[[2]]
    mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
    gettopchart(days, topbottom, stocklistperiod, period)
}

getbottomgraph <- function(market, mydate, days, topbottom, periodtext) {
    periodtexts <- getperiodtexts(market)
    period <- match(periodtext, periodtexts)
#    cat("perind ", period)
    stocks <- getstockmarket(allstocks, market)
    listdate <- split(stocks, stocks$date)
    datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
    alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
    periodmaps <- alist[[1]]
    stocklistperiod <- alist[[2]]
    mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
    getbottomchart(days, topbottom, stocklistperiod, period)
}

gettopchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getbottomchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getrisinggraph <- function(market, mydate, days, topbottom, periodtext) {
    periodtexts <- getperiodtexts(market)
    period <- match(periodtext, periodtexts)
#    cat("perind ", period)
    stocks <- getstockmarket(allstocks, market)
    listdate <- split(stocks, stocks$date)
    datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
    alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
    periodmaps <- alist[[1]]
    stocklistperiod <- alist[[2]]
    rise <- getrising(days, periodmaps, stocklistperiod, period)
#    str("riserise")
#    str(names(rise[[1]]))
    risetopids <- head(names(rise[[1]]))
    maindate <- "new"
    olddate <- "old"
    getchart(days, stocklistperiod, period, risetopids)
    #displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getchart <- function(days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, periodtext, maindate, olddate) {
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(period) {
    periodtext <- period
    if (period >= 0) {
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (period == pricetype) {
        return (df$price)
    }
    if (period == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, mydate, mytableintervaldays) {
#    str(mydate)
    datedstocklists <- list()
    if (!is.null(mydate)) {
        dateindex <- match(mydate, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:count) {
        index <- index - mytableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(mydate, ids, periodtext) {
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getstockmarket(allstocks, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, mydate, mytableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    ls <- list()
    names <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        dayset <- bigretl[[2]]
                        daynames <- names(dayset)
                        olddate <- min(daynames)
                        newdate <- max(daynames)
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        names[c] <- df$name
                    }
                }
            }
        }
    }
    displaychart(ls, names, 5, periodtext, newdate, olddate)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
                                        #    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- getmarketmeta(allmetas, market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmetas <- function() {
    return(dbGetQuery(con, "select * from meta"))
}

# not used

getmarketmeta <- function(metas, market) {
    return(subset(metas, marketid == market))
}

getstocks <- function() {
    return(dbGetQuery(con, "select * from stock"))
}

# not used

getstockmarket <- function(stocks, market) {
    return(subset(stocks, marketid == market))
}

# not in use now

getmarketold <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

if (!exists("marketid")) {
    marketid <- "morncat"
}

if (!exists("mydate")) {
    mydate <- NULL
}

allstocks <- getstocks()
allmetas <- getmetas()
#mymeta <- getmarketmeta(allmetas, marketid)
#data_3 <- getstockmarket(allstocks, marketid)

#for (i in 1:nrow(data_3)) {
                                        #print(data_3[i,"date"])
                                        #return()
#}

                                        #for (i in data_3) {
                                        #print(i["date"])
                                        #return
                                        #}

#listid2 <- splitid(data_3)
#listdate2 <- splitdate(data_3)
#listdate <- split(data_3, data_3$date)
#listid <- split(data_3, data_3$id)

                                        #l <- listdate[[104]]
if (!exists("days")) {
    days <- 10
}
if (!exists("topbottom")) {
    topbottom <- 5
}
count <- days
if (!exists("mytableintervaldays")) {
    mytableintervaldays <- 5
}
                                        #date <- "2016-05-02"

#datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)

if (!exists("period")) {
    period <- 3
}

                                        #alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
                                        #periodmaps <- alist[[1]]
                                        #stocklistperiod <- alist[[2]]
                                        #mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
                                        #mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)

                                        #gettopchart(days, topbottom, stocklistperiod, period)
                                        #getbottomchart(days, topbottom, stocklistperiod, period)
                                        #rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #risetopids <- head(names(rise[[1]]))

#getcontentgraph(date, ids, "1y")

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

tanimoto_analysis <- function(min.tx, K.values, MW, WT, minimum_threshold, similarity, filename, blind = FALSE) {
    # -----------------------------------------------------------------------------
    # # PARAMETERS:
    #     filename                name of file under which to same the results of the predictions
    #     min.tx                  minimal number of taxon for empirical food webs to be included in the analysis
    #     K.values                Kc and Kr values to test in the KNN algorithm
    #     MW                      Minimum weight for candidate resources to be included as predictions
    #     WT                      Weights for the two-way Tanimoto algorithm
    #     blind                   Whether the analysis whould be blind, i.e. no a priori information for taxa in catalog
    #     minimum_threshold       Minimum similarity threshold for similar taxa to be considered as candidate resources
    #     similarity              String character either being c('consumer', 'resource', 'both') for the similarity measurements
    #
    # # OUTPUT:
    #     tanimoto_analysis       List of predictions for all parameters tested
    # -----------------------------------------------------------------------------

    filename <- 'essai'
    min.tx = 45
    K.values = 5
    MW = 1
    WT = 0
    blind = FALSE
    minimum_threshold = 0.3
    similarity = 'both'


    load("./RData/Tanimoto_data.RData")
    load("./RData/interactions_source.RData")
    if(similarity == 'both') { # For similarity matrices already evaluated
        suppressMessages(load("./RData/Similarity_consumers.RData"))
        suppressMessages(load("./RData/Similarity_resources.RData"))
    } else if(similarity == 'consumer') {
        suppressMessages(load("./RData/Similarity_consumers.RData"))
    } else if (similarity == 'resource') {
        suppressMessages(load("./RData/Similarity_resources.RData"))
    }

    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 6, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource', 'consumer', 'non-consumer')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 5] <- Tanimoto_data[[6]][k, 'consumer']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 6] <- Tanimoto_data[[6]][k, 'non-consumer']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- wt.init <- c(0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            if(similarity == 'both') { # For similarity matrices already evaluated
                similarity.consumers[[i]] <- NULL
                similarity.resources[[i]] <- NULL
            } else if(similarity == 'consumer') {
                similarity.consumers[[i]] <- NULL
            } else if (similarity == 'resource') {
                similarity.resources[[i]] <- NULL
            }
        }

        sim.wt <- WT
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

        # List to store results of multiple K values
        K <- vector("list", length(K.values))
        for(i in 1:length(K.values)) {
            K[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- K
        names(Tanimoto_analysis) <- K.values
        remove(K)

        min.wt <- vector("list", length(MW))
        for(i in 1:length(MW)) {
            min.wt[[i]] <- Tanimoto_analysis
        }
        Tanimoto_analysis <- min.wt
        names(Tanimoto_analysis) <- MW
        remove(min.wt)

    # Initial time save for temporary saving in case analysis fails mid process
    file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    iteration <- 1
    init.time <- Sys.time()
    pb <- txtProgressBar(min = 0,max = length(Cm) * length(WT) * length(K.values) * length(MW), style = 3)
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon
                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog

                        if(similarity == 'both') { # For similarity matrices already evaluated
                            similarity.consumer <- similarity.consumers[[i]]
                            similarity.resource <- similarity.resources[[i]]
                        } else if(similarity == 'consumer') {
                            similarity.consumer <- similarity.consumers[[i]]
                        } else if (similarity == 'resource') {
                            similarity.resource <- similarity.resources[[i]]
                        }

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                              S0[S1[k], 'consumer'] <- ""
                              S0[S1[k], 'non-consumer'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                                consumer_set <- resource_set_of_consumer(consumer = interactions[, 'consumer'],
                                                                        resource = interactions[, 'resource'],
                                                                        inter_type = interactions[, 'inter'])


                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                  S0[consumer_set[k, 'resource'], 5] <- consumer_set[k, 'consumer']
                                  S0[consumer_set[k, 'resource'], 6] <- consumer_set[k, 'non-consumer']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.consumer <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.consumer,
                                                                                taxa = 'consumer')

                            similarity.resource <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.resource,
                                                                                taxa = 'resource')

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.consumer = similarity.consumer,
                                                                                    similarity.resource = similarity.resource,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.matrix)
                        iteration <- iteration + 1
                        setTxtProgressBar(pb, iteration)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values

        }#m
    }#n
    close(pb)
    print(Sys.time() - init.time)

    save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))
}
# Run init.r before other scripts
rm(list=ls())
 # for use in R console.
 # set own relevant directory if working in R console, otherwise ignore if in terminal
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "./Script/0-1-Tanimoto_data.r
#           RData <- file = './RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "./Script/0-1-Interactions_sources.r
#           RData <- file = "./RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = './Script/1-Similarity_matrix.r'
#       RData <- file = './RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = './Script/2-1-Tanimoto_analysis.r'
#           RData <- file = './RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = './Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = './RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("./Script/tanimoto.r") # basic tanimoto similarity
source("./Script/tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("./Script/similarity_taxon.r") # similarity matrix for set of taxa
source("./Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("./Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("./Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/consumer_set_of_resource.R")
source("./Script/resource_set_of_consumer.R")
source("./Script/prediction_accuracy.r") #
source("./Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("./Script/serialNext.r") # function to avoid overwriting existing files in temporary analyses folder
source("./Script/eplot.r") # empty plot for figure generation
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
#Similarity matrix as a single functions
similarity_taxon <- function(S0, wt) {
    # Note: the similarity on the diagonal has to be set to 1 since it's all the same species.

    similarity.matrix <- matrix(nrow = nrow(S0), ncol = nrow(S0), dimnames = list(S0[, 'taxon'], S0[, 'taxon']))

    taxonomy <- vector("list",nrow(S0))
    resource <- vector("list",nrow(S0))
    for(i in 1:nrow(S0)) {
      taxonomy[[i]] <- unlist(strsplit(S0[i, 'taxonomy'], " \\|\\ "))
      if(length(which(taxonomy[[i]] == "NA")) > 0) {
          taxonomy[[i]] <- taxonomy[[i]][-which(taxonomy[[i]] == "NA")]
      }
      resource[[i]] <- unlist(strsplit(S0[i, 'resource'], " \\|\\ "))
    }

    pb <- txtProgressBar(min = 0,max = nrow(S0), style = 3)

    for(i in 1:nrow(S0)){
      for(j in i:nrow(S0)){ #No need to evaluate both side of the matrix diagonal for the similarity matrix
          similarity.matrix[i,j] <- similarity.matrix[j,i] <- tanimoto_traits(resource_x = resource[[i]],
                                                                              resource_y = resource[[j]],
                                                                              trait_x = taxonomy[[i]],
                                                                              trait_y = taxonomy[[j]],
                                                                              trait_weight = wt
                                                                              )
      }#j
    setTxtProgressBar(pb, i)
    }#i
    close(pb)

    diag(similarity.matrix) <- 1

  return(similarity.matrix)
}#similarity_taxon function
#Similarity matrix as a single functions
similarity_taxon_predict <- function(S0, S1, wt, similarity.matrix) {

    # Parameters:
    #   S0                  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource'] (if blind = TRUE, it )
    #   S1                  The subset of S0 where we want to predict new preys, string vector
    #   wt                  Weight given to traits (including phylogeny) when computing similarities.
    #   similarity.matrix   Similarity.matrix for interaction catalogue (measured by function: similarity_taxon)
    #
    # Output
    #   A matrix of dimensions S x S with similarity measurements for all combinations of S[i,j]

    # Note: the similarity on the diagonal has to be set to 1 since it's all the same species.

    to.recalculate <- which(S0[, 'taxon'] %in% S1)
    similarity.matrix[, to.recalculate] <- similarity.matrix[to.recalculate, ] <- 0

    taxonomy <- vector("list",nrow(S0))
    resource <- vector("list",nrow(S0))
    for(i in 1:nrow(S0)) {
      taxonomy[[i]] <- unlist(strsplit(S0[i, 'taxonomy'], " \\|\\ "))
      if(length(which(taxonomy[[i]] == "NA")) > 0) {
          taxonomy[[i]] <- taxonomy[[i]][-which(taxonomy[[i]] == "NA")]
      }
      resource[[i]] <- unlist(strsplit(S0[i, 'resource'], " \\|\\ "))
    }


  # pb <- txtProgressBar(min = (nrow(similarity.matrix) - length(taxa.add)), max = ncol(similarity.matrix), style = 3)

  for(i in to.recalculate){
      for(j in 1:ncol(similarity.matrix)){ #No need to evaluate both side of the matrix diagonal for the similarity matrix
          similarity.matrix[i,j] <- similarity.matrix[j,i] <- tanimoto_traits(resource_x = resource[[i]],
                                                                              resource_y = resource[[j]],
                                                                              trait_x = taxonomy[[i]],
                                                                              trait_y = taxonomy[[j]],
                                                                              trait_weight = wt
                                                                              )
      }#j
  # setTxtProgressBar(pb, i)
  }#i
  # close(pb)
  diag(similarity.matrix) <- 1
  return(similarity.matrix)
}#similarity_taxon_predict function
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#    1. Evaluating similarity of consumers and resources
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
# // TODO: Evaluate similarity based on set of consumers for resources
# // TODO: Look into proximity graphs for better performance
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# LIBRARIES:
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------

# Measuring the similarity with multiple weights for all taxa in interaction catalogue
# Will be better once we code for proximity graphs
    wt <- seq(0, 1, by = 0.1)
    similarity.matrices <- vector('list',11)
    names(similarity.matrices) <- seq(0, 1, by = 0.1)
    for(i in 1:length(wt)) {
        similarity.matrices[[i]] <- similarity_taxon(S0 = S0_catalog, wt = wt[i])
        save(x = similarity.matrices, file = "./RData/Similarity.matrices.RData")
    }
    save(x = similarity.matrices, file = "./RData/Similarity.matrices.RData")
two_way_tanimoto_predict <- function(Kc, Kr, S0, S1, MW, similarity.matrix, minimum_threshold) {
    # Two-way Tanimoto Algorithm
    # ===========================

    # Parameters:
    #   Kc  Integer, how many neighbors to select for consumers
    #   Kr  Integer, how many neighbors to select for resources
    #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
    #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name
    #   MW  Mimimum weight to accept a candidate as a prey
    #

    # // TODO: I think MW should be a function of Kc & Kr and perhaps of the number of candidate resources. For example, a similar consumer could have multiple prey, which would artificially inflate the weight added to each prey in the candidate list. For exemple, Atlantic cod has over 600 prey species listed in the interaction catalogue... Hence, the longer the candidate list, the more likely a very small similarity will be turned into a predicted interaction
    # // REVIEW: Multiply similar.consumer[similarity] * similar.resource[similarity]? It's a similarity of a similarity in a sense...

    # // TODO: Different similarity measurement for resources and consumers

    # // REVIEW: Remove cannibalism from empirical data, or allow for it, or add parameter that allows or prevents cannibalism in the predictions


    # Output
    #   A vector of sets (the preys for each species)

    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # List of things to adjust - make it
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    # Process steps:
      # A prior process to this is to get the similarity matrix between all combinations of catalogue taxa and species in S1
      # For each species in S1:
      # 1. Identify resources already known in interaction catalogue (S0) for S1 species
        # 1.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
        # 1.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

      # 2. Identify Kc similar consumers to S1 in S0
        # 2.1 Extract set of candidate resources from each similar consumer, if any
        # 2.2 If candidate resource is in S1, add it to candidate list with weight 1
        # 2.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

      # 3. Make predictions:
        # 3.1 Remove taxa with weight < to minimum weight (MW) from prediction list
        # 3.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed


    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    # !!! étendre predator et non predator pour resource... il faudrait aussi calculer la similarité des proies sur la base de leurs prédateurs partagés !!!
    # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    predictions <- matrix(nrow = length(S1), ncol = 3, data = "", dimnames = list(c(S1), c('consumer','resource_empirical','resource_predictions'))) # empty object for resource predictions
    predictions[, 'consumer'] <- S1

    # pb <- txtProgressBar(min = 0,max = length(S1), style = 3)
    for(i in 1:length(S1)) { # loop through each taxon in S1
        candidates <- matrix(nrow = 0, ncol = 2, dimnames = list(c(), c('resource', 'weight')), data = NA) # empty matrix for resource candidate list for S1[i], with taxon name and weight
        resources.S1 <- unlist(strsplit(S0[S1[i], 'resource'], " \\|\\ ")) # resources of S1[i]

        # Add resources that are already listed as resources for S1[i] in predictions[, 'resource_empirical'] or
        # Find similar resources to resources for S1[i] in S1
        if(length(resources.S1) > 0) {
            empirical <- character()
            for(j in 1:length(resources.S1)) { #loop through empirical resources for S1
                if(resources.S1[j] %in% S1) {
                    empirical <- c(empirical, resources.S1[j]) # observed resource found in S1 are automatically added to the column resource_empirical
                } else { # selecting Kr most similar resources in S1
                    # Let's assume for this part that we are not compiling a different similarity measure for predators and preys.
                    similar.resource <- matrix(nrow = length(S1)-1, ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources
                    similar.resource[, 'resource'] <- names(sort(similarity.matrix[S1[-which(S1 == S1[i])], resources.S1[j]], decreasing = TRUE))
                    similar.resource[, 'similarity'] <- sort(similarity.matrix[S1[-which(S1 == S1[i])], resources.S1[j]], decreasing = TRUE)

                    # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
                    if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {
                        same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])
                        similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]
                        similar.resource <- similar.resource[1:Kr, ]
                    } else {
                        similar.resource <- similar.resource[1:Kr, ]
                    }# if for random draw

                    for(l in 1:Kr) { # extracting resource candidates
                        if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break
                            break
                        } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                            NULL
                            # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed
                        } else if(similar.resource[l, 'similarity'] < minimum_threshold) {
                            NULL
                        } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add resource' with wt to its weight
                          candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])
                        } else {
                              candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it resource' with wt to its weight
                        }#if3
                    }#l
                }#if
            }#j
            predictions[S1[i], 'resource_empirical'] <- paste(empirical, collapse = ' | ')
        }#if1

        # Identify similar consumers to S1[i]
        similar.consumer <- matrix(nrow = nrow(similarity.matrix)-1, ncol = 2, dimnames = list(c(), c('consumer','similarity')), data = NA) # emporting K nearest neighbors for consumers
        similar.consumer[, 'consumer'] <- names(sort(similarity.matrix[-which(colnames(similarity.matrix) == S1[i]), S1[i]], decreasing = TRUE))
        similar.consumer[, 'similarity'] <- sort(similarity.matrix[-which(colnames(similarity.matrix) == S1[i]), S1[i]], decreasing = TRUE)

        # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
        if(similar.consumer[Kc+1, 'similarity'] == similar.consumer[Kc, 'similarity']) {
            same.similarity <- which(similar.consumer[, 'similarity'] == similar.consumer[Kc, 'similarity'])
            similar.consumer[same.similarity, ] <- similar.consumer[sample(same.similarity), ]
            similar.consumer <- similar.consumer[1:Kc, ]
        } else {
            similar.consumer <- similar.consumer[1:Kc, ]
        }# if for random draw


        # Est-ce que la valeur de similarité a de l'importance pour l'attribution des proies?
        # If yes, we could add an argument call wt_predator.
          # if(wt_predator == FALSE) {
          #   resources <- unique of all prey species of all similar predators
          # } else {}

        for(j in 1:Kc) { #loop through consumers

            if(all.equal(similar.consumer[, 'similarity'], rep('0',Kc)) == TRUE) { # if similarities all == 0, break
                break
            } else if(similar.consumer[j, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                NULL
            } else {

                # It's possible that consumers in the list have high taxonomic similarity, but no recorded resource
                candidate.resource <- unlist(strsplit(S0[similar.consumer[j, 'consumer'], 'resource'], " \\|\\ ")) # list of resources for consumer j
                # candidate.resource <- candidate.resource[(candidate.resource %in% resources.S1) == FALSE] # substracting candidate resources that are already listed as resources for S1[i] and hence considered in the preceding code segment

                for(k in 1:length(candidate.resource)) { # loop through resources of consumer j
                    if(length(candidate.resource) == 0) { # if candidate resource list is empty, break
                        break
                    } else if(candidate.resource[1] == "") { # if candidate list is an empty vector "", break
                        break
                    } else if(candidate.resource[k] == S1[i]) {
                    #   #// FIXME: if candidate resource is taxon for which predictions are being made, break (unless we want to allow CANIBALISM). Add argument for cannibalism allowed or not
                         NULL
                    } else if((candidate.resource[k] %in% S1) == TRUE) {
                        if((candidate.resource[k] %in% candidates[, 'resource']) == TRUE) {# if candidate is already in candidate list, add 1 to its weight
                            candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == candidate.resource[k]), 'weight']) + 1
                        } else {
                            candidates <- rbind(candidates, c(candidate.resource[k], 1)) # if candidate is not in the list, add it with 1 to its weight
                        }#if2

                    } else {
                        # Let's assume for this part that we are not compiling a different similarity measure for predators and preys.
                        similar.resource <- matrix(nrow = length(S1)-1, ncol = 2, dimnames = list(c(), c('resource','similarity')), data = NA) # importing K nearest neighbors resources
                        similar.resource[, 'resource'] <- names(sort(similarity.matrix[S1[-which(S1 == S1[i])], candidate.resource[k]], decreasing = TRUE))
                        similar.resource[, 'similarity'] <- sort(similarity.matrix[S1[-which(S1 == S1[i])], candidate.resource[k]], decreasing = TRUE)

                        # If multiple taxa with same similarity, randomly select those that will be used as similar resources.
                        if(similar.resource[Kr+1, 'similarity'] == similar.resource[Kr, 'similarity']) {
                            same.similarity <- which(similar.resource[, 'similarity'] == similar.resource[Kr, 'similarity'])
                            similar.resource[same.similarity, ] <- similar.resource[sample(same.similarity), ]
                            similar.resource <- similar.resource[1:Kr, ]
                        } else {
                            similar.resource <- similar.resource[1:Kr, ]
                        }# if for random draw

                        for(l in 1:Kr) { # extracting resource candidates
                            if(all.equal(similar.resource[, 'similarity'], rep('0',Kr)) == TRUE) { # if similarities all == 0, break
                                break
                            } else if(similar.resource[l, 'similarity'] == '0') { # if similarity l == 0, no candidates provided
                                NULL
                                # minimum threshold try.. adding it as a Parameters.. might not make sense, have to discuss it. If we keep it, previous else ifs can be removed
                            } else if(similar.resource[l, 'similarity'] < minimum_threshold) {
                                NULL
                            } else if((similar.resource[l, 'resource'] %in% candidates[, 'resource']) == TRUE) { # if candidate is already in candidate list, add 1 to its weight
                              candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight'] <- as.numeric(candidates[which(candidates[, 'resource'] == similar.resource[l]), 'weight']) + as.numeric(similar.resource[l, 'similarity'])
                            } else {
                                  candidates <- rbind(candidates, similar.resource[l, ]) # if candidate is not in the list, add it with its weight = similarity
                            }#if3
                        }#l
                    } #if1
                }#k
            }#if
        }#j

        candidates <- candidates[which(candidates[, 'weight'] >= MW), ] # remove candidates with a weight below MW
        if(is.matrix(candidates) == TRUE) { #if it's a vector, there's only one predicted resource, no need to order
            candidates[order(candidates[, 'weight']), ] # sorts candidates according to their weight
            predictions[S1[i], 'resource_predictions'] <- paste(candidates[, 'resource'], collapse = ' | ')
        } else {
          predictions[S1[i], 'resource_predictions'] <- paste(candidates['resource'], collapse = ' | ')
        }#if
    # setTxtProgressBar(pb, i)
    }#i
    # close(pb)
    return(predictions)
}#two_way_tanimoto_predict function
# source("C:/GitHub/practice/datascience/datacamp/intro_to_r/lists.r")
                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, mytableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, date) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (date == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, mytableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]
    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
    }
    for (i in 1:max) {
        id <- list11$id[i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), list2[[id]], list11$id[[i]]))
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

gettopchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    periodtext <- getmyperiodtext(period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getbottomchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    periodtext <- getmyperiodtext(period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
}

getchart <- function(days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    periodtext <- getmyperiodtext(period)
    displaychart(ls, names, topbottom, periodtext, maindate, olddate)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        t.test(c1,c2,paired=TRUE)
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, periodtext, maindate, olddate) {
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getmyperiodtext <- function(period) {
    periodtext <- period
    if (period >= 0) {
        newtext <- getperiodtext(mymeta, period)
        if (!is.na(newtext)) {
            periodtext <- newtext
        }
    }
    return(periodtext)
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (period == pricetype) {
        return (df$price)
    }
    if (period == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
    dayset <- list()
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
            str2 <- as.character(el$date)
            dayset[str2] <- 1
        } else {
            print("err")
        }
    }
    return(list(retl, dayset))
}

getelem3tup <- function(id, days, datedstocklist, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, date, mytableintervaldays) {
    datedstocklists <- list()
    if (is.null(date)) {
        dateindex <- match(date, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    str(dateindex)
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:count) {
        index <- index - mytableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(con, date, ids, periodtext) {
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getmarket(con, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    olddate <- "old"
    newdate <- "new"
    ls <- list()
    names <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        bigretl <- getelem3(id, days, datedstocklists, period, topbottom)
                        l <- unlist(bigretl[[1]])
                        dayset <- bigretl[[2]]
                        daynames <- names(dayset)
                        olddate <- min(daynames)
                        newdate <- max(daynames)
                        ls[c] <- list(l)
                        listdf <- getelem3tup(id, days, datedstocklists, period, topbottom)
                        df <- data.frame(listdf[[1]])
                        names[c] <- df$name
                    }
                }
            }
        }
    }
    displaychart(ls, names, 5, periodtext, newdate, olddate)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- subset(meta, marketid == market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmarket <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

if (!exists("marketid")) {
    marketid <- "morncat"
}

data <- dbGetQuery(con, "select * from stock")
meta <- dbGetQuery(con, "select * from meta")
mymeta <- subset(meta, marketid == mymarketid)
data_3 <- getmarket(con, marketid)
names(data_3)
s <- subset(data_3, "id" == "EUCA000749")

for (i in 1:nrow(data_3)) {
                                        #print(data_3[i,"date"])
                                        #return()
}

                                        #for (i in data_3) {
                                        #print(i["date"])
                                        #return
                                        #}

listid2 <- splitid(data_3)
listdate2 <- splitdate(data_3)
listdate <- split(data_3, data_3$date)
listid <- split(data_3, data_3$id)

                                        #l <- listdate[[104]]
if (!exists("days")) {
    days <- 10
}
if (!exists("topbottom")) {
    topbottom <- 5
}
count <- days
if (!exists("mytableintervaldays")) {
    mytableintervaldays <- 5
}
                                        #date <- "2016-05-02"

datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)

if (!exists("period")) {
    period <- 3
}

                                        #alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
                                        #periodmaps <- alist[[1]]
                                        #stocklistperiod <- alist[[2]]
                                        #mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
                                        #mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)

                                        #gettopchart(days, topbottom, stocklistperiod, period)
                                        #getbottomchart(days, topbottom, stocklistperiod, period)
                                        #rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #risetopids <- head(names(rise[[1]]))

getcontentgraph(con, date, ids, "1y")

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

# Run init.r before other scripts
rm(list=ls())
 # for use in R console.
 # set own relevant directory if working in R console, otherwise ignore if in terminal
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "./Script/0-1-Tanimoto_data.r
#           RData <- file = './RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "./Script/0-1-Interactions_sources.r
#           RData <- file = "./RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = './Script/1-Similarity_matrix.r'
#       RData <- file = './RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = './Script/2-1-Tanimoto_analysis.r'
#           RData <- file = './RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = './Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = './RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("./Script/tanimoto.r") # basic tanimoto similarity
source("./Script/tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("./Script/similarity_taxon.r") # similarity matrix for set of taxa
source("./Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("./Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("./Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/consumer_set_of_resource.R")
source("./Script/prediction_accuracy.r") #
source("./Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("./Script/serialNext.r") # function to avoid overwriting existing files in temporary analyses folder
source("./Script/eplot.r") # empty plot for figure generation
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#    0.1   Formatting interaction catalog
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# LIBRARIES:
library(stringr)
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("../Interaction_catalog/RData/class_tx_tot.RData")
load("../Interaction_catalog/RData/GloBI_classification.RData")
load("../Interaction_catalog/RData/interactions.RData")
load("../Interaction_catalog/RData/GloBI_interactions.RData")
load("../Interaction_catalog/RData/sp_egsl.RData")
# ---------------------------------
# Unique binary interactions
# ---------------------------------

# Select binary interactions with species that have a fully resolved taxonomy
Biotic_inter <- vector('list',4)
names(Biotic_inter) <- c('Binary_interaction','Taxon_list','Inter_taxonomy','EGSL')

  # For Empirical Webs
    consumer <- numeric()
    resource <- numeric()
    pb <- txtProgressBar(min = 0,max = nrow(inter.tot), style = 3)
    for(i in 1:nrow(inter.tot)) {
      if(!is.na(class.tx.tot[inter.tot[i, 'Predator'], 1])) {
        consumer <- c(consumer, 1)
      } else {
        consumer <- c(consumer, 0)
      } #if

      if(!is.na(class.tx.tot[inter.tot[i, 'Prey'], 1])) {
        resource <- c(resource, 1)
      } else {
        resource <- c(resource, 0)
      } #if
      setTxtProgressBar(pb, i)
    } #i
    close(pb)

    # If all = 1, no need to adjust
    unique(consumer)
    unique(resource)

  # For GloBI interactions
    consumer <- numeric()
    resource <- numeric()
    pb <- txtProgressBar(min = 0,max = nrow(GloBI_interactions), style = 3)
    for(i in 1:nrow(GloBI_interactions)) {
      if(!is.na(GloBI_classification[GloBI_interactions[i, 'Predator'], 1])) {
        consumer <- c(consumer, 1)
      } else {
        consumer <- c(consumer, 0)
      } #if

      if(!is.na(GloBI_classification[GloBI_interactions[i, 'Prey'], 1])) {
        resource <- c(resource, 1)
      } else {
        resource <- c(resource, 0)
      } #if
      setTxtProgressBar(pb, i)
    } #i
    close(pb)

    # If all = 1, no need to adjust
    unique(consumer)
    unique(resource)

    cons_res <- cbind(resource,consumer)
    cons_res <- rowSums(cons_res)

    GloBI_interactions <- GloBI_interactions[-which(cons_res != 2), ]

    # Combining biotic interactions in complete dataset
    Biotic_inter[[1]] <- rbind(inter.tot[, 1:3], GloBI_interactions[, 1:3])
    colnames(Biotic_inter[[1]]) <- c('consumer','inter','resource')
    Biotic_inter[[1]] <- unique(Biotic_inter[[1]])

# ---------------------------------
# Unique taxon list
# ---------------------------------
  Biotic_inter[[2]] <- rbind(class.tx.tot, GloBI_classification)
  Biotic_inter[[2]] <- unique(Biotic_inter[[2]])
  rownames(Biotic_inter[[2]]) <- Biotic_inter[[2]][, 'taxon']

  # Adjust taxon names with taxonomy
  for(i in 1:nrow(Biotic_inter[[2]])) {
    Biotic_inter[[2]][i, 'taxon'] <- paste(Biotic_inter[[2]][i,paste(Biotic_inter[[2]][i, 'rank'])])
  }#i

  # Adjust taxon rank not kept
  Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'tribe'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'tribe'), 'family'])
  Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'superfamily'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'superfamily'), 'order'])
  Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'subfamily'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'subfamily'), 'family'])

  # First letter only as capital
  Names_change <- function(x){
    # Name resolve #1
    x <- str_trim(x, side="both") #remove spaces
    x <- tolower(x)
    x <- paste(toupper(substr(x,nchar(x)-(nchar(x)-1),nchar(x)-(nchar(x)-1))),substr(x,nchar(x)-(nchar(x)-2),nchar(x)),sep="")
    return(x)
  }

  Biotic_inter[[2]][, -13] <- apply(Biotic_inter[[2]][, -13], 2, Names_change)
  Biotic_inter[[1]][, -2] <- apply(Biotic_inter[[1]][, -2], 2, Names_change)
  Biotic_inter[[2]] <- apply(Biotic_inter[[2]], 2, gsub, pattern = 'NANA', replacement = 'NA')

  # Also adjust in interactions list
  for(i in 1:nrow(Biotic_inter[[1]])) {
    Biotic_inter[[1]][i, 'consumer'] <- Biotic_inter[[2]][paste(Biotic_inter[[1]][i, 'consumer']), 'taxon']
    Biotic_inter[[1]][i, 'resource'] <- Biotic_inter[[2]][paste(Biotic_inter[[1]][i, 'resource']), 'taxon']
  }

# Also adjust egsl species list
 Biotic_inter[[4]] <- matrix(nrow = nrow(sp.egsl), ncol = ncol(Biotic_inter[[2]]), data = NA, dimnames = list(c(), colnames(Biotic_inter[[2]])))
 rownames(Biotic_inter[[4]]) <- sp.egsl[,1]
 for(i in 1:nrow(sp.egsl)) {
    Biotic_inter[[4]][i, ] <- Biotic_inter[[2]][sp.egsl[i,1], ]
 }

# Also adjust for Empirical Webs interactions
for(i in 1:nrow(inter.tot)) {
  inter.tot[i, 'Predator'] <- Biotic_inter[[2]][paste(inter.tot[i, 'Predator']), 'taxon']
  inter.tot[i, 'Prey'] <- Biotic_inter[[2]][paste(inter.tot[i, 'Prey']), 'taxon']
}

# Also adjust GloBI_interactions
for(i in 1:nrow(GloBI_interactions)) {
  GloBI_interactions[i, 'Predator'] <- Biotic_inter[[2]][paste(GloBI_interactions[i, 'Predator']), 'taxon']
  GloBI_interactions[i, 'Prey'] <- Biotic_inter[[2]][paste(GloBI_interactions[i, 'Prey']), 'taxon']
}

Biotic_inter[[1]] <- Biotic_inter[[1]][-which(Biotic_inter[[1]][,'resource'] == "Copepod"), ]


  # Unique values and adjusting rownames
  Biotic_inter[[1]] <- unique(Biotic_inter[[1]])
  Biotic_inter[[2]] <- unique(Biotic_inter[[2]])
  rownames(Biotic_inter[[2]]) <- Biotic_inter[[2]][, 'taxon']
  rownames(Biotic_inter[[4]]) <- Biotic_inter[[4]][, 'taxon']
  Biotic_inter[[4]] <- Biotic_inter[[4]][,-c(7,9,10,13)]
  GloBI_interactions <- unique(GloBI_interactions[, 1:3])
  inter.tot <- unique(inter.tot[, 1:3])

# --------------------------------------------
# First dataset: taxon with taxonomy as vector
# --------------------------------------------

colnames(GloBI_interactions) <- c('consumer','inter','resource')
taxon.list <- unique(c(unique(Biotic_inter[[1]][, 'consumer']), unique(Biotic_inter[[1]][, 'resource'])))

taxon <- matrix(nrow = length(taxon.list), ncol = 2, data = NA, dimnames = list(c(), c("taxon", "kingdom | phylum | class | order | family | genus | species")))
taxon[, 1] <- taxon.list

# Extracting taxonomy for each binary interaction
rank <- c("kingdom","phylum","class","order","family","genus","species")
taxonomy <- matrix(nrow = nrow(taxon), ncol = length(rank), dimnames = list(c(), rank))

pb <- txtProgressBar(min = 0,max = nrow(taxon), style = 3)
for(i in 1:nrow(taxon)) {
  taxonomy[i, ] <- Biotic_inter[[2]][taxon[i, 'taxon'], rank]
  setTxtProgressBar(pb, i)
} #i
close(pb)

# Combining taxonomy into single element
# Ranks are  "kingdom | phylum | class | order | family | genus | species"
taxon[, 2] <- apply(taxonomy, 1, paste, collapse = ' | ')

# write.table(taxon, "Phil_data/0-taxon_list.txt", sep="\t")

# ---------------------------------------------------------------------------
# Second dataset: Predators with sets of prey and non-prey for Empirical Webs
# ---------------------------------------------------------------------------
rownames(inter.tot) <- seq(1,nrow(inter.tot))
emp.web.inter <- consumer_set_of_resource(consumer = inter.tot[, 'Predator'],
                                          resource = inter.tot[, 'Prey'],
                                          inter_type = inter.tot[, 'FeedInter']
                                          )

# write.table(emp.web.inter, "Phil_data/1-emp_webs_interactions.txt", sep="\t")

# ----------------------------------------------------------------------------------
# Third dataset: Predators with sets of prey and non-prey for Empirical Webs + GloBI
# ----------------------------------------------------------------------------------
rownames(Biotic_inter[[1]]) <- seq(1,nrow(Biotic_inter[[1]]))
total.inter <- consumer_set_of_resource(consumer = Biotic_inter[[1]][, 'consumer'],
                                        resource = Biotic_inter[[1]][, 'resource'],
                                        inter_type = Biotic_inter[[1]][, 'inter']
                                        )

# write.table(total.inter, "Phil_data/2-total_interactions.txt", sep="\t")

# ----------------------------
# Fourth dataset: EGSL species
# ----------------------------
egsl <- matrix(nrow = nrow(Biotic_inter[[4]]), ncol = 2, data = NA, dimnames = list(c(Biotic_inter[[4]][, 'taxon']), c("taxon", "kingdom | phylum | class | order | family | genus | species")))
egsl[, 'taxon'] <- Biotic_inter[[4]][, 'taxon']
egsl[, 2] <- apply(Biotic_inter[[4]][,3:9], 1, paste, collapse = ' | ')
egsl <- unique(egsl)

# remove duplicated taxon
which(duplicated(egsl[,'taxon']))
egsl <- egsl[-1209, ]

# write.table(egsl, "Phil_data/3-EGSL_species.txt", sep="\t", row.names = FALSE, col.names = c('EGSL_species'))

# ----------------------------
# RData
# ----------------------------
Tanimoto_data <- vector("list", 4)
Tanimoto_data[[1]] <- taxon
Tanimoto_data[[2]] <- emp.web.inter
Tanimoto_data[[3]] <- total.inter
Tanimoto_data[[4]] <- egsl

save(x = Tanimoto_data, file = "./RData/Tanimoto_data.RData")
# source("C:/GitHub/practice/datascience/datacamp/intro_to_r/data_frames.r")

mtcars <- read.csv("C:/GitHub/practice/datascience/datacamp/intro_to_r/data/mtcars.csv")
splitLog <- function(dt, burninP = .2){ ## get indicators and coefficients while discarding burn-in
  ## 'Product' is whether coefficients should be delta*beta (default) or just beta
  res <- vector(2, mode = "list")
  names(res) <- c("Indicators", "Coefficients")
  init <- round(.2 * nrow(dt))
  dt.b <- dt[init:nrow(dt), ]
  res[[1]] <- dt.b[, grep("coefIndicator", names(dt.b))]
  res[[2]] <- dt.b[, grep("GLM.glmCoefficients", names(dt.b))]
  return(res)
}
getSummary <- function(x, alpha = .95){
  return(
    data.frame(lwr = as.numeric(quantile(x, probs = (1 - alpha)/2 )),
         mean = mean(x), upr = as.numeric(quantile(x, probs = (1 + alpha)/2)), row.names = "")
  )
}
#
list2df <- function(ll){ ## could be skipped with a little of extra work... TODO
  N <- length(ll)
  dt <- data.frame(matrix(NA, nrow = N, ncol = 4 ))
  names(dt) <- c("parameter", "lwr", "mean", "upr")
  dt$parameter <- names(ll)
  for(i in 1:N) dt[i, 2:4] <- ll[[i]]
  return(dt)
}
#
getSummary <- function(x, alpha = .95){
  return(data.frame(lwr = quantile(x, probs = (1 - alpha)/2) ,
                    mean = mean(x),
                    upr = quantile(x, probs = (1 + alpha)/2)
  ))
}
#
conditional_betas_BEAST <- function(betas, inds){
  if(ncol(betas) != ncol(inds)) stop("Coefficients and indicators are not the same dimension")
  K <- ncol(betas)
  result <- data.frame(matrix(NA, ncol = 3 , nrow = K))
  names(result) <- c("lwr", "mean", "upr")
  for(k in 1:K){
    result[k, ] <- getSummary(betas[, k][inds[, k] == 1])
  }
  return(result)
}
#
plotSimpleGLM <- function(Names, Log, probZero = .5, BF = 3, intercept = FALSE, Burnin = .2,
                          export = TRUE, fileName = "GLM_plot", title = ""){
  require(ggplot2)
  require(repr)
  require(scales)
  require(grid)
  ## 'Names' is a vector with the predictor names
  ## 'Log' is the .log file [already loaded as a data.frame] to be analysed
  ## 'probZero' is the probability that no predictors are included
  ## 'BF' is the Bayes factor threshold (default 3)
  ## 'intercept' is a boolean specifying whether an intercept was included in the model
  ## 'Burnin' is the percent of the chain to be discarded as burn-in
  ## 'betaind' is a boolean specifying whether to report delta*beta
  Pars <- splitLog(Log, burninP = Burnin)
  if(intercept){
    if(!ncol(Pars$Indicators)== (length(Names)+ 1)) stop("Model probably doesn't have intercept")
    Pars <- lapply(Pars, function(x) x[, -ncol(x)])
  }
  Summaries <- lapply(Pars, function(d) apply(d, 2, getSummary))
  SumDf <- lapply(Summaries, list2df)
  npred <- length(Names)
  inclusion.probabilities <- data.frame(
    p.mean = SumDf$Indicators$mean,
    p.lwr =  SumDf$Indicators$lwr,
    p.upr =  SumDf$Indicators$upr,
    predictor = Names
  )
  #
  regression.coefficients <- data.frame(predictor = Names,
                                        b = conditional_betas_BEAST(betas = Pars$Coefficients,
                                                                    inds = Pars$Indicators))
  #
  q <- 1-((probZero)^(1/npred))
  bf <- BF
  cutoff <- (q*bf)/(q*(bf-1) + 1)
  #
  p0 <- ggplot(regression.coefficients, aes(x = predictor , y = b.mean))+
    geom_pointrange(aes(ymin = b.lwr, ymax = b.upr), position = position_dodge(0.5)) +
    coord_flip() +
    scale_y_continuous("Coefficient", expand = c(0, 0)) +
    scale_x_discrete("Predictor") +
    geom_hline(yintercept = 0, linetype = "solid", color = "black", size = 0.5) +
    theme_bw()

  p0 <- p0 +  theme(legend.position = "none")
  p1 <- ggplot(inclusion.probabilities, aes(x = predictor, y = p.mean))+
    geom_bar(stat = "identity") +
    coord_flip() +
    scale_y_continuous("Inclusion probability", expand = c(0, 0)) +
    scale_x_discrete("Predictor") +
    geom_hline(yintercept = cutoff, linetype = "dashed", colour = "black", size = 0.7) +
    geom_hline(yintercept = q, linetype = "solid", colour = "green", size = 0.2) +
    ggtitle(title) +
    theme_bw()
  p1 <- p1 + guides(fill = guide_legend(reverse = TRUE)) +
    theme(axis.text.y = element_blank(),
          axis.ticks.y = element_blank(),
          axis.title.y = element_blank()
    )
  if(export){
    pdf(paste(fileName, ".pdf", sep = ""))
  }
  options(repr.plot.width = 10, repr.plot.height = 5)
  grid.draw(cbind(ggplotGrob(p0), ggplotGrob(p1), size = "first"))
  if(export){
    dev.off()
  }
}
## Auxiliary functions to plot GLMs estimated using BEAST
#####################################
splitLog <- function(dt, burninP = .2){ ## get indicators and coefficients while discarding burn-in
  ## 'Product' is whether coefficients should be delta*beta (default) or just beta
  res <- vector(2, mode = "list")
  names(res) <- c("Indicators", "Coefficients")
  init <- round(.2 * nrow(dt))
  dt.b <- dt[init:nrow(dt), ]
  res[[1]] <- dt.b[, grep("coefIndicator", names(dt.b))]
  res[[2]] <- dt.b[, grep("GLM.glmCoefficients", names(dt.b))]
  return(res)
}
getSummary <- function(x, alpha = .95){
  return(
    data.frame(lwr = as.numeric(quantile(x, probs = (1 - alpha)/2 )),
         mean = mean(x), upr = as.numeric(quantile(x, probs = (1 + alpha)/2)), row.names = "")
  )
}
#
list2df <- function(ll){ ## could be skipped with a little of extra work... TODO
  N <- length(ll)
  dt <- data.frame(matrix(NA, nrow = N, ncol = 4 ))
  names(dt) <- c("parameter", "lwr", "mean", "upr")
  dt$parameter <- names(ll)
  for(i in 1:N) dt[i, 2:4] <- ll[[i]]
  return(dt)
}
#
getSummary <- function(x, alpha = .95){
  return(data.frame(lwr = quantile(x, probs = (1 - alpha)/2) ,
                    mean = mean(x),
                    upr = quantile(x, probs = (1 + alpha)/2)
  ))
}
#
conditional_betas_BEAST <- function(betas, inds){
  if(ncol(betas) != ncol(inds)) stop("Coefficients and indicators are not the same dimension")
  K <- ncol(betas)
  result <- data.frame(matrix(NA, ncol = 3 , nrow = K))
  names(result) <- c("lwr", "mean", "upr")
  for(k in 1:K){
    result[k, ] <- getSummary(betas[, k][inds[, k] == 1])
  }
  return(result)
}
#
plotSimpleGLM <- function(Names, Log, probZero = .5, BF = 3, intercept = FALSE, Burnin = .2,
                          export = TRUE, fileName = "GLM_plot", title = ""){
  require(ggplot2)
  require(repr)
  require(scales)
  require(grid)
  ## 'Names' is a vector with the predictor names
  ## 'Log' is the .log file [already loaded as a data.frame] to be analysed
  ## 'probZero' is the probability that no predictors are included
  ## 'BF' is the Bayes factor threshold (default 3)
  ## 'intercept' is a boolean specifying whether an intercept was included in the model
  ## 'Burnin' is the percent of the chain to be discarded as burn-in
  ## 'betaind' is a boolean specifying whether to report delta*beta
  Pars <- splitLog(Log, burninP = Burnin)
  if(intercept){
    if(!ncol(Pars$Indicators)== (length(Names)+ 1)) stop("Model probably doesn't have intercept")
    Pars <- lapply(Pars, function(x) x[, -ncol(x)])
  } 
  Summaries <- lapply(Pars, function(d) apply(d, 2, getSummary))
  SumDf <- lapply(Summaries, list2df)
  npred <- length(Names)
  inclusion.probabilities <- data.frame(
    p.mean = SumDf$Indicators$mean,
    p.lwr =  SumDf$Indicators$lwr,
    p.upr =  SumDf$Indicators$upr,
    predictor = Names
  )
  #
  regression.coefficients <- data.frame(predictor = Names,
                                        b = conditional_betas_BEAST(betas = Pars$Coefficients,
                                                                    inds = Pars$Indicators))
  #
  q <- 1-((probZero)^(1/npred))
  bf <- BF
  cutoff <- (q*bf)/(q*(bf-1) + 1)
  #
  p0 <- ggplot(regression.coefficients, aes(x = predictor , y = b.mean))+
    geom_pointrange(aes(ymin = b.lwr, ymax = b.upr), position = position_dodge(0.5)) + 
    coord_flip() +
    scale_y_continuous("Coefficient", expand = c(0, 0)) +
    scale_x_discrete("Predictor") +
    geom_hline(yintercept = 0, linetype = "solid", color = "black", size = 0.5) + 
    theme_bw()
  
  p0 <- p0 +  theme(legend.position = "none")
  p1 <- ggplot(inclusion.probabilities, aes(x = predictor, y = p.mean))+
    geom_bar(stat = "identity") +
    coord_flip() +
    scale_y_continuous("Inclusion probability", expand = c(0, 0)) +
    scale_x_discrete("Predictor") +
    geom_hline(yintercept = cutoff, linetype = "dashed", colour = "black", size = 0.7) +
    geom_hline(yintercept = q, linetype = "solid", colour = "green", size = 0.2) + 
    ggtitle(title) +
    theme_bw()
  p1 <- p1 + guides(fill = guide_legend(reverse = TRUE)) +
    theme(axis.text.y = element_blank(),
          axis.ticks.y = element_blank(),
          axis.title.y = element_blank()
    )
  if(export){
    pdf(paste(fileName, ".pdf", sep = ""))
  }
  options(repr.plot.width = 10, repr.plot.height = 5)
  grid.draw(cbind(ggplotGrob(p0), ggplotGrob(p1), size = "first"))
  if(export){
    dev.off()
  }
}# Run readme.r before other scripts
rm(list=ls())
 # for use in R console.
 # set own relevant directory if working in R console, otherwise ignore if in terminal
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "./Script/0-1-Tanimoto_data.r
#           RData <- file = './RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "./Script/0-1-Interactions_sources.r
#           RData <- file = "./RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = './Script/1-Similarity_matrix.r'
#       RData <- file = './RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = './Script/2-1-Tanimoto_analysis.r'
#           RData <- file = './RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = './Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = './RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("./Script/tanimoto.r") # basic tanimoto similarity
source("./Script/tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("./Script/similarity_taxon.r") # similarity matrix for set of taxa
source("./Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("./Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("./Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("./Script/consumer_set_of_resource.R")
source("./Script/prediction_accuracy.r") #
source("./Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("./Script/serialNext.r") # function to avoid overwriting existing files in temporary analyses folder
source("./Script/eplot.r") # empty plot for figure generation
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# Generating serial number for files in case file already exists
# http://stackoverflow.com/questions/25429557/how-to-create-a-new-output-file-in-r-if-a-file-with-that-name-already-exists
serialNext = function(prefix){
    if(!file.exists(prefix)){
        return(prefix)
    }
        i=1
    repeat {
        f = paste(unlist(strsplit(prefix, '[.]'))[1],i,'.',unlist(strsplit(prefix, '[.]'))[2],sep="")
        if(!file.exists(f)){return(f)}
        i=i+1
     }
  }
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:
    filename <- 'Multiple_parameters'
    min.tx = 45
    K.values = c(2,4,6,8)
    MW = c(1,3,5)
    WT = c(0,0.3,0.6,1)
    blind = FALSE
    minimum_threshold = 0.3
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("./RData/Tanimoto_data.RData")
load("./RData/interactions_source.RData")
suppressMessages(load("./RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
# Format interaction catalogue to fit this table format
    S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
    S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
    }

# setting up the analyses for multiple communities
# Data for communities on which to test the algorithm
    Cm <- unique(interactions_sources[, 'source'])
    communities <- vector("list", length(Cm))
    names(communities) <- Cm

    # Taxa list per community to predict
        for(i in 1:length(communities)) {
            Ci <- which(interactions_sources[, 'source'] == Cm[i])
            S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

            if(length(which(!S1 %in% S0_catalog)) > 0) {
                print('Taxa in C[i] are not all included in taxa list S0')
                break
            }

            communities[[i]] <- S1
        }

# Substracting GloBI interactions for this portion
    Cm.lg <- numeric()
    for(i in 1:length(communities)) {
        Cm.lg <- c(Cm.lg,length(communities[[i]]))
    }

    to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

    Cm <- Cm[-to.delete]
    for(i in rev(to.delete)) {
        communities[[i]] <- NULL
    }
    names(communities) <- Cm

# Setting up lists to store the results
    wt.init <- seq(0,1,by=0.1)
    wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
    for(i in rev(wt.remove)) {
        similarity.matrices[[i]] <- NULL
    }

    sim.wt <- names(similarity.matrices)
    Tanimoto_analysis <- vector("list",length(sim.wt))
    names(Tanimoto_analysis) <- sim.wt
    for(i in 1:length(sim.wt)) {
        Tanimoto_analysis[[i]] <- vector("list", length(Cm))
        names(Tanimoto_analysis[[i]]) <- Cm
    }

# List to store results of multiple K values
K <- vector("list", length(K.values))
for(i in 1:length(K.values)) {
    K[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- K
names(Tanimoto_analysis) <- K.values
remove(K)

min.wt <- vector("list", length(MW))
for(i in 1:length(MW)) {
    min.wt[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- min.wt
names(Tanimoto_analysis) <- MW
remove(min.wt)

file.to.save <- serialNext("./Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
save(x = Tanimoto_analysis, file = file.to.save)

init.time <- Sys.time()
for(n in 1:length(MW)) {
    mw <- MW[n]
    for(m in 1:length(K.values)) {

        # Tanimoto analysis with different weights for different communities
            # Parameters:
                Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
            #   wt  Weight of traits in similarity measurement
            #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
            #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

            # Output:
            #   A vector of sets of resources for each taxon

            for(i in 1:length(WT)){ #1st loop for all types of wt values
                wt <- WT[i]
                pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                for(j in 1:length(Cm)) { #2nd loop for all C[i]
                    S1 <- communities[[j]]
                    S0 <- S0_catalog
                    similarity.matrix <- similarity.matrices[[i]]

                    # Two choices here:
                    #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                    #   2. The analysis takes into account preexisting information already contained in the catalogue

                    # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                    if(blind == TRUE) {
                        for(k in 1:length(S1)) {
                          S0[S1[k], 'resource'] <- ""
                          S0[S1[k], 'non-resource'] <- ""
                        }

                    # 2. Preexisting information kept to inform algorithm
                    } else { # blind == FALSE

                        interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                        # Only modifying those that are loosing data from the catalogue, less time
                            to.change <- numeric()
                            for(k in 1:length(S1)) {
                                to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                            }
                            to.change <- unique(to.change)

                        # Modifying sets of resources and non-resources for taxa in S1
                            interactions <- interactions[to.change, ]
                            rownames(interactions) <- seq(1,nrow(interactions))
                            resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                      resource = interactions[, 'resource'],
                                                                      inter_type = interactions[, 'inter'])

                        # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                            for(k in 1:nrow(resource_set)) {
                              S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                              S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                            }
                        remove(interactions, resource_set, to.change)
                    } #if blind or not blind

                    # Recalculate similarity
                        similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                            S1 = S1,
                                                                            wt = wt,
                                                                            similarity.matrix = similarity.matrix)

                    # Predicting interactions
                        Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                Kr = Kr,
                                                                                S0 = S0,
                                                                                S1 = S1,
                                                                                MW = mw,
                                                                                similarity.matrix = similarity.matrix,
                                                                                minimum_threshold = minimum_threshold)

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(S0, S1, similarity.matrix)
                    setTxtProgressBar(pb, j)
                }#2nd loop for all C[i]

                save(x = Tanimoto_analysis, file = file.to.save)
                remove(wt)

            }#1st loop for all types of wt values
            close(pb)
    }#m
}#n
print(Sys.time() - init.time)

# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf("./Article/Catalog_vs_predictions.pdf",width=7,height=7)
# Plots
par(mfrow=c(2,2))
# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 1.09)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000088","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
            axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
            # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
            points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
        } #i

        ## Add legend
        if(j == 12) {
            legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        }
} #j
dev.off()

save(x = Tanimoto_analysis, file = paste('./Analyses/',filename,'.RData',sep=''))
# Run readme.r before other scripts
rm(list=ls())
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "Script/0-1-Tanimoto_data.r
#           RData <- file = 'RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "Script/0-1-Interactions_sources.r
#           RData <- file = "RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = 'Script/1-Similarity_matrix.r'
#       RData <- file = 'RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = 'Script/2-1-Tanimoto_analysis.r'
#           RData <- file = 'RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = 'Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = 'RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("./Script/tanimoto.r") # basic tanimoto similarity
source("Script/Tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("Script/similarity_taxon.r") # similarity matrix for set of taxa
source("Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/consumer_set_of_resource.R")
source("Script/prediction_accuracy.r") #
source("Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("Script/serialNext.r") # function to avoid overwriting existing files in temporary analyses folder
source("Script/eplot.r") # empty plot for figure generation
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#    0.2   Extracting which taxa is found in which community from empirical data
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# LIBRARIES:
library(stringr)
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------

#Loading all datasets with interactions
load("../Interaction_catalog/RData/barnes2008.RData")
load("../Interaction_catalog/RData/Kortsch2015.RData")
load("../Interaction_catalog/RData/GlobalWeb.RData")
load("../Interaction_catalog/RData/brose2005.RData")
load("../Interaction_catalog/RData/class_tx_tot.RData")
load("../Interaction_catalog/RData/GloBI_classification.RData")
load("../Interaction_catalog/RData/GloBI_interactions.RData")

# load("RData/EwE.RData") # Not yet finished
# load("RData/GloBI.RData") # Not yet finished

# List of webs
InterDataTot <- c(Barnes2008, Brose2005, GlobalWeb, Kortsch2015) # EwE to add

# Complete taxon list and interaction list from all webs
tx.list <- matrix(nrow=0, ncol=2, data=NA, dimnames = list(c(), c("taxon","rank")))
inter.list <- matrix(nrow=0, ncol=4, data=NA, dimnames = list(c(), c("Predator","FeedInter","Prey","Source")))


for(i in 1:length(InterDataTot)) {
  tx.list <- rbind(tx.list, as.matrix(InterDataTot[[i]][[5]]))
  inter.list <- rbind(inter.list, cbind(as.matrix(InterDataTot[[i]][[4]]), rep(names(InterDataTot[i]), nrow(InterDataTot[[i]][[4]]))))
}

tx.list <- unique(tx.list)
inter.list <- unique(inter.list)

# Taxonomic resolutions and those selected to move further in the analysis
# Decision is to use all taxonomic resolutions greater or equal to families
taxo.resol <- unique(inter.list[, 2])
taxo.resolution.accepted <- c("species", "genus", "family", "tribe", "subfamily", "superfamily")

# Extracting interactions for analysis
time_init <- Sys.time()
inter.tot <- inter_taxo_resolution(tx.list, inter.list, taxo.resolution.accepted)
Sys.time() - time_init

# Changing to binary interactions
for(i in 1:nrow(inter.tot)) {
  if(inter.tot[i, 2] != "0" & inter.tot[i, 2] != "1") {inter.tot[i, 2] <- "1"}
}

# Extracting taxon list for analysis
row.tx.accepted <- numeric()
for(i in 1:length(taxo.resolution.accepted)) {
  row.tx.accepted <- c(row.tx.accepted,which(tx.list[,2] == taxo.resolution.accepted[i]))
}

tx.list.tot <- tx.list[row.tx.accepted, ]

#inter.tot
#tx.list.tot

# ---------------- INTERACTIONS ---------------
GloBI_interactions <- cbind(GloBI_interactions[, c('Predator','FeedInter','Prey')], rep('GloBI', nrow(GloBI_interactions)), GloBI_interactions[, 'inter.resolution'])

Biotic_inter <- vector('list',4)
names(Biotic_inter) <- c('Binary_interaction','Taxon_list','Inter_taxonomy','EGSL')

# Combining biotic interactions in complete dataset
Biotic_inter[[1]] <- rbind(inter.tot[, 1:4], GloBI_interactions[, 1:4])
colnames(Biotic_inter[[1]]) <- c('consumer','inter','resource','source')
Biotic_inter[[1]] <- unique(Biotic_inter[[1]])

# ---------------------------------
# Unique taxon list
# ---------------------------------
Biotic_inter[[2]] <- rbind(class.tx.tot, GloBI_classification)
Biotic_inter[[2]] <- unique(Biotic_inter[[2]])
rownames(Biotic_inter[[2]]) <- Biotic_inter[[2]][, 'taxon']

# Adjust taxon names with taxonomy
for(i in 1:nrow(Biotic_inter[[2]])) {
Biotic_inter[[2]][i, 'taxon'] <- paste(Biotic_inter[[2]][i,paste(Biotic_inter[[2]][i, 'rank'])])
}#i

# Adjust taxon rank not kept
Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'tribe'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'tribe'), 'family'])
Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'superfamily'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'superfamily'), 'order'])
Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'subfamily'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'subfamily'), 'family'])

# First letter only as capital
Names_change <- function(x){
# Name resolve #1
x <- str_trim(x, side="both") #remove spaces
x <- tolower(x)
x <- paste(toupper(substr(x,nchar(x)-(nchar(x)-1),nchar(x)-(nchar(x)-1))),substr(x,nchar(x)-(nchar(x)-2),nchar(x)),sep="")
return(x)
}

Biotic_inter[[2]][, -13] <- apply(Biotic_inter[[2]][, -13], 2, Names_change)
Biotic_inter[[1]][, -2] <- apply(Biotic_inter[[1]][, -2], 2, Names_change)
Biotic_inter[[2]] <- apply(Biotic_inter[[2]], 2, gsub, pattern = 'NANA', replacement = 'NA')
Biotic_inter[[1]]<- Biotic_inter[[1]][-which(Biotic_inter[[1]][, 'resource'] == 'Unidentified'), ] # Removing unidentified

no.result.to.delete <- c( "Baraeoptera roria",
                          "Cydorus latus",
                          "Hemiuris communis",
                          "Hyponigrus obsidianus",
                          "Sarortherdon macrochir",
                          "Scaphaloberis mucronata",
                          "Secernentia nematodes",
                          "Zealolessica cheira",
                          "Haploparaksis crassirostris",
                          'Spermophilus armatus',
                          "Spermophilus brunneus",
                          "Spermophilus franklinii",
                          "Spermophilus richardsonii",
                          "Spermophilus tridecemlineatus",
                          "Spermophilus washingtoni",
                          'Glossoma',
                          "Paracentropristes pomospilus",
                          "Delphacinae",
                          "Staphylininae",
                          "Ursinae",
                          "Zelandoperlinae",
                          "Euclymeninae",
                          "Pilumninae")

to.delete <- numeric() # À utiliser à la fin après avoir combiner les jeux de données
for(i in 1:length(no.result.to.delete)){
to.delete <- c(to.delete,which(Biotic_inter[[1]][, 'resource'] == no.result.to.delete[i]), which(Biotic_inter[[1]][, 'consumer'] == no.result.to.delete[i]))
}
to.delete <- unique(to.delete)
Biotic_inter[[1]] <- Biotic_inter[[1]][-to.delete, ]

# Also adjust in interactions list
for(i in 1:nrow(Biotic_inter[[1]])) {
Biotic_inter[[1]][i, 'consumer'] <- Biotic_inter[[2]][paste(Biotic_inter[[1]][i, 'consumer']), 'taxon']
Biotic_inter[[1]][i, 'resource'] <- Biotic_inter[[2]][paste(Biotic_inter[[1]][i, 'resource']), 'taxon']
}

# Unique values and adjusting rownames
Biotic_inter[[1]] <- unique(Biotic_inter[[1]])
Biotic_inter[[2]] <- unique(Biotic_inter[[2]])
rownames(Biotic_inter[[2]]) <- Biotic_inter[[2]][, 'taxon']

# Les informations de GloBI peuvent être une duplication des informations déjà relevées des food webs empiriques. Il faudrait songer à les retirer.
for(i in 1:nrow(Biotic_inter[[1]])) {
    if(Biotic_inter[[1]][i, 'source'] == "Globi") {
        Biotic_inter[[1]][i, 'source'] <- ""
    }
}
interactions_sources <- Biotic_inter[[1]]
interactions_sources <- interactions_sources[-which(interactions_sources[,'resource'] == "Copepod"), ]
rownames(interactions_sources) <- seq(1,nrow(interactions_sources))
save(x = interactions_sources, file = "RData/interactions_source.RData")
#
# # Interactions unique avec sources
# multi_inter <- which(duplicated(Biotic_inter[[1]][,1:3]))
# # to.remove <- numeric() # If I wish to remove duplicated interactions at this stage
# for(i in 1:length(multi_inter)) {
#     duplicata <- which(Biotic_inter[[1]][, 1] == Biotic_inter[[1]][multi_inter[i], 1] & Biotic_inter[[1]][, 2] == Biotic_inter[[1]][multi_inter[i], 2] & Biotic_inter[[1]][, 3] == Biotic_inter[[1]][multi_inter[i], 3])
#
#     for(j in 2:length(duplicata)) {
#         if(Biotic_inter[[1]][duplicata[j], 'source'] == "") {
#             NULL
#         } else {
#             Biotic_inter[[1]][duplicata[1], 'source'] <- paste(c(Biotic_inter[[1]][duplicata[1], 'source'], Biotic_inter[[1]][duplicata[j], 'source']), collapse = " | ")
#         }
#         # to.remove <- c(to.remove, duplicata[j])
#     }#j
# }#i
# # Biotic_inter[[1]] <- Biotic_inter[[1]][-to.remove, ]
#
# # Set of sources
# #   Pour les analyses, tout sera retiré pour chaque S1, même si des informations alternatives sont disponibles. On sera donc nécessairement à blind = TRUE
# load("RData/Tanimoto_data.RData")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#    1. Evaluating similarity of consumers and resources
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
# // TODO: Evaluate similarity based on set of consumers for resources
# // TODO: Look into proximity graphs for better performance
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# LIBRARIES:
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------

# Measuring the similarity with multiple weights for all taxa in interaction catalogue
# Will be better once we code for proximity graphs
    wt <- seq(0, 1, by = 0.1)
    similarity.matrices <- vector('list',11)
    names(similarity.matrices) <- seq(0, 1, by = 0.1)
    for(i in 1:length(wt)) {
        similarity.matrices[[i]] <- similarity_taxon(S0 = S0_catalog, wt = wt[i])
        save(x = similarity.matrices, file = "RData/Similarity.matrices.RData")
    }
    save(x = similarity.matrices, file = "RData/Similarity.matrices.RData")
    # -----------------------------------------------------------------------------
    # PROJECT:
    #    Evaluating the structure of the communities of the estuary
    #    and gulf of St.Lawrence
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # STEP:
    #   2. Tanimoto analysis for multiple parameter values
    # -----------------------------------------------------------------------------

    # Evaluating the contribution of the catalog vs the predictions to the algorithm

    # -----------------------------------------------------------------------------
    # FILES:
    #   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
    #   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # PARAMETERS:
        filename <- 'Catalog_vs_predictions'
        min.tx = 45
        K.values = 8
        MW = 1
        WT = seq(0,1,by=0.1)
        blind = FALSE
        minimum_threshold = 0.3
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # SCRIPT
    # -----------------------------------------------------------------------------
    load("RData/Tanimoto_data.RData")
    load("RData/interactions_source.RData")
    suppressMessages(load("RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- seq(0,1,by=0.1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            similarity.matrices[[i]] <- NULL
        }

        sim.wt <- names(similarity.matrices)
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

    # List to store results of multiple K values
    K <- vector("list", length(K.values))
    for(i in 1:length(K.values)) {
        K[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- K
    names(Tanimoto_analysis) <- K.values
    remove(K)

    min.wt <- vector("list", length(MW))
    for(i in 1:length(MW)) {
        min.wt[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- min.wt
    names(Tanimoto_analysis) <- MW
    remove(min.wt)

    file.to.save <- serialNext("Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    init.time <- Sys.time()
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon

                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog
                        similarity.matrix <- similarity.matrices[[i]]

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.matrix)

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.matrix = similarity.matrix,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.matrix)
                        setTxtProgressBar(pb, j)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values
                close(pb)
        }#m
    }#n
    print(Sys.time() - init.time)

# Catalog vs predictions
    accuracy  <- vector('list', 3)
    names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
    accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
    accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
    accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
    pdf("Article/Catalog_vs_predictions.pdf",width=7,height=7)
    # Plots
    par(mfrow=c(2,2))
    # Graph
    for(j in 9:12) {
            eplot(xmin = -0.09, xmax = 1.09)
            par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
            foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
            names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
            col <- c("#FF8822","#449955","#2288FF")
            # col <- c("#FF000088","#00FF0088","#0000FF88")
            # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
            # col <- sample(colours(), length(foodwebs))

            # Axes
                # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
                axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
                axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
                axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
                axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
                # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
                # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

                mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
                mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

            for(i in 1:length(accuracy)) {
                accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                # hack: we draw arrows but with very special "arrowheads" for error bars
                arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
                points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
            } #i

            ## Add legend
            if(j == 12) {
                legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
            }
    } #j
    dev.off()

save(x = Tanimoto_analysis, file = paste('Analyses/',filename,'.RData',sep=''))
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#    0.1   Formatting interaction catalog
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# LIBRARIES:
library(stringr)
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("../Interaction_catalog/RData/class_tx_tot.RData")
load("../Interaction_catalog/RData/GloBI_classification.RData")
load("../Interaction_catalog/RData/interactions.RData")
load("../Interaction_catalog/RData/GloBI_interactions.RData")
load("../Interaction_catalog/RData/sp_egsl.RData")
# ---------------------------------
# Unique binary interactions
# ---------------------------------

# Select binary interactions with species that have a fully resolved taxonomy
Biotic_inter <- vector('list',4)
names(Biotic_inter) <- c('Binary_interaction','Taxon_list','Inter_taxonomy','EGSL')

  # For Empirical Webs
    consumer <- numeric()
    resource <- numeric()
    pb <- txtProgressBar(min = 0,max = nrow(inter.tot), style = 3)
    for(i in 1:nrow(inter.tot)) {
      if(!is.na(class.tx.tot[inter.tot[i, 'Predator'], 1])) {
        consumer <- c(consumer, 1)
      } else {
        consumer <- c(consumer, 0)
      } #if

      if(!is.na(class.tx.tot[inter.tot[i, 'Prey'], 1])) {
        resource <- c(resource, 1)
      } else {
        resource <- c(resource, 0)
      } #if
      setTxtProgressBar(pb, i)
    } #i
    close(pb)

    # If all = 1, no need to adjust
    unique(consumer)
    unique(resource)

  # For GloBI interactions
    consumer <- numeric()
    resource <- numeric()
    pb <- txtProgressBar(min = 0,max = nrow(GloBI_interactions), style = 3)
    for(i in 1:nrow(GloBI_interactions)) {
      if(!is.na(GloBI_classification[GloBI_interactions[i, 'Predator'], 1])) {
        consumer <- c(consumer, 1)
      } else {
        consumer <- c(consumer, 0)
      } #if

      if(!is.na(GloBI_classification[GloBI_interactions[i, 'Prey'], 1])) {
        resource <- c(resource, 1)
      } else {
        resource <- c(resource, 0)
      } #if
      setTxtProgressBar(pb, i)
    } #i
    close(pb)

    # If all = 1, no need to adjust
    unique(consumer)
    unique(resource)

    cons_res <- cbind(resource,consumer)
    cons_res <- rowSums(cons_res)

    GloBI_interactions <- GloBI_interactions[-which(cons_res != 2), ]

    # Combining biotic interactions in complete dataset
    Biotic_inter[[1]] <- rbind(inter.tot[, 1:3], GloBI_interactions[, 1:3])
    colnames(Biotic_inter[[1]]) <- c('consumer','inter','resource')
    Biotic_inter[[1]] <- unique(Biotic_inter[[1]])

# ---------------------------------
# Unique taxon list
# ---------------------------------
  Biotic_inter[[2]] <- rbind(class.tx.tot, GloBI_classification)
  Biotic_inter[[2]] <- unique(Biotic_inter[[2]])
  rownames(Biotic_inter[[2]]) <- Biotic_inter[[2]][, 'taxon']

  # Adjust taxon names with taxonomy
  for(i in 1:nrow(Biotic_inter[[2]])) {
    Biotic_inter[[2]][i, 'taxon'] <- paste(Biotic_inter[[2]][i,paste(Biotic_inter[[2]][i, 'rank'])])
  }#i

  # Adjust taxon rank not kept
  Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'tribe'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'tribe'), 'family'])
  Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'superfamily'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'superfamily'), 'order'])
  Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'subfamily'), 'taxon'] <- paste(Biotic_inter[[2]][which(Biotic_inter[[2]][, 'rank'] == 'subfamily'), 'family'])

  # First letter only as capital
  Names_change <- function(x){
    # Name resolve #1
    x <- str_trim(x, side="both") #remove spaces
    x <- tolower(x)
    x <- paste(toupper(substr(x,nchar(x)-(nchar(x)-1),nchar(x)-(nchar(x)-1))),substr(x,nchar(x)-(nchar(x)-2),nchar(x)),sep="")
    return(x)
  }

  Biotic_inter[[2]][, -13] <- apply(Biotic_inter[[2]][, -13], 2, Names_change)
  Biotic_inter[[1]][, -2] <- apply(Biotic_inter[[1]][, -2], 2, Names_change)
  Biotic_inter[[2]] <- apply(Biotic_inter[[2]], 2, gsub, pattern = 'NANA', replacement = 'NA')

  # Also adjust in interactions list
  for(i in 1:nrow(Biotic_inter[[1]])) {
    Biotic_inter[[1]][i, 'consumer'] <- Biotic_inter[[2]][paste(Biotic_inter[[1]][i, 'consumer']), 'taxon']
    Biotic_inter[[1]][i, 'resource'] <- Biotic_inter[[2]][paste(Biotic_inter[[1]][i, 'resource']), 'taxon']
  }

# Also adjust egsl species list
 Biotic_inter[[4]] <- matrix(nrow = nrow(sp.egsl), ncol = ncol(Biotic_inter[[2]]), data = NA, dimnames = list(c(), colnames(Biotic_inter[[2]])))
 rownames(Biotic_inter[[4]]) <- sp.egsl[,1]
 for(i in 1:nrow(sp.egsl)) {
    Biotic_inter[[4]][i, ] <- Biotic_inter[[2]][sp.egsl[i,1], ]
 }

# Also adjust for Empirical Webs interactions
for(i in 1:nrow(inter.tot)) {
  inter.tot[i, 'Predator'] <- Biotic_inter[[2]][paste(inter.tot[i, 'Predator']), 'taxon']
  inter.tot[i, 'Prey'] <- Biotic_inter[[2]][paste(inter.tot[i, 'Prey']), 'taxon']
}

# Also adjust GloBI_interactions
for(i in 1:nrow(GloBI_interactions)) {
  GloBI_interactions[i, 'Predator'] <- Biotic_inter[[2]][paste(GloBI_interactions[i, 'Predator']), 'taxon']
  GloBI_interactions[i, 'Prey'] <- Biotic_inter[[2]][paste(GloBI_interactions[i, 'Prey']), 'taxon']
}

Biotic_inter[[1]] <- Biotic_inter[[1]][-which(Biotic_inter[[1]][,'resource'] == "Copepod"), ]


  # Unique values and adjusting rownames
  Biotic_inter[[1]] <- unique(Biotic_inter[[1]])
  Biotic_inter[[2]] <- unique(Biotic_inter[[2]])
  rownames(Biotic_inter[[2]]) <- Biotic_inter[[2]][, 'taxon']
  rownames(Biotic_inter[[4]]) <- Biotic_inter[[4]][, 'taxon']
  Biotic_inter[[4]] <- Biotic_inter[[4]][,-c(7,9,10,13)]
  GloBI_interactions <- unique(GloBI_interactions[, 1:3])
  inter.tot <- unique(inter.tot[, 1:3])

# --------------------------------------------
# First dataset: taxon with taxonomy as vector
# --------------------------------------------

colnames(GloBI_interactions) <- c('consumer','inter','resource')
taxon.list <- unique(c(unique(Biotic_inter[[1]][, 'consumer']), unique(Biotic_inter[[1]][, 'resource'])))

taxon <- matrix(nrow = length(taxon.list), ncol = 2, data = NA, dimnames = list(c(), c("taxon", "kingdom | phylum | class | order | family | genus | species")))
taxon[, 1] <- taxon.list

# Extracting taxonomy for each binary interaction
rank <- c("kingdom","phylum","class","order","family","genus","species")
taxonomy <- matrix(nrow = nrow(taxon), ncol = length(rank), dimnames = list(c(), rank))

pb <- txtProgressBar(min = 0,max = nrow(taxon), style = 3)
for(i in 1:nrow(taxon)) {
  taxonomy[i, ] <- Biotic_inter[[2]][taxon[i, 'taxon'], rank]
  setTxtProgressBar(pb, i)
} #i
close(pb)

# Combining taxonomy into single element
# Ranks are  "kingdom | phylum | class | order | family | genus | species"
taxon[, 2] <- apply(taxonomy, 1, paste, collapse = ' | ')

# write.table(taxon, "Phil_data/0-taxon_list.txt", sep="\t")

# ---------------------------------------------------------------------------
# Second dataset: Predators with sets of prey and non-prey for Empirical Webs
# ---------------------------------------------------------------------------
rownames(inter.tot) <- seq(1,nrow(inter.tot))
emp.web.inter <- consumer_set_of_resource(consumer = inter.tot[, 'Predator'],
                                          resource = inter.tot[, 'Prey'],
                                          inter_type = inter.tot[, 'FeedInter']
                                          )

# write.table(emp.web.inter, "Phil_data/1-emp_webs_interactions.txt", sep="\t")

# ----------------------------------------------------------------------------------
# Third dataset: Predators with sets of prey and non-prey for Empirical Webs + GloBI
# ----------------------------------------------------------------------------------
rownames(Biotic_inter[[1]]) <- seq(1,nrow(Biotic_inter[[1]]))
total.inter <- consumer_set_of_resource(consumer = Biotic_inter[[1]][, 'consumer'],
                                        resource = Biotic_inter[[1]][, 'resource'],
                                        inter_type = Biotic_inter[[1]][, 'inter']
                                        )

# write.table(total.inter, "Phil_data/2-total_interactions.txt", sep="\t")

# ----------------------------
# Fourth dataset: EGSL species
# ----------------------------
egsl <- matrix(nrow = nrow(Biotic_inter[[4]]), ncol = 2, data = NA, dimnames = list(c(Biotic_inter[[4]][, 'taxon']), c("taxon", "kingdom | phylum | class | order | family | genus | species")))
egsl[, 'taxon'] <- Biotic_inter[[4]][, 'taxon']
egsl[, 2] <- apply(Biotic_inter[[4]][,3:9], 1, paste, collapse = ' | ')
egsl <- unique(egsl)

# remove duplicated taxon
which(duplicated(egsl[,'taxon']))
egsl <- egsl[-1209, ]

# write.table(egsl, "Phil_data/3-EGSL_species.txt", sep="\t", row.names = FALSE, col.names = c('EGSL_species'))

# ----------------------------
# RData
# ----------------------------
Tanimoto_data <- vector("list", 4)
Tanimoto_data[[1]] <- taxon
Tanimoto_data[[2]] <- emp.web.inter
Tanimoto_data[[3]] <- total.inter
Tanimoto_data[[4]] <- egsl

save(x = Tanimoto_data, file = "RData/Tanimoto_data.RData")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Tanimoto analysis for multiple parameter values
# -----------------------------------------------------------------------------

# Evaluating the effects of multiple parameters on the efficiency of the algorithm

# -----------------------------------------------------------------------------
# FILES:
#   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
#   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PARAMETERS:
    filename <- 'Multiple_parameters'
    min.tx = 45
    K.values = c(2,4,6,8)
    MW = c(1,3,5)
    WT = c(0,0.3,0.6,1)
    blind = FALSE
    minimum_threshold = 0.3
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# SCRIPT
# -----------------------------------------------------------------------------
load("RData/Tanimoto_data.RData")
load("RData/interactions_source.RData")
suppressMessages(load("RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


# S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
# Format interaction catalogue to fit this table format
    S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
    S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
    S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
    # From binary interactions catalogue with consumer, resources, interaction or non-interaction
    for(k in 1:nrow(Tanimoto_data[[3]])) {
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
        S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
    }

# setting up the analyses for multiple communities
# Data for communities on which to test the algorithm
    Cm <- unique(interactions_sources[, 'source'])
    communities <- vector("list", length(Cm))
    names(communities) <- Cm

    # Taxa list per community to predict
        for(i in 1:length(communities)) {
            Ci <- which(interactions_sources[, 'source'] == Cm[i])
            S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

            if(length(which(!S1 %in% S0_catalog)) > 0) {
                print('Taxa in C[i] are not all included in taxa list S0')
                break
            }

            communities[[i]] <- S1
        }

# Substracting GloBI interactions for this portion
    Cm.lg <- numeric()
    for(i in 1:length(communities)) {
        Cm.lg <- c(Cm.lg,length(communities[[i]]))
    }

    to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

    Cm <- Cm[-to.delete]
    for(i in rev(to.delete)) {
        communities[[i]] <- NULL
    }
    names(communities) <- Cm

# Setting up lists to store the results
    wt.init <- seq(0,1,by=0.1)
    wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
    for(i in rev(wt.remove)) {
        similarity.matrices[[i]] <- NULL
    }

    sim.wt <- names(similarity.matrices)
    Tanimoto_analysis <- vector("list",length(sim.wt))
    names(Tanimoto_analysis) <- sim.wt
    for(i in 1:length(sim.wt)) {
        Tanimoto_analysis[[i]] <- vector("list", length(Cm))
        names(Tanimoto_analysis[[i]]) <- Cm
    }

# List to store results of multiple K values
K <- vector("list", length(K.values))
for(i in 1:length(K.values)) {
    K[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- K
names(Tanimoto_analysis) <- K.values
remove(K)

min.wt <- vector("list", length(MW))
for(i in 1:length(MW)) {
    min.wt[[i]] <- Tanimoto_analysis
}
Tanimoto_analysis <- min.wt
names(Tanimoto_analysis) <- MW
remove(min.wt)

file.to.save <- serialNext("Analyses/Tanimoto_temp/Tanimoto_analysis.RData")
save(x = Tanimoto_analysis, file = file.to.save)

init.time <- Sys.time()
for(n in 1:length(MW)) {
    mw <- MW[n]
    for(m in 1:length(K.values)) {

        # Tanimoto analysis with different weights for different communities
            # Parameters:
                Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
            #   wt  Weight of traits in similarity measurement
            #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
            #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

            # Output:
            #   A vector of sets of resources for each taxon

            for(i in 1:length(WT)){ #1st loop for all types of wt values
                wt <- WT[i]
                pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                for(j in 1:length(Cm)) { #2nd loop for all C[i]
                    S1 <- communities[[j]]
                    S0 <- S0_catalog
                    similarity.matrix <- similarity.matrices[[i]]

                    # Two choices here:
                    #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                    #   2. The analysis takes into account preexisting information already contained in the catalogue

                    # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                    if(blind == TRUE) {
                        for(k in 1:length(S1)) {
                          S0[S1[k], 'resource'] <- ""
                          S0[S1[k], 'non-resource'] <- ""
                        }

                    # 2. Preexisting information kept to inform algorithm
                    } else { # blind == FALSE

                        interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                        # Only modifying those that are loosing data from the catalogue, less time
                            to.change <- numeric()
                            for(k in 1:length(S1)) {
                                to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                            }
                            to.change <- unique(to.change)

                        # Modifying sets of resources and non-resources for taxa in S1
                            interactions <- interactions[to.change, ]
                            rownames(interactions) <- seq(1,nrow(interactions))
                            resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                      resource = interactions[, 'resource'],
                                                                      inter_type = interactions[, 'inter'])

                        # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                            for(k in 1:nrow(resource_set)) {
                              S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                              S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                            }
                        remove(interactions, resource_set, to.change)
                    } #if blind or not blind

                    # Recalculate similarity
                        similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                            S1 = S1,
                                                                            wt = wt,
                                                                            similarity.matrix = similarity.matrix)

                    # Predicting interactions
                        Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                Kr = Kr,
                                                                                S0 = S0,
                                                                                S1 = S1,
                                                                                MW = mw,
                                                                                similarity.matrix = similarity.matrix,
                                                                                minimum_threshold = minimum_threshold)

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(S0, S1, similarity.matrix)
                    setTxtProgressBar(pb, j)
                }#2nd loop for all C[i]

                save(x = Tanimoto_analysis, file = file.to.save)
                remove(wt)

            }#1st loop for all types of wt values
            close(pb)
    }#m
}#n
print(Sys.time() - init.time)

# Catalog vs predictions
accuracy  <- vector('list', 3)
names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
pdf("Article/Catalog_vs_predictions.pdf",width=7,height=7)
# Plots
par(mfrow=c(2,2))
# Graph
for(j in 9:12) {
        eplot(xmin = -0.09, xmax = 1.09)
        par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
        foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
        names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
        col <- c("#FF8822","#449955","#2288FF")
        # col <- c("#FF000088","#00FF0088","#0000FF88")
        # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
        # col <- sample(colours(), length(foodwebs))

        # Axes
            # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
            axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
            axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
            # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
            # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

            mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
            mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

        for(i in 1:length(accuracy)) {
            accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
            # hack: we draw arrows but with very special "arrowheads" for error bars
            arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
            points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
        } #i

        ## Add legend
        if(j == 12) {
            legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
        }
} #j
dev.off()

save(x = Tanimoto_analysis, file = paste('Analyses/',filename,'.RData',sep=''))
# ---------------------------------------------------------------------------
# Two-way Tanimoto algorithm: prediction accuracy for 2-Tanimoto_analysis.r
# ---------------------------------------------------------------------------

tanimoto_accuracy <- function(Tanimoto_analysis, predict.only = FALSE, empirical.only = FALSE) {
    load("RData/interactions_source.RData")
    source("Script/prediction_matrix.r")
    source("Script/empirical_matrix.r")
    source("Script/prediction_accuracy.r")


    accuracy <- matrix(ncol = 12, nrow = length(Tanimoto_analysis) * length(Tanimoto_analysis[[1]]) * length(Tanimoto_analysis[[1]][[1]]) * length(Tanimoto_analysis[[1]][[1]][[1]]), data = 0, dimnames = list(c(), c('MW','K','wt','Cm','a','b','c','d','TSS','ScoreY1','ScoreY0','FSS')))
    iteration <- 1
    for(n in 1: length(Tanimoto_analysis)) { #loop through MW values
        for(m in 1: length(Tanimoto_analysis[[1]])) { # loop through K values
            for(i in 1:length(Tanimoto_analysis[[1]][[1]])){ #1st loop for all types of wt values
                for(j in 1:length(Tanimoto_analysis[[1]][[1]][[1]])) { #2nd loop for all C[i]
                    # Arguments:
                    S1 <- Tanimoto_analysis[[n]][[m]][[i]][[j]][, 'consumer']
                    predictions <- Tanimoto_analysis[[n]][[m]][[i]][[j]]
                    interactions_source <- interactions_sources
                    source <- names(Tanimoto_analysis[[n]][[m]][[i]])[j]

                    accuracy[iteration, 'MW'] <- names(Tanimoto_analysis)[n]
                    accuracy[iteration, 'K'] <- names(Tanimoto_analysis[[n]])[m]
                    accuracy[iteration, 'wt'] <- names(Tanimoto_analysis[[n]][[m]])[i]
                    accuracy[iteration, 'Cm'] <- names(Tanimoto_analysis[[n]][[m]][[i]])[j]
                    accuracy[iteration, 5:12] <- prediction_accuracy(predicted = prediction_matrix(S1 = S1, predictions = predictions, predict.only = predict.only, empirical.only = empirical.only),
                                                        empirical = empirical_matrix(S1 = S1, interactions_source = interactions_source, source = source))

                    iteration <- iteration + 1
                    remove(S1, predictions, interactions_source, source)
                }#j
            }#i
        }#m
    }#n

    return(accuracy)

}#Tanimoto_accuracy function
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# STEP:
#   2. Evaluation of analysis accuracy + tables and figures
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FILES:
#           Script <- file = 'Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = 'RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

load("RData/Tanimoto_analysis.RData")

Tanimoto_accuracy <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

# Creating an empty plot
eplot <- function(x, y) {
  plot(x = x, y = y, bty = "n",ann = FALSE,xaxt = "n",yaxt = "n",type = "n",bg = "grey", ylim = c(-0.09,1.09), xlim = c(-0.09,1.09))
}

pdf("Article/results4.pdf",width=7,height=7)
# Plots
par(mfrow=c(2,2))
# Graph
for(j in 8:11) {
    eplot(x = accuracy[, 'wt'], y = accuracy[, j])
    par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
    # foodwebs <- to.verify
    # col <- c('blue','green','black','red','yellow','darkgrey','orange','brown','grey','green','darkgreen','darkblue')
    col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL)
    names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
    # sample(colours(), length(foodwebs))
    # cols <- c("#FF000088","#00FF0088","#0000FF88")
    # cols2 <- c("#FF0000","#00FF00","#0000FF")

    # Axes
    # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
    axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 0)
    axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.09)
    axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1)
    axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.09)
    # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
    # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

    #
    mtext(text = names[j-7], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
    mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

    for(i in 1:12) {
        x <- as.numeric(names(Tanimoto_analysis[[1]]))
        y <- numeric()
        for(k in 1:6) {
            y <- c(y,mean(as.numeric(accuracy[which(accuracy[, 'K'] == i & accuracy[, 'wt'] == names(Tanimoto_analysis[[1]])[k]), j][-5])))
            # mean(as.numeric(accuracy[which(accuracy[, 'K'] == i & accuracy[, 'wt'] == names(Tanimoto_analysis[[1]])[k]), j][-5]))
        }

        points(x = x, y = y, bg = col[i], cex = 1.25, pch = 18, col = col[i])
        lines(x = x, y = y, col = col[i], lwd = 0.5)

        # points(x = accuracy[which(accuracy[, 'K'] == i), 'wt'], y = accuracy[which(accuracy[, 'K'] == i), j], bg = col[i], cex = 1.25, pch = 18, col = col[i])
        # lines(x = accuracy[which(accuracy[, 'K'] == i), 'wt'], y = accuracy[which(accuracy[, 'K'] == i), j], col = col[i], lwd = 0.5)
    }

    # boxplot(formula = as.numeric(accuracy[, j]) ~ accuracy[, 'wt'],
    #         data = accuracy,
    #         boxwex = 0.075,
    #         axes = FALSE,
    #         add = TRUE,
    #         at = seq(0, 1, by = 0.1))
}
dev.off()
    # -----------------------------------------------------------------------------
    # PROJECT:
    #    Evaluating the structure of the communities of the estuary
    #    and gulf of St.Lawrence
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # STEP:
    #   2. Tanimoto analysis for multiple parameter values
    # -----------------------------------------------------------------------------

    # Evaluating the contribution of the catalog vs the predictions to the algorithm

    # -----------------------------------------------------------------------------
    # FILES:
    #   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
    #   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # PARAMETERS:
        min.tx = 45
        K.values = 8
        MW = 1
        WT = c(0, 0.2, 0.5, 0.8, 1)
        blind = FALSE
        minimum_threshold = 0.3
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # SCRIPT
    # -----------------------------------------------------------------------------
    load("RData/Tanimoto_data.RData")
    load("RData/interactions_source.RData")
    suppressMessages(load("RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- seq(0,1,by=0.1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            similarity.matrices[[i]] <- NULL
        }

        sim.wt <- names(similarity.matrices)
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

    # List to store results of multiple K values
    K <- vector("list", length(K.values))
    for(i in 1:length(K.values)) {
        K[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- K
    names(Tanimoto_analysis) <- K.values
    remove(K)

    min.wt <- vector("list", length(MW))
    for(i in 1:length(MW)) {
        min.wt[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- min.wt
    names(Tanimoto_analysis) <- MW
    remove(min.wt)

    file.to.save <- serialNext("RData/tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    save(x = Tanimoto_analysis, file = paste(serialNext("RData/tanimoto_temp/Tanimoto_analysis.RData"),)

    init.time <- Sys.time()
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon

                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog
                        similarity.matrix <- similarity.matrices[[i]]

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.matrix)

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.matrix = similarity.matrix,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.matrix)
                        setTxtProgressBar(pb, j)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values
                close(pb)
        }#m
    }#n
    print(Sys.time() - init.time)


# Catalog vs predictions
    accuracy  <- vector('list', 3)
    names(accuracy) <- c('Catalog', 'Predict', 'Algorithm')
    accuracy[[1]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
    accuracy[[2]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, predict.only = TRUE)
    accuracy[[3]] <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)

#Figure
    pdf("Article/Catalog_vs_predictions.pdf",width=7,height=7)
    # Plots
    par(mfrow=c(2,2))
    # Graph
    for(j in 9:12) {
            eplot(xmin = -0.09, xmax = 1.09)
            par(pch = 21,  xaxs = "i", yaxs = "i", family = "serif")
            foodwebs <- names(Tanimoto_analysis[[1]][[1]][[1]])
            names <- c('TSS','Score y', 'Score -y', 'Accuracy score')
            col <- c("#FF8822","#99FF55","#2288FF")
            # col <- c("#FF000088","#00FF0088","#0000FF88")
            # col <- gray.colors(11, start = 0, end = 0.8, gamma = 2.2, alpha = NULL) # grey scale ramp
            # col <- sample(colours(), length(foodwebs))

            # Axes
                # rect(0, 0, 1, 1, col = "#eeeeee", border = NA)
                axis(side = 1, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
                axis(side = 2, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = -0.02)
                axis(side = 3, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
                axis(side = 4, at = seq(0, 1, by = 0.2), labels = seq(0, 1, by = 0.2), las = 1, pos = 1.02)
                # abline(v = seq(0,6,by = 2), col = "white", lty = 2)
                # abline(h = seq(1,2,by = 1), col = "white", lty = 2)

                mtext(text = names[j-8], side = 2, line = 2, at = 0.5, font = 2, cex = 1)
                mtext(text = "Similarity weight", side = 1, line = 2, at = 0.5, font = 2, cex = 1)

            for(i in 1:length(accuracy)) {
                accuracy_mean <- aggregate(as.numeric(accuracy[[i]][,j]) ~ as.numeric(accuracy[[i]][, 'wt']), data=accuracy[[i]], FUN=function(x) c(mean=mean(x), sd=sd(x)))
                # hack: we draw arrows but with very special "arrowheads" for error bars
                arrows(accuracy_mean[, 1], accuracy_mean[, 2][,1] - accuracy_mean[, 2][, 2], accuracy_mean[, 1], accuracy_mean[, 2][, 1] + accuracy_mean[, 2][, 2], length=0.05, angle=90, code=3, col = col[i])
                points(x = accuracy_mean[, 1], y = accuracy_mean[, 2][, 1], cex = 1.5, pch = 22, col = col[i])
            } #i

            ## Add legend
            if(j == 12) {
                legend(0.45, 0.3, lwd = 3, col = col, legend = names(accuracy), bty = 'n', y.intersp = 1)
            }
    } #j
    dev.off()
    # -----------------------------------------------------------------------------
    # PROJECT:
    #    Evaluating the structure of the communities of the estuary
    #    and gulf of St.Lawrence
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # STEP:
    #   2. Tanimoto analysis for multiple parameter values
    # -----------------------------------------------------------------------------

    # Analysis description:
    # Testing multiple Kr & Kc values
    # Only using 6 weight values to speed up analysis (seq(0,1,by=0.2))

    # -----------------------------------------------------------------------------
    # FILES:
    #   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
    #   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # PARAMETERS:
        min.tx = 45
        K.values = seq(3, 8, by = 1)
        MW = c(1,3,8)
        WT = c(0,0.2,0.5,0.8,1)
        blind = FALSE
        minimum_threshold = 0.3
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # SCRIPT
    # -----------------------------------------------------------------------------
    load("RData/Tanimoto_data.RData")
    load("RData/interactions_source.RData")
    suppressMessages(load("RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- seq(0,1,by=0.1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            similarity.matrices[[i]] <- NULL
        }

        sim.wt <- names(similarity.matrices)
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

    # List to store results of multiple K values
    K <- vector("list", length(K.values))
    for(i in 1:length(K.values)) {
        K[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- K
    names(Tanimoto_analysis) <- K.values
    remove(K)

    min.wt <- vector("list", length(MW))
    for(i in 1:length(MW)) {
        min.wt[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- min.wt
    names(Tanimoto_analysis) <- MW
    remove(min.wt)

    init.time <- Sys.time()
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon

                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog
                        similarity.matrix <- similarity.matrices[[i]]

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            # to.remove <- numeric()
                            # to.recalculate <- which(S0[, 'taxon'] %in% S1)
                            #
                            # for(k in 1:length(S1)) {
                            #     to.remove <- c(to.remove, which(S0[, 'taxon'] == S1[k]))
                            # }
                            # similarity.matrix <- similarity.matrix[-to.remove, -to.remove]    # Removing similarities to recalculate
                            similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.matrix)

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.matrix = similarity.matrix,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = "RData/tanimoto_temp/Tanimoto_analysis.RData")
                        remove(S0, S1, similarity.matrix, to.remove)
                        setTxtProgressBar(pb, j)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = "RData/tanimoto_temp/Tanimoto_analysis.RData")
                    remove(wt)

                }#1st loop for all types of wt values
                close(pb)
        }#m
    }#n
    print(Sys.time() - init.time)

save(x = Tanimoto_analysis, file = "RData/Tanimoto_analysis.RData")
# Run readme.r before other scripts
rm(list=ls())
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "Script/0-1-Tanimoto_data.r
#           RData <- file = 'RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "Script/0-1-Interactions_sources.r
#           RData <- file = "RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = 'Script/1-Similarity_matrix.r'
#       RData <- file = 'RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = 'Script/2-1-Tanimoto_analysis.r'
#           RData <- file = 'RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = 'Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = 'RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("Script/Tanimoto.r") # basic tanimoto similarity
source("Script/Tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("Script/similarity_taxon.r") # similarity matrix for set of taxa
source("Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/consumer_set_of_resource.R")
source("Script/prediction_accuracy.r") #
source("Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
source("Script/serialNext.r")
source("Script/eplot.r") # empty plot for figure generation
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
    # -----------------------------------------------------------------------------
    # PROJECT:
    #    Evaluating the structure of the communities of the estuary
    #    and gulf of St.Lawrence
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # STEP:
    #   2. Tanimoto analysis for multiple parameter values
    # -----------------------------------------------------------------------------

    # Evaluating the contribution of the catalog vs the predictions to the algorithm

    # -----------------------------------------------------------------------------
    # FILES:
    #   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
    #   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # PARAMETERS:
        min.tx = 45
        K.values = 5
        MW = 1
        WT = c(0,0.5,1)
        blind = FALSE
        minimum_threshold = 0.3
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # SCRIPT
    # -----------------------------------------------------------------------------
    load("RData/Tanimoto_data.RData")
    load("RData/interactions_source.RData")
    suppressMessages(load("RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- seq(0,1,by=0.1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            similarity.matrices[[i]] <- NULL
        }

        sim.wt <- names(similarity.matrices)
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

    # List to store results of multiple K values
    K <- vector("list", length(K.values))
    for(i in 1:length(K.values)) {
        K[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- K
    names(Tanimoto_analysis) <- K.values
    remove(K)

    min.wt <- vector("list", length(MW))
    for(i in 1:length(MW)) {
        min.wt[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- min.wt
    names(Tanimoto_analysis) <- MW
    remove(min.wt)

    file.to.save <- serialNext("RData/tanimoto_temp/Tanimoto_analysis.RData")
    save(x = Tanimoto_analysis, file = file.to.save)

    save(x = Tanimoto_analysis, file = paste(serialNext("RData/tanimoto_temp/Tanimoto_analysis.RData"),)

    init.time <- Sys.time()
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon

                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog
                        similarity.matrix <- similarity.matrices[[i]]

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.matrix)

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.matrix = similarity.matrix,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = file.to.save)
                        remove(S0, S1, similarity.matrix)
                        setTxtProgressBar(pb, j)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = file.to.save)
                    remove(wt)

                }#1st loop for all types of wt values
                close(pb)
        }#m
    }#n
    print(Sys.time() - init.time)


# Catalog vs predictions
    Catalog <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
    Predict <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis predict.only = TRUE)
    Algo <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)
# Run readme.r before other scripts
rm(list=ls())
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "Script/0-1-Tanimoto_data.r
#           RData <- file = 'RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "Script/0-1-Interactions_sources.r
#           RData <- file = "RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = 'Script/1-Similarity_matrix.r'
#       RData <- file = 'RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = 'Script/2-1-Tanimoto_analysis.r'
#           RData <- file = 'RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = 'Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = 'RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("Script/Tanimoto.r") # basic tanimoto similarity
source("Script/Tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("Script/similarity_taxon.r") # similarity matrix for set of taxa
source("Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/consumer_set_of_resource.R")
source("Script/prediction_accuracy.r") #
source("Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
Source("Script/serialNext.r"))
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Two-way Tanimoto algorithm: prediction accuracy for 2-Tanimoto_analysis.r
# ---------------------------------------------------------------------------

tanimoto_accuracy <- function(Tanimoto_analysis, predict.only = FALSE, empirical.only = FALSE) {
    load("RData/interactions_source.RData")
    source("Script/prediction_matrix.r")
    source("Script/empirical_matrix.r")
    source("Script/tanimoto_efficiency.r")


    accuracy <- matrix(ncol = 12, nrow = length(Tanimoto_analysis) * length(Tanimoto_analysis[[1]]) * length(Tanimoto_analysis[[1]][[1]]) * length(Tanimoto_analysis[[1]][[1]][[1]]), data = 0, dimnames = list(c(), c('MW','K','wt','Cm','a','b','c','d','TSS','ScoreY1','ScoreY0','FSS')))
    iteration <- 1
    for(n in 1: length(Tanimoto_analysis)) { #loop through MW values
        for(m in 1: length(Tanimoto_analysis[[1]])) { # loop through K values
            for(i in 1:length(Tanimoto_analysis[[1]][[1]])){ #1st loop for all types of wt values
                for(j in 1:length(Tanimoto_analysis[[1]][[1]][[1]])) { #2nd loop for all C[i]
                    # Arguments:
                    S1 <- Tanimoto_analysis[[n]][[m]][[i]][[j]][, 'consumer']
                    predictions <- Tanimoto_analysis[[n]][[m]][[i]][[j]]
                    interactions_source <- interactions_sources
                    source <- names(Tanimoto_analysis[[n]][[m]][[i]])[j]

                    accuracy[iteration, 'MW'] <- names(Tanimoto_analysis)[n]
                    accuracy[iteration, 'K'] <- names(Tanimoto_analysis[[n]])[m]
                    accuracy[iteration, 'wt'] <- names(Tanimoto_analysis[[n]][[m]])[i]
                    accuracy[iteration, 'Cm'] <- names(Tanimoto_analysis[[n]][[m]][[i]])[j]
                    accuracy[iteration, 5:12] <- prediction_accuracy(predicted = prediction_matrix(S1 = S1, predictions = predictions, predict.only = predict.only, empirical.only = empirical.only),
                                                        empirical = empirical_matrix(S1 = S1, interactions_source = interactions_source, source = source))

                    iteration <- iteration + 1
                    remove(S1, predictions, interactions_source, source)
                }#j
            }#i
        }#m
    }#n

    return(accuracy)

}#Tanimoto_accuracy function
    # -----------------------------------------------------------------------------
    # PROJECT:
    #    Evaluating the structure of the communities of the estuary
    #    and gulf of St.Lawrence
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # STEP:
    #   2. Tanimoto analysis for multiple parameter values
    # -----------------------------------------------------------------------------

    # Evaluating the contribution of the catalog vs the predictions to the algorithm

    # -----------------------------------------------------------------------------
    # FILES:
    #   RData <- file = "RData/Tanimoto_analysis.RData" XXX adjust name with type of analysis
    #   Script  <- file = "Script/2-1-Tanomoto_analysis.r"
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # PARAMETERS:
        min.tx = 45
        K.values = 5
        MW = 1
        WT = c(0,0.5,1)
        blind = FALSE
        minimum_threshold = 0.3
    # -----------------------------------------------------------------------------

    # -----------------------------------------------------------------------------
    # SCRIPT
    # -----------------------------------------------------------------------------
    load("RData/Tanimoto_data.RData")
    load("RData/interactions_source.RData")
    suppressMessages(load("RData/Similarity.matrices.RData")) # For similarity matrices already evaluated


    # S0: A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
    # Format interaction catalogue to fit this table format
        S0_catalog <- matrix(nrow = nrow(Tanimoto_data[[1]]), ncol = 4, data = "", dimnames = list(Tanimoto_data[[1]][, 'taxon'], c('taxon', 'taxonomy', 'resource', 'non-resource')))
        S0_catalog[, 1] <- Tanimoto_data[[1]][, 'taxon']
        S0_catalog[, 2] <- Tanimoto_data[[1]][, 'kingdom | phylum | class | order | family | genus | species']
        # From binary interactions catalogue with consumer, resources, interaction or non-interaction
        for(k in 1:nrow(Tanimoto_data[[3]])) {
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 3] <- Tanimoto_data[[3]][k, 'resource']
            S0_catalog[Tanimoto_data[[3]][k, 'consumer'], 4] <- Tanimoto_data[[3]][k, 'non-resource']
        }

    # setting up the analyses for multiple communities
    # Data for communities on which to test the algorithm
        Cm <- unique(interactions_sources[, 'source'])
        communities <- vector("list", length(Cm))
        names(communities) <- Cm

        # Taxa list per community to predict
            for(i in 1:length(communities)) {
                Ci <- which(interactions_sources[, 'source'] == Cm[i])
                S1 <- unique(c(interactions_sources[Ci, 'consumer'], interactions_sources[Ci, 'resource']))

                if(length(which(!S1 %in% S0_catalog)) > 0) {
                    print('Taxa in C[i] are not all included in taxa list S0')
                    break
                }

                communities[[i]] <- S1
            }

    # Substracting GloBI interactions for this portion
        Cm.lg <- numeric()
        for(i in 1:length(communities)) {
            Cm.lg <- c(Cm.lg,length(communities[[i]]))
        }

        to.delete <- c(which(Cm.lg < min.tx), which(Cm.lg > 1000)) # > 1000 is for GloBI

        Cm <- Cm[-to.delete]
        for(i in rev(to.delete)) {
            communities[[i]] <- NULL
        }
        names(communities) <- Cm

    # Setting up lists to store the results
        wt.init <- seq(0,1,by=0.1)
        wt.remove <- which(!wt.init %in% WT)# selecting a subset of similarity matrices
        for(i in rev(wt.remove)) {
            similarity.matrices[[i]] <- NULL
        }

        sim.wt <- names(similarity.matrices)
        Tanimoto_analysis <- vector("list",length(sim.wt))
        names(Tanimoto_analysis) <- sim.wt
        for(i in 1:length(sim.wt)) {
            Tanimoto_analysis[[i]] <- vector("list", length(Cm))
            names(Tanimoto_analysis[[i]]) <- Cm
        }

    # List to store results of multiple K values
    K <- vector("list", length(K.values))
    for(i in 1:length(K.values)) {
        K[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- K
    names(Tanimoto_analysis) <- K.values
    remove(K)

    min.wt <- vector("list", length(MW))
    for(i in 1:length(MW)) {
        min.wt[[i]] <- Tanimoto_analysis
    }
    Tanimoto_analysis <- min.wt
    names(Tanimoto_analysis) <- MW
    remove(min.wt)

    init.time <- Sys.time()
    for(n in 1:length(MW)) {
        mw <- MW[n]
        for(m in 1:length(K.values)) {

            # Tanimoto analysis with different weights for different communities
                # Parameters:
                    Kc <- K.values[m]  # Integer, how many neighbors to select for consumers
                    Kr <-  K.values[m]  # Integer, how many neighbors to select for resources
                    # MW = minimum_weight  # Mimimum weight to accept a candidate as a prey
                #   wt  Weight of traits in similarity measurement
                #   S0  A large set of species and their preys, with column structure ['taxon', 'taxonomy', 'resource', 'non-resource']
                #   S1  The subset of S0 where we want to predict new preys, string vector with taxa name

                # Output:
                #   A vector of sets of resources for each taxon

                for(i in 1:length(WT)){ #1st loop for all types of wt values
                    wt <- WT[i]
                    pb <- txtProgressBar(min = 0,max = length(Cm), style = 3)

                    for(j in 1:length(Cm)) { #2nd loop for all C[i]
                        S1 <- communities[[j]]
                        S0 <- S0_catalog
                        similarity.matrix <- similarity.matrices[[i]]

                        # Two choices here:
                        #   1. The analysis is blind, which means we remove all the information available in the catalogue for all species in S1
                        #   2. The analysis takes into account preexisting information already contained in the catalogue

                        # 1. Blind analysis, removing all information on taxa in S1 from S0 (rownames need to == taxa name)
                        if(blind == TRUE) {
                            for(k in 1:length(S1)) {
                              S0[S1[k], 'resource'] <- ""
                              S0[S1[k], 'non-resource'] <- ""
                            }

                        # 2. Preexisting information kept to inform algorithm
                        } else { # blind == FALSE

                            interactions <- interactions_sources[-which(interactions_sources[, 'source'] == Cm[j]), 1:3]

                            # Only modifying those that are loosing data from the catalogue, less time
                                to.change <- numeric()
                                for(k in 1:length(S1)) {
                                    to.change <- c(to.change, which(interactions[, 'consumer'] == S1[k]), which(interactions[, 'resource'] == S1[k]))
                                }
                                to.change <- unique(to.change)

                            # Modifying sets of resources and non-resources for taxa in S1
                                interactions <- interactions[to.change, ]
                                rownames(interactions) <- seq(1,nrow(interactions))
                                resource_set <- consumer_set_of_resource(consumer = interactions[, 'consumer'],
                                                                          resource = interactions[, 'resource'],
                                                                          inter_type = interactions[, 'inter'])

                            # From binary interactions catalogue with consumer, resources, interaction or non-interaction (rownames need to == taxa name)
                                for(k in 1:nrow(resource_set)) {
                                  S0[resource_set[k, 'consumer'], 3] <- resource_set[k, 'resource']
                                  S0[resource_set[k, 'consumer'], 4] <- resource_set[k, 'non-resource']
                                }
                            remove(interactions, resource_set, to.change)
                        } #if blind or not blind

                        # Recalculate similarity
                            # to.remove <- numeric()
                            # to.recalculate <- which(S0[, 'taxon'] %in% S1)
                            #
                            # for(k in 1:length(S1)) {
                            #     to.remove <- c(to.remove, which(S0[, 'taxon'] == S1[k]))
                            # }
                            # similarity.matrix <- similarity.matrix[-to.remove, -to.remove]    # Removing similarities to recalculate
                            similarity.matrix <- similarity_taxon_predict(S0 = S0,
                                                                                S1 = S1,
                                                                                wt = wt,
                                                                                similarity.matrix = similarity.matrix)

                        # Predicting interactions
                            Tanimoto_analysis[[n]][[m]][[i]][[j]] <- two_way_tanimoto_predict(Kc = Kc,
                                                                                    Kr = Kr,
                                                                                    S0 = S0,
                                                                                    S1 = S1,
                                                                                    MW = mw,
                                                                                    similarity.matrix = similarity.matrix,
                                                                                    minimum_threshold = minimum_threshold)

                        save(x = Tanimoto_analysis, file = "RData/tanimoto_temp/Tanimoto_analysis.RData")
                        remove(S0, S1, similarity.matrix, to.remove)
                        setTxtProgressBar(pb, j)
                    }#2nd loop for all C[i]

                    save(x = Tanimoto_analysis, file = "RData/tanimoto_temp/Tanimoto_analysis.RData")
                    remove(wt)

                }#1st loop for all types of wt values
                close(pb)
        }#m
    }#n
    print(Sys.time() - init.time)


# Catalog vs predictions
    Catalog <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis, empirical.only = TRUE)
    Predict <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis predict.only = TRUE)
    Algo <- tanimoto_accuracy(Tanimoto_analysis = Tanimoto_analysis)
# Run readme.r before other scripts
rm(list=ls())
setwd("/Users/davidbeauchesne/Dropbox/PhD/PhD_obj2/Structure_Comm_EGSL/Predict_interactions")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "Script/0-1-Tanimoto_data.r
#           RData <- file = 'RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "Script/0-1-Interactions_sources.r
#           RData <- file = "RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = 'Script/1-Similarity_matrix.r'
#       RData <- file = 'RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = 'Script/2-1-Tanimoto_analysis.r'
#           RData <- file = 'RData/Tanimoto_analysis.RData'
#
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = 'Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = 'RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("Script/Tanimoto.r") # basic tanimoto similarity
source("Script/Tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("Script/similarity_taxon.r") # similarity matrix for set of taxa
source("Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/consumer_set_of_resource.R")
source("Script/prediction_accuracy.r") #
source("Script/tanimoto_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# Run readme.r before other scripts
rm(list=ls())
setwd("/Users/davidbeauchesne/Dropbox/Structure_Comm_EGSL/Tanimoto_algorithm")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "Script/0-1-Tanimoto_data.r
#           RData <- file = 'RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "Script/0-1-Interactions_sources.r
#           RData <- file = "RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = 'Script/1-Similarity_matrix.r'
#       RData <- file = 'RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = 'Script/2-1-Tanimoto_analysis.r'
#           RData <- file = 'RData/Tanimoto_analysis.RData'
# 
#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = 'Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = 'RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("Script/Tanimoto.r") # basic tanimoto similarity
source("Script/Tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("Script/similarity_taxon.r") # similarity matrix for set of taxa
source("Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/consumer_set_of_resource.R")
source("Script/tanimoto_efficiency.r") # predictions formatted to food web matrix format (S x S)
source("Script/prediction_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# ---------------------------------------------------------------------------
# Two-way Tanimoto algorithm: prediction accuracy for 2-Tanimoto_analysis.r
# ---------------------------------------------------------------------------

tanimoto_accuracy <- function(Tanimoto_analysis, predict.only) {
    load("RData/interactions_source.RData")
    source("Script/prediction_matrix.r")
    source("Script/empirical_matrix.r")
    source("Script/tanimoto_efficiency.r")


    accuracy <- matrix(ncol = 12, nrow = length(Tanimoto_analysis) * length(Tanimoto_analysis[[1]]) * length(Tanimoto_analysis[[1]][[1]]) * length(Tanimoto_analysis[[1]][[1]][[1]]), data = 0, dimnames = list(c(), c('MW','K','wt','Cm','a','b','c','d','TSS','ScoreY1','ScoreY0','FSS')))
    iteration <- 1
    for(n in 1: length(Tanimoto_analysis)) { #loop through MW values
        for(m in 1: length(Tanimoto_analysis[[1]])) { # loop through K values
            for(i in 1:length(Tanimoto_analysis[[1]][[1]])){ #1st loop for all types of wt values
                for(j in 1:length(Tanimoto_analysis[[1]][[1]][[1]])) { #2nd loop for all C[i]
                    # Arguments:
                    S1 <- Tanimoto_analysis[[n]][[m]][[i]][[j]][, 'consumer']
                    predictions <- Tanimoto_analysis[[n]][[m]][[i]][[j]]
                    interactions_source <- interactions_sources
                    source <- names(Tanimoto_analysis[[n]][[m]][[i]])[j]

                    accuracy[iteration, 'MW'] <- names(Tanimoto_analysis)[n]
                    accuracy[iteration, 'K'] <- names(Tanimoto_analysis[[n]])[m]
                    accuracy[iteration, 'wt'] <- names(Tanimoto_analysis[[n]][[m]])[i]
                    accuracy[iteration, 'Cm'] <- names(Tanimoto_analysis[[n]][[m]][[i]])[j]
                    accuracy[iteration, 5:12] <- prediction_accuracy(predicted = prediction_matrix(S1 = S1, predictions = predictions, predict.only = predict.only),
                                                        empirical = empirical_matrix(S1 = S1, interactions_source = interactions_source, source = source))

                    iteration <- iteration + 1
                    remove(S1, predictions, interactions_source, source)
                }#j
            }#i
        }#m
    }#n

    return(accuracy)

}#Tanimoto_accuracy function
# Extracting as interaction matrix
prediction_matrix <- function(S1, predictions, predict.only) {
    predict.matrix <- matrix(nrow = length(S1), ncol = length(S1), data = 0, dimnames = list(S1,S1))

    for(i in 1:length(S1)) {
        predict <- unlist(strsplit(predictions[i, 'resource_predictions'], " \\|\\ ")) # list of resource predicted for consumer i
        empirical <- unlist(strsplit(predictions[i, 'resource_empirical'], " \\|\\ ")) # list of resource observed for consumer i

        if(length(predict) == 0) {
          NULL
        } else {
            for(j in 1:length(predict)) {
                predict.matrix[predict[j],i] <- 1
            }#j
        }#if

        if(length(empirical) == 0) {
          NULL
        } else {
            for(j in 1:length(empirical)) {
                if(predict.only == TRUE) {
                    break
                } else {
                    predict.matrix[empirical[j],i] <- 1
                } #if
            }#j
        }#if
    }#i
    return(predict.matrix)
}#prediction_matrix function end
# Run readme.r before other scripts
rm(list=ls())
setwd("/Users/davidbeauchesne/Dropbox/Structure_Comm_EGSL/Tanimoto_algorithm")
# -----------------------------------------------------------------------------
# PROJECT:
#    Evaluating the structure of the communities of the estuary
#    and gulf of St.Lawrence
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# REPOSITORY
#   Machine learning algorithm to predict biotic interactions. This repository
#   contains the scripts and the analyses to test the accuracy of the
#   algorithm.
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# PROCESS STEPS:
#   0. Setting up dataset with proper format for analysis
#
#       0.1 Data set from RData in interactions_catalog repository
#           Script <- file = "Script/0-1-Tanimoto_data.r
#           RData <- file = 'RData/Tanimoto_data.RData'
#
#       0.2 Extracting sources for each binary interaction forming the catalogue
#           Script <- file = "Script/0-1-Interactions_sources.r
#           RData <- file = "RData/interactions_source.RData")
#
#   1. Calculating similarity matrices for resources and consumers
#       Script <- file = 'Script/1-Similarity_matrix.r'
#       RData <- file = 'RData/similarity_matrices.RData'
#
#   2. Tanimoto analysis for XXX
#
#       2.1 Tanimoto predictions for set of X parameters
#           Script <- file = 'Script/2-1-Tanimoto_analysis.r'
#           RData <- file = 'RData/Tanimoto_analysis.RData'

#       2.2 Evaluation of analysis accuracy + tables and figures
#           Script <- file = 'Script/2-2-Tanimoto_accuracy.r'
#           RData <- file = 'RData/Tanimoto_accuracy.RData'
#           Figures <- file = ''
#           Tables <- file = ''









#       Script  <- file = "Script/1_EGSL_SpList.r"
#       RData <- file = "RData/sp_egsl.RData" - EGSL species list
#
#   2. Import and format empirical food web data
#
#     2.1 Barnes et al. 2008
#       Script  <- file = "Script/2-1_Emp_Webs.r"
#       RData <- file = "RData/barnes2008.RData"
#

# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# FUNCTIONS (add a description of the functions eventually)
source("Script/Tanimoto.r") # basic tanimoto similarity
source("Script/Tanimoto_traits.r") # extended tanimoto included trait/taxonomy vector
source("Script/similarity_taxon.r") # similarity matrix for set of taxa
source("Script/similarity_taxon_predict.r") #similarity of additional taxa in S1 not found in S0
source("Script/two_way_tanimoto_predict.r") # interaction predictions from two-way Tanimoto algorithm
source("Script/prediction_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/empirical_matrix.r") # predictions formatted to food web matrix format (S x S)
source("Script/consumer_set_of_resource.R")
source("Script/tanimoto_efficiency.r") # predictions formatted to food web matrix format (S x S)
source("Script/prediction_accuracy.r") # calculating the accuracy of predictions from Tanimoto_predictions
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# NOTES:
#   In this version of the algorithm, we use similarity matrices rather than graphs, which greatly slows down the analysis speed.
#   We therefore divide the algorightm between :
#     Similarity evaluation (functions: similarity_taxon & similarity_taxon_to_predict, 'wt' argument has to be the same for both functions)
#     Interaction predictions (function: two_way_tanimoto_predict)

# Process steps for analyses:
#   1. Similarity between taxa combinations
#     1.1 Evaluate the similarity matrix of S0 (i.e. all species in catalogue) for a number of wt values seq(0, 1, by = 0.1)
#     1.2 Define S1, set of species forming a community C[i] and for which we wish to predict interactions
#     1.3 Remove all species in S1 from similarity matrix alreay measured and interactions stemming from C[i]
#     1.4 Extend similarity matrix to include S1 taxa (Evaluate similarity for all additionnal combinations added to the matrix)
#
#   For each species in S1:
#   2. Identify resources already known in interaction catalogue (S0) for S1 species
#     2.1 If resoures are in S1, automatically add them to the predictions as empirically valid interactions
#     2.2 If resources are not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   3. Identify Kc similar consumers to S1 in S0
#     3.1 Extract set of candidate resources from each similar consumer, if any
#     3.2 If candidate resource is in S1, add it to candidate list with weight 1
#     3.3 If candidate resource not in S1, find Kr similar resources in S1 and add them to candidate list with weight equal to their similarity

#   4. Make predictions:
#     4.1 Remove taxa with weight < to minimum weight (MW) from prediction list
#     4.2 Sort prediction list according to weight. Higher weights mean higher likelihood for resource being consumed

#   Subset of communities based on the number of taxa available? Most of them end up having very few taxa represented in here. Less than I expected...
# -----------------------------------------------------------------------------
# The functions require rchart-helper.R preloaded

# getQ2TimelapsePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getQ2TimelapsePlot = function(data, names, colors, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    dateFactors = list()
    for (i in 1:length(data)) {
        dateFactors[[i]] = as.factor(data[[i]]$date)
        boxplot = boxplot(data[[i]]$x ~ dateFactors[[i]],
                          data=data.frame(dateFactors[[i]], data[[i]]$x), plot=FALSE)
        stats = setNames(as.data.frame(boxplot$stats), nm=NULL)

        # Timpstamp in miliseconds
        unixTimestamps = 1000 * as.numeric(as.POSIXct( sort(unique(data[[i]]$date))))
        statsMedian = rbind(setNames(unixTimestamps, nm=NULL), stats[3,])
        statsQ2 = rbind(setNames(unixTimestamps, nm=NULL), stats[c(2, 4),])

        series[[2 * (i - 1) + 1]] =
            list(name=names[i], data=statsMedian, zIndex=1, color=colors[i],
                 marker=list(fillColor="white", lineWidth=2, lineColor=colors[i]))
        series[[2 * i]] = list(name="50th quartile", data=statsQ2, zIndex=0,
                 type="arearange", color=colors[i], lineWidth=0, linkedTo=":previous", fillOpacity=0.3)
    }

    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=list(text=yLabel), min=0)
    chart$set(series=series)
    return(chart)
}

# Helper for creating histogram
getBinItemList = function(data, businesses, interval=100) {
    binItemList = c()
    currentBin = interval
    maxBin = max(data$count) + interval
    while (currentBin < maxBin) {
        items = filter(data, currentBin - interval <= count & count < currentBin)
        binItemList = c(binItemList,
                        paste("< ", currentBin, "<br>",
                              paste(items$name, collapse="<br>, ")))
        currentBin = currentBin + interval
    }
    return(binItemList)
}

# getStackedHistogram
# data[[]]$x
getStackedHistogram = function(data, names, xLabel, interval=100, logScale=FALSE, logBase=exp(1), normalize=FALSE, colors = c("#7cb5ec", "#000000")) {
    series = list()
    plotLines = list()
    for (i in 1:length(data)){
        x = data[[i]]$x

        plotLines[[i * 2 - 1]] =
            list(color=colors[i],
                 value=mean(x),
                 width=2,
                 label=list(text="mean", style=list(color=colors[i]), verticalAlign="middle"))
        plotLines[[i * 2]] =
            list(color=colors[i],
                 value=median(x),
                 dashStyle="dash",
                 width=2,
                 label=list(text="median", style=list(color=colors[i]), verticalAlign="middle"))

        maxBin = max(data[[i]]$x)
        actualInterval = interval

        if (logScale) {
            x = log(x + 1, base=logBase)
            maxBin = log(maxBin + 1, base=logBase)
            actualInterval = log(interval, base=logBase)
        }
        histogram = hist(x, breaks=seq(0, maxBin + actualInterval, actualInterval), plot=FALSE)
        histNames = getBinItemList(data[[i]], interval=actualInterval)

        nBins = min(length(histogram$breaks), length(histogram$counts))
        counts = histogram$counts[1:nBins]
        if (normalize) {
            counts = counts / nrow(data[[i]])
        }
        bins = getValues(
            histogram$breaks[1:nBins],
            counts,
            name=histNames)
        series[[i]] = list(name=names[i], data=bins)
    }
   
    chart <- Highcharts$new()
    chart$chart(type="column")
    chart$plotOptions(
        column="{ grouping: false, pointPadding: 0, borderWidth: 0, groupPadding: 0, shadow: false}")
    chart$xAxis(title=paste("{text: '", xLabel, "'}", sep=""),
                plotLines=plotLines)
    yLabel = "frequency"
    if (normalize) {
        yLabel = paste(yLabel, "(normalized)")
    }
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""))
    chart$set(series=series)
    return(chart)
}

# getTimelapseLinePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getTimelapseLinePlot = function(data, names, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    for (i in 1:length(data)){
        timelapseValues = getTimelapseValues(
            as.POSIXlt(strptime(as.character(data[[i]]$date), "%Y-%m-%d", tz=timezone)),
            data[[i]]$x)
        series[[i]] = list(name=names[i], data=timelapseValues)
    }


    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""), gridLineColor="#FFFFFF")
    chart$set(series=series)
    return(chart)
}
# The functions require rchart-helper.R preloaded

# getQ2TimelapsePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getQ2TimelapsePlot = function(data, names, colors, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    dateFactors = list()
    for (i in 1:length(data)) {
        dateFactors[[i]] = as.factor(data[[i]]$date)
        boxplot = boxplot(data[[i]]$x ~ dateFactors[[i]],
                          data=data.frame(dateFactors[[i]], data[[i]]$x), plot=FALSE)
        stats = setNames(as.data.frame(boxplot$stats), nm=NULL)

        # Timpstamp in miliseconds
        unixTimestamps = 1000 * as.numeric(as.POSIXct( sort(unique(data[[i]]$date))))
        statsMedian = rbind(setNames(unixTimestamps, nm=NULL), stats[3,])
        statsQ2 = rbind(setNames(unixTimestamps, nm=NULL), stats[c(2, 4),])

        series[[2 * (i - 1) + 1]] =
            list(name=names[i], data=statsMedian, zIndex=1, color=colors[i],
                 marker=list(fillColor="white", lineWidth=2, lineColor=colors[i]))
        series[[2 * i]] = list(name="50th quartile", data=statsQ2, zIndex=0,
                 type="arearange", color=colors[i], lineWidth=0, linkedTo=":previous", fillOpacity=0.3)
    }

    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=list(text=yLabel), min=0)
    chart$set(series=series)
    return(chart)
}

# Helper for creating histogram
getBinItemList = function(data, businesses, interval=100) {
    binItemList = c()
    currentBin = interval
    maxBin = max(data$count) + interval
    while (currentBin < maxBin) {
        items = filter(data, currentBin - interval <= count & count < currentBin)
        binItemList = c(binItemList,
                        paste("< ", currentBin, "<br>",
                              paste(items$name, collapse="<br>, ")))
        currentBin = currentBin + interval
    }
    return(binItemList)
}

# getStackedHistogram
# data[[]]$x
getStackedHistogram = function(data, names, xLabel, interval=100, logScale=FALSE, logBase=exp(1), normalize=FALSE) {
    series = list()
    for (i in 1:length(data)){
        x = data[[i]]$x
        maxBin = max(data[[i]]$x)
        actualInterval = interval

        if (logScale) {
            x = log(x + 1, base=logBase)
            maxBin = log(maxBin + 1, base=logBase)
            actualInterval = log(interval, base=logBase)
        }
        histogram = hist(x, breaks=seq(0, maxBin + actualInterval, actualInterval), plot=FALSE)
        histNames = getBinItemList(data[[i]], interval=actualInterval)

        nBins = min(length(histogram$breaks), length(histogram$counts))
        counts = histogram$counts[1:nBins]
        if (normalize) {
            counts = counts / nrow(data[[i]])
        }
        bins = getValues(
            histogram$breaks[1:nBins],
            counts,
            name=histNames)
        series[[i]] = list(name=names[i], data=bins)
    }
   
    chart <- Highcharts$new()
    chart$chart(type="column")
    chart$plotOptions(
        column="{ grouping: false, pointPadding: 0, borderWidth: 0, groupPadding: 0, shadow: false}")
    chart$xAxis(title=paste("{text: '", xLabel, "'}", sep=""))
    yLabel = "frequency"
    if (normalize) {
        yLabel = paste(yLabel, "(normalized)")
    }
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""))
    chart$set(series=series)
    return(chart)
}

# getTimelapseLinePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getTimelapseLinePlot = function(data, names, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    for (i in 1:length(data)){
        timelapseValues = getTimelapseValues(
            as.POSIXlt(strptime(as.character(data[[i]]$date), "%Y-%m-%d", tz=timezone)),
            data[[i]]$x)
        series[[i]] = list(name=names[i], data=timelapseValues)
    }


    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""), gridLineColor="#FFFFFF")
    chart$set(series=series)
    return(chart)
}
# The functions require rchart-helper.R preloaded

# getQ2TimelapsePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getQ2TimelapsePlot = function(data, names, colors, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    dateFactors = list()
    for (i in 1:length(data)) {
        dateFactors[[i]] = as.factor(data[[i]]$date)
        boxplot = boxplot(data[[i]]$x ~ dateFactors[[i]],
                          data=data.frame(dateFactors[[i]], data[[i]]$x), plot=FALSE)
        stats = setNames(as.data.frame(boxplot$stats), nm=NULL)

        # Timpstamp in miliseconds
        unixTimestamps = 1000 * as.numeric(as.POSIXct( sort(unique(allMetrics[[1]]$date))))
        statsMedian = rbind(setNames(unixTimestamps, nm=NULL), stats[3,])
        statsQ2 = rbind(setNames(unixTimestamps, nm=NULL), stats[c(2, 4),])

        series[[2 * (i - 1) + 1]] =
            list(name=names[i], data=statsMedian, zIndex=1, color=colors[i],
                 marker=list(fillColor="white", lineWidth=2, lineColor=colors[i]))
        series[[2 * i]] = list(name="50th quartile", data=statsQ2, zIndex=0,
                 type="arearange", color=colors[i], lineWidth=0, linkedTo=":previous", fillOpacity=0.3)
    }

    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=list(text=yLabel), min=0)
    chart$set(series=series)
    return(chart)
}

# Helper for creating histogram
getBinItemList = function(data, businesses, interval=100) {
    binItemList = c()
    currentBin = interval
    maxBin = max(data$count) + interval
    while (currentBin < maxBin) {
        items = filter(data, currentBin - interval <= count & count < currentBin)
        binItemList = c(binItemList,
                        paste("< ", currentBin, "<br>",
                              paste(items$name, collapse="<br>, ")))
        currentBin = currentBin + interval
    }
    return(binItemList)
}

# getStackedHistogram
# data[[]]$x
getStackedHistogram = function(data, names, xLabel, interval=100, logScale=FALSE, logBase=exp(1), normalize=FALSE) {
    series = list()
    for (i in 1:length(data)){
        x = data[[i]]$x
        maxBin = max(data[[i]]$x)
        actualInterval = interval

        if (logScale) {
            x = log(x + 1, base=logBase)
            maxBin = log(maxBin + 1, base=logBase)
            actualInterval = log(interval, base=logBase)
        }
        histogram = hist(x, breaks=seq(0, maxBin + actualInterval, actualInterval), plot=FALSE)
        histNames = getBinItemList(data[[i]], interval=actualInterval)

        nBins = min(length(histogram$breaks), length(histogram$counts))
        counts = histogram$counts[1:nBins]
        if (normalize) {
            counts = counts / nrow(data[[i]])
        }
        bins = getValues(
            histogram$breaks[1:nBins],
            counts,
            name=histNames)
        series[[i]] = list(name=names[i], data=bins)
    }
   
    chart <- Highcharts$new()
    chart$chart(type="column")
    chart$plotOptions(
        column="{ grouping: false, pointPadding: 0, borderWidth: 0, groupPadding: 0, shadow: false}")
    chart$xAxis(title=paste("{text: '", xLabel, "'}", sep=""))
    yLabel = "frequency"
    if (normalize) {
        yLabel = paste(yLabel, "(normalized)")
    }
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""))
    chart$set(series=series)
    return(chart)
}

# getTimelapseLinePlot
# data[[]]$x: Stats
# data[[]]$date: Date
getTimelapseLinePlot = function(data, names, yLabel, verticalLineDate=NULL, timezone="UTC") {
    series = list()
    for (i in 1:length(data)){
        timelapseValues = getTimelapseValues(
            as.POSIXlt(strptime(as.character(data[[i]]$date), "%Y-%m-%d", tz=timezone)),
            data[[i]]$x)
        series[[i]] = list(name=names[i], data=timelapseValues)
    }


    chart = Highcharts$new()
    xAxis = list(type="datetime")
    if (!is.null(verticalLineDate)){
        date = as.POSIXlt(strptime(as.character(verticalLineDate), "%Y-%m-%d", tz=timezone))
        xAxis[["plotLines"]] = paste("[{color: 'red',",
                                     "value: Date.UTC(", date$year + 1900, ",", date$mon, ",", date$mday, "),",
                                     "width: 2}]", sep="")
    }
    chart$set(xAxis=xAxis)
    chart$yAxis(title=paste("{text: '", yLabel, "'}", sep=""), gridLineColor="#FFFFFF")
    chart$set(series=series)
    return(chart)
}
                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, mytableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, date) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (date == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, mytableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]
    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
    }
    for (i in 1:max) {
        id <- list11$id[i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), list2[[id]], list11$id[[i]]))
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

gettopchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    displaychart(ls, names, topbottom, period, maindate, olddate)
}

getbottomchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    displaychart(ls, names, topbottom, period, maindate, olddate)
}

getchart <- function(days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    displaychart(ls, names, topbottom, period, maindate, olddate)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        print("here1")
        t.test(c1,c2,paired=TRUE)
        print("here2")
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, period, maindate, olddate) {
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }
        periodtext <- period

        if (period >= 0) {
            newtext <- getperiodtext(mymeta, period)
            if (!is.na(newtext)) {
                periodtext <- newtext
            }
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (period == pricetype) {
        return (df$price)
    }
    if (period == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
#                                            str("her")
#                                            str(id)
#                                            str(days)
#                                            str(period)
#                                            str(datedstocklist)
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, date, mytableintervaldays) {
    datedstocklists <- list()
    if (is.null(date)) {
        dateindex <- match(date, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    str(dateindex)
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:count) {
        index <- index - mytableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(con, date, ids, periodtext) {
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getmarket(con, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    ls <- list()
    names <- list()
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            c <- 0
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            for (pairkey in names(pairs)) {
                pair <- pairs[[pairkey]]
                market <- pair[[1]]
                period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
                marketdata <- marketdatamap[market]
                datedstocklists <- marketdata[[1]][3]
                for (i in 1:length(ids)) {
                    idpair <- ids[[i]]
                    idmarket <- idpair[1]
                    id <- idpair[2]
                                        #           str("for")
                    cat(market, idmarket, id)
                    str("")
                    if (market == idmarket) {
                        cat("per", text, " ", id, " ", period, " ")
                        str("")
                        c <- c + 1
                        l <- getelem3(id, days, datedstocklists, period, topbottom)
                        ls[c] <- list(l)
                        names[c] <- id
                    }
                }
            }
        }
    }
    maindate <- "1"
    olddate <- "2"
    displaychart(ls, names, 5, period, maindate, olddate)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- subset(meta, marketid == market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmarket <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

if (!exists("marketid")) {
    marketid <- "morncat"
}

data <- dbGetQuery(con, "select * from stock")
meta <- dbGetQuery(con, "select * from meta")
mymeta <- subset(meta, marketid == mymarketid)
data_3 <- getmarket(con, marketid)
names(data_3)
s <- subset(data_3, "id" == "EUCA000749")

for (i in 1:nrow(data_3)) {
                                        #print(data_3[i,"date"])
                                        #return()
}

                                        #for (i in data_3) {
                                        #print(i["date"])
                                        #return
                                        #}

listid2 <- splitid(data_3)
listdate2 <- splitdate(data_3)
listdate <- split(data_3, data_3$date)
listid <- split(data_3, data_3$id)

                                        #l <- listdate[[104]]
if (!exists("days")) {
    days <- 10
}
if (!exists("topbottom")) {
    topbottom <- 5
}
count <- days
if (!exists("mytableintervaldays")) {
    mytableintervaldays <- 5
}
                                        #date <- "2016-05-02"

datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)

if (!exists("period")) {
    period <- 3
}

                                        #alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
                                        #periodmaps <- alist[[1]]
                                        #stocklistperiod <- alist[[2]]
                                        #mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
                                        #mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)

                                        #gettopchart(days, topbottom, stocklistperiod, period)
                                        #getbottomchart(days, topbottom, stocklistperiod, period)
                                        #rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #risetopids <- head(names(rise[[1]]))

getcontentgraph(con, date, ids, "1y")

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

context('adapter reference class')

test_that('it can initialize an adapter correctly', {
  a <- adapter(identity, identity)
})

test_that('it can read using a simple example adapter correctly', {
  tmp <- new.env()
  read_function <- function(opts) tmp$x <- opts$resource
  a <- adapter(read_function, identity)
  expect_identical(a$read("test"), "test")
  expect_identical(tmp$x, "test")
})

test_that('it can write using a simple example adapter correctly', {
  tmp <- new.env()
  read_function <- function(opts) tmp[[opts$resource]]
  write_function <- function(val, opts) { force(opts); tmp$x <- val }
  a <- adapter(read_function, write_function)
  a$write("test")
  expect_identical(tmp$x, "test")
  expect_identical(a$read('x'), "test")
})

describe("RDS2 functionality", {
  library(RDS2)

  test_that("it can read an RDS2 object correctly", {
    file_adapter <- construct_file_adapter()
    rds2_object <- structure("foo", RDS2.serialize = list(
      read  = function(obj) paste0(obj, "bar"),
      write = identity
    ))
    file <- tempfile(fileext = ".rds")
    RDS2::saveRDS(rds2_object, file)
    with_mock(has_RDS2 = function() TRUE, {
      object <- file_adapter$read(file)
      expect_false("RDS2.serialize" %in% names(attributes(object)))
    })
    with_mock(has_RDS2 = function() FALSE, {
      object <- file_adapter$read(file)
      expect_true("RDS2.serialize" %in% names(attributes(object)))
    })
  })
})

test_that('it formats options according to a formatting function', {
  formatter <- function(opts) list(file = opts$resource)
  a <- adapter(identity, identity, formatter)
  expect_identical(a$read("test")$file, "test")
})

test_that('it merges in default options if set', {
  a <- adapter(identity, identity, identity, list(blah = 'foo'))
  expect_identical(a$read("test")$blah, "foo")
})

test_that('it does not overwrite set values with defaults', {
  a <- adapter(identity, identity, identity, list(blah = 'foo'))
  expect_identical(a$read(list(blah = 'bar'))$blah, "bar")
})

context('fetch_adapter')

test_that('it fetches the s3 adapter', {
  expect_identical(fetch_adapter('s3')$.keyword, 's3')
})

test_that('it fetches the default adapter', {
  expect_identical(fetch_adapter('file')$.keyword, 'file')
})

test_that('it fetches the R adapter', {
  expect_identical(fetch_adapter('R')$.keyword, 'R')
})

#' @export
SummaryFromFiles <- function(){
  BEG1 <- as.numeric(infoTable[1,2])
  END1 <- as.numeric(infoTable[2,2])
  str1 <- toString(infoTable[4,2])
  assign("str1", str1, globalenv())
  dir.create(paste(c(str1, "/PloidyRFiles"), collapse= ""), showWarnings = FALSE)
  str1.1 <- "/I"
  str2 <- "/I"
  str3 <- "_allelesFromPost_4_diffs.txt"
  infoFile <- toString(infoTable[6,2])
  info <- read.csv(infoFile)
  Notes <- table(info$PrePloidy)
  LocusRef <- scan(infoTable[11,2])
  testLoci <- sort(LocusRef)
  numLoci <- length(testLoci)
  refCheck <- as.numeric(infoTable[7,2])
  alleleMat <- matrix(ncol=8)
  if(refCheck == 1){
    allMat <- as.matrix(read.csv(infoTable[8,2], header = FALSE) )
    allDistancesMat <- as.matrix(read.csv(infoTable[9,2], header = FALSE))
    prevInfo <- read.csv(infoTable[10,2], header = TRUE)
    info <- rbind(info, prevInfo)
  } else{
    allMat <- matrix(ncol=5)
    allDistancesMat <- matrix(data=c("Locus",testLoci),nrow=numLoci+1,ncol=1)
  }
  assign("info",info,globalenv())
  ########## This part summarizes all allele data into allMat ################
  for (i in BEG1:END1){
    filePath <- paste(c(str1,str1.1,i,str2,i,str3), collapse = "")
    iNum <- paste(c("I",i), collapse = "")
    if (file.exists(filePath) == TRUE){
      dat <- read.table(filePath)	
      matLen <- length(dat[,7])/6
      valuesMat <- matrix(ncol=5)
      rowRef <- which(grepl(paste(c("^",iNum,"$"), collapse = ""), info$Individual))
      alleleCounter <- 1
      for (j in 1:matLen){
        if(dat[(alleleCounter),1] <= testLoci[length(testLoci)] & dat[(alleleCounter),1] %in% testLoci){
          alleles <- sort(c((dat[(alleleCounter),7]/dat[alleleCounter,8]), (dat[(alleleCounter+1),7]/dat[alleleCounter,8]), 					(dat[(alleleCounter+2),7]/dat[alleleCounter,8]), (dat[(alleleCounter+3),7]/dat[alleleCounter,8]), (dat[(alleleCounter+4),				7]/dat[alleleCounter,8]), (dat[(alleleCounter+5),7]/dat[alleleCounter,8])))
          allAlleleDists <- alleles		
          sameAlleles <- alleles[3:6]
          alleles <- alleles[1:2]
          
          valuesMat <- rbind(valuesMat, c(dat[alleleCounter,1],i,info$PrePloidy[rowRef], mean(alleles), sd(sameAlleles)))
          alleleMat <- rbind(alleleMat,c(i,dat[alleleCounter,1],allAlleleDists[1],allAlleleDists[2], 										allAlleleDists[3],allAlleleDists[4], allAlleleDists[5], allAlleleDists[6]))
        }
        else{}
        alleleCounter <- alleleCounter+6
        
      }
      valuesMat <- valuesMat[2:length(valuesMat[,1]),]
      allMat <- rbind(allMat, valuesMat)
      ## tempVal <- mean(filtMat)
      indDist <- matrix(nrow=numLoci+1, ncol = 1)
      indDist[1,] = iNum
      for (k in 1:numLoci){
        M <- valuesMat[valuesMat[,1] == testLoci[k], 4]
        indDist[k+1,] <-mean(M)
      }	
      allDistancesMat <- cbind(allDistancesMat,indDist)
      print(paste(c(iNum, " COMPLETED"), collapse = ""), quote = FALSE)
    }
    
    else {
      print(paste(c(iNum," FILE NOT FOUND"), collapse = ""), quote = FALSE)
    }
  }
  
  
  
  
  
  
  write.table(allDistancesMat, file = paste(c(str1,"/PloidyRFiles/allDistancesMat.csv"), collapse=""), row.names=FALSE, col.names=FALSE, sep=",")
  cat(c("Writing:" ,paste(c(str1,"/PloidyRFiles/allDistancesMat.csv"), collapse = "") ,"\n"))
  
  allMat <- allMat[2:length(allMat[,1]),]  ####Important!
  
  write.table(allMat, file = paste(c(str1,"/PloidyRFiles/allMat.csv"), collapse=""), row.names=FALSE, col.names=FALSE, sep=",")
  cat(c("Writing:" , paste(c(str1,"/PloidyRFiles/allMat.csv"), collapse = ""), "\n"))
  alleleMat <- alleleMat[2:length(alleleMat[,1]),] 
  write.table(alleleMat, file = paste(c(str1,"/PloidyRFiles/alleleMat.csv"), collapse=""), row.names=FALSE, col.names=FALSE, sep=",")
  cat(c("Writing:" , paste(c(str1,"/PloidyRFiles/alleleMat.csv"), collapse = ""), "\n"))
  assign("allMat",allMat,globalenv())
  assign("alleleMat", alleleMat, globalenv())
  assign("testLoci",testLoci,globalenv())
  assign("numLoci", numLoci, globalenv())
  avgDist <- matrix(nrow=numLoci, ncol = 1)
  devDist <- matrix(nrow=numLoci, ncol = 1)
  for (k in 1:numLoci){
    M <- allMat[allMat[,1] == testLoci[k], 3]
    avgDist[k,] <- mean(M)
    devDist[k,] <- sd(M)
  }
}######################################################################
######################################################################
## ROUTINE ZUM EINLESEN VON ERA-DATEN (ZONAL-WIND) IM NCDF-FORMAT
## UND AUFFINDEN DES JETSTREAMS AUF NORDHEMISPHÄRE
## source('~/Master_Thesis/r-code-git/locate_jetstream_polynomial_2d.r')
######################################################################
######################################################################


######################################################################
## AUFRUF WICHTIGER BIBLIOTHEKEN UND PAKETE
######################################################################
##

library(ncdf4)
library(parallel)
library(chron)

# eigenes package für least squares fit mit chebyshev polynomen
# install.packages("pckg.cheb_0.2.tar.gz", repos = NULL, type = "source")
library(pckg.cheb)

setwd("~/Master_Thesis/r-code-git/")
path <- "data/"
# path <- "/home/skiefer/era/raw/"
file <- "era-t63-1957-2016.nh-trop-inv.nc"  # Nordhemisphäre + Tropen


######################################################################
## KLEINE HILFSFUNKTIONEN
######################################################################
##

fun.fill <- function(x, n) {
  while (length(x) < n) {
    x <- c(x, NA)
  }
  return(x)
}


######################################################################
## EINLESEN DER DATEN
## ERA40 / ERA-INTERIM
## T63 - GRID - GAUSSIAN
## NORDHEMISPHÄRE & TROPEN
## 192 (lat) * 64 (lon)
######################################################################
##

nc <- nc_open(paste(path, file, sep = ""))
# print(nc)
u.monmean <- ncvar_get(nc, "var131") # U-Wind-Komponente
# v.monmean <- ncvar_get(nc, "var132") # V-Wind-Komponente
# w.monmean <- ncvar_get(nc, "var135") # W-Wind-Komponente
# z.monmean <- ncvar_get(nc, "var129") # Geopotenzial
# t.monmean <- ncvar_get(nc, "var130") # Temperatur
# d.monmean <- ncvar_get(nc, "var155") # Divergenz

lon <- ncvar_get(nc, "lon") # Längengrad
lat <- ncvar_get(nc, "lat") # Breitengrad
lev <- ncvar_get(nc, "lev") # Drucklevel
date.help <- ncvar_get(nc, "time")

nc_close(nc)
rm(nc)


######################################################################
## VARIABLEN UND PARAMETER
######################################################################
##

n.cpu <- 5 #5 # Anzahl der CPUs für parApply
n.order.lat <- 23 # Ordnung des Least-Square-Verfahrens für Fit über Breitengrad
n.order.lon <- 8 # Ordnung des Least-Square-Verfahrens für Fit über Längengrad
n.order.lat.seq <- 3 # Ordnung des Least-Square-Verfahrens für sequentiellen Fit über Breitengrad
len.seq <- 8 # Länge der ersten Sequenz der 

## Räumliche Auflösung
n.lat <- length(lat)
n.lon <- length(lon)

## Zeitliche Auflösung
dts = chron(dates. = date.help/24, origin. = c(month = 9,day = 1,year = 1957), format = "day mon year")
dts.month <- months(dts, abbreviate = TRUE)
dts.year <- years(dts)

## Zeitlich gemittelter Zonalwind
u.mean <- apply(u.monmean,c(1,2),mean)
u.std <- apply(u.monmean,c(1,2),sd)

## Meridional und zeitlich gemittelter Zonalwind
u.mon.mer.mean <- apply(u.monmean, 2, mean)
u.mon.mer.sd <- apply(u.mean, 2, sd)

## Meridional gemittelter Zonalwind
# u.monmean.mermean <- apply(u.monmean, c(2,3), mean)
# u.monmean.mersd <- apply(u.monmean, c(2,3), sd)


######################################################################
## LEAST SQUARES FIT 
## CHEBYSHEV POLYNOME 23-TER ORDNUNG
## AN ZONAL WIND IN MERIDIONALER RICHTUNG
######################################################################
##

# list.model.lat <- apply(u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
list.model.lat <- parApply(cl, u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
stopCluster(cl)
dim.list <- dim(list.model.lat)

## Chebyshev-Koeffizienten
cheb.coeff <- sapply(list.model.lat, "[[", 1)
cheb.coeff <- apply(array(data = cheb.coeff, dim = c((n.order.lat + 1), dim.list[1], dim.list[2])) , c(1,3), t)

## Gefiltertes Modell für Zonal-Wind
model.u <- sapply(list.model.lat, "[[", 2)
model.u <- apply(array(data = model.u, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)

## Erste Ableitung des gefilterten Modells für Zonalwind
model.u.deriv.1st <- sapply(list.model.lat, "[[", 3)
model.u.deriv.1st <- apply(array(data = model.u.deriv.1st, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)

## Extrema des Modells (Positionen und Werte)
model.extr.lat <- sapply(list.model.lat, "[[", 4)
model.extr.u <- sapply(list.model.lat, "[[", 5)
model.extr.lat <- sapply(model.extr.lat, fun.fill, n = 24)
model.extr.lat <- apply(array(model.extr.lat, c(24, dim.list[1], dim.list[2])), c(1,3), t)
model.extr.u <- sapply(model.extr.u, fun.fill, n = 24)
model.extr.u <- apply(array(model.extr.u, c(24, dim.list[1], dim.list[2])), c(1,3), t)

## Maxima des Modells (Positionen und Werte)
model.max.u <- apply(model.extr.u, c(1,3), max, na.rm = TRUE)
model.max.lat <- array(rep(0, 192*664), c(dim.list))
for (i in 1:dim.list[2]) {
  for (j in 1:dim.list[1]) {
    model.max.lat[j,i] <- model.extr.lat[j, which(model.extr.u[j,,i] == model.max.u[j,i]), i]
  }
}
rm(list.model.lat, dim.list)
rm(dim.list)


######################################################################
## LEAST SQUARES FIT 
## CHEBYSHEV POLYNOME 8-TER ORDNUNG
## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
######################################################################
##

#list.model.lon <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
cl <- makeCluster(getOption("cl.cores", n.cpu))
list.model.lon <- parApply(cl, model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
stopCluster(cl)

## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
model.max.lon <- sapply(list.model.lon, "[[", 2)
rm(list.model.lon)




######################################################################
## FEHLERGRÖẞEN
## MSE
## RMSE
######################################################################
##

residuals.cheb <- u.monmean - model.u
residuals.cheb.seq <- u.monmean - model.u.seq
mse <- sum(residuals.cheb ** 2) / length(residuals.cheb)
mse.seq <- sum(residuals.cheb.seq **2) / length(residuals.cheb.seq)
rmse <- sqrt(sum(residuals.cheb ** 2) / length(residuals.cheb))
rmse.seq <- sqrt(sum(residuals.cheb.seq **2) / length(residuals.cheb.seq))

## rmse.seq = 0.4079846  ## mse.seq = 0.1664514
## rmse     = 0.2911683  ## mse     = 0.08477901


######################################################################
######################################################################
save.image()


######################################################################
## Berechnung von Mean und Sd
## über fünf Jahre & saisonal
######################################################################
dts.year.mn <- seq(1960, 2010, 5)

ind.mam <- which(dts.month == "Mar" | dts.month == "Apr" | dts.month == "May")
ind.jja <- which(dts.month == "Jun" | dts.month == "Jul" | dts.month == "Aug")
ind.son <- which(dts.month == "Sep" | dts.month == "Oct" | dts.month == "Nov")
ind.djf <- which(dts.month == "Dec" | dts.month == "Jan" | dts.month == "Feb")

## Mittelwerte global
u.seas.mam.mean <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.mam.sd <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.jja.mean <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.jja.sd <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.son.mean <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.son.sd <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.djf.mean <- array( NA , dim = c(n.lon, n.lat, 11))
u.seas.djf.sd <- array( NA , dim = c(n.lon, n.lat, 11))

## Mittelwerte meridional *???*
u.mer.seas.mam.mean <- array( NA , dim = c(n.lat, 11))
u.mer.seas.mam.sd <- array( NA , dim = c(n.lat, 11))
u.mer.seas.jja.mean <- array( NA , dim = c(n.lat, 11))
u.mer.seas.jja.sd <- array( NA , dim = c(n.lat, 11))
u.mer.seas.son.mean <- array( NA , dim = c(n.lat, 11))
u.mer.seas.son.sd <- array( NA , dim = c(n.lat, 11))
u.mer.seas.djf.mean <- array( NA , dim = c(n.lat, 11))
u.mer.seas.djf.sd <- array( NA , dim = c(n.lat, 11))

for (i in seq(1, 11)) {
  print(i)
  yr.i <- dts.year.mn[i]
  ind.yr <- which(dts.year ==  yr.i | dts.year == (yr.i + 1) | dts.year == (yr.i + 2) | dts.year == (yr.i + 3) | dts.year == (yr.i + 4) )
  ## Mar Apr May
  ind.mam.yr <- intersect(ind.yr, ind.mam)
  u.seas.mam.mean[,,i] <- apply(u.monmean[,, ind.mam.yr], c(1,2), mean)
  u.seas.mam.sd[,,i] <- apply(u.monmean[,, ind.mam.yr], c(1,2), sd)
  u.mer.seas.mam.mean[,i] <- apply(u.monmean[,, ind.mam.yr], 2, mean)
  u.mer.seas.mam.sd[,i] <- apply(u.monmean[,, ind.mam.yr], 2, sd)
  ## Jun Jul Aug
  ind.jja.yr <- intersect(ind.yr, ind.jja)
  u.seas.jja.mean[,,i] <- apply(u.monmean[,, ind.jja.yr], c(1,2), mean)
  u.seas.jja.sd[,,i] <- apply(u.monmean[,, ind.jja.yr], c(1,2), sd)
  u.mer.seas.jja.mean[,i] <- apply(u.monmean[,, ind.jja.yr], 2, mean)
  u.mer.seas.jja.sd[,i] <- apply(u.monmean[,, ind.jja.yr], 2, sd)
  ## Sep Oct Nov
  ind.son.yr <- intersect(ind.yr, ind.son)
  u.seas.son.mean[,,i] <- apply(u.monmean[,, ind.son.yr], c(1,2), mean)
  u.seas.son.sd[,,i] <- apply(u.monmean[,, ind.son.yr], c(1,2), sd)
  u.mer.seas.son.mean[,i] <- apply(u.monmean[,, ind.son.yr], 2, mean)
  u.mer.seas.son.sd[,i] <- apply(u.monmean[,, ind.son.yr], 2, sd)
  ## Dec Jan Feb
  ind.djf.yr <- intersect(ind.yr, ind.djf)
  u.seas.djf.mean[,,i] <- apply(u.monmean[,, ind.djf.yr], c(1,2), mean)
  u.seas.djf.sd[,,i] <- apply(u.monmean[,, ind.djf.yr], c(1,2), sd)
  u.mer.seas.djf.mean[,i] <- apply(u.monmean[,, ind.djf.yr], 2, mean)
  u.mer.seas.djf.sd[,i] <- apply(u.monmean[,, ind.djf.yr], 2, sd)
  ## Löschen von Übergangsvariablen
  rm(yr.i, ind.yr, ind.mam.yr, ind.jja.yr, ind.son.yr, ind.djf.yr, i)
}

max(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
min(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)
range(u.seas.mam.mean, u.seas.jja.mean, u.seas.son.mean, u.seas.djf.mean)

max(u.seas.mam.mean)
min(u.seas.mam.mean)
range(u.seas.mam.mean)

max(u.seas.jja.mean)
min(u.seas.jja.mean)
range(u.seas.jja.mean)

max(u.seas.son.mean)
min(u.seas.son.mean)
range(u.seas.son.mean)

max(u.seas.djf.mean)
min(u.seas.djf.mean)
range(u.seas.djf.mean)


image.plot(lon, lat, u.seas.mam.mean[,,1])
contour(lon, lat, u.seas.mam.sd[,,1], add=TRUE)


####################################################################################################
########## ableitung des drehimpulses ##############################################################
########## aus zonal wind ##########################################################################
####################################################################################################
### ref: m = 
### formel noch inkorrekt
### keine schleife benutzen
##
# m <- matrix(NA,n.lon,n.lat)
# for (i in 1:n.lon){
#   for (j in 1:n.lat){
#     m[i,j] <- u.era.t63.monmean[i,j,1]*cos(lat.era.t63[j]) + 1/86400*u.era.t63.monmean[i,j,1]**2*cos(lat.era.t63[j])**2
#   }
# }
# #m <- u.era.t63.monmean*cos(lat.era.t63)
# 




# ######################################################################
# ## LEAST SQUARES FIT ÜBER **SEQUENZEN** (l=8)
# ## CHEBYSHEV POLYNOME 3-TER ORDNUNG
# ## AN ZONAL-WIND IN MERIDIONALER RICHTUNG
# ######################################################################
# ##
# 
# # list.model.lat.seq <- apply(u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
# list.model.lat.seq <- parApply(cl, u.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# stopCluster(cl)
# dim.list <- dim(list.model.lat.seq)
# 
# ## Gefiltertes Modell für Zonal-Wind
# model.u.seq <- sapply(list.model.lat.seq, "[[", 1)
# model.u.seq <- apply(array(data = model.u.seq, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Erste Ableitung des gefilterten Modells für Zonalwind
# model.u.deriv.1st.seq <- sapply(list.model.lat.seq, "[[", 2)
# model.u.deriv.1st.seq <- apply(array(data = model.u.deriv.1st.seq, dim = c(n.lon, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Extrema des Modells (Positionen und Werte)
# model.extr.lat.seq <- sapply(list.model.lat.seq, "[[", 3)
# model.extr.lat.seq <- sapply(model.extr.lat.seq, fun.fill, n = 24)
# model.extr.lat.seq <- apply(array(model.extr.lat.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# model.extr.u.seq <- sapply(list.model.lat.seq, "[[", 4)
# model.extr.u.seq <- sapply(model.extr.u.seq, fun.fill, n = 24)
# model.extr.u.seq <- apply(array(model.extr.u.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# 
# ## Maxima des Modells (Positionen und Werte)
# model.max.u.seq <- apply(model.extr.u.seq, c(1,3), max, na.rm = TRUE)
# model.max.lat.seq <- array(rep(0, dim.list[1]*dim.list[2]), c(dim.list))
# for (i in 1:dim.list[2]) {
#   for (j in 1:dim.list[1]) {
#     model.max.lat.seq[j,i] <- model.extr.lat.seq[j, which(model.extr.u.seq[j,,i] == model.max.u.seq[j,i]), i]
#   }
# }
# rm(list.model.lat.seq, dim.list)
# 
# 
# ######################################################################
# ## LEAST SQUARES FIT 
# ## CHEBYSHEV POLYNOME 8-TER ORDNUNG
# ## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
# ## ANGEWANDT AUF SEQUENZIERTES MODELL
# ######################################################################
# ##
# 
# #list.model.lon.seq <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = 8)
# cl <- makeCluster(getOption("cl.cores", n.cpu))
# list.model.lon.seq <- parApply(cl, model.max.lat.seq, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
# stopCluster(cl)
# 
# ## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
# model.max.lon.seq <- sapply(list.model.lon.seq, "[[", 2)
# rm(list.model.lon.seq)

repoConfig <- getOption("repos")
repoConfig["CRAN"] = "http://cran.r-project.org/"
options(repos = repoConfig)

manifestName <- '.rip'
args <- commandArgs(trailingOnly = T)

info <- function(...)
{
	cat(paste0(...), "\n")
}

assertPwd <- function(isRipProject)
{
	if (isRipProject != file.exists(manifestName))
	{
		stop("Current directory ", if (isRipProject) "is not" else "is already" , " a rip project")
	}
}

loadPackages <- function()
{
	fh <- file(manifestName, open = "r")
	packages <- c()
	while (length(line <- readLines(fh, n = 1)) > 0)
	{
		packages <- c(packages, line);
	}
	close(fh)
	return(packages)
}

savePackages <- function(packages)
{
	fh <- file(manifestName, open = "w")
	writeLines(sort(packages), fh)
	close(fh)
}

quietInstall <- function(packages)
{
	install.packages(packages, verbose = F, quiet = T)
}

restore <- function()
{
	assertPwd(T)
	packages <- loadPackages()
	packageCount <- length(packages)

	if (!packageCount)
	{
		stop("No packages in manifest to restore")
	}

	info("Restoring ", packageCount, " package(s)")
	quietInstall(packages)
}

install <- function()
{
	assertPwd(T)
	packagesToInstall <- args[0:-1]

	if (!length(packagesToInstall))
	{
		stop("Please specify at least one package")
	}

	packages <- loadPackages()

	for (package in packagesToInstall)
	{
		if (!(package %in% available.packages()[,"Package"]))
		{
			stop("Package is not available in the repository: ", package)
		}
	}

	quietInstall(packagesToInstall)
	savePackages(union(packages, packagesToInstall))
}

init <- function()
{
	assertPwd(F)
	file.create(manifestName)
}

listVersions <- function()
{
	assertPwd(T)
	packages <- loadPackages()

	for (package in packages)
	{
		version <- packageVersion(package)
		info(package, ": ", version)
	}
}

help <- function(commandName = NA)
{
	if (!is.na(commandName))
	{
		info("Invalid command: ", commandName, "\n")
	}

	commands <- list(
		init = "initialises an empty manifest",
		install = "installs one or more packages and records them in your manifest",
		restore = "installs all packages referenced in your manifest",
		list = "displays a list of currently installed packages with their versions")

	output = paste0("rip ", names(commands), "\n  ", commands, "\n")

	info("Usage:\n")
	for (command in output)
	{
		info(command)
	}
}

main <- function()
{
	commandName <- args[1]
	command <- switch(commandName,
		init = init,
		install = install,
		restore = restore,
		list = listVersions,
		"-h" = , "--help" = , help = help,
		function() { help(commandName) })

	command()
}

dummy <- main()                                        # rm(list=ls())
                                        # install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
                                        #require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

                                        # out of use
splitdate <- function(stocks) {
    list <- list()
    j <- 0
    dates <- unique(stocks$date)
    for (di in 1:length(dates)) {
        mydate <- dates[di];
        sublist <- subset(stocks, date == mydate)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

                                        # out of use
splitid <- function(stocks) {
    list <- list()
    j <- 0
    ids <- unique(stocks$id)
    for (ii in 1:length(ids)) {
        myid <- ids[ii];
        sublist <- subset(stocks, id = myid)
        j <- j + 1
        list[j] <- list(sublist)
    }
    return (list)
}

getdforderperiod <- function(df, period) {
    ds <- df
    if (period == 1) {
        ds <- df[order(-df$period1),]
    }
    if (period == 2) {
        ds <- df[order(-df$period2),]
    }
    if (period == 3) {
        ds <- df[order(-df$period3),]
    }
    if (period == 4) {
        ds <- df[order(-df$period4),]
    }
    if (period == 5) {
        ds <- df[order(-df$period5),]
    }
    if (period == 6) {
        ds <- df[order(-df$period6),]
    }
    return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, mytableintervaldays) {
    periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        for (i in 1:periods) {
            df <- data.frame(datedstocklists[j])
            hasperiod <- FALSE
            hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
            if (hasperiod) {
                ds <- getdforderperiod(df, i)
                tmp <- list(ds)
                stocklistperiod[i, j] <- tmp
                if (j > 1) {
                    df1 <- stocklistperiod[i, j - 1]
                    df2 <- tmp
                    tmplist <- getperiodmap(df1, df2)
                    periodmaps[i, j - 1] <- list(tmplist)
                }
            } else {
                cat("no period day ", j, " period ", i)
            }
        }
    }
    return(list(periodmaps, stocklistperiod))
}

                                        # out of use
getstockdate <- function(listdate, date) {
    c <- 0
    for (i in names(listdate)) {
        c <- c + 1
        if (date == i) {
            return(c)
        }
    }
    return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, mytableintervaldays, period) {
    periodmap <- list()
    stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
    for (j in 1:count) {
        hasperiod <- FALSE
                                        # fix later
        hasperiod <- TRUE
        if (hasperiod) {
            df <- data.frame(datedstocklists[j])
            ds <- getdforderperiod(df, i)
            print("")
            tmp <- list(ds)
            stocklistperiod[[1]][[j]] <- tmp
            if (j > 1) {
                df1 <- stocklistperiod[j - 1]
                stocklistperiod[i][j] <- list2
                df2 <- tmp
                tmplist <- getperiodmap(df1, df2)
            }
        }
    }
    return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
    c <- 0
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        c <- c + 1
        list[c] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[j, "id"], df2[i, "id"])) {
                list[c] <- i - j
            }
        }
    }
    return (list)
}


getperiodmap <- function(list1, list2) {
    list <- list()
    df1 <- data.frame(list1[1])
    df2 <- data.frame(list2[1])
    for (j in 1:nrow(df2)) {
        id <- df2[j, "id"]
        list[id] <- NA
        for (i in 1:nrow(df1)) {
            if (identical(df1[i, "id"], id)) {
                list[id] <- j - i
            }
        }
    }
    return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[[period]][[1]]
    list11=stocklistperiod[[1]][1]
    list12=stocklistperiod[[1]][2]
    list13=stocklistperiod[[1]][3]
    list14=stocklistperiod[[1]][4]
    list15=stocklistperiod[[1]][5]
    list21=list2[[1]]
    list211=list21[1]
    list22=list2[2]
    list23=list2[3]
    list24=list2[4]
    list25=list2[5]
    for (i in 1:max) {
        print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
    }
}

listperiod <- function(list, period, index) {
    if (period == 1) {
        return (list$period1[index])
    }
    if (period == 2) {
        return (list$period2[index])
    }
    if (period == 3) {
        return (list$period3[index])
    }
    if (period == 4) {
        return (list$period4[index])
    }
    if (period == 5) {
        return (list$period5[index])
    }
    if (period == 6) {
        return (list$period6[index])
    }
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]
    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
    }
    for (i in 1:max) {
        id <- list11$id[i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), list2[[id]], list11$id[[i]]))
    }
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
    list1 <- stocklistperiod
    list2 <- periodmaps[period, 1][[1]]

    list11 <- stocklistperiod[period, 1][[1]]
    list12 <- stocklistperiod[period, 2][[1]]

    len <- nrow(list12)
    len <- len + 1

    for (i in 1:max) {
        print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
    }

    len <- nrow(list11)
    len <- len + 1

    for (i in 1:max) {
        id <- list11$id[len - i]
        print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
    }
}

gettopchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[i]
    }
    displaychart(ls, names, topbottom, period, maindate, olddate)
}

getbottomchart <- function(days, topbottom, stocklistperiod, period) {
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    len <- nrow(mainlist)
    print(len)
    len <- len + 1
    for (i in 1:topbottom) {
        l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        names[c] <- mainlist$name[len - i]
    }
    displaychart(ls, names, topbottom, period, maindate, olddate)
}

getchart <- function(days, stocklistperiod, period, ids) {
    topbottom <- length(ids)
    mainlist <- stocklistperiod[period, 1][[1]]
    oldlist <- stocklistperiod[period, days][[1]]
    maindate <- mainlist$date[1]
    olddate <- oldlist$date[1]
    ls <- list()
    names <- list()
    c <- 0
    for (i in 1:topbottom) {
        l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
        c <- c + 1
        ls[c] <- list(l)
        listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
        df <- data.frame(listdf[[1]])
        names[c] <- df$name
    }
    displaychart(ls, names, topbottom, period, maindate, olddate)
    if (topbottom == 2) {
        c1 <- c(unlist(ls[1]))
        c2 <- c(unlist(ls[2]))
        print("here1")
        t.test(c1,c2,paired=TRUE)
        print("here2")
                                        #t.test(c1,c1,paired=TRUE)
        cor.test(c1, c2, method = c("pearson"))
        str(c1)
        str(c2)
    }
}

getperiodtext <- function(meta, period) {
    if (period == 1) {
        return (meta$period1)
    }
    if (period == 2) {
        return (meta$period2)
    }
    if (period == 3) {
        return (meta$period3)
    }
    if (period == 4) {
        return (meta$period4)
    }
    if (period == 5) {
        return (meta$period5)
    }
    if (period == 6) {
        return (meta$period6)
    }
    cat("should not be here")
}

displaychart <- function(ls, names, topbottom, period, maindate, olddate) {
    g_range = range(0, ls, na.rm=TRUE)
    print("g_range")
    str(g_range)
    for (i in 1:topbottom) {
        if (i == 1) {
                                        #str(l$id[[1]])
                                        #str(l$name[[2]])
            c = c(unlist(ls[1]))
            str(c)
            plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
            axis(1, at=1:days, lab=c(-(days-1):0))
            axis(2, las=2)
            grid(NULL,NULL)
            box()
                                        #l2 <- getc(l, period)
                                        #str(l[[1]]$period1)
                                        #str(l2)
        } else {
                                        #cat("count", i)
            c = c(unlist(ls[i]))
                                        #str(c)
            lines(c, type="o")
        }
        periodtext <- period

        if (period >= 0) {
            newtext <- getperiodtext(mymeta, period)
            if (!is.na(newtext)) {
                periodtext <- newtext
            }
        }

        title(main=sprintf("Period %s", periodtext))
        title(xlab=sprintf("Time %s - %s", olddate, maindate))
        title(ylab="Value")
        n = c(unlist(names[1]))
        legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
    }
                                        #}
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
    retl <- list()
    for (i in 1:(days - 1)) {
        p <- periodmaps[period, i][[1]]
        l <- stocklistperiod[period, i + 1]
        df <- data.frame(l[[1]])
                                        #str(i)
                                        #str(period)
                                        #str(df)
                                        #str(nrow(df))
        if (nrow(df) > 0) {
            for (j in 1:nrow(df)) {
                                        #str(j)
                id <- df[j, "id"]
                                        #cat("id",id)
                if (is.null(retl[[id]])) {
                    retl[[id]] <- 0
                }
                if (!is.na(p[[id]])) {
                    retl[[id]] <- retl[[id]] + p[[id]]
                }
            }
        } else {
            cat("empty df for ",i)
        }
    }
    return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
    retl <- list[[1]]$period1
    return (retl)
}

getdfperiod <- function(df, index, period) {
    if (period == 1) {
        return (df[index, "period1"])
    }
    if (period == 2) {
        return (df[index, "period2"])
    }
    if (period == 3) {
        return (df[index, "period3"])
    }
    if (period == 4) {
        return (df[index, "period4"])
    }
    if (period == 5) {
        return (df[index, "period5"])
    }
    if (period == 6) {
        return (df[index, "period6"])
    }
    cat("should not be here")
}

getonedfperiod <- function(df, period) {
    if (period == 1) {
        return (df$period1)
    }
    if (period == 2) {
        return (df$period2)
    }
    if (period == 3) {
        return (df$period3)
    }
    if (period == 4) {
        return (df$period4)
    }
    if (period == 5) {
        return (df$period5)
    }
    if (period == 6) {
        return (df$period6)
    }
    cat("should not be here")
}

getonedfspecial <- function(df, type) {
    if (period == pricetype) {
        return (df$price)
    }
    if (period == indextype) {
        return (df$index)
    }
    cat("should not be here")
}

getonedfvalue <- function(df, type) {
    if (type > 0) {
        return(getonedfperiod(df, type))
    }
    if (type < 0) {
        return(getonedfspecial(df, type))
    }
    cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
                                        #    str("her")
                                        #    str(id)
                                        #    str(days)
                                        #    str(period)
                                        #    str(datedstocklist)
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- datedstocklist[[1]][i]
                                        #str(l[[1]])
        df <- data.frame(l[[1]])
                                        #str(df)
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
                                        #str(i)
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfvalue(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
    retl <- list()
    c <- 0
    for (i in days:1) {
        c <- c + 1
        retl[c] <- NA
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])
                                        #cat("mylen ", nrow(df))
        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            retl[c] <- c(getonedfperiod(el, period))
        } else {
            print("err")
        }
    }
    return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
                                        #cat("id",id)
    retl <- list()
    for (i in days:1) {
        l <- stocklistperiod[period, i]
        df <- data.frame(l[[1]])

        el <- df[which(df$id == id),]
        if (nrow(el) == 1) {
            return(list(el))
        } else {
            print("err")
        }

    }
                                        #TODO
    return()
}

                                        # out of use
listfiltertop <- function(list, listmain, size) {
    retl <- list()
    max <- max(size, length(listmain))
    for (i in 1:max) {
        id <- listmain$id[i]
        for (j in 1:length(list)) {
            if (identical(id, list[j]$id)) {
                retl.add(list[j])
            }
        }
    }
}

getdatedstocklists <- function(listdate, date, mytableintervaldays) {
    datedstocklists <- list()
    if (is.null(date)) {
        dateindex <- match(date, names(listdate))
    } else {
        dateindex <- length(listdate)
    }
    str(dateindex)
    index <- dateindex
                                        #index <- length(listdate)
    c <- 0
    c <- c + 1
    datedstocklists[c] <- listdate[index]

    for (j in 1:count) {
        index <- index - mytableintervaldays
        c <- c + 1
        datedstocklists[c] <- listdate[index]
    }
    return(datedstocklists)
}

getcontentgraph <- function(con, date, ids, periodtext) {
    markets <- list()
    for (id in ids) {
                                        #        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getmarket(con, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
                                        #            str(text)
            if (is.null(perioddatamap[[text]])) {
                                        #                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
    }
    retl <- list()
                                        #perioddata <- perioddatamap[periodtext]
                                        #pairs <- perioddata["text"]
                                        #str("bla")
                                        #str(perioddatamap);
                                        #str("bla2")
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
                                        #        str(text)
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pair <- pairs[[pairkey]]
            market <- pair[[1]]
            period <- pair[[2]]
                                        #        str("mark")
                                        #        str(market)
                                        #        str(period)
            marketdata <- marketdatamap[market]
            datedstocklists <- marketdata[[1]][3]
            ls <- list()
            names <- list()
            c <- 0
            for (i in 1:length(ids)) {
                idpair <- ids[[i]]
                idmarket <- idpair[1]
                id <- idpair[2]
                                        #           str("for")
                cat(market, idmarket, id)
                if (market == idmarket) {
                    cat("per", text, " ", id, " ", period, " ")
                    c <- c + 1
                    l <- getelem3(id, days, datedstocklists, period, topbottom)
                    ls[c] <- list(l)
                    names[c] <- "test"
                                        #                str(l)
                }
            }
        }
    }
    maindate <- "1"
    olddate <- "2"
    displaychart(ls, names, 5, period, maindate, olddate)
}

getperiodtexts <- function(market) {
    periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
    meta <- dbGetQuery(con, "select * from meta")
    mymeta <- subset(meta, marketid == market)
    if (nrow(mymeta) > 0) {
        for (i in 1:periods) {
            if (!is.na(getperiodtext(mymeta, i))) {
                periodtext[i] = getperiodtext(mymeta, i)
            }
        }
    }
    return(periodtext)
}

getmarket <- function(con, market) {
    query <- paste("select * from stock where marketid = '", market, "'", sep = "")
    return(dbGetQuery(con, query))
}

                                        # create a connection
                                        # save the password that we can "hide" it as best as we can by collapsing it
pw <- {
    "password"
}

if (exists("drv")) {
    cons <- dbListConnections(drv)
    for (con in cons) {
        print(con)
        dbDisconnect(con)
    }
                                        #dbUnloadDriver(drv)
}

                                        # loads the PostgreSQL driver
if (!exists("drv")) {
    drv <- dbDriver("PostgreSQL")
}
                                        # creates a connection to the postgres database
                                        # note that "con" will be used later in each connection to the database
if (!exists("con")) {
    con <- dbConnect(drv, dbname = "stockstat",
                     host = "localhost", port = 5432,
                     user = "stockstat", password = pw)
    rm(pw) # removes the password
}
                                        #on.exit(dbDisconnect(con))
                                        #on.exit(dbUnloadDriver(drv), add = TRUE)

                                        # check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
                                        # TRUE

if (!exists("marketid")) {
    marketid <- "morncat"
}

data <- dbGetQuery(con, "select * from stock")
meta <- dbGetQuery(con, "select * from meta")
mymeta <- subset(meta, marketid == mymarketid)
data_3 <- getmarket(con, marketid)
names(data_3)
s <- subset(data_3, "id" == "EUCA000749")

for (i in 1:nrow(data_3)) {
                                        #print(data_3[i,"date"])
                                        #return()
}

                                        #for (i in data_3) {
                                        #print(i["date"])
                                        #return
                                        #}

listid2 <- splitid(data_3)
listdate2 <- splitdate(data_3)
listdate <- split(data_3, data_3$date)
listid <- split(data_3, data_3$id)

                                        #l <- listdate[[104]]
if (!exists("days")) {
    days <- 10
}
if (!exists("topbottom")) {
    topbottom <- 5
}
count <- days
if (!exists("mytableintervaldays")) {
    mytableintervaldays <- 5
}
                                        #date <- "2016-05-02"

datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)

if (!exists("period")) {
    period <- 3
}

                                        #alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
                                        #periodmaps <- alist[[1]]
                                        #stocklistperiod <- alist[[2]]
                                        #mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
                                        #mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)

                                        #gettopchart(days, topbottom, stocklistperiod, period)
                                        #getbottomchart(days, topbottom, stocklistperiod, period)
                                        #rise <- getrising(days, periodmaps, stocklistperiod, period)
                                        #risetopids <- head(names(rise[[1]]))

getcontentgraph(con, date, ids, "1y")

                                        # close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
                                        #rm(list = ls())
rm(con)
rm(drv)
print("ending")
                                        #return

# rm(list=ls())
# install.packages("RPostgreSQL")
require("RPostgreSQL")
require("ggplot2")
#require("tabplot")
require("gridExtra")

pricetype <- -1
indextype <- -2
periods <- 6

# out of use
splitdate <- function(stocks) {
  list <- list()
  j <- 0
  dates <- unique(stocks$date)
  for (di in 1:length(dates)) {
    mydate <- dates[di];
    sublist <- subset(stocks, date == mydate)
    j <- j + 1
    list[j] <- list(sublist)
  }
  return (list)
}

# out of use
splitid <- function(stocks) {
  list <- list()
  j <- 0
  ids <- unique(stocks$id)
  for (ii in 1:length(ids)) {
    myid <- ids[ii];
    sublist <- subset(stocks, id = myid)
    j <- j + 1
    list[j] <- list(sublist)
  }
  return (list)
}

getdforderperiod <- function(df, period) {
	ds <- df
	if (period == 1) {
	  ds <- df[order(-df$period1),]
	}
	if (period == 2) {
	  ds <- df[order(-df$period2),]
	}
	if (period == 3) {
	  ds <- df[order(-df$period3),]
	}
	if (period == 4) {
	  ds <- df[order(-df$period4),]
	}
	if (period == 5) {
	  ds <- df[order(-df$period5),]
	}
	if (period == 6) {
	  ds <- df[order(-df$period6),]
	}
return (ds)
}

getlistanddiff <- function(datedstocklists, listid, listdate, count, mytableintervaldays) {
  periodmaps <- matrix(list(), nrow = periods, ncol = (count - 1))
  stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
  for (j in 1:count) {
    for (i in 1:periods) {
      df <- data.frame(datedstocklists[j])
      hasperiod <- FALSE
      hasperiod <- !is.infinite(max(getonedfperiod(df, i), na.rm = TRUE))
      if (hasperiod) {
	ds <- getdforderperiod(df, i)
	tmp <- list(ds)
        stocklistperiod[i, j] <- tmp
	if (j > 1) {
	df1 <- stocklistperiod[i, j - 1]
	df2 <- tmp
	   tmplist <- getperiodmap(df1, df2)
	   periodmaps[i, j - 1] <- list(tmplist)
	}
      } else {
      	cat("no period day ", j, " period ", i)
      }
    }
  }
  return(list(periodmaps, stocklistperiod))
}

# out of use
getstockdate <- function(listdate, date) {
c <- 0
for (i in names(listdate)) {
c <- c + 1
if (date == i) {
return(c)
}
}
return (length(listdate))
}

getlistanddiffperiod <- function(datedstocklists, listid, listdate, count, mytableintervaldays, period) {
  periodmap <- list()
  stocklistperiod <- matrix(list(), nrow = periods, ncol = count)
  for (j in 1:count) {
      hasperiod <- FALSE
      # fix later
      hasperiod <- TRUE
      if (hasperiod) {
      	df <- data.frame(datedstocklists[j])
	ds <- getdforderperiod(df, i)
	print("")
	tmp <- list(ds)
        stocklistperiod[[1]][[j]] <- tmp
	if (j > 1) {
	df1 <- stocklistperiod[j - 1]
        stocklistperiod[i][j] <- list2
	df2 <- tmp
	   tmplist <- getperiodmap(df1, df2)
	}
      }
  }
  return(list(periodmap, stocklistperiod))
}

getperiodlist <- function(list1, list2) {
  c <- 0
  list <- list()
  df1 <- data.frame(list1[1])
  df2 <- data.frame(list2[1])
  for (j in 1:nrow(df2)) {
    c <- c + 1
    list[c] <- NA
      for (i in 1:nrow(df1)) {
      if (identical(df1[j, "id"], df2[i, "id"])) {
        list[c] <- i - j
      }
    }
  }
  return (list)
}


getperiodmap <- function(list1, list2) {
  list <- list()
  df1 <- data.frame(list1[1])
  df2 <- data.frame(list2[1])
  for (j in 1:nrow(df2)) {
    id <- df2[j, "id"]
    list[id] <- NA
      for (i in 1:nrow(df1)) {
      if (identical(df1[i, "id"], id)) {
        list[id] <- j - i
      }
    }
  }
  return (list)
}

mytop <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
list1 <- stocklistperiod
list2 <- periodmaps[[period]][[1]]
list11=stocklistperiod[[1]][1]
list12=stocklistperiod[[1]][2]
list13=stocklistperiod[[1]][3]
list14=stocklistperiod[[1]][4]
list15=stocklistperiod[[1]][5]
list21=list2[[1]]
list211=list21[1]
list22=list2[2]
list23=list2[3]
list24=list2[4]
list25=list2[5]
for (i in 1:max) {
print(sprintf("%-40s %12s %3.2f %3d %3.2f %3d\n", strtrim(list11[[1]]$name[i],38), as.POSIXct(list11[[1]]$date[i], origin="1970-01-01"), list11[[1]]$period1[i], list2[[1]][[i]], list12[[1]]$period1[i], list2[[2]][[i]]))
}
}

listperiod <- function(list, period, index) {
if (period == 1) {
return (list$period1[index])
}
if (period == 2) {
return (list$period2[index])
}
if (period == 3) {
return (list$period3[index])
}
if (period == 4) {
return (list$period4[index])
}
if (period == 5) {
return (list$period5[index])
}
if (period == 6) {
return (list$period6[index])
}
}

mytopperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
list1 <- stocklistperiod
list2 <- periodmaps[period, 1][[1]]

list11 <- stocklistperiod[period, 1][[1]]
list12 <- stocklistperiod[period, 2][[1]]
for (i in 1:max) {
print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[i],33), as.POSIXct(list12$date[i], origin="1970-01-01"), listperiod(list12, period, i)))
}
for (i in 1:max) {
id <- list11$id[i]
print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[i],33), as.POSIXct(list11$date[i], origin="1970-01-01"), listperiod(list11, period, i), list2[[id]], list11$id[[i]]))
}
}

mybottomperiod <- function(datedstocklists, stocklistperiod, periodmaps, period, max) {
list1 <- stocklistperiod
list2 <- periodmaps[period, 1][[1]]

list11 <- stocklistperiod[period, 1][[1]]
list12 <- stocklistperiod[period, 2][[1]]

len <- nrow(list12)
len <- len + 1

for (i in 1:max) {
print(sprintf("%3d %-35s %12s %3.2f", i, strtrim(list12$name[len - i],33), as.POSIXct(list12$date[len - i], origin="1970-01-01"), listperiod(list12, period, len - i)))
}

len <- nrow(list11)
len <- len + 1

for (i in 1:max) {
id <- list11$id[len - i]
print(sprintf("%3d %-35s %12s %3.2f %3d %s", i, strtrim(list11$name[len - i],33), as.POSIXct(list11$date[len - i], origin="1970-01-01"), listperiod(list11, period, len - i), list2[[id]], list11$id[[len - i]]))
}
}

gettopchart <- function(days, topbottom, stocklistperiod, period) {
mainlist <- stocklistperiod[period, 1][[1]]
oldlist <- stocklistperiod[period, days][[1]]
maindate <- mainlist$date[1]
olddate <- oldlist$date[1]
ls <- list()
names <- list()
c <- 0
for (i in 1:topbottom) {
l <- getelem(mainlist$id[i], days, stocklistperiod, period, topbottom)
c <- c + 1
ls[c] <- list(l)
names[c] <- mainlist$name[i]
}
displaychart(ls, names, topbottom, period, maindate, olddate)
}

getbottomchart <- function(days, topbottom, stocklistperiod, period) {
mainlist <- stocklistperiod[period, 1][[1]]
oldlist <- stocklistperiod[period, days][[1]]
maindate <- mainlist$date[1]
olddate <- oldlist$date[1]
ls <- list()
names <- list()
c <- 0
len <- nrow(mainlist)
print(len)
len <- len + 1
for (i in 1:topbottom) {
l <- getelem(mainlist$id[len - i], days, stocklistperiod, period, topbottom)
c <- c + 1
ls[c] <- list(l)
names[c] <- mainlist$name[len - i]
}
displaychart(ls, names, topbottom, period, maindate, olddate)
}

getchart <- function(days, stocklistperiod, period, ids) {
topbottom <- length(ids)
mainlist <- stocklistperiod[period, 1][[1]]
oldlist <- stocklistperiod[period, days][[1]]
maindate <- mainlist$date[1]
olddate <- oldlist$date[1]
ls <- list()
names <- list()
c <- 0
for (i in 1:topbottom) {
l <- getelem(ids[[i]], days, stocklistperiod, period, topbottom)
c <- c + 1
ls[c] <- list(l)
listdf <- getelemtup(ids[[i]], days, stocklistperiod, period, topbottom)
df <- data.frame(listdf[[1]])
names[c] <- df$name
}
displaychart(ls, names, topbottom, period, maindate, olddate)
if (topbottom == 2) {
c1 <- c(unlist(ls[1]))
c2 <- c(unlist(ls[2]))
print("here1")
t.test(c1,c2,paired=TRUE)
print("here2")
#t.test(c1,c1,paired=TRUE)
cor.test(c1, c2, method = c("pearson"))
str(c1)
str(c2)
}
}

getperiodtext <- function(meta, period) {
if (period == 1) {
return (meta$period1)
}
if (period == 2) {
return (meta$period2)
}
if (period == 3) {
return (meta$period3)
}
if (period == 4) {
return (meta$period4)
}
if (period == 5) {
return (meta$period5)
}
if (period == 6) {
return (meta$period6)
}
cat("should not be here")
}

displaychart <- function(ls, names, topbottom, period, maindate, olddate) {
g_range = range(0, ls, na.rm=TRUE)
print("g_range")
str(g_range)
for (i in 1:topbottom) {
if (i == 1) {
#str(l$id[[1]])
#str(l$name[[2]])
c = c(unlist(ls[1]))
str(c)
plot(c, type="o", ylim=g_range, axes=FALSE, ann=FALSE)
axis(1, at=1:days, lab=c(-(days-1):0))
axis(2, las=2)
grid(NULL,NULL)
box()
#l2 <- getc(l, period)
#str(l[[1]]$period1)
#str(l2)
} else {
#cat("count", i)
c = c(unlist(ls[i]))
#str(c)
lines(c, type="o")
}
periodtext <- period

if (period >= 0) {
newtext <- getperiodtext(mymeta, period)
if (!is.na(newtext)) {
periodtext <- newtext
}
}

title(main=sprintf("Period %s", periodtext))
title(xlab=sprintf("Time %s - %s", olddate, maindate))
title(ylab="Value")
n = c(unlist(names[1]))
legend(1, g_range[2], names, cex=0.8, pch=21:22, lty=1:2) 
}
#}
}

getrising <- function(days, periodmaps, stocklistperiod, period) {
retl <- list()
for (i in 1:(days - 1)) {
p <- periodmaps[period, i][[1]]
l <- stocklistperiod[period, i + 1]
df <- data.frame(l[[1]])
#str(i)
#str(period)
#str(df)
#str(nrow(df))
if (nrow(df) > 0) {
for (j in 1:nrow(df)) {
#str(j)
id <- df[j, "id"]
#cat("id",id)
if (is.null(retl[[id]])) {
retl[[id]] <- 0
}
if (!is.na(p[[id]])) {
retl[[id]] <- retl[[id]] + p[[id]]
}
}
} else {
cat("empty df for ",i)
}
}
return(list(sort(data.frame(retl), decreasing = TRUE)))
}

getc <- function(list, period) {
retl <- list[[1]]$period1
return (retl)
}

getdfperiod <- function(df, index, period) {
if (period == 1) {
return (df[index, "period1"])
}
if (period == 2) {
return (df[index, "period2"])
}
if (period == 3) {
return (df[index, "period3"])
}
if (period == 4) {
return (df[index, "period4"])
}
if (period == 5) {
return (df[index, "period5"])
}
if (period == 6) {
return (df[index, "period6"])
}
cat("should not be here")
}

getonedfperiod <- function(df, period) {
if (period == 1) {
return (df$period1)
}
if (period == 2) {
return (df$period2)
}
if (period == 3) {
return (df$period3)
}
if (period == 4) {
return (df$period4)
}
if (period == 5) {
return (df$period5)
}
if (period == 6) {
return (df$period6)
}
cat("should not be here")
}

getonedfspecial <- function(df, type) {
if (period == pricetype) {
return (df$price)
}
if (period == indextype) {
return (df$index)
}
cat("should not be here")
}

getonedfvalue <- function(df, type) {
if (type > 0) {
return(getonedfperiod(df, type))
}
if (type < 0) {
return(getonedfspecial(df, type))
}
cat("should not be here")
}

getelem3 <- function(id, days, datedstocklist, period, size) {
#    str("her")
#    str(id)
#    str(days)
#    str(period)
#    str(datedstocklist)
retl <- list()
c <- 0
for (i in days:1) {
c <- c + 1
retl[c] <- NA
l <- datedstocklist[[1]][i]
#str(l[[1]])
df <- data.frame(l[[1]])
#str(df)
                                        #cat("mylen ", nrow(df))
el <- df[which(df$id == id),]
#str(i)
if (nrow(el) == 1) {
retl[c] <- c(getonedfvalue(el, period))
} else {
print("err")
}
}
return(unlist(retl))
}

getelem <- function(id, days, stocklistperiod, period, size) {
retl <- list()
c <- 0
for (i in days:1) {
c <- c + 1
retl[c] <- NA
l <- stocklistperiod[period, i]
df <- data.frame(l[[1]])
#cat("mylen ", nrow(df))
el <- df[which(df$id == id),]
if (nrow(el) == 1) {
retl[c] <- c(getonedfperiod(el, period))
} else {
print("err")
}
}
return(unlist(retl))
}

getelemtup <- function(id, days, stocklistperiod, period, size) {
#cat("id",id)
retl <- list()
for (i in days:1) {
l <- stocklistperiod[period, i]
df <- data.frame(l[[1]])

el <- df[which(df$id == id),]
if (nrow(el) == 1) {
return(list(el))
} else {
print("err")
}

}
#TODO
return()
}

# out of use
listfiltertop <- function(list, listmain, size) {
retl <- list()
max <- max(size, length(listmain))
for (i in 1:max) {
id <- listmain$id[i]
for (j in 1:length(list)) {
if (identical(id, list[j]$id)) {
retl.add(list[j])
}
}
}
}

getdatedstocklists <- function(listdate, date, mytableintervaldays) {
datedstocklists <- list()
if (is.null(date)) {
dateindex <- match(date, names(listdate))
} else {
dateindex <- length(listdate)
}
str(dateindex)
index <- dateindex
#index <- length(listdate)
  c <- 0
  c <- c + 1
  datedstocklists[c] <- listdate[index]

  for (j in 1:count) {
    index <- index - mytableintervaldays
    c <- c + 1
    datedstocklists[c] <- listdate[index]
  }
  return(datedstocklists)
}

getcontentgraph <- function(con, date, ids, periodtext) {
    markets <- list()
    for (id in ids) {
#        str(id)
        markets[id[1]] <- id[1]
    }
    marketdatamap <- list()
    for (market in names(markets)) {
        stocks <- getmarket(con, market)
        listdate <- split(stocks, stocks$date)
                                        #listid <- split(stocks, stocks$id)
        periodtexts <- getperiodtexts(market)
        datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)
        marketdatamap[market] <- list(list(stocks, periodtexts, datedstocklists))
                                        #for (j in 1:count) {
                                        #stocks <- datedstocklist[j]
                                        #df <- data.frame(stocks[[1]])
                                        #el <- df[which(df$id == id),]
                                        #}
    }
    perioddatamap <- list()
    for (market in names(markets)) {
        marketdata <- marketdatamap[market]
        periodtexts <- marketdata[[1]][2]
        for (i in 1:periods) {
            text <- periodtexts[[1]][[i]]
            pair <- list(market, i)
            pairkey <- paste(1, market)
#            str(text)
            if (is.null(perioddatamap[[text]])) {
#                str("new")
                perioddata <- list()
                perioddata[["text"]] <- list()
                perioddatamap[text] <- perioddata
            }
            perioddata <- perioddatamap[[text]]
            pairs <- perioddata[["text"]]
            pairs[[pairkey]] <- pair
            perioddata[["text"]] <- pairs
            perioddatamap[[text]] <- perioddata
        }
    }
    retl <- list()
    #perioddata <- perioddatamap[periodtext]
    #pairs <- perioddata["text"]
    #str("bla")
    #str(perioddatamap);
    #str("bla2")
    for (text in names(perioddatamap)) {
        if (text == periodtext) {
#        str(text)
        perioddata <- perioddatamap[[text]]
        pairs <- perioddata[["text"]]
        pair <- pairs[[pairkey]]
        market <- pair[[1]]
        period <- pair[[2]]
#        str("mark")
#        str(market)
#        str(period)
        marketdata <- marketdatamap[market]
            datedstocklists <- marketdata[[1]][3]
            ls <- list()
            names <- list()
            c <- 0
        for (i in 1:length(ids)) {
            idpair <- ids[[i]]
            idmarket <- idpair[1]
            id <- idpair[2]
 #           str("for")
            cat(market, idmarket, id)
            if (market == idmarket) {
                cat("per", text, " ", id, " ", period, " ")
                c <- c + 1
                l <- getelem3(id, days, datedstocklists, period, topbottom)
                ls[c] <- list(l)
                names[c] <- "test"
#                str(l)
            }
        }
        }
    }
    maindate <- "1"
    olddate <- "2"
    displaychart(ls, names, 5, period, maindate, olddate)
}

getperiodtexts <- function(market) {
periodtext = list("Period1", "Period2", "Period3", "Period4", "Period5", "Period6")
meta <- dbGetQuery(con, "select * from meta")
mymeta <- subset(meta, marketid == market)
if (nrow(mymeta) > 0) {
for (i in 1:periods) {
if (!is.na(getperiodtext(mymeta, i))) {
periodtext[i] = getperiodtext(mymeta, i)
}
}
}
return(periodtext)
}

getmarket <- function(con, market) {
query <- paste("select * from stock where marketid = '", market, "'", sep = "")
return(dbGetQuery(con, query))
}

# create a connection
# save the password that we can "hide" it as best as we can by collapsing it
pw <- {
  "password"
  }

if (exists("drv")) {
cons <- dbListConnections(drv)
for (con in cons) {
print(con)
dbDisconnect(con)
}
#dbUnloadDriver(drv)
}

# loads the PostgreSQL driver
if (!exists("drv")) {
drv <- dbDriver("PostgreSQL")
}
# creates a connection to the postgres database
# note that "con" will be used later in each connection to the database
if (!exists("con")) {
con <- dbConnect(drv, dbname = "stockstat",
                 host = "localhost", port = 5432,
		                  user = "stockstat", password = pw)
				  rm(pw) # removes the password
}
#on.exit(dbDisconnect(con))
#on.exit(dbUnloadDriver(drv), add = TRUE)

# check for the cartable
dbExistsTable(con, "stockstat")
dbExistsTable(con, "stock")
# TRUE

if (!exists("marketid")) {
marketid <- "morncat"
}

data <- dbGetQuery(con, "select * from stock")
meta <- dbGetQuery(con, "select * from meta")
mymeta <- subset(meta, marketid == mymarketid)
data_3 <- getmarket(con, marketid)
names(data_3)
s <- subset(data_3, "id" == "EUCA000749")

for (i in 1:nrow(data_3)) {
#print(data_3[i,"date"])
#return()
}

#for (i in data_3) {
#print(i["date"])
#return
#}

listid2 <- splitid(data_3)
listdate2 <- splitdate(data_3)
listdate <- split(data_3, data_3$date)
listid <- split(data_3, data_3$id)

#l <- listdate[[104]]
if (!exists("days")) {
days <- 10
}
if (!exists("topbottom")) {
topbottom <- 5
}
count <- days
if (!exists("mytableintervaldays")) {
mytableintervaldays <- 5
}
#date <- "2016-05-02"

datedstocklists <- getdatedstocklists(listdate, date, mytableintervaldays)

if (!exists("period")) {
period <- 3
}

#alist <- getlistanddiff(datedstocklists, listid, listdate, days, mytableintervaldays)
#periodmaps <- alist[[1]]
#stocklistperiod <- alist[[2]]
#mybottomperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)
#mytopperiod(datedstocklists, stocklistperiod, periodmaps, period, topbottom)

#gettopchart(days, topbottom, stocklistperiod, period)
#getbottomchart(days, topbottom, stocklistperiod, period)
#rise <- getrising(days, periodmaps, stocklistperiod, period)
#risetopids <- head(names(rise[[1]]))

getcontentgraph(con, date, ids, "1y")

# close the connection
dbDisconnect(con)
dbUnloadDriver(drv)
#rm(list = ls())
rm(con)
rm(drv)
print("ending")
#return

## Preliminary analysis of water inflow data

# Import the water inflow sample data
samples <- read.csv("./water_inflow_data.csv",  stringsAsFactors = FALSE)
# I did edit a couple of the dates because R seems to struggle with dates (but then don't we all)

# Rename all the measurements for easier reading
rn <- function(old.name, new.name){
  names(samples)[names(samples) == old.name] <<- new.name
}

rn("Flow.rate..litres.sec.", "Flow")

rn("BOD.5.Day.ATU..mg.l.", "BOD")
rn("Nitrogen...Total.as.N..mg.l.", "Nitrogen.Total")
rn("Phosphorus...Total.as.P..mg.l.", "Phosphorus")
rn("Alkalinity.to.pH.4.5.as.CaCO3..mg.l.", "Alkalinity")
rn("Ammoniacal.Nitrogen.as.N..mg.l.", "Nitrogen.Ammoniacal")
rn("Chloride..mg.l.", "Chloride")
rn("Nitrite.as.N..mg.l.", "Nitrite")
rn("Nitrogen...Total.Oxidised.as.N..mg.l.", "Nitrogen.Oxidised")
rn("Orthophosphate..reactive.as.P..mg.l.", "Orthophosphate")
rn("Silicate..reactive.as.SiO2..mg.l.", "Silicate")
rn("Phosphate...Total.as.P..mg.l.", "Phosphate")
rn("Conductivity.at.20C..uS.cm.", "Conductivity")
rn("Turbidity..NTU.", "Turbidity")
rn("Solids..Suspended.at.105.C..mg.l.", "Solids")
rn("Calcium..mg.l.", "Calcium")
rn("Magnesium..mg.l.", "Magnesium")
rn("Potassium..mg.l.", "Potassium")
rn("Sodium..mg.l.", "Sodium")

# Also remane the comment because it actually contains the site name
rn("Comment", "Name")

# Remove the spaces from the grid references
samples$Grid.reference <- gsub(" ", "", samples$Grid.reference, fixed = TRUE)

# How many site names are there?
length(unique(samples$Name))

# How many grid references are there?
length(unique(samples$Grid.reference))

# How many pairs of comments and grid references?
sites <- data.frame(OSGrid = samples$Grid.reference, Name = samples$Name)
sites <- unique(sites)
nrow(sites)

# Give each of the sites a unique id (might come in handy)
sites$Id <- seq.int(nrow(sites))

# Export the sites list so WGS84 can be added to it
write.table(sites, "sites.csv", row.names = FALSE, col.names = TRUE, sep = ",")

## Go to http://gridreferencefinder.com/batchConvert/batchConvert.php to do the geocoding

# Import the geocoded sites
sites <- read.csv("./sites_with_locations.csv", header = TRUE, stringsAsFactors = FALSE)

# Cluster using k-means
km <- kmeans(cbind(sites$X, sites$Y), centers = 3)
# Plot without a background to look at the clusters
plot(sites$X, sites$Y, col = km$cluster, pch = 20)
plot(sites$Lng, sites$Lat, col = km$cluster, pch = 20)

# Get a map of the area and plot sites
library(ggmap)
map_centre <- c(lon = -2.85, lat = 52.80) # chosen by inspection
map <- qmap(map_centre) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)

# Zoom in in the Marton cluster of 10
map_centre <- c(lon = -3.045, lat = 52.623) # chosen by inspection
map <- qmap(map_centre, zoom = 15) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)


# Let's check out the distribution of measurments
# A function to standardised the graphs
graf <- function(column.name){
  scratch <- samples[,c(column.name)]
  scratch <- gsub("[^.0-9]+", "", scratch) # just the numbers and nothing else
  scratch <- as.numeric(scratch)
  title <- paste("Histogram of", column.name, sep = " ")
  hist(main = title, scratch, xlab = column.name, breaks = 20)
}
# Complete graph-arama
graf("BOD")
graf("Nitrogen.Total")             
graf("Phosphorus")           
graf("Alkalinity")          
graf("Nitrogen.Ammoniacal")
graf("Chloride")
graf("Nitrite") 
graf("Nitrogen.Oxidised") 
graf("Orthophosphate")       
graf("Silicate")
graf("Phosphate")             
graf("Conductivity")
graf("Turbidity")
graf("Solids")
graf("Calcium")              
graf("Magnesium")
graf("Potassium")
graf("Sodium")

"
The graphs for calcium, conductivity, silicate, alkalinity look like they might have been censored.
There appears to be a spike at one end of the distribution, like the data might have contained
a bunch of < or > but inspection reveals that silicate contains only one reading with < (<0.200).
"

# Let's find the bad boys
baduns <- function(column.name){
  # The column.name is passed as a string so the column has to be accessed using [] notation
  # rather than directly.
  scratch <- samples[,c("Name", column.name)]
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)]) # then convert to numeric
  scratch <- aggregate(scratch[,column.name], by = list(scratch$Name), max)
  scratch <- scratch[order(-scratch$x),] # Bad boys at the top
  names(scratch)[names(scratch) == "Group.1"] <- "Name"
  scratch <- head(scratch, n=8) # Calcium etc... have only been recorded for 8 sites.
  print(scratch)
  scratch <- scratch[order(scratch$x),] # reverse the order
  bp <- barplot(scratch$x, xlab=column.name, horiz=TRUE)
  text(0, bp, scratch$Name, cex=1, pos=4)
}

baduns("BOD")
baduns("Nitrogen.Total")             
baduns("Phosphorus")           
baduns("Alkalinity")          
baduns("Nitrogen.Ammoniacal")
baduns("Chloride")
baduns("Nitrite") 
baduns("Nitrogen.Oxidised") 
baduns("Orthophosphate")       
baduns("Silicate")
baduns("Phosphate")             
baduns("Conductivity")
baduns("Turbidity")
baduns("Solids")
baduns("Calcium")              
baduns("Magnesium")
baduns("Potassium")
baduns("Sodium")

# Sites with 9 or more samples.
scratch <- as.data.frame(table(samples$Name))
colnames(scratch) <- c("Name", "Freq")
sites <- merge(sites, scratch, by="Name")
scratch <- sites[sites$Freq >= 8,]
scratch <- merge(scratch, samples, by = "Name")

# The dates are ambiguous so stick in the century using a regex
scratch$Sample.taken <- gsub("(\\d{2}-[A-Z]{3}-)", "\\120", scratch$Sample.taken, perl = TRUE)
scratch$Sample.taken <- strptime(scratch$Sample.taken, "%d-%b-%Y %H:%M")
scratch$Sample.taken <- as.Date(scratch$Sample.taken)
scratch$Sample.taken <- as.POSIXct(scratch$Sample.taken, "%d-%b-%Y")

# The flows include some comments to the effect that there is no flow so these are made into zeros
scratch$Flow <- as.numeric(scratch$Flow)
scratch$Flow[is.na(scratch$Flow)] <- 0

library(ggplot2)
library(scales)

# Let's graph the ones with reasonable amounts of data
timegraph <- function(column.name){
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)])
  scratch$total <- scratch[,c(column.name)] * scratch$Flow
  ggplot(scratch, aes(x = Sample.taken, y = scratch$total, colour=Name, group=Name)) +
    geom_line() +
    scale_x_datetime(date_breaks = "1 month", date_labels = "%b") +
    xlab("2015-2016") + 
    ylab(paste0(column.name, " * Flow"))
}

timegraph("BOD")
timegraph("Nitrogen.Total")             
timegraph("Phosphorus")           
timegraph("Alkalinity")          
timegraph("Nitrogen.Ammoniacal")
timegraph("Chloride")
timegraph("Nitrite") 
timegraph("Nitrogen.Oxidised") 
timegraph("Orthophosphate")       
timegraph("Silicate")
timegraph("Phosphate")             
timegraph("Conductivity")
timegraph("Turbidity")
timegraph("Solids")
timegraph("Calcium")              
timegraph("Magnesium")
timegraph("Potassium")
timegraph("Sodium")


## Preliminary analysis of water inflow data

# Import the water inflow sample data
samples <- read.csv("./water_inflow_data.csv",  stringsAsFactors = FALSE)
# I did edit a couple of the dates because R seems to struggle with dates (but then don't we all)

# Rename all the measurements for easier reading
rn <- function(old.name, new.name){
  names(samples)[names(samples) == old.name] <<- new.name
}

rn("Flow.rate..litres.sec.", "Flow")

rn("BOD.5.Day.ATU..mg.l.", "BOD")
rn("Nitrogen...Total.as.N..mg.l.", "Nitrogen.Total")
rn("Phosphorus...Total.as.P..mg.l.", "Phosphorus")
rn("Alkalinity.to.pH.4.5.as.CaCO3..mg.l.", "Alkalinity")
rn("Ammoniacal.Nitrogen.as.N..mg.l.", "Nitrogen.Ammoniacal")
rn("Chloride..mg.l.", "Chloride")
rn("Nitrite.as.N..mg.l.", "Nitrite")
rn("Nitrogen...Total.Oxidised.as.N..mg.l.", "Nitrogen.Oxidised")
rn("Orthophosphate..reactive.as.P..mg.l.", "Orthophosphate")
rn("Silicate..reactive.as.SiO2..mg.l.", "Silicate")
rn("Phosphate...Total.as.P..mg.l.", "Phosphate")
rn("Conductivity.at.20C..uS.cm.", "Conductivity")
rn("Turbidity..NTU.", "Turbidity")
rn("Solids..Suspended.at.105.C..mg.l.", "Solids")
rn("Calcium..mg.l.", "Calcium")
rn("Magnesium..mg.l.", "Magnesium")
rn("Potassium..mg.l.", "Potassium")
rn("Sodium..mg.l.", "Sodium")

# Also remane the comment because it actually contains the site name
rn("Comment", "Name")

# Remove the spaces from the grid references
samples$Grid.reference <- gsub(" ", "", samples$Grid.reference, fixed = TRUE)

# How many site names are there?
length(unique(samples$Name))

# How many grid references are there?
length(unique(samples$Grid.reference))

# How many pairs of comments and grid references?
sites <- data.frame(OSGrid = samples$Grid.reference, Name = samples$Name)
sites <- unique(sites)
nrow(sites)

# Give each of the sites a unique id (might come in handy)
sites$Id <- seq.int(nrow(sites))

# Export the sites list so WGS84 can be added to it
write.table(sites, "sites.csv", row.names = FALSE, col.names = TRUE, sep = ",")

## Go to http://gridreferencefinder.com/batchConvert/batchConvert.php to do the geocoding

# Import the geocoded sites
sites <- read.csv("./sites_with_locations.csv", header = TRUE, stringsAsFactors = FALSE)

# Cluster using k-means
km <- kmeans(cbind(sites$X, sites$Y), centers = 3)
# Plot without a background to look at the clusters
plot(sites$X, sites$Y, col = km$cluster, pch = 20)
plot(sites$Lng, sites$Lat, col = km$cluster, pch = 20)

# Get a map of the area and plot sites
library(ggmap)
map_centre <- c(lon = -2.85, lat = 52.80) # chosen by inspection
map <- qmap(map_centre) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)

# Zoom in in the Marton cluster of 10
map_centre <- c(lon = -3.045, lat = 52.623) # chosen by inspection
map <- qmap(map_centre, zoom = 15) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)


# Let's check out the distribution of measurments
# A function to standardised the graphs
graf <- function(column.name){
  scratch <- samples[,c(column.name)]
  scratch <- gsub("[^.0-9]+", "", scratch) # just the numbers and nothing else
  scratch <- as.numeric(scratch)
  title <- paste("Histogram of", column.name, sep = " ")
  hist(main = title, scratch, xlab = column.name, breaks = 20)
}
# Complete graph-arama
graf("BOD")
graf("Nitrogen.Total")             
graf("Phosphorus")           
graf("Alkalinity")          
graf("Nitrogen.Ammoniacal")
graf("Chloride")
graf("Nitrite") 
graf("Nitrogen.Oxidised") 
graf("Orthophosphate")       
graf("Silicate")
graf("Phosphate")             
graf("Conductivity")
graf("Turbidity")
graf("Solids")
graf("Calcium")              
graf("Magnesium")
graf("Potassium")
graf("Sodium")

"
The graphs for calcium, conductivity, silicate, alkalinity look like they might have been censored.
There appears to be a spike at one end of the distribution, like the data might have contained
a bunch of < or > but inspection reveals that silicate contains only one reading with < (<0.200).
"

# Let's find the bad boys
baduns <- function(column.name){
  # The column.name is passed as a string so the column has to be accessed using [] notation
  # rather than directly.
  scratch <- samples[,c("Name", column.name)]
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)]) # then convert to numeric
  scratch <- aggregate(scratch[,column.name], by = list(scratch$Name), max)
  scratch <- scratch[order(-scratch$x),] # Bad boys at the top
  names(scratch)[names(scratch) == "Group.1"] <- "Name"
  scratch <- head(scratch, n=8) # Calcium etc... have only been recorded for 8 sites.
  print(scratch)
  scratch <- scratch[order(scratch$x),] # reverse the order
  bp <- barplot(scratch$x, xlab=column.name, horiz=TRUE)
  text(0, bp, scratch$Name, cex=1, pos=4)
}

baduns("BOD")
baduns("Nitrogen.Total")             
baduns("Phosphorus")           
baduns("Alkalinity")          
baduns("Nitrogen.Ammoniacal")
baduns("Chloride")
baduns("Nitrite") 
baduns("Nitrogen.Oxidised") 
baduns("Orthophosphate")       
baduns("Silicate")
baduns("Phosphate")             
baduns("Conductivity")
baduns("Turbidity")
baduns("Solids")
baduns("Calcium")              
baduns("Magnesium")
baduns("Potassium")
baduns("Sodium")

# Sites with 9 or more samples.
scratch <- as.data.frame(table(samples$Name))
colnames(scratch) <- c("Name", "Freq")
sites <- merge(sites, scratch, by="Name")
scratch <- sites[sites$Freq >= 8,]
scratch <- merge(scratch, samples, by = "Name")

# The dates are ambiguous so stick in the century using a regex
scratch$Sample.taken <- gsub("(\\d{2}-[A-Z]{3}-)", "\\120", scratch$Sample.taken, perl = TRUE)
scratch$Sample.taken <- strptime(scratch$Sample.taken, "%d-%b-%Y %H:%M")
scratch$Sample.taken <- as.Date(scratch$Sample.taken)
scratch$Sample.taken <- as.POSIXct(scratch$Sample.taken, "%d-%b-%Y")

# The flows include some comments to the effect that there is no flow so these are made into zeros
scratch$Flow <- as.numeric(scratch$Flow)
scratch$Flow[is.na(scratch$Flow)] <- 0

library(ggplot2)
library(scales)

# Let's graph the ones with reasonable amounts of data
timegraph <- function(column.name){
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)])
  scratch$total <- scratch[,c(column.name)] * scratch$Flow
  ggplot(scratch, aes(x = Sample.taken, y = scratch$total, colour=Name, group=Name)) +
    geom_line() +
    scale_x_datetime(date_breaks = "1 month", date_labels = "%b") +
    xlab("2015-2016") + 
    ylab(paste0(column.name, " * Flow"))
}

timegraph("BOD")
timegraph("Nitrogen.Total")             
timegraph("Phosphorus")           
timegraph("Alkalinity")          
timegraph("Nitrogen.Ammoniacal")
timegraph("Chloride")
timegraph("Nitrite") 
timegraph("Nitrogen.Oxidised") 
timegraph("Orthophosphate")       
timegraph("Silicate")
timegraph("Phosphate")             
timegraph("Conductivity")
timegraph("Turbidity")
timegraph("Solids")
timegraph("Calcium")              
timegraph("Magnesium")
timegraph("Potassium")
timegraph("Sodium")
## Preliminary analysis of water inflow data

# Import the water inflow sample data
samples <- read.csv("./water_inflow_data.csv",  stringsAsFactors = FALSE)
# I did edit a couple of the dates because R seems to struggle with dates (but then don't we all)

# Rename all the measurements for easier reading
rn <- function(old.name, new.name){
  names(samples)[names(samples) == old.name] <<- new.name
}

rn("Flow.rate..litres.sec.", "Flow")

rn("BOD.5.Day.ATU..mg.l.", "BOD")
rn("Nitrogen...Total.as.N..mg.l.", "Nitrogen.Total")
rn("Phosphorus...Total.as.P..mg.l.", "Phosphorus")
rn("Alkalinity.to.pH.4.5.as.CaCO3..mg.l.", "Alkalinity")
rn("Ammoniacal.Nitrogen.as.N..mg.l.", "Nitrogen.Ammoniacal")
rn("Chloride..mg.l.", "Chloride")
rn("Nitrite.as.N..mg.l.", "Nitrite")
rn("Nitrogen...Total.Oxidised.as.N..mg.l.", "Nitrogen.Oxidised")
rn("Orthophosphate..reactive.as.P..mg.l.", "Orthophosphate")
rn("Silicate..reactive.as.SiO2..mg.l.", "Silicate")
rn("Phosphate...Total.as.P..mg.l.", "Phosphate")
rn("Conductivity.at.20C..uS.cm.", "Conductivity")
rn("Turbidity..NTU.", "Turbidity")
rn("Solids..Suspended.at.105.C..mg.l.", "Solids")
rn("Calcium..mg.l.", "Calcium")
rn("Magnesium..mg.l.", "Magnesium")
rn("Potassium..mg.l.", "Potassium")
rn("Sodium..mg.l.", "Sodium")

# Also remane the comment because it actually contains the site name
rn("Comment", "Name")

# Remove the spaces from the grid references
samples$Grid.reference <- gsub(" ", "", samples$Grid.reference, fixed = TRUE)

# How many site names are there?
length(unique(samples$Name))

# How many grid references are there?
length(unique(samples$Grid.reference))

# How many pairs of comments and grid references?
sites <- data.frame(OSGrid = samples$Grid.reference, Name = samples$Name)
sites <- unique(sites)
nrow(sites)

# Give each of the sites a unique id (might come in handy)
sites$Id <- seq.int(nrow(sites))

# Export the sites list so WGS84 can be added to it
write.table(sites, "sites.csv", row.names = FALSE, col.names = TRUE, sep = ",")

## Go to http://gridreferencefinder.com/batchConvert/batchConvert.php to do the geocoding

# Import the geocoded sites
sites <- read.csv("./sites_with_locations.csv", header = TRUE, stringsAsFactors = FALSE)

# Cluster using k-means
km <- kmeans(cbind(sites$X, sites$Y), centers = 3)
# Plot without a background to look at the clusters
plot(sites$X, sites$Y, col = km$cluster, pch = 20)
plot(sites$Lng, sites$Lat, col = km$cluster, pch = 20)

# Get a map of the area and plot sites
library(ggmap)
map_centre <- c(lon = -2.85, lat = 52.80) # chosen by inspection
map <- qmap(map_centre) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)

# Zoom in in the Marton cluster of 10
map_centre <- c(lon = -3.045, lat = 52.623) # chosen by inspection
map <- qmap(map_centre, zoom = 15) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)


# Let's check out the distribution of measurments
# A function to standardised the graphs
graf <- function(column.name){
  scratch <- samples[,c(column.name)]
  scratch <- gsub("[^.0-9]+", "", scratch) # just the numbers and nothing else
  scratch <- as.numeric(scratch)
  title <- paste("Histogram of", column.name, sep = " ")
  hist(main = title, scratch, xlab = column.name, breaks = 20)
}
# Complete graph-arama
graf("BOD")
graf("Nitrogen.Total")             
graf("Phosphorus")           
graf("Alkalinity")          
graf("Nitrogen.Ammoniacal")
graf("Chloride")
graf("Nitrite") 
graf("Nitrogen.Oxidised") 
graf("Orthophosphate")       
graf("Silicate")
graf("Phosphate")             
graf("Conductivity")
graf("Turbidity")
graf("Solids")
graf("Calcium")              
graf("Magnesium")
graf("Potassium")
graf("Sodium")

"
The graphs for calcium, conductivity, silicate, alkalinity look like they might have been censored.
There appears to be a spike at one end of the distribution, like the data might have contained
a bunch of < or > but inspection reveals that silicate contains only one reading with < (<0.200).
"

# Let's find the bad boys
baduns <- function(column.name){
  # The column.name is passed as a string so the column has to be accessed using [] notation
  # rather than directly.
  scratch <- samples[,c("Name", column.name)]
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)]) # then convert to numeric
  scratch <- aggregate(scratch[,column.name], by = list(scratch$Name), max)
  scratch <- scratch[order(-scratch$x),] # Bad boys at the top
  names(scratch)[names(scratch) == "Group.1"] <- "Name"
  scratch <- head(scratch, n=8) # Calcium etc... have only been recorded for 8 sites.
  print(scratch)
  scratch <- scratch[order(scratch$x),] # reverse the order
  bp <- barplot(scratch$x, xlab=column.name, horiz=TRUE)
  text(0, bp, scratch$Name, cex=1, pos=4)
}

baduns("BOD")
baduns("Nitrogen.Total")             
baduns("Phosphorus")           
baduns("Alkalinity")          
baduns("Nitrogen.Ammoniacal")
baduns("Chloride")
baduns("Nitrite") 
baduns("Nitrogen.Oxidised") 
baduns("Orthophosphate")       
baduns("Silicate")
baduns("Phosphate")             
baduns("Conductivity")
baduns("Turbidity")
baduns("Solids")
baduns("Calcium")              
baduns("Magnesium")
baduns("Potassium")
baduns("Sodium")

# Sites with 9 or more samples.
scratch <- as.data.frame(table(samples$Name))
colnames(scratch) <- c("Name", "Freq")
sites <- merge(sites, scratch, by="Name")
scratch <- sites[sites$Freq >= 8,]
scratch <- merge(scratch, samples, by = "Name")

# The dates are ambiguous so stick in the century using a regex
scratch$Sample.taken <- gsub("(\\d{2}-[A-Z]{3}-)", "\\120", scratch$Sample.taken, perl = TRUE)
scratch$Sample.taken <- strptime(scratch$Sample.taken, "%d-%b-%Y %H:%M")
scratch$Sample.taken <- as.Date(scratch$Sample.taken)
scratch$Sample.taken <- as.POSIXct(scratch$Sample.taken, "%d-%b-%Y")

# The flows include some comments to the effect that there is no flow so these are made into zeros
scratch$Flow <- as.numeric(scratch$Flow)
scratch$Flow[is.na(scratch$Flow)] <- 0

library(ggplot2)
library(scales)

# Let's graph the ones with reasonable amounts of data
timegraph <- function(column.name){
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)])
  scratch$total <- scratch[,c(column.name)] * scratch$Flow
  ggplot(scratch, aes(x = Sample.taken, y = scratch$total, colour=Name, group=Name)) +
    geom_line() +
    scale_x_datetime(date_breaks = "1 month", date_labels = "%b") +
    xlab("2015-2016") + 
    ylab(paste0(column.name, " * Flow"))
}

timegraph("BOD")
timegraph("Nitrogen.Total")             
timegraph("Phosphorus")           
timegraph("Alkalinity")          
timegraph("Nitrogen.Ammoniacal")
timegraph("Chloride")
timegraph("Nitrite") 
timegraph("Nitrogen.Oxidised") 
timegraph("Orthophosphate")       
timegraph("Silicate")
timegraph("Phosphate")             
timegraph("Conductivity")
timegraph("Turbidity")
timegraph("Solids")
timegraph("Calcium")              
timegraph("Magnesium")
timegraph("Potassium")
timegraph("Sodium")


## Preliminary analysis of water inflow data

# Import the water inflow sample data
samples <- read.csv("./water_inflow_data.csv",  stringsAsFactors = FALSE)
# I did edit a couple of the dates because R seems to struggle with dates (but then don't we all)

# Rename all the measurements for easier reading
rn <- function(old.name, new.name){
  names(samples)[names(samples) == old.name] <<- new.name
}

rn("BOD.5.Day.ATU..mg.l.", "BOD")
rn("Nitrogen...Total.as.N..mg.l.", "Nitrogen.Total")
rn("Phosphorus...Total.as.P..mg.l.", "Phosphorus")
rn("Alkalinity.to.pH.4.5.as.CaCO3..mg.l.", "Alkalinity")
rn("Ammoniacal.Nitrogen.as.N..mg.l.", "Nitrogen.Ammoniacal")
rn("Chloride..mg.l.", "Chloride")
rn("Nitrite.as.N..mg.l.", "Nitrite")
rn("Nitrogen...Total.Oxidised.as.N..mg.l.", "Nitrogen.Oxidised")
rn("Orthophosphate..reactive.as.P..mg.l.", "Orthophosphate")
rn("Silicate..reactive.as.SiO2..mg.l.", "Silicate")
rn("Phosphate...Total.as.P..mg.l.", "Phosphate")
rn("Conductivity.at.20C..uS.cm.", "Conductivity")
rn("Turbidity..NTU.", "Turbidity")
rn("Solids..Suspended.at.105.C..mg.l.", "Solids")
rn("Calcium..mg.l.", "Calcium")
rn("Magnesium..mg.l.", "Magnesium")
rn("Potassium..mg.l.", "Potassium")
rn("Sodium..mg.l.", "Sodium")

# Also remane the comment because it actually contains the site name
rn("Comment", "Name")

# Remove the spaces from the grid references
samples$Grid.reference <- gsub(" ", "", samples$Grid.reference, fixed = TRUE)

# How many site names are there?
length(unique(samples$Name))

# How many grid references are there?
length(unique(samples$Grid.reference))

# How many pairs of comments and grid references?
sites <- data.frame(OSGrid = samples$Grid.reference, Name = samples$Name)
sites <- unique(sites)
nrow(sites)

# Give each of the sites a unique id (might come in handy)
sites$Id <- seq.int(nrow(sites))

# Export the sites list so WGS84 can be added to it
write.table(sites, "sites.csv", row.names = FALSE, col.names = TRUE, sep = ",")

## Go to http://gridreferencefinder.com/batchConvert/batchConvert.php to do the geocoding

# Import the geocoded sites
sites <- read.csv("./sites_with_locations.csv", header = TRUE, stringsAsFactors = FALSE)

# Cluster using k-means
km <- kmeans(cbind(sites$X, sites$Y), centers = 3)
# Plot without a background to look at the clusters
plot(sites$X, sites$Y, col = km$cluster, pch = 20)
plot(sites$Lng, sites$Lat, col = km$cluster, pch = 20)

# Get a map of the area and plot sites
library(ggmap)
map_centre <- c(lon = -2.85, lat = 52.80) # chosen by inspection
map <- qmap(map_centre) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)

# Zoom in in the Marton cluster of 10
map_centre <- c(lon = -3.045, lat = 52.623) # chosen by inspection
map <- qmap(map_centre, zoom = 15) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)


# Let's check out the distribution of measurments
# A function to standardised the graphs
graf <- function(column.name){
  scratch <- samples[,c(column.name)]
  scratch <- gsub("[^.0-9]+", "", scratch) # just the numbers and nothing else
  scratch <- as.numeric(scratch)
  title <- paste("Histogram of", column.name, sep = " ")
  hist(main = title, scratch, xlab = column.name, breaks = 20)
}
# Complete graph-arama
graf("BOD")
graf("Nitrogen.Total")             
graf("Phosphorus")           
graf("Alkalinity")          
graf("Nitrogen.Ammoniacal")
graf("Chloride")
graf("Nitrite") 
graf("Nitrogen.Oxidised") 
graf("Orthophosphate")       
graf("Silicate")
graf("Phosphate")             
graf("Conductivity")
graf("Turbidity")
graf("Solids")
graf("Calcium")              
graf("Magnesium")
graf("Potassium")
graf("Sodium")

"
The graphs for calcium, conductivity, silicate, alkalinity look like they might have been censored.
There appears to be a spike at one end of the distribution, like the data might have contained
a bunch of < or > but inspection reveals that silicate contains only one reading with < (<0.200).
"

# Let's find the bad boys
baduns <- function(column.name){
  # The column.name is passed as a string so the column has to be accessed using [] notation
  # rather than directly.
  scratch <- samples[,c("Name", column.name)]
  scratch[,c(column.name)] <- gsub("[^.0-9]+", "", scratch[,c(column.name)]) # just the numbers and nothing else
  scratch[,c(column.name)] <- as.numeric(scratch[,c(column.name)]) # then convert to numeric
  scratch <- aggregate(scratch[,column.name], by = list(scratch$Name), max)
  scratch <- scratch[order(-scratch$x),] # Bad boys at the top
  names(scratch)[names(scratch) == "Group.1"] <- "Name"
  scratch <- head(scratch, n=8) # Calcium etc... have only been recorded for 8 sites.
  print(scratch)
  scratch <- scratch[order(scratch$x),] # reverse the order
  bp <- barplot(scratch$x, xlab=column.name, horiz=TRUE)
  text(0, bp, scratch$Name, cex=1, pos=4)
}

baduns("Nitrogen.Total")
baduns("BOD")
baduns("Nitrogen.Total")             
baduns("Phosphorus")           
baduns("Alkalinity")          
baduns("Nitrogen.Ammoniacal")
baduns("Chloride")
baduns("Nitrite") 
baduns("Nitrogen.Oxidised") 
baduns("Orthophosphate")       
baduns("Silicate")
baduns("Phosphate")             
baduns("Conductivity")
baduns("Turbidity")
baduns("Solids")
baduns("Calcium")              
baduns("Magnesium")
baduns("Potassium")
baduns("Sodium")

# Sites with 9 or more samples.
scratch <- as.data.frame(table(samples$Name))
colnames(scratch) <- c("Name", "Freq")
sites <- merge(sites, scratch, by="Name")
scratch <- sites[sites$Freq >= 8,]
scratch <- merge(scratch, samples, by = "Name")

# The dates are ambiguous so stick in the century using a regex
scratch$Sample.taken <- gsub("(\\d{2}-[A-Z]{3}-)", "\\120", scratch$Sample.taken, perl = TRUE)
scratch$Sample.taken <- strptime(scratch$Sample.taken, "%d-%b-%Y %H:%M")
scratch$Sample.taken <- as.Date(scratch$Sample.taken)
scratch$Sample.taken <- as.POSIXct(scratch$Sample.taken, "%d-%b-%Y")

library(ggplot2)
library(scales)

# Let's graph the ones with reasonable amounts of data
timegraph <- function(column.name){
  ggplot(scratch, aes(x=Sample.taken, y=scratch[,c(column.name)], colour=Name, group=Name)) +
    geom_line() +
    scale_x_datetime(date_breaks = "1 month", date_labels = "%b") +
    xlab("2015-2016") + 
    ylab(column.name)
}

timegraph("Nitrogen.Total")
timegraph("BOD")
timegraph("Nitrogen.Total")             
timegraph("Phosphorus")           
timegraph("Alkalinity")          
timegraph("Nitrogen.Ammoniacal")
timegraph("Chloride")
timegraph("Nitrite") 
timegraph("Nitrogen.Oxidised") 
timegraph("Orthophosphate")       
timegraph("Silicate")
timegraph("Phosphate")             
timegraph("Conductivity")
timegraph("Turbidity")
timegraph("Solids")
timegraph("Calcium")              
timegraph("Magnesium")
timegraph("Potassium")
timegraph("Sodium")
## Preliminary analysis of water inflow data

# Import the water inflow sample data
samples <- read.csv("./water_inflow_data.csv",  stringsAsFactors=FALSE)

# Rename all the measurements for easier reading
rn <- function(old.name, new.name){
  names(samples)[names(samples) == old.name] <<- new.name
}

rn("BOD.5.Day.ATU..mg.l.", "BOD")
rn("Nitrogen...Total.as.N..mg.l.", "Nitrogen")
rn("Phosphorus...Total.as.P..mg.l.", "Phosphorus")
rn("Alkalinity.to.pH.4.5.as.CaCO3..mg.l.", "Alkalinity")
rn("Ammoniacal.Nitrogen.as.N..mg.l.", "Nitrogen.Ammoniacal")
rn("Chloride..mg.l.", "Chloride")
rn("Nitrite.as.N..mg.l.", "Nitrite")
rn("Nitrogen...Total.Oxidised.as.N..mg.l.", "Nitrogen.Oxidised")
rn("Orthophosphate..reactive.as.P..mg.l.", "Orthophosphate")
rn("Silicate..reactive.as.SiO2..mg.l.", "Silicate")
rn("Phosphate...Total.as.P..mg.l.", "Phosphate")
rn("Conductivity.at.20C..uS.cm.", "Conductivity")
rn("Turbidity..NTU.", "Turbidity")
rn("Solids..Suspended.at.105.C..mg.l.", "Solids")
rn("Calcium..mg.l.", "Calcium")
rn("Magnesium..mg.l.", "Magnesium")
rn("Potassium..mg.l.", "Potassium")
rn("Sodium..mg.l.", "Sodium")

# Remove the spaces from the grid references
samples$Grid.reference <- gsub(" ", "", samples$Grid.reference, fixed = TRUE)

# How many site names are there?
length(unique(samples$Comment))

# How many grid references are there?
length(unique(samples$Grid.reference))

# How many pairs of comments and grid references?
sites <- data.frame(OSGrid = samples$Grid.reference, Name = samples$Comment)
sites <- unique(sites)
nrow(sites)

# Give each of the sites a unique id (might come in handy)
sites$Id <- seq.int(nrow(sites))

# Export the sites list so WGS84 can be added to it
write.table(sites, "sites.csv", row.names = FALSE, col.names = TRUE, sep = ",")

## Go to http://gridreferencefinder.com/batchConvert/batchConvert.php to do the geocoding

# Import the geocoded sites
sites <- read.csv("./sites_with_locations.csv", header = TRUE, stringsAsFactors = FALSE)

# Cluster using k-means
km <- kmeans(cbind(sites$X, sites$Y), centers = 3)
# Plot without a background to look at the clusters
plot(sites$X, sites$Y, col = km$cluster, pch = 20)
plot(sites$Lng, sites$Lat, col = km$cluster, pch = 20)

# Get a map of the area and plot sites
library(ggmap)
map_centre <- c(lon = -2.85, lat = 52.80) # chosen by inspection
map <- qmap(map_centre) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)

# Zoom in in the Marton cluster of 10
map_centre <- c(lon = -3.045, lat = 52.623) # chosen by inspection
map <- qmap(map_centre, zoom = 15) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)


# Let's check out the distribution of measurments
# A function to standardised the graphs
graf <- function(column.name){
  scratch <- samples[,c(column.name)]
  scratch <- gsub("[^\\d]", "", scratch, fixed = TRUE)
  scratch <- as.numeric(scratch)
  title <- paste("Histogram of", column.name, sep = " ")
  hist(main = title, scratch, xlab = column.name, breaks = 20)
}
# Complete graph-arama
graf("BOD")
graf("Nitrogen")             
graf("Phosphorus")           
graf("Alkalinity")          
graf("Nitrogen.Ammoniacal")
graf("Chloride")
graf("Nitrite") 
graf("Nitrogen.Oxidised") 
graf("Orthophosphate")       
graf("Silicate")
graf("Phosphate")             
graf("Conductivity")
graf("Turbidity")
graf("Solids")
graf("Calcium")              
graf("Magnesium")
graf("Potassium")
graf("Sodium")

"
The graphs for calcium, conductivity, silicate, alkalinity look like they might have been censored.
There appears to be a spike at one end of the distribution, like the data might have contained
a bunch of < or > but inspection reveals that silicate contains only one reading with < (<0.200).
"




#' Calibrate oli images to TM images
#'
#' Calibrate oli images to TM images using linear regression
#' @param oliwrs2dir character. oli WRS-2 scene directory path
#' @param tmwrs2dir character. TM WRS-2 scene directory path
#' @import raster
#' @import ggplot2
#' @import gridExtra
#' @export


olical_single = function(oli_file, tm_file, overwrite=F){
  
  get_intersection = function(files){
    int = intersect(extent(raster(files[1])),extent(raster(files[2])))
    if(length(files) >= 3){for(i in 3:length(files))int = intersect(extent(raster(files[i])), int)}
    return(int)
  }
  

#   sample_it = function(img, bins, n){
#     
#     mi = min(img, na.rm=T)
#     ma = max(img, na.rm=T)
#     
#     step = (ma - mi)/bins
#     breaks = seq(mi,ma,step)
#     
#     min_samp = array(n, bins)
#     for(i in 1:(length(breaks)-1)){
#       these = which(img > breaks[i] & img <= breaks[i+1])
#       if(i == 1){samp = sample(these, size=min(min_samp[i],length(these)))} else {
#         samp = c(samp, sample(these, size=min(min_samp[i],length(these))))
#       } 
#     }
#     return(samp)
#   }
  
  #define the filenames
  oli_sr_file = oli_file
  oli_mask_file = sub("l8sr.tif", "cloudmask.tif", oli_sr_file)
  ref_tc_file = tm_file
  ref_tca_file = sub("tc", "tca", ref_tc_file)
  ref_mask_file = sub("tc", "cloudmask", ref_tc_file)
  
  #make new directory
  dname = dirname(oli_sr_file)
  oliimgid = substr(basename(oli_sr_file),1,16)
  outdir = file.path(substr(dname,1,nchar(dname)-12),"calibration", oliimgid)  #-5
  dir.create(outdir, showWarnings = F, recursive=T)
  
  #check to see if single cal has already been run
  files = list.files(outdir)
  thesefiles = c("tca_cal_plot.png","tcb_cal_plot.png","tcg_cal_plot.png","tcw_cal_plot.png",
                 "tca_cal_samp.csv","tcb_cal_samp.csv","tcg_cal_samp.csv","tcw_cal_samp.csv")
  results = rep(NA,length(thesefiles))
  for(i in 1:length(results)){
    test = grep(thesefiles[i], files)
    results[i] = length(test) > 0
  }
  if(all(results) == T & overwrite == F){return(0)}
  
  
  #load files as raster
  oli_sr_img = brick(oli_sr_file)
  oli_mask_img = raster(oli_mask_file)
  ref_tc_img = brick(ref_tc_file)
  ref_tca_img  = raster(ref_tca_file)
  ref_mask_img = raster(ref_mask_file)
  
  #align the extents
  extent(oli_sr_img)  = alignExtent(oli_sr_img, ref_tc_img, snap="near")
  extent(oli_mask_img) = alignExtent(oli_mask_img, ref_tc_img, snap="near")
  extent(ref_tc_img)   = alignExtent(ref_tc_img, ref_tc_img, snap="near")
  extent(ref_tca_img)  = alignExtent(ref_tca_img, ref_tc_img, snap="near")
  extent(ref_mask_img) = alignExtent(ref_mask_img, ref_tc_img, snap="near")
  
  #crop the images to their intersection
  int = get_intersection(c(oli_mask_file,ref_mask_file))
  oli_b5_img = crop(subset(oli_sr_img,5),int)
  ref_tca_img = crop(ref_tca_img,int)
  oli_mask_img = crop(oli_mask_img,int)
  ref_mask_img = crop(ref_mask_img,int)
  
  #make a composite mask

  oli_mask_v = as.vector(oli_mask_img)
  ref_mask_v = as.vector(ref_mask_img)

  mask = oli_mask_v*ref_mask_v #make composite mask
  oli_mask_v = ref_mask_v = 0 # save memory
  
  #load oli and etm+ bands
  oli_b5_v = as.vector(oli_b5_img)
  ref_tca_v = as.vector(ref_tca_img)
  
  dif = oli_b5_v - ref_tca_v #find the difference
  oli_b5_v = ref_tca_v = 0 #save memory
  nas = which(mask == 0) #find the bads in the mask
  dif[nas] = NA #set the bads in the dif to NA so they are not included in the calc of mean and stdev
  stdv = sd(dif, na.rm=T) #get stdev of difference
  center = mean(dif, na.rm=T) #get the mean difference
  dif = dif < (center+stdv*2) & dif > (center-stdv*2) #find the pixels that are not that different
    
  
  goods = which(dif == 1)
  if(length(goods) < 20000){return(0)}
  
  #stratified sample
  #refpix = as.matrix(ref_tca_img)[goods]
  #samp = sample_it(refpix, bins=20, n=1000)
  
  #random sample
  samp = sample(1:length(goods), 20000)
  samp = goods[samp]
  sampxy = xyFromCell(oli_mask_img, samp)
  
  #save memory
  mask = 0
  
  #extract the sample pixels from the bands
  olisamp = extract(subset(oli_sr_img, 2:7), sampxy)
  tcsamp = extract(ref_tc_img, sampxy)
  tcasamp = extract(ref_tca_img, sampxy)
  
  #make sure the values are good for running regression on (diversity)
  unib2samp = length(unique(olisamp[,1]))
  unib3samp = length(unique(olisamp[,2]))
  unib4samp = length(unique(olisamp[,3]))
  unib5samp = length(unique(olisamp[,4]))
  unib6samp = length(unique(olisamp[,5]))
  unib7samp = length(unique(olisamp[,6]))
  
  unitcbsamp = length(unique(tcsamp[,1]))
  unitcgsamp = length(unique(tcsamp[,2]))
  unitcwsamp = length(unique(tcsamp[,3]))
  unitcasamp = length(unique(tcasamp))
  
  
  if(unib2samp < 15 | unib3samp < 15 | unib4samp < 15 | unib5samp < 15 | unib6samp < 15 | 
     unib7samp < 15 | unitcbsamp < 15 | unitcgsamp < 15 | unitcwsamp < 15 | unitcasamp < 15){return()}
  
  olibname = basename(oli_sr_file)
  refbname = basename(ref_tc_file)
  refabname = basename(ref_tca_file)
  
  tcb_tbl = data.frame(olibname,refbname,"tcb",sampxy,tcsamp[,1],olisamp)
  tcg_tbl = data.frame(olibname,refbname,"tcg",sampxy,tcsamp[,2],olisamp)
  tcw_tbl = data.frame(olibname,refbname,"tcw",sampxy,tcsamp[,3],olisamp)
  tca_tbl = data.frame(olibname,refabname,"tca",sampxy,tcasamp,olisamp)
  
  
  tcb_tbl = tcb_tbl[complete.cases(tcb_tbl),]
  tcg_tbl = tcg_tbl[complete.cases(tcg_tbl),]
  tcw_tbl = tcw_tbl[complete.cases(tcw_tbl),]
  tca_tbl = tca_tbl[complete.cases(tca_tbl),]
  
  ##############take this out################
  #print(all.equal(nrow(tcb_tbl),nrow(tcg_tbl),nrow(tcw_tbl)))
  ###########################################
  
  cnames = c("oli_img","ref_img","index","x","y","refsamp","b2samp","b3samp","b4samp","b5samp","b6samp","b7samp") 
  colnames(tcb_tbl) = cnames
  colnames(tcg_tbl) = cnames
  colnames(tcw_tbl) = cnames
  colnames(tca_tbl) = cnames
  
  #predict the indices
  #TCB
  outsampfile = file.path(outdir,paste(oliimgid,"_tcb_cal_samp.csv",sep=""))
  model = predict_oli_index(tcb_tbl, outsampfile)
  bcoef = model[[1]]
  bsamp = model[[2]]
  br = cor(bsamp$refsamp, bsamp$singlepred)
  
  #TCG
  outsampfile = file.path(outdir,paste(oliimgid,"_tcg_cal_samp.csv",sep=""))
  model = predict_oli_index(tcg_tbl, outsampfile)
  gcoef = model[[1]]
  gsamp = model[[2]]
  gr = cor(gsamp$refsamp, gsamp$singlepred)
  
  #TCW
  outsampfile = file.path(outdir,paste(oliimgid,"_tcw_cal_samp.csv",sep=""))
  model = predict_oli_index(tcw_tbl, outsampfile)
  wcoef = model[[1]]
  wsamp = model[[2]]
  wr = cor(wsamp$refsamp, wsamp$singlepred)
  
  #TCA
  outsampfile = file.path(outdir,paste(oliimgid,"_tca_cal_samp.csv",sep=""))
  model = predict_oli_index(tca_tbl, outsampfile)
  acoef = model[[1]]
  asamp = model[[2]]
  ar = cor(asamp$refsamp, asamp$singlepred)
  
  #TCA
  #singlepred = atan(gsamp$singlepred/bsamp$singlepred) * (180/pi) * 100
  #refsamp = atan(gsamp$refsamp/bsamp$refsamp) * (180/pi) * 100
  #tbl = data.frame(oli_img = olibname,
  #                 ref_img = refbname,
  #                 index = "tca",
  #                 x = tcb_tbl$x,
  #                 y = tcb_tbl$y,
  #                 refsamp,singlepred)
  #final = tbl[complete.cases(tbl),]
  #outsampfile = file.path(outdir,paste(oliimgid,"_tca_cal_samp.csv",sep=""))
  #write.csv(final, outsampfile, row.names=F)
  
  #plot it
  #r = cor(final$refsamp, final$singlepred)
  #coef = rlm(final$refsamp ~ final$singlepred)

  #pngout = sub("samp.csv", "plot.png",outsampfile)
  #png(pngout,width=700, height=700)
  #title = paste("tca linear regression: slope =",paste(signif(coef$coefficients[2], digits=3),",",sep=""),
  #              "y Intercept =",paste(round(coef$coefficients[1], digits=3),",",sep=""),
  #              "r =",signif(r, digits=3))
  #plot(x=final$singlepred,y=final$refsamp,
  #     main=title,
  #     xlab=paste(olibname,"tca"),
  #     ylab=paste(refbname,"tca"))
  #abline(coef = coef$coefficients, col="red")  
  #dev.off()
  
  #info = data.frame(oli_file = olibname, ref_file = refbname,
  #                  index = "tca", yint = as.numeric(coef$coefficients[1]),
  #                  b1c = as.numeric(coef$coefficients[2]), r=r)
  
  #coefoutfile = file.path(outdir,paste(oliimgid,"_tca_cal_coef.csv",sep=""))
  #write.csv(info, coefoutfile, row.names=F)
  
  
  #write out the coef files
  tcbinfo = data.frame(oli_file=olibname, ref_file=refbname, index="tcb", bcoef, r=br)
  tcginfo = data.frame(oli_file=olibname, ref_file=refbname, index="tcg", gcoef, r=gr)
  tcwinfo = data.frame(oli_file=olibname, ref_file=refbname, index="tcw", wcoef, r=wr)
  tcainfo = data.frame(oli_file=olibname, ref_file=refabname, index="tca", acoef, r=ar)
  
  tcbcoefoutfile = file.path(outdir,paste(oliimgid,"_tcb_cal_coef.csv",sep=""))
  tcgcoefoutfile = file.path(outdir,paste(oliimgid,"_tcg_cal_coef.csv",sep=""))
  tcwcoefoutfile = file.path(outdir,paste(oliimgid,"_tcw_cal_coef.csv",sep=""))
  tcacoefoutfile = file.path(outdir,paste(oliimgid,"_tca_cal_coef.csv",sep=""))
  
  write.csv(tcbinfo, tcbcoefoutfile, row.names=F)
  write.csv(tcginfo, tcgcoefoutfile, row.names=F)
  write.csv(tcwinfo, tcwcoefoutfile, row.names=F)
  write.csv(tcainfo, tcacoefoutfile, row.names=F)
  
  
  #outfile = file.path(outdir,paste(oliimgid,"_tc_cal_planes.png",sep=""))
  #make_tc_planes_comparison(bsamp, gsamp, wsamp, outfile)
  
}
#' Calibrate MSS images to TM images
#'
#' Calibrate MSS images to TM images using linear regression
#' @param msswrs2dir character. MSS WRS-2 scene directory path
#' @param tmwrs2dir character. TM WRS-2 scene directory path
#' @import raster
#' @import ggplot2
#' @import gridExtra
#' @export


msscal_single = function(mss_file, tm_file){
  
  #mss_file = "K:/test/mss/wrs2/038029/images/1986/LM50380291986214_dos_sr_30m.tif"
  #tm_file = "K:/test/tm/wrs2/038029/images/1986/LT50380291986214_tc.tif"
  
  get_intersection = function(files){
    int = intersect(extent(raster(files[1])),extent(raster(files[2])))
    if(length(files) >= 3){for(i in 3:length(files))int = intersect(extent(raster(files[i])), int)}
    return(int)
  }
  
  #write_coef = function(mss_file, ref_file, index, coef,r){
  #  info = data.frame(mss_file = basename(mss_file),
  #                    ref_file = basename(ref_file),
  #                    index = index,
  #                    yint = as.numeric(coef[1]),
  #                    b1c = as.numeric(coef[2]),
  #                    b2c = as.numeric(coef[3]),
  #                    b3c = as.numeric(coef[4]),
  #                    b4c = as.numeric(coef[5]),
  #                    r=r)
  #  
  #  coefoutfile = file.path(outdir,paste(mssimgid,"_",index,"_cal_coef.csv",sep=""))
  #  write.csv(info, coefoutfile, row.names=F)
  #}
  
  #sample_it = function(img, bins, n){
  #  
  #  mi = min(img, na.rm=T)
  #  ma = max(img, na.rm=T)
  #  
  #  step = (ma - mi)/bins
  #  breaks = seq(mi,ma,step)
  #  
  #  min_samp = array(n, bins)
  #  for(i in 1:(length(breaks)-1)){
  #    these = which(img > breaks[i] & img <= breaks[i+1])
  #    if(i == 1){samp = sample(these, size=min(min_samp[i],length(these)))} else {
  #      samp = c(samp, sample(these, size=min(min_samp[i],length(these))))
  #    } 
  #  }
  #  return(samp)
  #}
  

  #define the filenames
  mss_sr_file = mss_file
  mss_mask_file = sub("dos_sr_30m.tif", "cloudmask_30m.tif", mss_sr_file)
  ref_tc_file = tm_file
  ref_tca_file = sub("tc", "tca", ref_tc_file)
  ref_mask_file = sub("tc", "cloudmask", ref_tc_file)
  
  #make new directory
  dname = dirname(mss_sr_file)
  mssimgid = substr(basename(mss_sr_file),1,16)
  outdir = file.path(substr(dname,1,nchar(dname)-12),"calibration", mssimgid)  #-5
  dir.create(outdir, showWarnings = F, recursive=T)
  
  #load files as raster
  mss_sr_img = brick(mss_sr_file)
  mss_mask_img = raster(mss_mask_file)
  ref_tc_img = brick(ref_tc_file)
  ref_tca_img  = raster(ref_tca_file)
  ref_mask_img = raster(ref_mask_file)
  
  #align the extents
  extent(mss_sr_img)  = alignExtent(mss_sr_img, ref_tc_img, snap="near")
  extent(mss_mask_img) = alignExtent(mss_mask_img, ref_tc_img, snap="near")
  extent(ref_tc_img)   = alignExtent(ref_tc_img, ref_tc_img, snap="near")
  extent(ref_tca_img)  = alignExtent(ref_tca_img, ref_tc_img, snap="near")
  extent(ref_mask_img) = alignExtent(ref_mask_img, ref_tc_img, snap="near")
  
  #crop the images to their intersection
  int = get_intersection(c(mss_sr_file,mss_mask_file,ref_tc_file,ref_tca_file,ref_mask_file))
  mss_sr_img = crop(mss_sr_img,int)
  mss_mask_img = crop(mss_mask_img,int)
  ref_tc_img = crop(ref_tc_img,int)
  ref_tca_img = crop(ref_tca_img,int)
  ref_mask_img = crop(ref_mask_img,int)
  
  #make a composite mask
  #mss_mask_img = as.matrix(mss_mask_img)
  #ref_mask_img = as.matrix(ref_mask_img)
  mss_mask_v = as.vector(mss_mask_img)
  ref_mask_v = as.vector(ref_mask_img)
  #mask = mss_mask_img*ref_mask_img
  mask = mss_mask_v*ref_mask_v
  mss_mask_v = ref_mask_v = 0 # save memory
  
  goods = which(mask == 1)
  if(length(goods) < 20000){return()}
  
  #stratified sample
  #refpix = as.matrix(ref_tca_img)[goods]
  #samp = sample_it(refpix, bins=20, n=1000)
  
  #random sample
  samp = sample(1:length(goods), 20000)
  samp = goods[samp]
  sampxy = xyFromCell(mss_mask_img, samp) #added on 1/22/2016
  
  #save memory
  mask = 0
  
  #extract the sample pixels from the bands
  #b1samp = as.matrix(subset(mss_sr_img, 1))[samp]
  #b2samp = as.matrix(subset(mss_sr_img, 2))[samp]
  #b3samp = as.matrix(subset(mss_sr_img, 3))[samp]
  #b4samp = as.matrix(subset(mss_sr_img, 4))[samp]
  
  
  msssamp = extract(mss_sr_img, sampxy)
  tcsamp = extract(ref_tc_img, sampxy)
  tcasamp = extract(ref_tca_img, sampxy)
  
  #make sure the values are good for running regression on (diversity)
  unib1samp = length(unique(msssamp[,1]))
  unib2samp = length(unique(msssamp[,2]))
  unib3samp = length(unique(msssamp[,3]))
  unib4samp = length(unique(msssamp[,4]))
  
  unitcbsamp = length(unique(tcsamp[,1]))
  unitcgsamp = length(unique(tcsamp[,2]))
  unitcwsamp = length(unique(tcsamp[,3]))
  unitcasamp = length(unique(tcasamp))
  
  
  #if(unib1samp < 15 | unib2samp < 15 | unib3samp < 15 | unib4samp < 15 ){return()}
  if(unib1samp < 15 | unib2samp < 15 | unib3samp < 15 | unib4samp < 15 |
     unitcbsamp < 15 | unitcgsamp < 15 | unitcwsamp < 15 | unitcasamp < 15){return()}
  
  print("Made it here!")
  
  #samplen = length(samp)
  
  mssbname = basename(mss_sr_file)
  refbname = basename(ref_tc_file)
  refabname = basename(ref_tca_file)
  
  tcb_tbl = data.frame(mssbname,refbname,"tcb",sampxy,tcsamp[,1],msssamp)
  tcg_tbl = data.frame(mssbname,refbname,"tcg",sampxy,tcsamp[,2],msssamp)
  tcw_tbl = data.frame(mssbname,refbname,"tcw",sampxy,tcsamp[,3],msssamp)
  tca_tbl = data.frame(mssbname,refabname,"tca",sampxy,tcasamp,msssamp)
  
  
  tcb_tbl = tcb_tbl[complete.cases(tcb_tbl),]
  tcg_tbl = tcg_tbl[complete.cases(tcg_tbl),]
  tcw_tbl = tcw_tbl[complete.cases(tcw_tbl),]
  tca_tbl = tca_tbl[complete.cases(tca_tbl),]
  
  cnames = c("mss_img","ref_img","index","x","y","refsamp","b1samp","b2samp","b3samp","b4samp") 
  colnames(tcb_tbl) = cnames
  colnames(tcg_tbl) = cnames
  colnames(tcw_tbl) = cnames
  colnames(tca_tbl) = cnames
  
  #predict the indices
  #TCB
  #refsamp = as.matrix(subset(ref_tc_img, 1))[samp]
  #unirefsamp = length(unique(refsamp))
  #if(unirefsamp < 15){return()}
  #sampoutfile = file.path(outdir,paste(mssimgid,"_tcb_cal_samp.csv",sep=""))
  #model = predict_mss_index(refsamp, b1samp, b2samp, b3samp, b4samp, mss_sr_file, ref_tc_file, "tcb", sampoutfile, samplen)
  #bcoef = model[[1]]
  #bsamp = model[[2]]
  #br = cor(bsamp$refsamp, bsamp$singlepred)
  
  outsampfile = file.path(outdir,paste(mssimgid,"_tcb_cal_samp.csv",sep=""))
  model = predict_mss_index(tcb_tbl, outsampfile)
  bcoef = model[[1]]
  bsamp = model[[2]]
  br = cor(bsamp$refsamp, bsamp$singlepred)
  
  
  #TCG
  #refsamp = as.matrix(subset(ref_tc_img, 2))[samp]
  #unirefsamp = length(unique(refsamp))
  #if(unirefsamp < 15){return()}
  #sampoutfile = file.path(outdir,paste(mssimgid,"_tcg_cal_samp.csv",sep=""))
  #model = predict_mss_index(refsamp, b1samp, b2samp, b3samp, b4samp, mss_sr_file, ref_tc_file, "tcg", sampoutfile, samplen)
  #gcoef = model[[1]]
  #gsamp = model[[2]]
  #gr = cor(gsamp$refsamp, gsamp$singlepred)
  
  outsampfile = file.path(outdir,paste(mssimgid,"_tcg_cal_samp.csv",sep=""))
  model = predict_mss_index(tcg_tbl, outsampfile)
  gcoef = model[[1]]
  gsamp = model[[2]]
  gr = cor(gsamp$refsamp, gsamp$singlepred)
  
  #TCW
  #refsamp = as.matrix(subset(ref_tc_img, 3))[samp]
  #unirefsamp = length(unique(refsamp))
  #if(unirefsamp < 15){return()}
  #sampoutfile = file.path(outdir,paste(mssimgid,"_tcw_cal_samp.csv",sep=""))
  #model = predict_mss_index(refsamp, b1samp, b2samp, b3samp, b4samp, mss_sr_file, ref_tc_file, "tcw", sampoutfile, samplen)
  #wcoef = model[[1]]
  #wsamp = model[[2]]
  #wr = cor(wsamp$refsamp, wsamp$singlepred)
  
  outsampfile = file.path(outdir,paste(mssimgid,"_tcw_cal_samp.csv",sep=""))
  model = predict_mss_index(tcw_tbl, outsampfile)
  wcoef = model[[1]]
  wsamp = model[[2]]
  wr = cor(wsamp$refsamp, wsamp$singlepred)
  
  
  #TCA
  outsampfile = file.path(outdir,paste(mssimgid,"_tca_cal_samp.csv",sep=""))
  model = predict_mss_index(tca_tbl, outsampfile)
  acoef = model[[1]]
  asamp = model[[2]]
  ar = cor(asamp$refsamp, asamp$singlepred)
  
  
  #singlepred = atan(gsamp$singlepred/bsamp$singlepred) * (180/pi) * 100
  #refsamp = atan(gsamp$refsamp/bsamp$refsamp) * (180/pi) * 100
  #tbl = data.frame(mss_img = rep(basename(mss_sr_file),length(singlepred)),
  #                 ref_img = rep(basename(ref_tc_file),length(singlepred)),
  #                 index = rep("tca",length(singlepred)),
  #                 refsamp,singlepred)
  #final = tbl[complete.cases(tbl),]
  #sampoutfile = file.path(outdir,paste(mssimgid,"_tca_cal_samp.csv",sep=""))
  #write.csv(final, sampoutfile, row.names=F)
  
  
  #r = cor(final$refsamp, final$singlepred)
  #coef = rlm(final$refsamp ~ final$singlepred)
  
  #pngout = sub("samp.csv", "plot.png",sampoutfile)
  #png(pngout,width=700, height=700)
  #title = paste("tca linear regression: slope =",paste(signif(coef$coefficients[2], digits=3),",",sep=""),
  #                                 "y Intercept =",paste(round(coef$coefficients[1], digits=3),",",sep=""),
  #                                 "r =",signif(r, digits=3))
  #plot(x=final$singlepred,y=final$refsamp,
  #     main=title,
  #     xlab=paste(basename(mss_sr_file),"tca"),
  #     ylab=paste(basename(ref_tc_file),"tca"))
  #abline(coef = coef$coefficients, col="red")  
  #dev.off()
  
  #info = data.frame(mss_file = basename(mss_sr_file), ref_file = basename(ref_tc_file),
  #                  index = "tca", yint = as.numeric(coef$coefficients[1]),
  #                  b1c = as.numeric(coef$coefficients[2]), r=r)
  
  #coefoutfile = file.path(outdir,paste(mssimgid,"_tca_cal_coef.csv",sep=""))
  #write.csv(info, coefoutfile, row.names=F)
  
  #write out the coef files
  #write_coef(mss_sr_file, ref_tc_file, "tcb", bcoef, br)
  #write_coef(mss_sr_file, ref_tc_file, "tcg", gcoef, gr)
  #write_coef(mss_sr_file, ref_tc_file, "tcw", wcoef, wr)

  
  tcbinfo = data.frame(mss_file=mssbname, ref_file=refbname, index="tcb", bcoef, r=br)
  tcginfo = data.frame(mss_file=mssbname, ref_file=refbname, index="tcg", gcoef, r=gr)
  tcwinfo = data.frame(mss_file=mssbname, ref_file=refbname, index="tcw", wcoef, r=wr)
  tcainfo = data.frame(mss_file=mssbname, ref_file=refabname, index="tca", acoef, r=ar)
  
  tcbcoefoutfile = file.path(outdir,paste(mssimgid,"_tcb_cal_coef.csv",sep=""))
  tcgcoefoutfile = file.path(outdir,paste(mssimgid,"_tcg_cal_coef.csv",sep=""))
  tcwcoefoutfile = file.path(outdir,paste(mssimgid,"_tcw_cal_coef.csv",sep=""))
  tcacoefoutfile = file.path(outdir,paste(mssimgid,"_tca_cal_coef.csv",sep=""))
  
  write.csv(tcbinfo, tcbcoefoutfile, row.names=F)
  write.csv(tcginfo, tcgcoefoutfile, row.names=F)
  write.csv(tcwinfo, tcwcoefoutfile, row.names=F)
  write.csv(tcainfo, tcacoefoutfile, row.names=F)
  
  
  #outfile = file.path(outdir,paste(mssimgid,"_tc_cal_planes.png",sep=""))
  #make_tc_planes_comparison(bsamp, gsamp, wsamp, outfile)
  
}
######################################################################
######################################################################
## ROUTINE ZUM EINLESEN VON ERA-DATEN (ZONAL-WIND) IM NCDF-FORMAT
## UND AUFFINDEN DES JETSTREAMS AUF NORDHEMISPHÄRE
## source('~/Master_Thesis/r-code-git/locate_jetstream_polynomial_2d.r')
######################################################################
######################################################################


######################################################################
## AUFRUF WICHTIGER BIBLIOTHEKEN UND PAKETE
######################################################################
##

library(ncdf4)
library(parallel)
library(chron)

# eigenes package für least squares fit mit chebyshev polynomen
# install.packages("pckg.cheb_0.2.tar.gz", repos = NULL, type = "source")
library(pckg.cheb)

setwd("~/Master_Thesis/r-code-git/")
path <- "data/"
file <- "era-79-16-nh-trop-inv.nc"  # Nordhemisphäre + Tropen
#file <- "era--t63_ua_monmean_300hpa_sh.nc"  # Südhemisphäre
#file <- "era--t63_ua_monmean_300hpa.nc"     # Globus


######################################################################
## KLEINE HILFSFUNKTIONEN
######################################################################
##

fun.fill <- function(x, n) {
  while (length(x) < n) {
    x <- c(x, NA)
  }
  return(x)
}


######################################################################
## EINLESEN DER DATEN
## ERA40 / ERA-INTERIM
## T63 - GRID
## NCDF4
######################################################################
##

nc <- nc_open(paste(path, file, sep = ""))
print(nc)
uwind.monmean <- ncvar_get(nc, "var131")
vwind.monmean <- ncvar_get(nc, "var132")
lon <- ncvar_get(nc, "lon")
lat <- ncvar_get(nc, "lat")
lev <- ncvar_get(nc, "lev")
date.help <- ncvar_get(nc, "time")
nc_close(nc)
rm(nc)


######################################################################
## VARIABLEN UND PARAMETER
######################################################################
##

n.cpu <- 4 #5 # Anzahl der CPUs für parApply
n.order.lat <- 59 # 23 # Ordnung des Least-Square-Verfahrens für Fit über Breitengrad
n.order.lon <- 8 # Ordnung des Least-Square-Verfahrens für Fit über Längengrad
n.order.lat.seq <- 3 # Ordnung des Least-Square-Verfahrens für sequentiellen Fit über Breitengrad
len.seq <- 8 # Länge der ersten Sequenz der 

## Räumliche Auflösung
n.lat <- length(lat)
n.lon <- length(lon)

## Zeitliche Auflösung
dts = chron(dates. = date.help/24, origin. = c(month = 9,day = 1,year = 1957), format = "day mon year")
dts.month <- months(dts, abbreviate = TRUE)
dts.year <- years(dts)

## Zeitlich gemittelter Zonalwind
uwind.mean <- apply(uwind.monmean,c(1,2),mean)
uwind.std <- apply(uwind.monmean,c(1,2),sd)

## Meridional und zeitlich gemittelter Zonalwind
uwind.mon.mer.mean <- apply(uwind.monmean, 2, mean)
uwind.mon.mer.sd <- apply(uwind.mean, 2, sd)

## Meridional gemittelter Zonalwind
# uwind.monmean.mermean <- apply(uwind.monmean, c(2,3), mean)
# uwind.monmean.mersd <- apply(uwind.monmean, c(2,3), sd)


######################################################################
## LEAST SQUARES FIT 
## CHEBYSHEV POLYNOME 23-TER ORDNUNG
## AN ZONAL WIND IN MERIDIONALER RICHTUNG
######################################################################
##

# list.model.lat <- apply(uwind.monmean[,,], c(1,3), pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
list.model.lat <- parApply(cl, uwind.monmean[,,], c(1,3), pckg.cheb:::cheb.fit, x.axis = lat, n = n.order.lat)
stopCluster(cl)
dim.list <- dim(list.model.lat)

## Chebyshev-Koeffizienten
cheb.coeff <- sapply(list.model.lat, "[[", 1)
cheb.coeff <- apply(array(data = cheb.coeff, dim = c((n.order.lat + 1), dim.list[1], dim.list[2])) , c(1,3), t)

## Gefiltertes Modell für Zonal-Wind
model.uwind <- sapply(list.model.lat, "[[", 2)
model.uwind <- apply(array(data = model.uwind, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)

## Erste Ableitung des gefilterten Modells für Zonalwind
model.uwind.deriv.1st <- sapply(list.model.lat, "[[", 3)
model.uwind.deriv.1st <- apply(array(data = model.uwind.deriv.1st, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)

## Extrema des Modells (Positionen und Werte)
model.extr.lat <- sapply(list.model.lat, "[[", 4)
model.extr.uwind <- sapply(list.model.lat, "[[", 5)
model.extr.lat <- sapply(model.extr.lat, fun.fill, n = 24)
model.extr.lat <- apply(array(model.extr.lat, c(24, dim.list[1], dim.list[2])), c(1,3), t)
model.extr.uwind <- sapply(model.extr.uwind, fun.fill, n = 24)
model.extr.uwind <- apply(array(model.extr.uwind, c(24, dim.list[1], dim.list[2])), c(1,3), t)

## Maxima des Modells (Positionen und Werte)
model.max.uwind <- apply(model.extr.uwind, c(1,3), max, na.rm = TRUE)
model.max.lat <- array(rep(0, 192*664), c(dim.list))
for (i in 1:dim.list[2]) {
  for (j in 1:dim.list[1]) {
    model.max.lat[j,i] <- model.extr.lat[j, which(model.extr.uwind[j,,i] == model.max.uwind[j,i]), i]
  }
}
rm(list.model.lat, dim.list)
rm(dim.list)


######################################################################
## LEAST SQUARES FIT 
## CHEBYSHEV POLYNOME 8-TER ORDNUNG
## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
######################################################################
##

#list.model.lon <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
cl <- makeCluster(getOption("cl.cores", n.cpu))
list.model.lon <- parApply(cl, model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
stopCluster(cl)

## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
model.max.lon <- sapply(list.model.lon, "[[", 2)
rm(list.model.lon)




######################################################################
## FEHLERGRÖẞEN
## MSE
## RMSE
######################################################################
##

residuals.cheb <- uwind.monmean - model.uwind
residuals.cheb.seq <- uwind.monmean - model.uwind.seq
mse <- sum(residuals.cheb ** 2) / length(residuals.cheb)
mse.seq <- sum(residuals.cheb.seq **2) / length(residuals.cheb.seq)
rmse <- sqrt(sum(residuals.cheb ** 2) / length(residuals.cheb))
rmse.seq <- sqrt(sum(residuals.cheb.seq **2) / length(residuals.cheb.seq))

## rmse.seq = 0.4079846  ## mse.seq = 0.1664514
## rmse     = 0.2911683  ## mse     = 0.08477901


######################################################################
######################################################################
save.image()


######################################################################
## Berechnung von Mean und Sd
## über fünf Jahre & saisonal
######################################################################
dts.year.mn <- seq(1960, 2010, 5)

ind.mam <- which(dts.month == "Mar" | dts.month == "Apr" | dts.month == "May")
ind.jja <- which(dts.month == "Jun" | dts.month == "Jul" | dts.month == "Aug")
ind.son <- which(dts.month == "Sep" | dts.month == "Oct" | dts.month == "Nov")
ind.djf <- which(dts.month == "Dec" | dts.month == "Jan" | dts.month == "Feb")

## Mittelwerte global
uwind.seas.mam.mean <- array( NA , dim = c(n.lon, n.lat, 11))
uwind.seas.mam.sd <- array( NA , dim = c(n.lon, n.lat, 11))
uwind.seas.jja.mean <- array( NA , dim = c(n.lon, n.lat, 11))
uwind.seas.jja.sd <- array( NA , dim = c(n.lon, n.lat, 11))
uwind.seas.son.mean <- array( NA , dim = c(n.lon, n.lat, 11))
uwind.seas.son.sd <- array( NA , dim = c(n.lon, n.lat, 11))
uwind.seas.djf.mean <- array( NA , dim = c(n.lon, n.lat, 11))
uwind.seas.djf.sd <- array( NA , dim = c(n.lon, n.lat, 11))

## Mittelwerte meridional *???*
uwind.mer.seas.mam.mean <- array( NA , dim = c(n.lat, 11))
uwind.mer.seas.mam.sd <- array( NA , dim = c(n.lat, 11))
uwind.mer.seas.jja.mean <- array( NA , dim = c(n.lat, 11))
uwind.mer.seas.jja.sd <- array( NA , dim = c(n.lat, 11))
uwind.mer.seas.son.mean <- array( NA , dim = c(n.lat, 11))
uwind.mer.seas.son.sd <- array( NA , dim = c(n.lat, 11))
uwind.mer.seas.djf.mean <- array( NA , dim = c(n.lat, 11))
uwind.mer.seas.djf.sd <- array( NA , dim = c(n.lat, 11))

for (i in seq(1, 11)) {
  print(i)
  yr.i <- dts.year.mn[i]
  ind.yr <- which(dts.year ==  yr.i | dts.year == (yr.i + 1) | dts.year == (yr.i + 2) | dts.year == (yr.i + 3) | dts.year == (yr.i + 4) )
  ## Mar Apr May
  ind.mam.yr <- intersect(ind.yr, ind.mam)
  uwind.seas.mam.mean[,,i] <- apply(uwind.monmean[,, ind.mam.yr], c(1,2), mean)
  uwind.seas.mam.sd[,,i] <- apply(uwind.monmean[,, ind.mam.yr], c(1,2), sd)
  uwind.mer.seas.mam.mean[,i] <- apply(uwind.monmean[,, ind.mam.yr], 2, mean)
  uwind.mer.seas.mam.sd[,i] <- apply(uwind.monmean[,, ind.mam.yr], 2, sd)
  ## Jun Jul Aug
  ind.jja.yr <- intersect(ind.yr, ind.jja)
  uwind.seas.jja.mean[,,i] <- apply(uwind.monmean[,, ind.jja.yr], c(1,2), mean)
  uwind.seas.jja.sd[,,i] <- apply(uwind.monmean[,, ind.jja.yr], c(1,2), sd)
  uwind.mer.seas.jja.mean[,i] <- apply(uwind.monmean[,, ind.jja.yr], 2, mean)
  uwind.mer.seas.jja.sd[,i] <- apply(uwind.monmean[,, ind.jja.yr], 2, sd)
  ## Sep Oct Nov
  ind.son.yr <- intersect(ind.yr, ind.son)
  uwind.seas.son.mean[,,i] <- apply(uwind.monmean[,, ind.son.yr], c(1,2), mean)
  uwind.seas.son.sd[,,i] <- apply(uwind.monmean[,, ind.son.yr], c(1,2), sd)
  uwind.mer.seas.son.mean[,i] <- apply(uwind.monmean[,, ind.son.yr], 2, mean)
  uwind.mer.seas.son.sd[,i] <- apply(uwind.monmean[,, ind.son.yr], 2, sd)
  ## Dec Jan Feb
  ind.djf.yr <- intersect(ind.yr, ind.djf)
  uwind.seas.djf.mean[,,i] <- apply(uwind.monmean[,, ind.djf.yr], c(1,2), mean)
  uwind.seas.djf.sd[,,i] <- apply(uwind.monmean[,, ind.djf.yr], c(1,2), sd)
  uwind.mer.seas.djf.mean[,i] <- apply(uwind.monmean[,, ind.djf.yr], 2, mean)
  uwind.mer.seas.djf.sd[,i] <- apply(uwind.monmean[,, ind.djf.yr], 2, sd)
  ## Löschen von Übergangsvariablen
  rm(yr.i, ind.yr, ind.mam.yr, ind.jja.yr, ind.son.yr, ind.djf.yr, i)
}

max(uwind.seas.mam.mean, uwind.seas.jja.mean, uwind.seas.son.mean, uwind.seas.djf.mean)
min(uwind.seas.mam.mean, uwind.seas.jja.mean, uwind.seas.son.mean, uwind.seas.djf.mean)
range(uwind.seas.mam.mean, uwind.seas.jja.mean, uwind.seas.son.mean, uwind.seas.djf.mean)

max(uwind.seas.mam.mean)
min(uwind.seas.mam.mean)
range(uwind.seas.mam.mean)

max(uwind.seas.jja.mean)
min(uwind.seas.jja.mean)
range(uwind.seas.jja.mean)

max(uwind.seas.son.mean)
min(uwind.seas.son.mean)
range(uwind.seas.son.mean)

max(uwind.seas.djf.mean)
min(uwind.seas.djf.mean)
range(uwind.seas.djf.mean)


####################################################################################################
########## ableitung des drehimpulses ##############################################################
########## aus zonal wind ##########################################################################
####################################################################################################
### ref: m = 
### formel noch inkorrekt
### keine schleife benutzen
##
# m <- matrix(NA,n.lon,n.lat)
# for (i in 1:n.lon){
#   for (j in 1:n.lat){
#     m[i,j] <- uwind.era.t63.monmean[i,j,1]*cos(lat.era.t63[j]) + 1/86400*uwind.era.t63.monmean[i,j,1]**2*cos(lat.era.t63[j])**2
#   }
# }
# #m <- uwind.era.t63.monmean*cos(lat.era.t63)
# 




# ######################################################################
# ## LEAST SQUARES FIT ÜBER **SEQUENZEN** (l=8)
# ## CHEBYSHEV POLYNOME 3-TER ORDNUNG
# ## AN ZONAL-WIND IN MERIDIONALER RICHTUNG
# ######################################################################
# ##
# 
# # list.model.lat.seq <- apply(uwind.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# cl <- makeCluster(getOption("cl.cores", n.cpu)) ## Variante für paralleles Rechnen
# list.model.lat.seq <- parApply(cl, uwind.monmean[,,], c(1,3), pckg.cheb:::cheb.fit.seq, x.axis = lat, n = n.order.lat.seq, l = len.seq)
# stopCluster(cl)
# dim.list <- dim(list.model.lat.seq)
# 
# ## Gefiltertes Modell für Zonal-Wind
# model.uwind.seq <- sapply(list.model.lat.seq, "[[", 1)
# model.uwind.seq <- apply(array(data = model.uwind.seq, dim = c(n.lat, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Erste Ableitung des gefilterten Modells für Zonalwind
# model.uwind.deriv.1st.seq <- sapply(list.model.lat.seq, "[[", 2)
# model.uwind.deriv.1st.seq <- apply(array(data = model.uwind.deriv.1st.seq, dim = c(n.lon, dim.list[1], dim.list[2])),  c(1,3), t)
# 
# ## Extrema des Modells (Positionen und Werte)
# model.extr.lat.seq <- sapply(list.model.lat.seq, "[[", 3)
# model.extr.lat.seq <- sapply(model.extr.lat.seq, fun.fill, n = 24)
# model.extr.lat.seq <- apply(array(model.extr.lat.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# model.extr.uwind.seq <- sapply(list.model.lat.seq, "[[", 4)
# model.extr.uwind.seq <- sapply(model.extr.uwind.seq, fun.fill, n = 24)
# model.extr.uwind.seq <- apply(array(model.extr.uwind.seq, c(24, dim.list[1], dim.list[2])), c(1,3), t)
# 
# ## Maxima des Modells (Positionen und Werte)
# model.max.uwind.seq <- apply(model.extr.uwind.seq, c(1,3), max, na.rm = TRUE)
# model.max.lat.seq <- array(rep(0, dim.list[1]*dim.list[2]), c(dim.list))
# for (i in 1:dim.list[2]) {
#   for (j in 1:dim.list[1]) {
#     model.max.lat.seq[j,i] <- model.extr.lat.seq[j, which(model.extr.uwind.seq[j,,i] == model.max.uwind.seq[j,i]), i]
#   }
# }
# rm(list.model.lat.seq, dim.list)
# 
# 
# ######################################################################
# ## LEAST SQUARES FIT 
# ## CHEBYSHEV POLYNOME 8-TER ORDNUNG
# ## AN MERIDIONALE MAXIMA DES ZONALWINDS IN ZONALER RICHTUNG
# ## ANGEWANDT AUF SEQUENZIERTES MODELL
# ######################################################################
# ##
# 
# #list.model.lon.seq <- apply(model.max.lat, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = 8)
# cl <- makeCluster(getOption("cl.cores", n.cpu))
# list.model.lon.seq <- parApply(cl, model.max.lat.seq, 2, pckg.cheb:::cheb.fit, x.axis = lon, n = n.order.lon)
# stopCluster(cl)
# 
# ## Gefiltertes Modell für Maxima des Zonal-Wind in Zonalrichtung
# model.max.lon.seq <- sapply(list.model.lon.seq, "[[", 2)
# rm(list.model.lon.seq)

## Preliminary analysis of water inflow data

# Import the water inflow sample data
samples <- read.csv("./water_inflow_data.csv",  stringsAsFactors=FALSE)

# Rename all the measurements for easier reading
rn <- function(old.name, new.name){
  names(samples)[names(samples) == old.name] <<- new.name
}

rn("BOD.5.Day.ATU..mg.l.", "BOD")
rn("Nitrogen...Total.as.N..mg.l.", "Nitrogen")
rn("Phosphorus...Total.as.P..mg.l.", "Phosphorus")
rn("Alkalinity.to.pH.4.5.as.CaCO3..mg.l.", "Alkalinity")
rn("Ammoniacal.Nitrogen.as.N..mg.l.", "Nitrogen.Ammoniacal")
rn("Chloride..mg.l", "Chloride")
rn("Nitrite.as.N..mg.l.", "Nitrite")
rn("Nitrogen...Total.Oxidised.as.N..mg.l.", "Nitrogen.Oxidised")
rn("Orthophosphate..reactive.as.P..mg.l.", "Orthophosphate")
rn("Silicate..reactive.as.SiO2..mg.l.", "Silicate")
rn("Phosphate...Total.as.P..mg.l.", "Phosphate")
rn("Conductivity.at.20C..uS.cm.", "Conductivity")
rn("Turbidity..NTU.", "Turbidity")
rn("Solids..Suspended.at.105.C..mg.l.", "Solids")
rn("Calcium..mg.l.", "Calcium")
rn("Magnesium..mg.l.", "Magnesium")
rn("Potassium..mg.l.", "Potassium")
rn("Sodium..mg.l.", "Sodium")

# Remove the spaces from the grid references
samples$Grid.reference <- gsub(" ", "", samples$Grid.reference, fixed = TRUE)

# How many site names are there?
length(unique(samples$Comment))

# How many grid references are there?
length(unique(samples$Grid.reference))

# How many pairs of comments and grid references?
sites <- data.frame(OSGrid = samples$Grid.reference, Name = samples$Comment)
sites <- unique(sites)
nrow(sites)

# Give each of the sites a unique id (might come in handy)
sites$Id <- seq.int(nrow(sites))

# Export the sites list so WGS84 can be added to it
write.table(sites, "sites.csv", row.names = FALSE, col.names = TRUE, sep = ",")

## Go to http://gridreferencefinder.com/batchConvert/batchConvert.php to do the geocoding

# Import the geocoded sites
sites <- read.csv("./sites_with_locations.csv", header = TRUE, stringsAsFactors = FALSE)

# Cluster using k-means
km <- kmeans(cbind(sites$X, sites$Y), centers = 3)
# Plot without a background to look at the clusters
plot(sites$X, sites$Y, col = km$cluster, pch = 20)
plot(sites$Lng, sites$Lat, col = km$cluster, pch = 20)

# Get a map of the area and plot sites
library(ggmap)
map_centre <- c(lon = -2.85, lat = 52.80) # chosen by inspection
map <- qmap(map_centre) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)

# Zoom in in the Marton cluster of 10
map_centre <- c(lon = -3.045, lat = 52.623) # chosen by inspection
map <- qmap(map_centre, zoom = 15) 
map + geom_point(aes(x=Lng, y=Lat), data=sites, col = km$cluster)


# Remove non numeric from 
scratch <- samples[,c("Phosphorus...Total.as.P..mg.l.")]
scratch <- gsub("[^\\d]", "", scratch, fixed = TRUE)
scratch <- as.numeric(scratch)
hist(scratch)

# Remove non numeric from 
shit <- samples[,c("BOD.5.Day.ATU..mg.l.")]
shit <- gsub("[^\\d]", "", shit, fixed = TRUE)
shit <- as.numeric(shit)
hist(shit, breaks = 50)

colnames(samples)
           