text
stringlengths 54
60.6k
|
|---|
<commit_before>df9abb7a-2e4e-11e5-9284-b827eb9e62be<commit_msg>df9fbce2-2e4e-11e5-9284-b827eb9e62be<commit_after>df9fbce2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>39c17d32-2e4f-11e5-9284-b827eb9e62be<commit_msg>39c6776a-2e4f-11e5-9284-b827eb9e62be<commit_after>39c6776a-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>0324e6ca-2e4e-11e5-9284-b827eb9e62be<commit_msg>0329e6f2-2e4e-11e5-9284-b827eb9e62be<commit_after>0329e6f2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>950291f0-2e4e-11e5-9284-b827eb9e62be<commit_msg>9508be4a-2e4e-11e5-9284-b827eb9e62be<commit_after>9508be4a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>3d4093e0-2e4e-11e5-9284-b827eb9e62be<commit_msg>3d459b1a-2e4e-11e5-9284-b827eb9e62be<commit_after>3d459b1a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>344b558a-2e4f-11e5-9284-b827eb9e62be<commit_msg>345055da-2e4f-11e5-9284-b827eb9e62be<commit_after>345055da-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>9728b086-2e4e-11e5-9284-b827eb9e62be<commit_msg>972dd17e-2e4e-11e5-9284-b827eb9e62be<commit_after>972dd17e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>1bfb7034-2e4d-11e5-9284-b827eb9e62be<commit_msg>1c009ac8-2e4d-11e5-9284-b827eb9e62be<commit_after>1c009ac8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>4b44cbf0-2e4e-11e5-9284-b827eb9e62be<commit_msg>4b49f558-2e4e-11e5-9284-b827eb9e62be<commit_after>4b49f558-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>98c7d3b8-2e4e-11e5-9284-b827eb9e62be<commit_msg>98ce57d8-2e4e-11e5-9284-b827eb9e62be<commit_after>98ce57d8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>fd42fc66-2e4c-11e5-9284-b827eb9e62be<commit_msg>fd47f2d4-2e4c-11e5-9284-b827eb9e62be<commit_after>fd47f2d4-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>76139db2-2e4d-11e5-9284-b827eb9e62be<commit_msg>76188f34-2e4d-11e5-9284-b827eb9e62be<commit_after>76188f34-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>88943c58-2e4d-11e5-9284-b827eb9e62be<commit_msg>88992c2c-2e4d-11e5-9284-b827eb9e62be<commit_after>88992c2c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>aee983e0-2e4d-11e5-9284-b827eb9e62be<commit_msg>aeee7382-2e4d-11e5-9284-b827eb9e62be<commit_after>aeee7382-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>5884f07a-2e4d-11e5-9284-b827eb9e62be<commit_msg>5889f5ac-2e4d-11e5-9284-b827eb9e62be<commit_after>5889f5ac-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b28214d6-2e4d-11e5-9284-b827eb9e62be<commit_msg>b2870ba8-2e4d-11e5-9284-b827eb9e62be<commit_after>b2870ba8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>1860a5be-2e4f-11e5-9284-b827eb9e62be<commit_msg>1865bcf2-2e4f-11e5-9284-b827eb9e62be<commit_after>1865bcf2-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>8c14567e-2e4d-11e5-9284-b827eb9e62be<commit_msg>8c195426-2e4d-11e5-9284-b827eb9e62be<commit_after>8c195426-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>e2cf4f22-2e4e-11e5-9284-b827eb9e62be<commit_msg>e2d4a6ac-2e4e-11e5-9284-b827eb9e62be<commit_after>e2d4a6ac-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>09dae76c-2e4e-11e5-9284-b827eb9e62be<commit_msg>09dff464-2e4e-11e5-9284-b827eb9e62be<commit_after>09dff464-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c1813002-2e4d-11e5-9284-b827eb9e62be<commit_msg>c18648d0-2e4d-11e5-9284-b827eb9e62be<commit_after>c18648d0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>142b316c-2e4f-11e5-9284-b827eb9e62be<commit_msg>14304ab2-2e4f-11e5-9284-b827eb9e62be<commit_after>14304ab2-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>bf613ad8-2e4d-11e5-9284-b827eb9e62be<commit_msg>bf66320e-2e4d-11e5-9284-b827eb9e62be<commit_after>bf66320e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>20a92130-2e4d-11e5-9284-b827eb9e62be<commit_msg>20ae1820-2e4d-11e5-9284-b827eb9e62be<commit_after>20ae1820-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>4baab780-2e4e-11e5-9284-b827eb9e62be<commit_msg>4bafcc3e-2e4e-11e5-9284-b827eb9e62be<commit_after>4bafcc3e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>0a3059ee-2e4f-11e5-9284-b827eb9e62be<commit_msg>0a356970-2e4f-11e5-9284-b827eb9e62be<commit_after>0a356970-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>4cf7789e-2e4e-11e5-9284-b827eb9e62be<commit_msg>4cfc8884-2e4e-11e5-9284-b827eb9e62be<commit_after>4cfc8884-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f87a73b2-2e4c-11e5-9284-b827eb9e62be<commit_msg>f87f7c04-2e4c-11e5-9284-b827eb9e62be<commit_after>f87f7c04-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>687d79a6-2e4e-11e5-9284-b827eb9e62be<commit_msg>68826b14-2e4e-11e5-9284-b827eb9e62be<commit_after>68826b14-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c222876c-2e4e-11e5-9284-b827eb9e62be<commit_msg>c2277eb6-2e4e-11e5-9284-b827eb9e62be<commit_after>c2277eb6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d67b1058-2e4e-11e5-9284-b827eb9e62be<commit_msg>d680101c-2e4e-11e5-9284-b827eb9e62be<commit_after>d680101c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b1048a3a-2e4d-11e5-9284-b827eb9e62be<commit_msg>b1098170-2e4d-11e5-9284-b827eb9e62be<commit_after>b1098170-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>40692466-2e4d-11e5-9284-b827eb9e62be<commit_msg>406e26be-2e4d-11e5-9284-b827eb9e62be<commit_after>406e26be-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>23f3b7e6-2e4e-11e5-9284-b827eb9e62be<commit_msg>23f8be4e-2e4e-11e5-9284-b827eb9e62be<commit_after>23f8be4e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>3278ffc0-2e4d-11e5-9284-b827eb9e62be<commit_msg>327e0f7e-2e4d-11e5-9284-b827eb9e62be<commit_after>327e0f7e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c51931f0-2e4e-11e5-9284-b827eb9e62be<commit_msg>c51e2cb4-2e4e-11e5-9284-b827eb9e62be<commit_after>c51e2cb4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>34d486fc-2e4f-11e5-9284-b827eb9e62be<commit_msg>34d979fa-2e4f-11e5-9284-b827eb9e62be<commit_after>34d979fa-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>5f1f08d4-2e4e-11e5-9284-b827eb9e62be<commit_msg>5f241838-2e4e-11e5-9284-b827eb9e62be<commit_after>5f241838-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>0e495e36-2e4f-11e5-9284-b827eb9e62be<commit_msg>0e4e75ce-2e4f-11e5-9284-b827eb9e62be<commit_after>0e4e75ce-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>62faef50-2e4d-11e5-9284-b827eb9e62be<commit_msg>62fff9e6-2e4d-11e5-9284-b827eb9e62be<commit_after>62fff9e6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f6fac906-2e4c-11e5-9284-b827eb9e62be<commit_msg>f6ffda0e-2e4c-11e5-9284-b827eb9e62be<commit_after>f6ffda0e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>100aea5c-2e4d-11e5-9284-b827eb9e62be<commit_msg>100ffefc-2e4d-11e5-9284-b827eb9e62be<commit_after>100ffefc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c3f566f0-2e4d-11e5-9284-b827eb9e62be<commit_msg>c3fa8928-2e4d-11e5-9284-b827eb9e62be<commit_after>c3fa8928-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>698d7364-2e4e-11e5-9284-b827eb9e62be<commit_msg>6992eca4-2e4e-11e5-9284-b827eb9e62be<commit_after>6992eca4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>0afdb2c8-2e4e-11e5-9284-b827eb9e62be<commit_msg>0b02afc6-2e4e-11e5-9284-b827eb9e62be<commit_after>0b02afc6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>116a8dd8-2e4f-11e5-9284-b827eb9e62be<commit_msg>116f80e0-2e4f-11e5-9284-b827eb9e62be<commit_after>116f80e0-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>20fff83c-2e4f-11e5-9284-b827eb9e62be<commit_msg>2104eee6-2e4f-11e5-9284-b827eb9e62be<commit_after>2104eee6-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c7955f32-2e4c-11e5-9284-b827eb9e62be<commit_msg>c79a4e8e-2e4c-11e5-9284-b827eb9e62be<commit_after>c79a4e8e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>36826524-2e4e-11e5-9284-b827eb9e62be<commit_msg>36875660-2e4e-11e5-9284-b827eb9e62be<commit_after>36875660-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>50b1f3ba-2e4e-11e5-9284-b827eb9e62be<commit_msg>50b720ec-2e4e-11e5-9284-b827eb9e62be<commit_after>50b720ec-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>45e1b25e-2e4e-11e5-9284-b827eb9e62be<commit_msg>45e71a82-2e4e-11e5-9284-b827eb9e62be<commit_after>45e71a82-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>01b5638c-2e4e-11e5-9284-b827eb9e62be<commit_msg>01ba5e6e-2e4e-11e5-9284-b827eb9e62be<commit_after>01ba5e6e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>4a705faa-2e4e-11e5-9284-b827eb9e62be<commit_msg>4a7551c2-2e4e-11e5-9284-b827eb9e62be<commit_after>4a7551c2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>241c73d4-2e4e-11e5-9284-b827eb9e62be<commit_msg>24217c4e-2e4e-11e5-9284-b827eb9e62be<commit_after>24217c4e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>101530ca-2e4d-11e5-9284-b827eb9e62be<commit_msg>101a3ce6-2e4d-11e5-9284-b827eb9e62be<commit_after>101a3ce6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>0dd16e40-2e4e-11e5-9284-b827eb9e62be<commit_msg>0dd66332-2e4e-11e5-9284-b827eb9e62be<commit_after>0dd66332-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>b942b808-2e4c-11e5-9284-b827eb9e62be<commit_msg>b947bf2e-2e4c-11e5-9284-b827eb9e62be<commit_after>b947bf2e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>dbf1f3c6-2e4e-11e5-9284-b827eb9e62be<commit_msg>dbf6e52a-2e4e-11e5-9284-b827eb9e62be<commit_after>dbf6e52a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>5fe4952c-2e4e-11e5-9284-b827eb9e62be<commit_msg>5fe9ab3e-2e4e-11e5-9284-b827eb9e62be<commit_after>5fe9ab3e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>1366d904-2e4d-11e5-9284-b827eb9e62be<commit_msg>136be9ee-2e4d-11e5-9284-b827eb9e62be<commit_after>136be9ee-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>db6d4fb0-2e4c-11e5-9284-b827eb9e62be<commit_msg>db724dee-2e4c-11e5-9284-b827eb9e62be<commit_after>db724dee-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d29a77bc-2e4e-11e5-9284-b827eb9e62be<commit_msg>d29f751e-2e4e-11e5-9284-b827eb9e62be<commit_after>d29f751e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>0409578c-2e4f-11e5-9284-b827eb9e62be<commit_msg>040e53e0-2e4f-11e5-9284-b827eb9e62be<commit_after>040e53e0-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>70e3c960-2e4e-11e5-9284-b827eb9e62be<commit_msg>70e8c1fe-2e4e-11e5-9284-b827eb9e62be<commit_after>70e8c1fe-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c146dae6-2e4e-11e5-9284-b827eb9e62be<commit_msg>c14bda46-2e4e-11e5-9284-b827eb9e62be<commit_after>c14bda46-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>10a0925e-2e4e-11e5-9284-b827eb9e62be<commit_msg>10a58a48-2e4e-11e5-9284-b827eb9e62be<commit_after>10a58a48-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>61ea9d44-2e4e-11e5-9284-b827eb9e62be<commit_msg>61efb5b8-2e4e-11e5-9284-b827eb9e62be<commit_after>61efb5b8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>cf394918-2e4e-11e5-9284-b827eb9e62be<commit_msg>cf3e5bb0-2e4e-11e5-9284-b827eb9e62be<commit_after>cf3e5bb0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f1ee55ac-2e4e-11e5-9284-b827eb9e62be<commit_msg>f1f35142-2e4e-11e5-9284-b827eb9e62be<commit_after>f1f35142-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>d68f01bc-2e4e-11e5-9284-b827eb9e62be<commit_msg>d69400a4-2e4e-11e5-9284-b827eb9e62be<commit_after>d69400a4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c2632dbc-2e4e-11e5-9284-b827eb9e62be<commit_msg>c268261e-2e4e-11e5-9284-b827eb9e62be<commit_after>c268261e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>8cbf22b6-2e4d-11e5-9284-b827eb9e62be<commit_msg>8cc452e0-2e4d-11e5-9284-b827eb9e62be<commit_after>8cc452e0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>0e2b10bc-2e4e-11e5-9284-b827eb9e62be<commit_msg>0e300716-2e4e-11e5-9284-b827eb9e62be<commit_after>0e300716-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>611b5868-2e4e-11e5-9284-b827eb9e62be<commit_msg>61206592-2e4e-11e5-9284-b827eb9e62be<commit_after>61206592-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>7af7149e-2e4d-11e5-9284-b827eb9e62be<commit_msg>7b005b6c-2e4d-11e5-9284-b827eb9e62be<commit_after>7b005b6c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>f7184a1a-2e4e-11e5-9284-b827eb9e62be<commit_msg>f71d44a2-2e4e-11e5-9284-b827eb9e62be<commit_after>f71d44a2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>3a4345fc-2e4e-11e5-9284-b827eb9e62be<commit_msg>3a486550-2e4e-11e5-9284-b827eb9e62be<commit_after>3a486550-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>1b3fc8fa-2e4f-11e5-9284-b827eb9e62be<commit_msg>1b44d3b8-2e4f-11e5-9284-b827eb9e62be<commit_after>1b44d3b8-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>0e9e9d16-2e4e-11e5-9284-b827eb9e62be<commit_msg>0ea3a202-2e4e-11e5-9284-b827eb9e62be<commit_after>0ea3a202-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>e7da0324-2e4c-11e5-9284-b827eb9e62be<commit_msg>e7defd98-2e4c-11e5-9284-b827eb9e62be<commit_after>e7defd98-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>c49831c4-2e4c-11e5-9284-b827eb9e62be<commit_msg>c49d2ac6-2e4c-11e5-9284-b827eb9e62be<commit_after>c49d2ac6-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>eb35d58e-2e4c-11e5-9284-b827eb9e62be<commit_msg>eb3ac8d2-2e4c-11e5-9284-b827eb9e62be<commit_after>eb3ac8d2-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>8e2586da-2e4e-11e5-9284-b827eb9e62be<commit_msg>8e2a9efe-2e4e-11e5-9284-b827eb9e62be<commit_after>8e2a9efe-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>7827a922-2e4d-11e5-9284-b827eb9e62be<commit_msg>782c9982-2e4d-11e5-9284-b827eb9e62be<commit_after>782c9982-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>258556f4-2e4f-11e5-9284-b827eb9e62be<commit_msg>2594e6a0-2e4f-11e5-9284-b827eb9e62be<commit_after>2594e6a0-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>cfd0e6b2-2e4c-11e5-9284-b827eb9e62be<commit_msg>cfd5de7e-2e4c-11e5-9284-b827eb9e62be<commit_after>cfd5de7e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>eec86dc8-2e4d-11e5-9284-b827eb9e62be<commit_msg>eecd6bfc-2e4d-11e5-9284-b827eb9e62be<commit_after>eecd6bfc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>42fcc074-2e4e-11e5-9284-b827eb9e62be<commit_msg>4301c8e4-2e4e-11e5-9284-b827eb9e62be<commit_after>4301c8e4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>06d191fc-2e4d-11e5-9284-b827eb9e62be<commit_msg>06d6f2b4-2e4d-11e5-9284-b827eb9e62be<commit_after>06d6f2b4-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>363c1c44-2e4f-11e5-9284-b827eb9e62be<commit_msg>364111fe-2e4f-11e5-9284-b827eb9e62be<commit_after>364111fe-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
|
<commit_before>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include <cassert>
#include "runtimes/libjoynr-runtime/websocket/LibJoynrWebSocketRuntime.h"
#include "joynr/SingleThreadedIOService.h"
#include "joynr/Util.h"
#include "joynr/WebSocketMulticastAddressCalculator.h"
#include "joynr/exceptions/JoynrException.h"
#include "joynr/serializer/Serializer.h"
#include "joynr/system/RoutingTypes/WebSocketClientAddress.h"
#include "joynr/IKeychain.h"
#include "libjoynr/websocket/WebSocketLibJoynrMessagingSkeleton.h"
#include "libjoynr/websocket/WebSocketMessagingStubFactory.h"
#include "libjoynr/websocket/WebSocketPpClientNonTLS.h"
#include "libjoynr/websocket/WebSocketPpClientTLS.h"
namespace joynr
{
INIT_LOGGER(LibJoynrWebSocketRuntime);
LibJoynrWebSocketRuntime::LibJoynrWebSocketRuntime(std::unique_ptr<Settings> settings,
std::shared_ptr<IKeychain> keyChain)
: LibJoynrRuntime(std::move(settings)),
wsSettings(*this->settings),
websocket(nullptr),
initializationMsg()
{
createWebsocketClient(keyChain);
}
LibJoynrWebSocketRuntime::~LibJoynrWebSocketRuntime()
{
assert(websocket);
websocket->close();
// synchronously stop the underlying boost::asio::io_service
// this ensures all asynchronous operations are stopped now
// which allows a safe shutdown
assert(singleThreadIOService);
singleThreadIOService->stop();
}
void LibJoynrWebSocketRuntime::connect(
std::function<void()> onSuccess,
std::function<void(const joynr::exceptions::JoynrRuntimeException&)> onError)
{
std::string uuid = util::createUuid();
// remove dashes
uuid.erase(std::remove(uuid.begin(), uuid.end(), '-'), uuid.end());
std::string libjoynrMessagingId = "libjoynr.messaging.participantid_" + uuid;
auto libjoynrMessagingAddress =
std::make_shared<const joynr::system::RoutingTypes::WebSocketClientAddress>(
libjoynrMessagingId);
// send initialization message containing libjoynr messaging address
initializationMsg = joynr::serializer::serializeToJson(*libjoynrMessagingAddress);
JOYNR_LOG_TRACE(logger,
"OUTGOING sending websocket intialization message\nmessage: {}\nto: {}",
initializationMsg,
libjoynrMessagingAddress->toString());
// create connection to parent routing service
auto ccMessagingAddress = std::make_shared<const joynr::system::RoutingTypes::WebSocketAddress>(
wsSettings.createClusterControllerMessagingAddress());
auto factory = std::make_shared<WebSocketMessagingStubFactory>();
factory->addServer(*ccMessagingAddress, websocket->getSender());
std::weak_ptr<WebSocketMessagingStubFactory> weakFactoryRef(factory);
websocket->registerDisconnectCallback([weakFactoryRef, ccMessagingAddress]() {
if (auto factory = weakFactoryRef.lock()) {
factory->onMessagingStubClosed(*ccMessagingAddress);
}
});
auto connectCallback = [
this,
onSuccess = std::move(onSuccess),
onError = std::move(onError),
factory,
libjoynrMessagingAddress,
ccMessagingAddress
]()
{
sendInitializationMsg();
std::unique_ptr<IMulticastAddressCalculator> addressCalculator =
std::make_unique<joynr::WebSocketMulticastAddressCalculator>(ccMessagingAddress);
init(factory,
libjoynrMessagingAddress,
ccMessagingAddress,
std::move(addressCalculator),
std::move(onSuccess),
std::move(onError));
};
auto reconnectCallback = [this]() { sendInitializationMsg(); };
websocket->registerConnectCallback(connectCallback);
websocket->registerReconnectCallback(reconnectCallback);
websocket->connect(*ccMessagingAddress);
}
void LibJoynrWebSocketRuntime::sendInitializationMsg()
{
auto onFailure = [this](const exceptions::JoynrRuntimeException& e) {
// initialization message will be sent after reconnect
JOYNR_LOG_ERROR(logger,
"Sending websocket initialization message failed. Error: {}",
e.getMessage());
};
smrf::ByteVector rawMessage(initializationMsg.begin(), initializationMsg.end());
websocket->send(smrf::ByteArrayView(rawMessage), onFailure);
}
void LibJoynrWebSocketRuntime::createWebsocketClient(std::shared_ptr<IKeychain> keyChain)
{
system::RoutingTypes::WebSocketAddress webSocketAddress =
wsSettings.createClusterControllerMessagingAddress();
std::string certificateAuthorityPemFilename = wsSettings.getCertificateAuthorityPemFilename();
std::string certificatePemFilename = wsSettings.getCertificatePemFilename();
std::string privateKeyPemFilename = wsSettings.getPrivateKeyPemFilename();
if (webSocketAddress.getProtocol() == system::RoutingTypes::WebSocketProtocol::WSS) {
if (keyChain == nullptr) {
const std::string message(
"TLS websocket connection was configured for but no keychain was provided");
JOYNR_LOG_FATAL(logger, message);
throw exceptions::JoynrRuntimeException(message);
}
JOYNR_LOG_INFO(logger, "Using TLS connection");
websocket = std::make_shared<WebSocketPpClientTLS>(
wsSettings, singleThreadIOService->getIOService(), keyChain);
} else if (webSocketAddress.getProtocol() == system::RoutingTypes::WebSocketProtocol::WS) {
JOYNR_LOG_INFO(logger, "Using non-TLS connection");
websocket = std::make_shared<WebSocketPpClientNonTLS>(
wsSettings, singleThreadIOService->getIOService());
} else {
throw exceptions::JoynrRuntimeException(
"Unknown protocol used for settings property 'cluster-controller-messaging-url'");
}
}
void LibJoynrWebSocketRuntime::startLibJoynrMessagingSkeleton(
std::shared_ptr<IMessageRouter> messageRouter)
{
auto wsLibJoynrMessagingSkeleton =
std::make_shared<WebSocketLibJoynrMessagingSkeleton>(util::as_weak_ptr(messageRouter));
websocket->registerReceiveCallback([wsLibJoynrMessagingSkeleton](smrf::ByteVector&& msg) {
wsLibJoynrMessagingSkeleton->onMessageReceived(std::move(msg));
});
}
} // namespace joynr
<commit_msg>[C++] Remove dead code from LibJoynrWebSocketRuntime<commit_after>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
#include <cassert>
#include "runtimes/libjoynr-runtime/websocket/LibJoynrWebSocketRuntime.h"
#include "joynr/SingleThreadedIOService.h"
#include "joynr/Util.h"
#include "joynr/WebSocketMulticastAddressCalculator.h"
#include "joynr/exceptions/JoynrException.h"
#include "joynr/serializer/Serializer.h"
#include "joynr/system/RoutingTypes/WebSocketClientAddress.h"
#include "joynr/IKeychain.h"
#include "libjoynr/websocket/WebSocketLibJoynrMessagingSkeleton.h"
#include "libjoynr/websocket/WebSocketMessagingStubFactory.h"
#include "libjoynr/websocket/WebSocketPpClientNonTLS.h"
#include "libjoynr/websocket/WebSocketPpClientTLS.h"
namespace joynr
{
INIT_LOGGER(LibJoynrWebSocketRuntime);
LibJoynrWebSocketRuntime::LibJoynrWebSocketRuntime(std::unique_ptr<Settings> settings,
std::shared_ptr<IKeychain> keyChain)
: LibJoynrRuntime(std::move(settings)),
wsSettings(*this->settings),
websocket(nullptr),
initializationMsg()
{
createWebsocketClient(keyChain);
}
LibJoynrWebSocketRuntime::~LibJoynrWebSocketRuntime()
{
assert(websocket);
websocket->close();
// synchronously stop the underlying boost::asio::io_service
// this ensures all asynchronous operations are stopped now
// which allows a safe shutdown
assert(singleThreadIOService);
singleThreadIOService->stop();
}
void LibJoynrWebSocketRuntime::connect(
std::function<void()> onSuccess,
std::function<void(const joynr::exceptions::JoynrRuntimeException&)> onError)
{
std::string uuid = util::createUuid();
// remove dashes
uuid.erase(std::remove(uuid.begin(), uuid.end(), '-'), uuid.end());
std::string libjoynrMessagingId = "libjoynr.messaging.participantid_" + uuid;
auto libjoynrMessagingAddress =
std::make_shared<const joynr::system::RoutingTypes::WebSocketClientAddress>(
libjoynrMessagingId);
// send initialization message containing libjoynr messaging address
initializationMsg = joynr::serializer::serializeToJson(*libjoynrMessagingAddress);
JOYNR_LOG_TRACE(logger,
"OUTGOING sending websocket intialization message\nmessage: {}\nto: {}",
initializationMsg,
libjoynrMessagingAddress->toString());
// create connection to parent routing service
auto ccMessagingAddress = std::make_shared<const joynr::system::RoutingTypes::WebSocketAddress>(
wsSettings.createClusterControllerMessagingAddress());
auto factory = std::make_shared<WebSocketMessagingStubFactory>();
factory->addServer(*ccMessagingAddress, websocket->getSender());
std::weak_ptr<WebSocketMessagingStubFactory> weakFactoryRef(factory);
websocket->registerDisconnectCallback([weakFactoryRef, ccMessagingAddress]() {
if (auto factory = weakFactoryRef.lock()) {
factory->onMessagingStubClosed(*ccMessagingAddress);
}
});
auto connectCallback = [
this,
onSuccess = std::move(onSuccess),
onError = std::move(onError),
factory,
libjoynrMessagingAddress,
ccMessagingAddress
]()
{
sendInitializationMsg();
std::unique_ptr<IMulticastAddressCalculator> addressCalculator =
std::make_unique<joynr::WebSocketMulticastAddressCalculator>(ccMessagingAddress);
init(factory,
libjoynrMessagingAddress,
ccMessagingAddress,
std::move(addressCalculator),
std::move(onSuccess),
std::move(onError));
};
auto reconnectCallback = [this]() { sendInitializationMsg(); };
websocket->registerConnectCallback(connectCallback);
websocket->registerReconnectCallback(reconnectCallback);
websocket->connect(*ccMessagingAddress);
}
void LibJoynrWebSocketRuntime::sendInitializationMsg()
{
auto onFailure = [this](const exceptions::JoynrRuntimeException& e) {
// initialization message will be sent after reconnect
JOYNR_LOG_ERROR(logger,
"Sending websocket initialization message failed. Error: {}",
e.getMessage());
};
smrf::ByteVector rawMessage(initializationMsg.begin(), initializationMsg.end());
websocket->send(smrf::ByteArrayView(rawMessage), onFailure);
}
void LibJoynrWebSocketRuntime::createWebsocketClient(std::shared_ptr<IKeychain> keyChain)
{
system::RoutingTypes::WebSocketAddress webSocketAddress =
wsSettings.createClusterControllerMessagingAddress();
if (webSocketAddress.getProtocol() == system::RoutingTypes::WebSocketProtocol::WSS) {
if (keyChain == nullptr) {
const std::string message(
"TLS websocket connection was configured for but no keychain was provided");
JOYNR_LOG_FATAL(logger, message);
throw exceptions::JoynrRuntimeException(message);
}
JOYNR_LOG_INFO(logger, "Using TLS connection");
websocket = std::make_shared<WebSocketPpClientTLS>(
wsSettings, singleThreadIOService->getIOService(), keyChain);
} else if (webSocketAddress.getProtocol() == system::RoutingTypes::WebSocketProtocol::WS) {
JOYNR_LOG_INFO(logger, "Using non-TLS connection");
websocket = std::make_shared<WebSocketPpClientNonTLS>(
wsSettings, singleThreadIOService->getIOService());
} else {
throw exceptions::JoynrRuntimeException(
"Unknown protocol used for settings property 'cluster-controller-messaging-url'");
}
}
void LibJoynrWebSocketRuntime::startLibJoynrMessagingSkeleton(
std::shared_ptr<IMessageRouter> messageRouter)
{
auto wsLibJoynrMessagingSkeleton =
std::make_shared<WebSocketLibJoynrMessagingSkeleton>(util::as_weak_ptr(messageRouter));
websocket->registerReceiveCallback([wsLibJoynrMessagingSkeleton](smrf::ByteVector&& msg) {
wsLibJoynrMessagingSkeleton->onMessageReceived(std::move(msg));
});
}
} // namespace joynr
<|endoftext|>
|
<commit_before>/* world plugin
# Authors: Mohammad Hossein Gohari Nejad <mhgoharinejad@gmail.com>
# License: BSD 3 clause
*/
#include <gazebo/common/Plugin.hh>
#include <ignition/math/Pose3.hh>
#include <ignition/math/Vector3.hh>
#include "gazebo/physics/physics.hh"
#include "gazebo/common/common.hh"
#include "gazebo/gazebo.hh"
#include "gazebo_information_plugins/distance_serivce.h"
#include <ros/ros.h>
#include <string>
#include <vector>
#include <iostream>
#include <math.h>
#include <nav_msgs/OccupancyGrid.h>
#include <std_msgs/String.h>
namespace gazebo {
class WorldPluginTutorial : public WorldPlugin {
public:
physics::WorldPtr _world;
ros::NodeHandle n;
ros::Subscriber map_subscriber;
ros::ServiceServer service1,service2,service3,service4;
std::vector<std::string> vec;
std::string object_name;
int check;
WorldPluginTutorial() : WorldPlugin() {}
// double get_Temperature(){return _world->Atmosphere ().Temperature(0.0);}
// double get_Pressure(){return _world->Atmosphere ().Pressure(0.0);}
//TODO ignition::math::Vector3d get_Magnetic_Field(){return _world->MagneticField(); }
int get_walls(std::string robot_name1, std::string robot_name2) {
physics::ModelPtr model1, model2;
model1 = _world->GetModel(robot_name1);
model2 = _world->GetModel(robot_name2);
if (model1 == 0 || model2 == 0) {
ROS_WARN("invalid model name!");
return -1;
}
float start_x, start_y, slope;
int iterations;
if (model1->GetWorldPose().pos.x > model2->GetWorldPose().pos.x) {
start_x = model2->GetWorldPose().pos.x;
start_y = model2->GetWorldPose().pos.y;
slope = (model1->GetWorldPose().pos.y - start_y) / (model1->GetWorldPose().pos.x - start_x);
iterations = (model1->GetWorldPose().pos.x - start_x) * 50;
} else {
start_x = model1->GetWorldPose().pos.x;
start_y = model1->GetWorldPose().pos.y;
slope = (model2->GetWorldPose().pos.y - start_y) / (model2->GetWorldPose().pos.x - start_x);
iterations = (model2->GetWorldPose().pos.x - start_x) * 50;
}
ROS_WARN("iterations %d \n", iterations);
std::string test_object = "unique_sphere";
vec.clear();
vec.push_back(robot_name1);
vec.push_back(robot_name2);
check = 1;
_world->GetModel(test_object)->SetStatic(true);
for (int i = 0; i < iterations; i++) {
math::Pose new_test_pose(start_x + i * 0.02, start_y + i * 0.02 * slope, 0.05, 0, 0, 0);
_world->GetModel(test_object)->SetWorldPose(new_test_pose);
this->object_name = "";
_world->GetModel(test_object)->SetWorldPose(new_test_pose);
ROS_WARN("pose x: %f y: %f \n", start_x + i * 0.02, start_y + i * 0.02 * slope);
for (int j = 0; j < vec.size(); j++) {
if (vec[j] == this->object_name) { break; }
else if (j + 1 == vec.size() && this->object_name != "") {
vec.push_back(this->object_name);
ROS_INFO("these are the objects %s \n", this->object_name.c_str());
}
}
}
int number_of_walls = vec.size() - 2;
check = 0;
vec.clear();
math::Pose new_test_pose(200.0, 200.0, 10.0, 0, 0, 0);
_world->GetModel(test_object)->SetWorldPose(new_test_pose);
return number_of_walls;
}
float get_distance(std::string robot_name1, std::string robot_name2) {
physics::ModelPtr model1, model2;
model1 = _world->GetModel(robot_name1);
model2 = _world->GetModel(robot_name2);
if (model1 == 0 || model2 == 0) {
ROS_WARN("invalid model name!");
return -1;
} else {
float x_diff = model1->GetWorldPose().pos.x - model2->GetWorldPose().pos.x;
float y_diff = model1->GetWorldPose().pos.y - model2->GetWorldPose().pos.y;
return sqrt((x_diff * x_diff) + (y_diff * y_diff));
}
}
void Load(physics::WorldPtr _parent, sdf::ElementPtr _sdf) {
check = 0;
// Make sure the ROS node for Gazebo has already been initialized
if (!ros::isInitialized()) {
ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized, unable to load plugin. "
<< "Load the Gazebo system plugin 'libgazebo_ros_api_plugin.so' in the gazebo_ros package)");
return;
}
_world = _parent;
ROS_INFO("Hello World!");
ROS_INFO("Hello World!");
ROS_INFO("Hello World!");
sdf::SDF sphereSDF;
sphereSDF.SetFromString(
"<sdf version ='1.4'>\
<model name ='test_sphere'>\
<pose>-100 -120 0.2 0 0 0</pose>\
<link name ='link'>\
<sensor name='my_contact' type='contact'>\
<plugin name='my_plugin' filename='libgazebo_plugin_contact.so'/>\
<contact>\
<collision>test_collision</collision>\
</contact>\
</sensor>\
<pose>0 0 0 0 0 0</pose>\
<collision name ='test_collision'>\
<geometry>\
<sphere><radius>0.01</radius></sphere>\
</geometry>\
</collision>\
<visual name ='test_visual'>\
<geometry>\
<sphere><radius>0.01</radius></sphere>\
</geometry>\
</visual>\
</link>\
</model>\
</sdf>");
// Demonstrate using a custom model name.
sdf::ElementPtr model = sphereSDF.Root()->GetElement("model");
model->GetAttribute("name")->SetFromString("unique_sphere");
_world->InsertModelSDF(sphereSDF);
ROS_INFO("Hello World!");
//ros::WallDuration(15.0).sleep();
//std::string asfj="asphalt_plane";
//std::string hi=_world->GetModel(asfj)->GetName();
//ROS_INFO("%s",hi.c_str());
//ROS_INFO("%f",_world->GetModel(1)->GetWorldPose().pos.x );
//ROS_INFO("%f",get_distance("asphalt_plane","asphalt_plane_1"));
//math::Pose asdfjk(20,20,0,0,0,0);
//_world->GetModel(asfj)->SetWorldPose(asdfjk);
//boost::bind(&MoveBase::goalCB, this, _1)
int argc = 0;
char **argv = NULL;
ros::init(argc, argv, "gazebo_client", ros::init_options::NoSigintHandler);
service1 = n.advertiseService("GzInfo_service1", &WorldPluginTutorial::service_handler1, this);
service2 = n.advertiseService("GzInfo_service2", &WorldPluginTutorial::service_handler2, this);
service3 = n.advertiseService("GzInfo_service3", &WorldPluginTutorial::service_handler3, this);
service4 = n.advertiseService("GzInfo_service4", &WorldPluginTutorial::service_handler4, this);
std::string subscribing_topic = "collision_topic";//move_base/local_costmap/costmap";
map_subscriber = n.subscribe(subscribing_topic, 10, &WorldPluginTutorial::collision_callback, this);
}
void collision_callback(const std_msgs::String object_name) {
this->object_name = object_name.data;
if (vec.size() > 0 && check == 1) {
for (int j = 0; j < vec.size(); j++) {
if (vec[j] == object_name.data) {
break;
} else if (j + 1 == vec.size() && object_name.data != "") {
vec.push_back(object_name.data);
ROS_INFO("these are the objects %s \n", object_name.data.c_str());
}
}
}
//ROS_INFO("%s",object_name.data.c_str());
}
bool service_handler1(gazebo_information_plugins::distance_serivce::Request &req,
gazebo_information_plugins::distance_serivce::Response &res) {
std::string command = req.command, robot1 = req.robot1, robot2 = req.robot2;
if (command == "distance") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = 0;
} else if (command == "walls") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = get_walls(robot1, robot2);
}
else if (command == "temp") {
res.distance = 0;
res.number_of_objects = 0;
}
else if (command == "pressure") {
res.distance = 0;
res.number_of_objects = 0;
}
/*TODO else if (command == "magnet") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = get_walls(robot1, robot2);
} */
return true;
}
bool service_handler2(gazebo_information_plugins::distance_serivce::Request &req,
gazebo_information_plugins::distance_serivce::Response &res) {
std::string command = req.command, robot1 = req.robot1, robot2 = req.robot2;
if (command == "distance") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = 0;
} else if (command == "walls") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = get_walls(robot1, robot2);
}
else if (command == "temp") {
res.distance = 0;
res.number_of_objects = 0;
}
else if (command == "pressure") {
res.distance = 0;
res.number_of_objects = 0;
}
/*TODO else if (command == "magnet") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = get_walls(robot1, robot2);
} */
return true;
}
bool service_handler3(gazebo_information_plugins::distance_serivce::Request &req,
gazebo_information_plugins::distance_serivce::Response &res) {
std::string command = req.command, robot1 = req.robot1, robot2 = req.robot2;
if (command == "distance") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = 0;
} else if (command == "walls") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = get_walls(robot1, robot2);
}
else if (command == "temp") {
res.distance = 0;
res.number_of_objects = 0;
}
else if (command == "pressure") {
res.distance = 0;
res.number_of_objects = 0;
}
/*TODO else if (command == "magnet") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = get_walls(robot1, robot2);
} */
return true;
}
bool service_handler4(gazebo_information_plugins::distance_serivce::Request &req,
gazebo_information_plugins::distance_serivce::Response &res) {
std::string command = req.command, robot1 = req.robot1, robot2 = req.robot2;
if (command == "distance") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = 0;
} else if (command == "walls") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = get_walls(robot1, robot2);
}
else if (command == "temp") {
res.distance = 0;
res.number_of_objects = 0;
}
else if (command == "pressure") {
res.distance = 0;
res.number_of_objects = 0;
}
/*TODO else if (command == "magnet") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = get_walls(robot1, robot2);
} */
return true;
}
};
GZ_REGISTER_WORLD_PLUGIN(WorldPluginTutorial)
}
<commit_msg>adding class for generic message handling<commit_after>/* world plugin
# Authors: Mohammad Hossein Gohari Nejad <mhgoharinejad@gmail.com>
# License: BSD 3 clause
*/
#include <gazebo/common/Plugin.hh>
#include <ignition/math/Pose3.hh>
#include <ignition/math/Vector3.hh>
#include "gazebo/physics/physics.hh"
#include "gazebo/common/common.hh"
#include "gazebo/gazebo.hh"
#include "gazebo_information_plugins/distance_serivce.h"
#include <ros/ros.h>
#include <string>
#include <vector>
#include <iostream>
#include <math.h>
#include <nav_msgs/OccupancyGrid.h>
#include <std_msgs/String.h>
#define NUM_SRV 4
namespace gazebo {
class service_handle;
class WorldPluginTutorial : public WorldPlugin {
public:
physics::WorldPtr _world;
ros::NodeHandle n;
ros::Subscriber map_subscriber;
ros::ServiceServer service1,service2,service3,service4;
std::vector<std::string> vec;
std::vector<service_handle*> vec_srv;
std::string object_name;
int check;
WorldPluginTutorial() : WorldPlugin() {}
// double get_Temperature(){return _world->Atmosphere ().Temperature(0.0);}
// double get_Pressure(){return _world->Atmosphere ().Pressure(0.0);}
//TODO ignition::math::Vector3d get_Magnetic_Field(){return _world->MagneticField(); }
int get_walls(std::string robot_name1, std::string robot_name2) {
physics::ModelPtr model1, model2;
model1 = _world->GetModel(robot_name1);
model2 = _world->GetModel(robot_name2);
if (model1 == 0 || model2 == 0) {
ROS_WARN("invalid model name!");
return -1;
}
float start_x, start_y, slope;
int iterations;
if (model1->GetWorldPose().pos.x > model2->GetWorldPose().pos.x) {
start_x = model2->GetWorldPose().pos.x;
start_y = model2->GetWorldPose().pos.y;
slope = (model1->GetWorldPose().pos.y - start_y) / (model1->GetWorldPose().pos.x - start_x);
iterations = (model1->GetWorldPose().pos.x - start_x) * 50;
} else {
start_x = model1->GetWorldPose().pos.x;
start_y = model1->GetWorldPose().pos.y;
slope = (model2->GetWorldPose().pos.y - start_y) / (model2->GetWorldPose().pos.x - start_x);
iterations = (model2->GetWorldPose().pos.x - start_x) * 50;
}
ROS_WARN("iterations %d \n", iterations);
std::string test_object = "unique_sphere";
vec.clear();
vec.push_back(robot_name1);
vec.push_back(robot_name2);
check = 1;
_world->GetModel(test_object)->SetStatic(true);
for (int i = 0; i < iterations; i++) {
math::Pose new_test_pose(start_x + i * 0.02, start_y + i * 0.02 * slope, 0.05, 0, 0, 0);
_world->GetModel(test_object)->SetWorldPose(new_test_pose);
this->object_name = "";
_world->GetModel(test_object)->SetWorldPose(new_test_pose);
ROS_WARN("pose x: %f y: %f \n", start_x + i * 0.02, start_y + i * 0.02 * slope);
for (int j = 0; j < vec.size(); j++) {
if (vec[j] == this->object_name) { break; }
else if (j + 1 == vec.size() && this->object_name != "") {
vec.push_back(this->object_name);
ROS_INFO("these are the objects %s \n", this->object_name.c_str());
}
}
}
int number_of_walls = vec.size() - 2;
check = 0;
vec.clear();
math::Pose new_test_pose(200.0, 200.0, 10.0, 0, 0, 0);
_world->GetModel(test_object)->SetWorldPose(new_test_pose);
return number_of_walls;
}
float get_distance(std::string robot_name1, std::string robot_name2) {
physics::ModelPtr model1, model2;
model1 = _world->GetModel(robot_name1);
model2 = _world->GetModel(robot_name2);
if (model1 == 0 || model2 == 0) {
ROS_WARN("invalid model name!");
return -1;
} else {
float x_diff = model1->GetWorldPose().pos.x - model2->GetWorldPose().pos.x;
float y_diff = model1->GetWorldPose().pos.y - model2->GetWorldPose().pos.y;
return sqrt((x_diff * x_diff) + (y_diff * y_diff));
}
}
void Load(physics::WorldPtr _parent, sdf::ElementPtr _sdf) {
check = 0;
// Make sure the ROS node for Gazebo has already been initialized
if (!ros::isInitialized()) {
ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized, unable to load plugin. "
<< "Load the Gazebo system plugin 'libgazebo_ros_api_plugin.so' in the gazebo_ros package)");
return;
}
_world = _parent;
ROS_INFO("Hello World!");
ROS_INFO("Hello World!");
ROS_INFO("Hello World!");
sdf::SDF sphereSDF;
sphereSDF.SetFromString(
"<sdf version ='1.4'>\
<model name ='test_sphere'>\
<pose>-100 -120 0.2 0 0 0</pose>\
<link name ='link'>\
<sensor name='my_contact' type='contact'>\
<plugin name='my_plugin' filename='libgazebo_plugin_contact.so'/>\
<contact>\
<collision>test_collision</collision>\
</contact>\
</sensor>\
<pose>0 0 0 0 0 0</pose>\
<collision name ='test_collision'>\
<geometry>\
<sphere><radius>0.01</radius></sphere>\
</geometry>\
</collision>\
<visual name ='test_visual'>\
<geometry>\
<sphere><radius>0.01</radius></sphere>\
</geometry>\
</visual>\
</link>\
</model>\
</sdf>");
// Demonstrate using a custom model name.
sdf::ElementPtr model = sphereSDF.Root()->GetElement("model");
model->GetAttribute("name")->SetFromString("unique_sphere");
_world->InsertModelSDF(sphereSDF);
ROS_INFO("Hello World!");
//ros::WallDuration(15.0).sleep();
//std::string asfj="asphalt_plane";
//std::string hi=_world->GetModel(asfj)->GetName();
//ROS_INFO("%s",hi.c_str());
//ROS_INFO("%f",_world->GetModel(1)->GetWorldPose().pos.x );
//ROS_INFO("%f",get_distance("asphalt_plane","asphalt_plane_1"));
//math::Pose asdfjk(20,20,0,0,0,0);
//_world->GetModel(asfj)->SetWorldPose(asdfjk);
//boost::bind(&MoveBase::goalCB, this, _1)
int argc = 0;
char **argv = NULL;
ros::init(argc, argv, "gazebo_client", ros::init_options::NoSigintHandler);
for (int i=0;i<NUM_SRV;i++){
vec_srv.push_back(new service_handle("GzInfo_service"+(std::to_string(i)),this))
};
// service1 = n.advertiseService("GzInfo_service1", &WorldPluginTutorial::service_handler1, this);
// service2 = n.advertiseService("GzInfo_service2", &WorldPluginTutorial::service_handler2, this);
// service3 = n.advertiseService("GzInfo_service3", &WorldPluginTutorial::service_handler3, this);
// service4 = n.advertiseService("GzInfo_service4", &WorldPluginTutorial::service_handler4, this);
std::string subscribing_topic = "collision_topic";//move_base/local_costmap/costmap";
map_subscriber = n.subscribe(subscribing_topic, 10, &WorldPluginTutorial::collision_callback, this);
}
void collision_callback(const std_msgs::String object_name) {
this->object_name = object_name.data;
if (vec.size() > 0 && check == 1) {
for (int j = 0; j < vec.size(); j++) {
if (vec[j] == object_name.data) {
break;
} else if (j + 1 == vec.size() && object_name.data != "") {
vec.push_back(object_name.data);
ROS_INFO("these are the objects %s \n", object_name.data.c_str());
}
}
}
//ROS_INFO("%s",object_name.data.c_str());
}
bool service_handler1(gazebo_information_plugins::distance_serivce::Request &req,
gazebo_information_plugins::distance_serivce::Response &res) {
std::string command = req.command, robot1 = req.robot1, robot2 = req.robot2;
if (command == "distance") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = 0;
} else if (command == "walls") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = get_walls(robot1, robot2);
}
else if (command == "temp") {
res.distance = 0;
res.number_of_objects = 0;
}
else if (command == "pressure") {
res.distance = 0;
res.number_of_objects = 0;
}
/*TODO else if (command == "magnet") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = get_walls(robot1, robot2);
} */
return true;
}
};
class service_handle {
public:
WorldPluginTutorial* WPT;
std::string sn;
ros::ServiceServer service1;
service_handle(std::string service_name,WorldPluginTutorial* world_plugin){
sn=service_name;
WPT=world_plugin;
service1 = (WPT->n).advertiseService(sn, &service_handle::service_handler1, this);
};
bool service_handler1(gazebo_information_plugins::distance_serivce::Request &req,
gazebo_information_plugins::distance_serivce::Response &res) {
std::string command = req.command, robot1 = req.robot1, robot2 = req.robot2;
if (command == "distance") {
res.distance = WPT->get_distance(robot1, robot2);
res.number_of_objects = 0;
} else if (command == "walls") {
res.distance = WPT->get_distance(robot1, robot2);
res.number_of_objects = WPT->get_walls(robot1, robot2);
}
else if (command == "temp") {
res.distance = 0;
res.number_of_objects = 0;
}
else if (command == "pressure") {
res.distance = 0;
res.number_of_objects = 0;
}
/*TODO else if (command == "magnet") {
res.distance = get_distance(robot1, robot2);
res.number_of_objects = get_walls(robot1, robot2);
} */
return true;
}
};
GZ_REGISTER_WORLD_PLUGIN(WorldPluginTutorial)
}
<|endoftext|>
|
<commit_before>/*
* This file is part of the UnTech Editor Suite.
* Copyright (c) 2016 - 2018, Marcus Rowe <undisbeliever@gmail.com>.
* Distributed under The MIT License: https://opensource.org/licenses/MIT
*/
#include "mttilesetpropertymanager.h"
#include "mttilesetaccessors.h"
#include "mttilesetresourceitem.h"
#include "gui-qt/accessor/gridundohelper.h"
#include "gui-qt/accessor/resourceitemundohelper.h"
#include "gui-qt/common/helpers.h"
#include "gui-qt/resources/palette/paletteresourcelist.h"
using namespace UnTech::GuiQt::MetaTiles;
using TilesetUndoHelper = UnTech::GuiQt::Accessor::ResourceItemUndoHelper<MtTilesetResourceItem>;
MtTilesetPropertyManager::MtTilesetPropertyManager(QObject* parent)
: AbstractPropertyManager(parent)
, _tileset(nullptr)
{
using Type = UnTech::GuiQt::PropertyType;
addProperty(tr("Name"), NAME, Type::IDSTRING);
addProperty(tr("Scratchpad Size"), SCRATCHPAD_SIZE, Type::SIZE, QSize(0, 0), QSize(255, 255));
addProperty(tr("Palettes"), PALETTES, Type::IDSTRING_LIST);
addPropertyGroup(tr("Animation Frames:"));
addProperty(tr("Frame Images"), FRAME_IMAGES, Type::FILENAME_LIST,
QStringLiteral("PNG Image (*.png)"));
addProperty(tr("Animation Delay"), ANIMATION_DELAY, Type::UNSIGNED, 0, 0x10000);
addProperty(tr("Bit Depth"), BIT_DEPTH, Type::COMBO, QStringList{ "2 bpp", "4 bpp", "8 bpp" }, QVariantList{ 2, 4, 8 });
addProperty(tr("Add Transparent Tile"), ADD_TRANSPARENT_TILE, Type::BOOLEAN);
}
void MtTilesetPropertyManager::setResourceItem(AbstractResourceItem* abstractItem)
{
MtTilesetResourceItem* item = qobject_cast<MtTilesetResourceItem*>(abstractItem);
if (_tileset == item) {
return;
}
if (_tileset) {
_tileset->disconnect(this);
}
_tileset = item;
setEnabled(_tileset != nullptr);
if (_tileset) {
setEnabled(_tileset->tilesetInput() != nullptr);
connect(_tileset, &MtTilesetResourceItem::dataChanged,
this, &MtTilesetPropertyManager::dataChanged);
}
emit dataChanged();
}
void MtTilesetPropertyManager::updateParameters(int id, QVariant& param1, QVariant&) const
{
if (_tileset == nullptr) {
return;
}
if (id == PALETTES) {
param1 = _tileset->project()->paletteResourceList()->itemNames();
}
}
QVariant MtTilesetPropertyManager::data(int id) const
{
if (_tileset == nullptr) {
return QVariant();
}
const MT::MetaTileTilesetInput* ti = _tileset->tilesetInput();
if (ti == nullptr) {
return QVariant();
}
switch ((PropertyId)id) {
case NAME:
return QString::fromStdString(ti->name);
case SCRATCHPAD_SIZE:
return fromUsize(ti->scratchpad.size());
case PALETTES:
return convertStringList(ti->palettes);
case FRAME_IMAGES:
return convertStringList(ti->animationFrames.frameImageFilenames);
case ANIMATION_DELAY:
return ti->animationFrames.animationDelay;
case BIT_DEPTH:
return ti->animationFrames.bitDepth;
case ADD_TRANSPARENT_TILE:
return ti->animationFrames.addTransparentTile;
}
return QVariant();
}
bool MtTilesetPropertyManager::setData(int id, const QVariant& value)
{
Q_ASSERT(_tileset);
Q_ASSERT(_tileset->data());
TilesetUndoHelper undoHelper(_tileset);
switch ((PropertyId)id) {
case NAME:
return undoHelper.editName(value.toString().toStdString());
case SCRATCHPAD_SIZE:
return MtTilesetScratchpadGridUndoHelper(_tileset->scratchpadGrid())
.resizeSelectedGrid(toUsize(value.toSize()), 0,
tr("Resize scratchpad"));
case PALETTES:
return undoHelper.editField(toIdstringVector(value.toStringList()),
tr("Edit Palette List"),
[](MT::MetaTileTilesetInput& ti) -> std::vector<idstring>& { return ti.palettes; },
[](MtTilesetResourceItem& item) { emit item.palettesChanged();
item.updateDependencies(); });
case FRAME_IMAGES:
return undoHelper.editField(toStringVector(value.toStringList()),
tr("Edit Frame Image List"),
[](MT::MetaTileTilesetInput& ti) -> std::vector<std::string>& { return ti.animationFrames.frameImageFilenames; },
[](MtTilesetResourceItem& item) { item.updateExternalFiles(); });
case ANIMATION_DELAY:
return undoHelper.editField(value.toUInt(),
tr("Edit Animation Delay"),
[](MT::MetaTileTilesetInput& ti) -> unsigned& { return ti.animationFrames.animationDelay; },
[](MtTilesetResourceItem& item) { emit item.animationDelayChanged(); });
case BIT_DEPTH:
return undoHelper.editField(value.toUInt(),
tr("Edit Bit Depth"),
[](MT::MetaTileTilesetInput& ti) -> unsigned& { return ti.animationFrames.bitDepth; });
case ADD_TRANSPARENT_TILE:
return undoHelper.editField(value.toBool(),
tr("Edit Add Transparent Tile"),
[](MT::MetaTileTilesetInput& ti) -> bool& { return ti.animationFrames.addTransparentTile; });
}
}
<commit_msg>Fix compiler warning when compiling with g++<commit_after>/*
* This file is part of the UnTech Editor Suite.
* Copyright (c) 2016 - 2018, Marcus Rowe <undisbeliever@gmail.com>.
* Distributed under The MIT License: https://opensource.org/licenses/MIT
*/
#include "mttilesetpropertymanager.h"
#include "mttilesetaccessors.h"
#include "mttilesetresourceitem.h"
#include "gui-qt/accessor/gridundohelper.h"
#include "gui-qt/accessor/resourceitemundohelper.h"
#include "gui-qt/common/helpers.h"
#include "gui-qt/resources/palette/paletteresourcelist.h"
using namespace UnTech::GuiQt::MetaTiles;
using TilesetUndoHelper = UnTech::GuiQt::Accessor::ResourceItemUndoHelper<MtTilesetResourceItem>;
MtTilesetPropertyManager::MtTilesetPropertyManager(QObject* parent)
: AbstractPropertyManager(parent)
, _tileset(nullptr)
{
using Type = UnTech::GuiQt::PropertyType;
addProperty(tr("Name"), NAME, Type::IDSTRING);
addProperty(tr("Scratchpad Size"), SCRATCHPAD_SIZE, Type::SIZE, QSize(0, 0), QSize(255, 255));
addProperty(tr("Palettes"), PALETTES, Type::IDSTRING_LIST);
addPropertyGroup(tr("Animation Frames:"));
addProperty(tr("Frame Images"), FRAME_IMAGES, Type::FILENAME_LIST,
QStringLiteral("PNG Image (*.png)"));
addProperty(tr("Animation Delay"), ANIMATION_DELAY, Type::UNSIGNED, 0, 0x10000);
addProperty(tr("Bit Depth"), BIT_DEPTH, Type::COMBO, QStringList{ "2 bpp", "4 bpp", "8 bpp" }, QVariantList{ 2, 4, 8 });
addProperty(tr("Add Transparent Tile"), ADD_TRANSPARENT_TILE, Type::BOOLEAN);
}
void MtTilesetPropertyManager::setResourceItem(AbstractResourceItem* abstractItem)
{
MtTilesetResourceItem* item = qobject_cast<MtTilesetResourceItem*>(abstractItem);
if (_tileset == item) {
return;
}
if (_tileset) {
_tileset->disconnect(this);
}
_tileset = item;
setEnabled(_tileset != nullptr);
if (_tileset) {
setEnabled(_tileset->tilesetInput() != nullptr);
connect(_tileset, &MtTilesetResourceItem::dataChanged,
this, &MtTilesetPropertyManager::dataChanged);
}
emit dataChanged();
}
void MtTilesetPropertyManager::updateParameters(int id, QVariant& param1, QVariant&) const
{
if (_tileset == nullptr) {
return;
}
if (id == PALETTES) {
param1 = _tileset->project()->paletteResourceList()->itemNames();
}
}
QVariant MtTilesetPropertyManager::data(int id) const
{
if (_tileset == nullptr) {
return QVariant();
}
const MT::MetaTileTilesetInput* ti = _tileset->tilesetInput();
if (ti == nullptr) {
return QVariant();
}
switch ((PropertyId)id) {
case NAME:
return QString::fromStdString(ti->name);
case SCRATCHPAD_SIZE:
return fromUsize(ti->scratchpad.size());
case PALETTES:
return convertStringList(ti->palettes);
case FRAME_IMAGES:
return convertStringList(ti->animationFrames.frameImageFilenames);
case ANIMATION_DELAY:
return ti->animationFrames.animationDelay;
case BIT_DEPTH:
return ti->animationFrames.bitDepth;
case ADD_TRANSPARENT_TILE:
return ti->animationFrames.addTransparentTile;
}
return QVariant();
}
bool MtTilesetPropertyManager::setData(int id, const QVariant& value)
{
Q_ASSERT(_tileset);
Q_ASSERT(_tileset->data());
TilesetUndoHelper undoHelper(_tileset);
switch ((PropertyId)id) {
case NAME:
return undoHelper.editName(value.toString().toStdString());
case SCRATCHPAD_SIZE:
return MtTilesetScratchpadGridUndoHelper(_tileset->scratchpadGrid())
.resizeSelectedGrid(toUsize(value.toSize()), 0,
tr("Resize scratchpad"));
case PALETTES:
return undoHelper.editField(toIdstringVector(value.toStringList()),
tr("Edit Palette List"),
[](MT::MetaTileTilesetInput& ti) -> std::vector<idstring>& { return ti.palettes; },
[](MtTilesetResourceItem& item) { emit item.palettesChanged();
item.updateDependencies(); });
case FRAME_IMAGES:
return undoHelper.editField(toStringVector(value.toStringList()),
tr("Edit Frame Image List"),
[](MT::MetaTileTilesetInput& ti) -> std::vector<std::string>& { return ti.animationFrames.frameImageFilenames; },
[](MtTilesetResourceItem& item) { item.updateExternalFiles(); });
case ANIMATION_DELAY:
return undoHelper.editField(value.toUInt(),
tr("Edit Animation Delay"),
[](MT::MetaTileTilesetInput& ti) -> unsigned& { return ti.animationFrames.animationDelay; },
[](MtTilesetResourceItem& item) { emit item.animationDelayChanged(); });
case BIT_DEPTH:
return undoHelper.editField(value.toUInt(),
tr("Edit Bit Depth"),
[](MT::MetaTileTilesetInput& ti) -> unsigned& { return ti.animationFrames.bitDepth; });
case ADD_TRANSPARENT_TILE:
return undoHelper.editField(value.toBool(),
tr("Edit Add Transparent Tile"),
[](MT::MetaTileTilesetInput& ti) -> bool& { return ti.animationFrames.addTransparentTile; });
}
return false;
}
<|endoftext|>
|
<commit_before>// Copyright 2017 SAS Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <Python.h>
#include <iostream>
#include "its/itm.h"
static PyObject* itm_point_to_point(PyObject* self, PyObject* args) {
PyObject* elev_obj = NULL;
double tht_m, rht_m;
double eps_dielect, sgm_conductivity, eno_ns_surfref;
double frq_mhz;
int radio_climate, pol;
double conf, rel;
int mdvar = 12; // Default arguments
int eno_final = 0;
if (!PyArg_ParseTuple(args, "Oddddddiidd|ii:point_to_point",
&elev_obj, &tht_m, &rht_m, &eps_dielect, &sgm_conductivity,
&eno_ns_surfref,
&frq_mhz, &radio_climate, &pol, &conf, &rel, &mdvar, &eno_final)) {
return NULL;
}
if (!PyList_Check(elev_obj)) {
return NULL;
}
Py_ssize_t size = PyList_Size(elev_obj);
if (size < 4) {
PyErr_SetString(PyExc_ValueError, "Invalid profile size. Should be >= 4.");
return NULL;
}
double* elev = new double[size];
for (Py_ssize_t i = 0; i < size; i++) {
PyObject* i_obj = PyList_GetItem(elev_obj, i);
double elev_val = PyFloat_AsDouble(i_obj);
elev[i] = elev_val;
}
if (PyErr_Occurred()) {
delete[] elev;
PyErr_SetString(PyExc_ValueError, "Profile should only contain numerical values.");
return NULL;
}
if (elev[0] > size-3) {
delete[] elev;
PyErr_SetString(PyExc_ValueError, "Invalid Profile. Size in slot 0 bigger than actual list size.");
return NULL;
}
double dbloss;
char strmode[100];
int errnum;
double ver0, ver1;
point_to_point(elev, tht_m, rht_m, eps_dielect, sgm_conductivity,
eno_ns_surfref, frq_mhz, radio_climate, pol, conf, rel,
mdvar, !!eno_final,
dbloss, strmode, errnum, ver0, ver1);
delete[] elev;
return Py_BuildValue("dddsi", dbloss, ver0, ver1, strmode, errnum);
}
static PyObject* itm_point_to_point_rels(PyObject* self, PyObject* args) {
PyObject* elev_obj = NULL;
double tht_m, rht_m;
double eps_dielect, sgm_conductivity, eno_ns_surfref;
double frq_mhz;
int radio_climate, pol;
double conf;
PyObject* rels_obj = NULL;
int mdvar = 12; // Default arguments
int eno_final = 0;
if (!PyArg_ParseTuple(args, "OddddddiidO|ii:point_to_point_rels",
&elev_obj, &tht_m, &rht_m, &eps_dielect, &sgm_conductivity,
&eno_ns_surfref,
&frq_mhz, &radio_climate, &pol, &conf, &rels_obj,
&mdvar, &eno_final)) {
return NULL;
}
if (!PyList_Check(elev_obj)) {
return NULL;
}
if (!PyList_Check(rels_obj)) {
return NULL;
}
// Get the profile
Py_ssize_t size = PyList_Size(elev_obj);
if (size < 4) {
PyErr_SetString(PyExc_ValueError, "Invalid profile size. Should be >= 4.");
return NULL;
}
double* elev = new double[size];
for (Py_ssize_t i = 0; i < size; i++) {
PyObject* i_obj = PyList_GetItem(elev_obj, i);
double elev_val = PyFloat_AsDouble(i_obj);
elev[i] = elev_val;
}
if (PyErr_Occurred()) {
delete[] elev;
PyErr_SetString(PyExc_ValueError, "Profile should only contain numerical values.");
return NULL;
}
if (elev[0] > size-3) {
delete[] elev;
PyErr_SetString(PyExc_ValueError, "Invalid Profile. Size in slot 0 bigger than actual list size.");
return NULL;
}
// Get the reliability list
size = PyList_Size(rels_obj);
if (size <= 0) {
delete[] elev;
PyErr_SetString(PyExc_ValueError, "Reliabilities list empty.");
return NULL;
}
double* rels = new double[size];
for (Py_ssize_t i = 0; i < size; i++) {
PyObject* rel_obj = PyList_GetItem(rels_obj, i);
double rel = PyFloat_AsDouble(rel_obj);
rels[i] = rel;
}
if (PyErr_Occurred()) {
delete[] elev;
delete[] rels;
PyErr_SetString(PyExc_ValueError, "Reliabilities list should only contain numerical values.");
return NULL;
}
int num_rels = size;
double* db_losses = new double[num_rels];
double ver0, ver1;
char strmode[100];
int errnum;
point_to_point_rels(elev, tht_m, rht_m, eps_dielect, sgm_conductivity,
eno_ns_surfref, frq_mhz, radio_climate, pol, conf,
rels, num_rels,
mdvar, !!eno_final,
db_losses, strmode, errnum, ver0, ver1);
delete[] elev;
delete[] rels;
PyObject* loss_obj = PyList_New(num_rels);
for (int k = 0; k < size; k++ ) {
PyList_SET_ITEM(loss_obj, k, Py_BuildValue("d", db_losses[k]));
}
delete[] db_losses;
return Py_BuildValue("Oddsi", loss_obj, ver0, ver1, strmode, errnum);
}
static PyMethodDef ITMMethods[] = {
{"point_to_point", itm_point_to_point, METH_VARARGS, "Point-to-point model"},
{"point_to_point_rels", itm_point_to_point_rels, METH_VARARGS, "Point-to-point-Rels model"},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC inititm_its(void) {
Py_InitModule3("itm_its", ITMMethods, "Longley-Rice ITM Propagation Module");
}
<commit_msg>Fix mem leak on ITM Python-C++ interface. (#847)<commit_after>// Copyright 2017 SAS Project Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <Python.h>
#include <iostream>
#include "its/itm.h"
static PyObject* itm_point_to_point(PyObject* self, PyObject* args) {
PyObject* elev_obj = NULL;
double tht_m, rht_m;
double eps_dielect, sgm_conductivity, eno_ns_surfref;
double frq_mhz;
int radio_climate, pol;
double conf, rel;
int mdvar = 12; // Default arguments
int eno_final = 0;
if (!PyArg_ParseTuple(args, "Oddddddiidd|ii:point_to_point",
&elev_obj, &tht_m, &rht_m, &eps_dielect, &sgm_conductivity,
&eno_ns_surfref,
&frq_mhz, &radio_climate, &pol, &conf, &rel, &mdvar, &eno_final)) {
return NULL;
}
if (!PyList_Check(elev_obj)) {
return NULL;
}
Py_ssize_t size = PyList_Size(elev_obj);
if (size < 4) {
PyErr_SetString(PyExc_ValueError, "Invalid profile size. Should be >= 4.");
return NULL;
}
double* elev = new double[size];
for (Py_ssize_t i = 0; i < size; i++) {
PyObject* i_obj = PyList_GetItem(elev_obj, i);
double elev_val = PyFloat_AsDouble(i_obj);
elev[i] = elev_val;
}
if (PyErr_Occurred()) {
delete[] elev;
PyErr_SetString(PyExc_ValueError, "Profile should only contain numerical values.");
return NULL;
}
if (elev[0] > size-3) {
delete[] elev;
PyErr_SetString(PyExc_ValueError, "Invalid Profile. Size in slot 0 bigger than actual list size.");
return NULL;
}
double dbloss;
char strmode[100];
int errnum;
double ver0, ver1;
point_to_point(elev, tht_m, rht_m, eps_dielect, sgm_conductivity,
eno_ns_surfref, frq_mhz, radio_climate, pol, conf, rel,
mdvar, !!eno_final,
dbloss, strmode, errnum, ver0, ver1);
delete[] elev;
return Py_BuildValue("dddsi", dbloss, ver0, ver1, strmode, errnum);
}
static PyObject* itm_point_to_point_rels(PyObject* self, PyObject* args) {
PyObject* elev_obj = NULL;
double tht_m, rht_m;
double eps_dielect, sgm_conductivity, eno_ns_surfref;
double frq_mhz;
int radio_climate, pol;
double conf;
PyObject* rels_obj = NULL;
int mdvar = 12; // Default arguments
int eno_final = 0;
if (!PyArg_ParseTuple(args, "OddddddiidO|ii:point_to_point_rels",
&elev_obj, &tht_m, &rht_m, &eps_dielect, &sgm_conductivity,
&eno_ns_surfref,
&frq_mhz, &radio_climate, &pol, &conf, &rels_obj,
&mdvar, &eno_final)) {
return NULL;
}
if (!PyList_Check(elev_obj)) {
return NULL;
}
if (!PyList_Check(rels_obj)) {
return NULL;
}
// Get the profile
Py_ssize_t size = PyList_Size(elev_obj);
if (size < 4) {
PyErr_SetString(PyExc_ValueError, "Invalid profile size. Should be >= 4.");
return NULL;
}
double* elev = new double[size];
for (Py_ssize_t i = 0; i < size; i++) {
PyObject* i_obj = PyList_GetItem(elev_obj, i);
double elev_val = PyFloat_AsDouble(i_obj);
elev[i] = elev_val;
}
if (PyErr_Occurred()) {
delete[] elev;
PyErr_SetString(PyExc_ValueError, "Profile should only contain numerical values.");
return NULL;
}
if (elev[0] > size-3) {
delete[] elev;
PyErr_SetString(PyExc_ValueError, "Invalid Profile. Size in slot 0 bigger than actual list size.");
return NULL;
}
// Get the reliability list
size = PyList_Size(rels_obj);
if (size <= 0) {
delete[] elev;
PyErr_SetString(PyExc_ValueError, "Reliabilities list empty.");
return NULL;
}
double* rels = new double[size];
for (Py_ssize_t i = 0; i < size; i++) {
PyObject* rel_obj = PyList_GetItem(rels_obj, i);
double rel = PyFloat_AsDouble(rel_obj);
rels[i] = rel;
}
if (PyErr_Occurred()) {
delete[] elev;
delete[] rels;
PyErr_SetString(PyExc_ValueError, "Reliabilities list should only contain numerical values.");
return NULL;
}
int num_rels = size;
double* db_losses = new double[num_rels];
double ver0, ver1;
char strmode[100];
int errnum;
point_to_point_rels(elev, tht_m, rht_m, eps_dielect, sgm_conductivity,
eno_ns_surfref, frq_mhz, radio_climate, pol, conf,
rels, num_rels,
mdvar, !!eno_final,
db_losses, strmode, errnum, ver0, ver1);
delete[] elev;
delete[] rels;
PyObject* loss_obj = PyList_New(num_rels);
for (int k = 0; k < size; k++ ) {
PyList_SET_ITEM(loss_obj, k, Py_BuildValue("d", db_losses[k]));
}
delete[] db_losses;
// Note: use N instead of O here to avoid increment of ref count of loss_obj.
// Otherwise would have a mem leak, since it would never be released.
return Py_BuildValue("Nddsi", loss_obj, ver0, ver1, strmode, errnum);
}
static PyMethodDef ITMMethods[] = {
{"point_to_point", itm_point_to_point, METH_VARARGS, "Point-to-point model"},
{"point_to_point_rels", itm_point_to_point_rels, METH_VARARGS, "Point-to-point-Rels model"},
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC inititm_its(void) {
Py_InitModule3("itm_its", ITMMethods, "Longley-Rice ITM Propagation Module");
}
<|endoftext|>
|
<commit_before>/*
Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open
Source Software License
Copyright (c) 2008 Ames Laboratory Iowa State University
All rights reserved.
Redistribution and use of HOOMD, in source and binary forms, with or
without modification, are permitted, provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names HOOMD's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND
CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
// $Id$
// $URL$
/*! \file LJForceComputeGPU.cc
\brief Defines the LJForceComputeGPU class
*/
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif
#include "LJForceComputeGPU.h"
#include "cuda_runtime.h"
#include <stdexcept>
#include <boost/python.hpp>
using namespace boost::python;
#include <boost/bind.hpp>
using namespace boost;
using namespace std;
/*! \param sysdef System to compute forces on
\param nlist Neighborlist to use for computing the forces
\param r_cut Cuttoff radius beyond which the force is 0
\param slj Determines if Diameter Shifted LJ potential is being used
\post memory is allocated and all parameters lj1 and lj2 are set to 0.0
\note The LJForceComputeGPU does not own the Neighborlist, the caller should
delete the neighborlist when done.
*/
LJForceComputeGPU::LJForceComputeGPU(boost::shared_ptr<SystemDefinition> sysdef, boost::shared_ptr<NeighborList> nlist, Scalar r_cut)
: LJForceCompute(sysdef, nlist, r_cut)
{
// can't run on the GPU if there aren't any GPUs in the execution configuration
if (exec_conf.gpu.size() == 0)
{
cerr << endl << "***Error! Creating a LJForceComputeGPU with no GPU in the execution configuration" << endl << endl;
throw std::runtime_error("Error initializing LJForceComputeGPU");
}
if (m_ntypes > 44)
{
cerr << endl << "***Error! LJForceComputeGPU cannot handle " << m_ntypes << " types" << endl << endl;
throw runtime_error("Error initializing LJForceComputeGPU");
}
// default block size is the highest performance in testing on different hardware
// choose based on compute capability of the device
cudaDeviceProp deviceProp;
int dev;
exec_conf.gpu[0]->call(bind(cudaGetDevice, &dev));
exec_conf.gpu[0]->call(bind(cudaGetDeviceProperties, &deviceProp, dev));
if (deviceProp.major == 1 && deviceProp.minor == 0)
m_block_size = 320;
else if (deviceProp.major == 1 && deviceProp.minor == 1)
m_block_size = 256;
else if (deviceProp.major == 1 && deviceProp.minor < 4)
m_block_size = 384;
else
{
cout << "***Warning! Unknown compute " << deviceProp.major << "." << deviceProp.minor << " when tuning block size for LJForceComputeGPU" << endl;
m_block_size = 64;
}
// ulf workaround setup
#ifndef DISABLE_ULF_WORKAROUND
// the ULF workaround is needed on GTX280 and older GPUS
// it is not needed on C1060, S1070, GTX285, GTX295, and (hopefully) newer ones
m_ulf_workaround = true;
if (deviceProp.major == 1 && deviceProp.minor >= 3)
m_ulf_workaround = false;
if (string(deviceProp.name) == "GTX 280")
m_ulf_workaround = true;
if (m_ulf_workaround)
cout << "Notice: ULF bug workaround enabled for LJForceComputeGPU" << endl;
#else
m_ulf_workaround = false;
#endif
// allocate the coeff data on the GPU
int nbytes = sizeof(float2)*m_pdata->getNTypes()*m_pdata->getNTypes();
d_coeffs.resize(exec_conf.gpu.size());
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
exec_conf.gpu[cur_gpu]->setTag(__FILE__, __LINE__);
exec_conf.gpu[cur_gpu]->call(bind(cudaMalloc, (void **)((void *)&d_coeffs[cur_gpu]), nbytes));
assert(d_coeffs[cur_gpu]);
exec_conf.gpu[cur_gpu]->call(bind(cudaMemset, (void *)d_coeffs[cur_gpu], 0, nbytes));
}
// allocate the coeff data on the CPU
h_coeffs = new float2[m_pdata->getNTypes()*m_pdata->getNTypes()];
}
LJForceComputeGPU::~LJForceComputeGPU()
{
// free the coefficients on the GPU
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
assert(d_coeffs[cur_gpu]);
exec_conf.gpu[cur_gpu]->call(bind(cudaFree, (void *)d_coeffs[cur_gpu]));
}
delete[] h_coeffs;
}
/*! \param block_size Size of the block to run on the device
Performance of the code may be dependant on the block size run
on the GPU. \a block_size should be set to be a multiple of 32.
*/
void LJForceComputeGPU::setBlockSize(int block_size)
{
m_block_size = block_size;
}
/*! \post The parameters \a lj1 and \a lj2 are set for the pairs \a typ1, \a typ2 and \a typ2, \a typ1.
\note \a lj? are low level parameters used in the calculation. In order to specify
these for a normal lennard jones formula (with alpha), they should be set to the following.
- \a lj1 = 4.0 * epsilon * pow(sigma,12.0)
- \a lj2 = alpha * 4.0 * epsilon * pow(sigma,6.0);
Setting the parameters for typ1,typ2 automatically sets the same parameters for typ2,typ1: there
is no need to call this funciton for symmetric pairs. Any pairs that this function is not called
for will have lj1 and lj2 set to 0.0.
\param typ1 Specifies one type of the pair
\param typ2 Specifies the second type of the pair
\param lj1 First parameter used to calcluate forces
\param lj2 Second parameter used to calculate forces
*/
void LJForceComputeGPU::setParams(unsigned int typ1, unsigned int typ2, Scalar lj1, Scalar lj2)
{
assert(h_coeffs);
if (typ1 >= m_ntypes || typ2 >= m_ntypes)
{
cerr << endl << "***Error! Trying to set LJ params for a non existant type! " << typ1 << "," << typ2 << endl << endl;
throw runtime_error("LJForceComputeGpu::setParams argument error");
}
// set coeffs in both symmetric positions in the matrix
h_coeffs[typ1*m_pdata->getNTypes() + typ2] = make_float2(lj1, lj2);
h_coeffs[typ2*m_pdata->getNTypes() + typ1] = make_float2(lj1, lj2);
int nbytes = sizeof(float2)*m_pdata->getNTypes()*m_pdata->getNTypes();
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->call(bind(cudaMemcpy, d_coeffs[cur_gpu], h_coeffs, nbytes, cudaMemcpyHostToDevice));
}
/*! \post The lennard jones forces are computed for the given timestep on the GPU.
The neighborlist's compute method is called to ensure that it is up to date
before forces are computed.
\param timestep Current time step of the simulation
Calls gpu_compute_lj_forces to do the dirty work.
*/
void LJForceComputeGPU::computeForces(unsigned int timestep)
{
// start by updating the neighborlist
m_nlist->compute(timestep);
// start the profile
if (m_prof) m_prof->push(exec_conf, "LJ pair");
// The GPU implementation CANNOT handle a half neighborlist, error out now
bool third_law = m_nlist->getStorageMode() == NeighborList::half;
if (third_law)
{
cerr << endl << "***Error! LJForceComputeGPU cannot handle a half neighborlist" << endl << endl;
throw runtime_error("Error computing forces in LJForceComputeGPU");
}
// access the neighbor list, which just selects the neighborlist into the device's memory, copying
// it there if needed
vector<gpu_nlist_array>& nlist = m_nlist->getListGPU();
// access the particle data
vector<gpu_pdata_arrays>& pdata = m_pdata->acquireReadOnlyGPU();
gpu_boxsize box = m_pdata->getBoxGPU();
// run the kernel on all GPUs in parallel
exec_conf.tagAll(__FILE__, __LINE__);
lj_options opt;
opt.r_cutsq = m_r_cut * m_r_cut;
opt.block_size = m_block_size;
opt.xplor_fraction = m_xplor_fraction;
opt.ulf_workaround = m_ulf_workaround;
opt.shift_mode = m_shift_mode;
opt.slj = m_slj;
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->callAsync(bind(gpu_compute_lj_forces, m_gpu_forces[cur_gpu].d_data, pdata[cur_gpu], box, nlist[cur_gpu], d_coeffs[cur_gpu], m_pdata->getNTypes(), opt));
exec_conf.syncAll();
m_pdata->release();
// the force data is now only up to date on the gpu
m_data_location = gpu;
Scalar avg_neigh = m_nlist->estimateNNeigh();
int64_t n_calc = int64_t(avg_neigh * m_pdata->getN());
int64_t mem_transfer = m_pdata->getN() * (4 + 16 + 20) + n_calc * (4 + 16);
int64_t flops = n_calc * (3+12+5+2+2+6+3+2+7);
if (m_prof) m_prof->pop(exec_conf, flops, mem_transfer);
}
void export_LJForceComputeGPU()
{
class_<LJForceComputeGPU, boost::shared_ptr<LJForceComputeGPU>, bases<LJForceCompute>, boost::noncopyable >
("LJForceComputeGPU", init< boost::shared_ptr<SystemDefinition>, boost::shared_ptr<NeighborList>, Scalar >(), bool >())
.def("setBlockSize", &LJForceComputeGPU::setBlockSize)
;
}
#ifdef WIN32
#pragma warning( pop )
#endif
<commit_msg>fixed a little oopsie in the LJ GPU code.<commit_after>/*
Highly Optimized Object-Oriented Molecular Dynamics (HOOMD) Open
Source Software License
Copyright (c) 2008 Ames Laboratory Iowa State University
All rights reserved.
Redistribution and use of HOOMD, in source and binary forms, with or
without modification, are permitted, provided that the following
conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names HOOMD's
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
Disclaimer
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND
CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
*/
// $Id$
// $URL$
/*! \file LJForceComputeGPU.cc
\brief Defines the LJForceComputeGPU class
*/
#ifdef WIN32
#pragma warning( push )
#pragma warning( disable : 4103 4244 )
#endif
#include "LJForceComputeGPU.h"
#include "cuda_runtime.h"
#include <stdexcept>
#include <boost/python.hpp>
using namespace boost::python;
#include <boost/bind.hpp>
using namespace boost;
using namespace std;
/*! \param sysdef System to compute forces on
\param nlist Neighborlist to use for computing the forces
\param r_cut Cuttoff radius beyond which the force is 0
\param slj Determines if Diameter Shifted LJ potential is being used
\post memory is allocated and all parameters lj1 and lj2 are set to 0.0
\note The LJForceComputeGPU does not own the Neighborlist, the caller should
delete the neighborlist when done.
*/
LJForceComputeGPU::LJForceComputeGPU(boost::shared_ptr<SystemDefinition> sysdef, boost::shared_ptr<NeighborList> nlist, Scalar r_cut)
: LJForceCompute(sysdef, nlist, r_cut)
{
// can't run on the GPU if there aren't any GPUs in the execution configuration
if (exec_conf.gpu.size() == 0)
{
cerr << endl << "***Error! Creating a LJForceComputeGPU with no GPU in the execution configuration" << endl << endl;
throw std::runtime_error("Error initializing LJForceComputeGPU");
}
if (m_ntypes > 44)
{
cerr << endl << "***Error! LJForceComputeGPU cannot handle " << m_ntypes << " types" << endl << endl;
throw runtime_error("Error initializing LJForceComputeGPU");
}
// default block size is the highest performance in testing on different hardware
// choose based on compute capability of the device
cudaDeviceProp deviceProp;
int dev;
exec_conf.gpu[0]->call(bind(cudaGetDevice, &dev));
exec_conf.gpu[0]->call(bind(cudaGetDeviceProperties, &deviceProp, dev));
if (deviceProp.major == 1 && deviceProp.minor == 0)
m_block_size = 320;
else if (deviceProp.major == 1 && deviceProp.minor == 1)
m_block_size = 256;
else if (deviceProp.major == 1 && deviceProp.minor < 4)
m_block_size = 384;
else
{
cout << "***Warning! Unknown compute " << deviceProp.major << "." << deviceProp.minor << " when tuning block size for LJForceComputeGPU" << endl;
m_block_size = 64;
}
// ulf workaround setup
#ifndef DISABLE_ULF_WORKAROUND
// the ULF workaround is needed on GTX280 and older GPUS
// it is not needed on C1060, S1070, GTX285, GTX295, and (hopefully) newer ones
m_ulf_workaround = true;
if (deviceProp.major == 1 && deviceProp.minor >= 3)
m_ulf_workaround = false;
if (string(deviceProp.name) == "GTX 280")
m_ulf_workaround = true;
if (m_ulf_workaround)
cout << "Notice: ULF bug workaround enabled for LJForceComputeGPU" << endl;
#else
m_ulf_workaround = false;
#endif
// allocate the coeff data on the GPU
int nbytes = sizeof(float2)*m_pdata->getNTypes()*m_pdata->getNTypes();
d_coeffs.resize(exec_conf.gpu.size());
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
exec_conf.gpu[cur_gpu]->setTag(__FILE__, __LINE__);
exec_conf.gpu[cur_gpu]->call(bind(cudaMalloc, (void **)((void *)&d_coeffs[cur_gpu]), nbytes));
assert(d_coeffs[cur_gpu]);
exec_conf.gpu[cur_gpu]->call(bind(cudaMemset, (void *)d_coeffs[cur_gpu], 0, nbytes));
}
// allocate the coeff data on the CPU
h_coeffs = new float2[m_pdata->getNTypes()*m_pdata->getNTypes()];
}
LJForceComputeGPU::~LJForceComputeGPU()
{
// free the coefficients on the GPU
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
{
assert(d_coeffs[cur_gpu]);
exec_conf.gpu[cur_gpu]->call(bind(cudaFree, (void *)d_coeffs[cur_gpu]));
}
delete[] h_coeffs;
}
/*! \param block_size Size of the block to run on the device
Performance of the code may be dependant on the block size run
on the GPU. \a block_size should be set to be a multiple of 32.
*/
void LJForceComputeGPU::setBlockSize(int block_size)
{
m_block_size = block_size;
}
/*! \post The parameters \a lj1 and \a lj2 are set for the pairs \a typ1, \a typ2 and \a typ2, \a typ1.
\note \a lj? are low level parameters used in the calculation. In order to specify
these for a normal lennard jones formula (with alpha), they should be set to the following.
- \a lj1 = 4.0 * epsilon * pow(sigma,12.0)
- \a lj2 = alpha * 4.0 * epsilon * pow(sigma,6.0);
Setting the parameters for typ1,typ2 automatically sets the same parameters for typ2,typ1: there
is no need to call this funciton for symmetric pairs. Any pairs that this function is not called
for will have lj1 and lj2 set to 0.0.
\param typ1 Specifies one type of the pair
\param typ2 Specifies the second type of the pair
\param lj1 First parameter used to calcluate forces
\param lj2 Second parameter used to calculate forces
*/
void LJForceComputeGPU::setParams(unsigned int typ1, unsigned int typ2, Scalar lj1, Scalar lj2)
{
assert(h_coeffs);
if (typ1 >= m_ntypes || typ2 >= m_ntypes)
{
cerr << endl << "***Error! Trying to set LJ params for a non existant type! " << typ1 << "," << typ2 << endl << endl;
throw runtime_error("LJForceComputeGpu::setParams argument error");
}
// set coeffs in both symmetric positions in the matrix
h_coeffs[typ1*m_pdata->getNTypes() + typ2] = make_float2(lj1, lj2);
h_coeffs[typ2*m_pdata->getNTypes() + typ1] = make_float2(lj1, lj2);
int nbytes = sizeof(float2)*m_pdata->getNTypes()*m_pdata->getNTypes();
exec_conf.tagAll(__FILE__, __LINE__);
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->call(bind(cudaMemcpy, d_coeffs[cur_gpu], h_coeffs, nbytes, cudaMemcpyHostToDevice));
}
/*! \post The lennard jones forces are computed for the given timestep on the GPU.
The neighborlist's compute method is called to ensure that it is up to date
before forces are computed.
\param timestep Current time step of the simulation
Calls gpu_compute_lj_forces to do the dirty work.
*/
void LJForceComputeGPU::computeForces(unsigned int timestep)
{
// start by updating the neighborlist
m_nlist->compute(timestep);
// start the profile
if (m_prof) m_prof->push(exec_conf, "LJ pair");
// The GPU implementation CANNOT handle a half neighborlist, error out now
bool third_law = m_nlist->getStorageMode() == NeighborList::half;
if (third_law)
{
cerr << endl << "***Error! LJForceComputeGPU cannot handle a half neighborlist" << endl << endl;
throw runtime_error("Error computing forces in LJForceComputeGPU");
}
// access the neighbor list, which just selects the neighborlist into the device's memory, copying
// it there if needed
vector<gpu_nlist_array>& nlist = m_nlist->getListGPU();
// access the particle data
vector<gpu_pdata_arrays>& pdata = m_pdata->acquireReadOnlyGPU();
gpu_boxsize box = m_pdata->getBoxGPU();
// run the kernel on all GPUs in parallel
exec_conf.tagAll(__FILE__, __LINE__);
lj_options opt;
opt.r_cutsq = m_r_cut * m_r_cut;
opt.block_size = m_block_size;
opt.xplor_fraction = m_xplor_fraction;
opt.ulf_workaround = m_ulf_workaround;
opt.shift_mode = m_shift_mode;
opt.slj = m_slj;
for (unsigned int cur_gpu = 0; cur_gpu < exec_conf.gpu.size(); cur_gpu++)
exec_conf.gpu[cur_gpu]->callAsync(bind(gpu_compute_lj_forces, m_gpu_forces[cur_gpu].d_data, pdata[cur_gpu], box, nlist[cur_gpu], d_coeffs[cur_gpu], m_pdata->getNTypes(), opt));
exec_conf.syncAll();
m_pdata->release();
// the force data is now only up to date on the gpu
m_data_location = gpu;
Scalar avg_neigh = m_nlist->estimateNNeigh();
int64_t n_calc = int64_t(avg_neigh * m_pdata->getN());
int64_t mem_transfer = m_pdata->getN() * (4 + 16 + 20) + n_calc * (4 + 16);
int64_t flops = n_calc * (3+12+5+2+2+6+3+2+7);
if (m_prof) m_prof->pop(exec_conf, flops, mem_transfer);
}
void export_LJForceComputeGPU()
{
class_<LJForceComputeGPU, boost::shared_ptr<LJForceComputeGPU>, bases<LJForceCompute>, boost::noncopyable >
("LJForceComputeGPU", init< boost::shared_ptr<SystemDefinition>, boost::shared_ptr<NeighborList>, Scalar >())
.def("setBlockSize", &LJForceComputeGPU::setBlockSize)
;
}
#ifdef WIN32
#pragma warning( pop )
#endif
<|endoftext|>
|
<commit_before>#include "Makefile.hpp"
#include <configure/BuildGraph.hpp>
#include <configure/Build.hpp>
#include <configure/Command.hpp>
#include <configure/Filesystem.hpp>
#include <configure/Graph.hpp>
#include <configure/quote.hpp>
#include <configure/utils/path.hpp>
#include <configure/PropertyMap.hpp>
#include <configure/log.hpp>
#include <configure/Rule.hpp>
#include <configure/ShellCommand.hpp>
#include <configure/error.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include <unordered_set>
namespace configure { namespace generators {
Makefile::Makefile(Build& build,
path_t project_directory,
path_t configure_exe,
char const* name)
: Generator(
build,
std::move(project_directory),
std::move(configure_exe),
(name == nullptr ? Makefile::name() : name)
)
{}
static std::string relative_node_path(Build& b, Node& n)
{ return n.relative_path(b.directory()).string(); }
static std::string absolute_node_path(Build&, Node& n)
{ return n.path().string(); }
void Makefile::prepare()
{
BuildGraph const& bg = _build.build_graph();
Graph const& g = bg.graph();
for (auto vertex_range = boost::vertices(g);
vertex_range.first != vertex_range.second;
++vertex_range.first)
{
auto vertex = *vertex_range.first;
auto& node = bg.node(vertex);
if (node->is_virtual())
{
if (!node->name().empty())
_virtual_nodes.push_back(node);
}
else
{
// Check for nodes that are not generated by us (no inputs).
// (this does not apply to virtual nodes, that always
// considered as targets).
auto in_edge_range = boost::in_edges(vertex, g);
if (in_edge_range.first == in_edge_range.second)
{
_sources.push_back(node);
continue;
}
}
// At this point we know that the node is a target.
_targets.push_back(node);
auto out_edge_range = boost::out_edges(vertex, g);
if (out_edge_range.first == out_edge_range.second)
{
// Nothing depends on this node, this target is final.
_final_targets.push_back(node);
}
else
{
// Something depends on this Node, it is a also a source.
if (!node->is_virtual())
_sources.push_back(node);
// The node is still considered final if the root node depends
// on it.
if (bg.has_link(*_build.root_node(), *node))
_final_targets.push_back(node);
}
}
for (auto& node: _sources)
{
if (!node->is_file() || !node->has_property("language"))
continue;
auto& lang = node->property<std::string>("language");
if (lang == "c" || lang == "c++")
{
auto include_directories = node->property<std::vector<boost::filesystem::path>>("include_directories");
NodePtr first_target;
for (auto out_edge_range = boost::out_edges(node->index, g);
out_edge_range.first != out_edge_range.second;
++out_edge_range.first)
{
first_target = bg.node(boost::target(*out_edge_range.first, g));
break;
}
if (first_target == nullptr)
{
log::warning("Ignore implicit dependencies for",
node->string(), ", no target node found...");
continue;
}
auto& target = _build.target_node(
first_target->relative_path(_build.directory()).string() + ".mk"
);
_dependencies.push_back(target);
ShellCommand cmd;
cmd.append(
_configure_exe, "-E" , "c-header-dependencies",
target, node
);
for (auto out_edge_range = boost::out_edges(node->index, g);
out_edge_range.first != out_edge_range.second;
++out_edge_range.first)
cmd.append(bg.node(boost::target(*out_edge_range.first, g)));
cmd.append("--");
for (auto& dir: include_directories)
cmd.append(_build.directory_node(dir));
_build.add_rule(
Rule()
.add_source(node)
.add_target(target)
.add_shell_command(std::move(cmd))
);
}
}
// We still need to add dependencies to the final targets
for (auto& node: _dependencies)
_targets.push_back(node);
}
namespace {
struct RelativePathShellFormatter
: public ShellFormatter
{
boost::filesystem::path const& _build_dir;
boost::filesystem::path const& _project_dir;
RelativePathShellFormatter(Build& build,
boost::filesystem::path const& project_dir)
: _build_dir(build.directory())
, _project_dir(project_dir)
{}
std::string
operator ()(boost::filesystem::path const& value) const override
{
if (utils::starts_with(value, _project_dir))
return utils::relative_path(value, _build_dir).string();
return value.string();
}
};
}
void Makefile::generate() const
{
bool use_relpath = _build.option<bool>(
"GENERATOR_" + std::string(this->name()) + "_USE_RELATIVE_PATH",
std::string(this->name()) + " generator uses relative path",
this->use_relative_path()
);
std::unique_ptr<ShellFormatter> formatter;
if (use_relpath)
formatter = std::unique_ptr<ShellFormatter>(
new RelativePathShellFormatter(_build, _project_directory)
);
else
formatter = std::unique_ptr<ShellFormatter>(new ShellFormatter);
std::string (*node_path)(Build&, Node&);
if (use_relpath)
node_path = &relative_node_path;
else
node_path = &absolute_node_path;
std::ofstream out((_build.directory() / "Makefile").string());
out << "# Generated makefile" << std::endl;
if (_name == "Makefile")
{
// This speed up the makefile
out << "MAKEFLAGS += --no-builtin-rules" << std::endl;
out << ".SUFFIXES:" << std::endl;
}
BuildGraph const& bg = _build.build_graph();
Graph const& g = bg.graph();
// Fill the "all" and ".PHONY" rules
out << ".PHONY:" << std::endl;
out << ".PHONY: all";
for (auto node: _virtual_nodes)
out << ' ' << node->name();
out << "\n\n";
if (!_final_targets.empty())
{
out << "all:";
for (auto& node: _final_targets)
{
if (node->is_file())
out << ' ' << node_path(_build, *node);
else if (node->is_virtual() && !node->name().empty())
out << ' ' << node->name();
}
out << "\n\n";
out << "clean:\n";
for (auto& node: _targets)
if (node->is_file())
out << '\t' << "rm -f " << node_path(_build, *node) << '\n';
out << "\n";
}
std::unordered_set<Node const*> to_delete;
for (auto& node: _targets)
{
if (node->is_virtual())
out << node->name() << ':';
else
out << node_path(_build, *node) << ':';
auto in_edge_range = boost::in_edges(node->index, g);
for (GraphTraits::in_edge_iterator i = in_edge_range.first;
i != in_edge_range.second; ++i)
{
auto node = bg.node(boost::source(*i, g)).get();
if (node->is_file())
out << ' ' << node_path(_build, *node);
else if (node->is_virtual())
out << ' ' << node->name();
}
out << std::endl;
std::vector<std::string> command_strings;
std::unordered_set<Command const*> seen_commands;
for (; in_edge_range.first != in_edge_range.second;
++in_edge_range.first)
{
auto& link = bg.link(*in_edge_range.first);
Command const* cmd_ptr = &link.command();
if (seen_commands.insert(cmd_ptr).second == false)
continue;
for (auto const& shell_command: cmd_ptr->shell_commands())
{
command_strings.push_back(
this->dump_command(
shell_command.string(_build, link, *formatter)
)
);
out << '\t' << command_strings.back() << std::endl;
}
}
out << std::endl;
if (node->is_file())
{
node->set_property<std::string>(
std::string(this->name()) + "_GENERATED_COMMANDS",
boost::join(command_strings, "\n")
);
if (node->properties().dirty())
to_delete.insert(node.get());
}
}
for (auto node: to_delete)
{
log::verbose("Deleting node", node->string(), "(command line changed)");
try {
boost::filesystem::remove(node->path());
} catch (...) {
log::warning("Couldn't remove", node->string(), ":", error_string());
}
}
for (auto& node: _dependencies)
out << "-include " << node_path(_build, *node) << std::endl;
}
std::string Makefile::dump_command(std::vector<std::string> const& cmd) const
{
#ifdef _WIN32
if (cmd.size() == 1)
{
// Workaroung a bug in GNU Make, when commands contain a double quote
// they are spawned through CreateProcess() as 'sh -c \"COMMAND HERE\"'
// when the argument does have any special character other than slash
// and there is only one argument, quotes are left ...
auto res = quote<CommandParser::make>(cmd);
if (res[0] == '"' && res.back() == '"' )
{
res = res.substr(1, res.size() - 2);
}
return res;
}
#endif
return quote<CommandParser::make>(cmd);
}
bool Makefile::is_available(Build& build)
{ return build.fs().which("make") != boost::none; }
std::vector<std::string>
Makefile::build_command(std::string const& target) const
{
return {
"make", "-C", _build.directory().string(),
target.empty() ? "all" : target
};
}
bool Makefile::use_relative_path() const { return true; }
}}
<commit_msg>Discard empty virtual nodes.<commit_after>#include "Makefile.hpp"
#include <configure/BuildGraph.hpp>
#include <configure/Build.hpp>
#include <configure/Command.hpp>
#include <configure/Filesystem.hpp>
#include <configure/Graph.hpp>
#include <configure/quote.hpp>
#include <configure/utils/path.hpp>
#include <configure/PropertyMap.hpp>
#include <configure/log.hpp>
#include <configure/Rule.hpp>
#include <configure/ShellCommand.hpp>
#include <configure/error.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include <unordered_set>
namespace configure { namespace generators {
Makefile::Makefile(Build& build,
path_t project_directory,
path_t configure_exe,
char const* name)
: Generator(
build,
std::move(project_directory),
std::move(configure_exe),
(name == nullptr ? Makefile::name() : name)
)
{}
static std::string relative_node_path(Build& b, Node& n)
{ return n.relative_path(b.directory()).string(); }
static std::string absolute_node_path(Build&, Node& n)
{ return n.path().string(); }
void Makefile::prepare()
{
BuildGraph const& bg = _build.build_graph();
Graph const& g = bg.graph();
for (auto vertex_range = boost::vertices(g);
vertex_range.first != vertex_range.second;
++vertex_range.first)
{
auto vertex = *vertex_range.first;
auto& node = bg.node(vertex);
if (node->is_virtual())
{
if (node->name().empty())
continue;
_virtual_nodes.push_back(node);
}
else
{
// Check for nodes that are not generated by us (no inputs).
// (this does not apply to virtual nodes, that always
// considered as targets).
auto in_edge_range = boost::in_edges(vertex, g);
if (in_edge_range.first == in_edge_range.second)
{
_sources.push_back(node);
continue;
}
}
// At this point we know that the node is a target.
_targets.push_back(node);
auto out_edge_range = boost::out_edges(vertex, g);
if (out_edge_range.first == out_edge_range.second)
{
// Nothing depends on this node, this target is final.
_final_targets.push_back(node);
}
else
{
// Something depends on this Node, it is a also a source.
if (!node->is_virtual())
_sources.push_back(node);
// The node is still considered final if the root node depends
// on it.
if (bg.has_link(*_build.root_node(), *node))
_final_targets.push_back(node);
}
}
for (auto& node: _sources)
{
if (!node->is_file() || !node->has_property("language"))
continue;
auto& lang = node->property<std::string>("language");
if (lang == "c" || lang == "c++")
{
auto include_directories = node->property<std::vector<boost::filesystem::path>>("include_directories");
NodePtr first_target;
for (auto out_edge_range = boost::out_edges(node->index, g);
out_edge_range.first != out_edge_range.second;
++out_edge_range.first)
{
first_target = bg.node(boost::target(*out_edge_range.first, g));
break;
}
if (first_target == nullptr)
{
log::warning("Ignore implicit dependencies for",
node->string(), ", no target node found...");
continue;
}
auto& target = _build.target_node(
first_target->relative_path(_build.directory()).string() + ".mk"
);
_dependencies.push_back(target);
ShellCommand cmd;
cmd.append(
_configure_exe, "-E" , "c-header-dependencies",
target, node
);
for (auto out_edge_range = boost::out_edges(node->index, g);
out_edge_range.first != out_edge_range.second;
++out_edge_range.first)
cmd.append(bg.node(boost::target(*out_edge_range.first, g)));
cmd.append("--");
for (auto& dir: include_directories)
cmd.append(_build.directory_node(dir));
_build.add_rule(
Rule()
.add_source(node)
.add_target(target)
.add_shell_command(std::move(cmd))
);
}
}
// We still need to add dependencies to the final targets
for (auto& node: _dependencies)
_targets.push_back(node);
}
namespace {
struct RelativePathShellFormatter
: public ShellFormatter
{
boost::filesystem::path const& _build_dir;
boost::filesystem::path const& _project_dir;
RelativePathShellFormatter(Build& build,
boost::filesystem::path const& project_dir)
: _build_dir(build.directory())
, _project_dir(project_dir)
{}
std::string
operator ()(boost::filesystem::path const& value) const override
{
if (utils::starts_with(value, _project_dir))
return utils::relative_path(value, _build_dir).string();
return value.string();
}
};
}
void Makefile::generate() const
{
bool use_relpath = _build.option<bool>(
"GENERATOR_" + std::string(this->name()) + "_USE_RELATIVE_PATH",
std::string(this->name()) + " generator uses relative path",
this->use_relative_path()
);
std::unique_ptr<ShellFormatter> formatter;
if (use_relpath)
formatter = std::unique_ptr<ShellFormatter>(
new RelativePathShellFormatter(_build, _project_directory)
);
else
formatter = std::unique_ptr<ShellFormatter>(new ShellFormatter);
std::string (*node_path)(Build&, Node&);
if (use_relpath)
node_path = &relative_node_path;
else
node_path = &absolute_node_path;
std::ofstream out((_build.directory() / "Makefile").string());
out << "# Generated makefile" << std::endl;
if (_name == "Makefile")
{
// This speed up the makefile
out << "MAKEFLAGS += --no-builtin-rules" << std::endl;
out << ".SUFFIXES:" << std::endl;
}
BuildGraph const& bg = _build.build_graph();
Graph const& g = bg.graph();
// Fill the "all" and ".PHONY" rules
out << ".PHONY:" << std::endl;
out << ".PHONY: all";
for (auto node: _virtual_nodes)
out << ' ' << node->name();
out << "\n\n";
if (!_final_targets.empty())
{
out << "all:";
for (auto& node: _final_targets)
{
if (node->is_file())
out << ' ' << node_path(_build, *node);
else if (node->is_virtual() && !node->name().empty())
out << ' ' << node->name();
}
out << "\n\n";
out << "clean:\n";
for (auto& node: _targets)
if (node->is_file())
out << '\t' << "rm -f " << node_path(_build, *node) << '\n';
out << "\n";
}
std::unordered_set<Node const*> to_delete;
for (auto& node: _targets)
{
if (node->is_virtual())
out << node->name() << ':';
else
out << node_path(_build, *node) << ':';
auto in_edge_range = boost::in_edges(node->index, g);
for (GraphTraits::in_edge_iterator i = in_edge_range.first;
i != in_edge_range.second; ++i)
{
auto node = bg.node(boost::source(*i, g)).get();
if (node->is_file())
out << ' ' << node_path(_build, *node);
else if (node->is_virtual())
out << ' ' << node->name();
}
out << std::endl;
std::vector<std::string> command_strings;
std::unordered_set<Command const*> seen_commands;
for (; in_edge_range.first != in_edge_range.second;
++in_edge_range.first)
{
auto& link = bg.link(*in_edge_range.first);
Command const* cmd_ptr = &link.command();
if (seen_commands.insert(cmd_ptr).second == false)
continue;
for (auto const& shell_command: cmd_ptr->shell_commands())
{
command_strings.push_back(
this->dump_command(
shell_command.string(_build, link, *formatter)
)
);
out << '\t' << command_strings.back() << std::endl;
}
}
out << std::endl;
if (node->is_file())
{
node->set_property<std::string>(
std::string(this->name()) + "_GENERATED_COMMANDS",
boost::join(command_strings, "\n")
);
if (node->properties().dirty())
to_delete.insert(node.get());
}
}
for (auto node: to_delete)
{
log::verbose("Deleting node", node->string(), "(command line changed)");
try {
boost::filesystem::remove(node->path());
} catch (...) {
log::warning("Couldn't remove", node->string(), ":", error_string());
}
}
for (auto& node: _dependencies)
out << "-include " << node_path(_build, *node) << std::endl;
}
std::string Makefile::dump_command(std::vector<std::string> const& cmd) const
{
#ifdef _WIN32
if (cmd.size() == 1)
{
// Workaroung a bug in GNU Make, when commands contain a double quote
// they are spawned through CreateProcess() as 'sh -c \"COMMAND HERE\"'
// when the argument does have any special character other than slash
// and there is only one argument, quotes are left ...
auto res = quote<CommandParser::make>(cmd);
if (res[0] == '"' && res.back() == '"' )
{
res = res.substr(1, res.size() - 2);
}
return res;
}
#endif
return quote<CommandParser::make>(cmd);
}
bool Makefile::is_available(Build& build)
{ return build.fs().which("make") != boost::none; }
std::vector<std::string>
Makefile::build_command(std::string const& target) const
{
return {
"make", "-C", _build.directory().string(),
target.empty() ? "all" : target
};
}
bool Makefile::use_relative_path() const { return true; }
}}
<|endoftext|>
|
<commit_before>// g++ j.cc -o j -L/usr/local/lib -lroaring
#include <iostream>
#include <vector>
#include <string>
#include <array>
#include <map>
#include "roaring.hh"
enum FieldType {
TIMESTAMP,
DIMENSION,
BOOL,
METRIC_INT,
METRIC_FLOAT
};
class FieldBase {};
template <FieldType, typename T>
class Field : FieldBase {
private:
std::string name;
std::vector<T> vals;
std::vector< std::vector<T> > mvals;
std::map<T, Roaring *> dict_;
Roaring *roar_;
int count_;
FieldType type_;
public:
Field(std::string name);
void insert(T &val);
std::map<std::string, Roaring *> &dict();
Roaring *roar() {
return roar_;
}
};
template <FieldType type, typename T>
Field<type, T>::Field(std::string name):
type_(type), name(name) {
switch (type) {
case METRIC_INT:
case METRIC_FLOAT: {
} break;
default:
throw std::runtime_error("invalid field type for Field<>");
}
}
template <>
Field<DIMENSION, std::string>::Field(std::string name):
type_(DIMENSION), name(name) {
// switch (type) {
// case DIMENSION: {
// } break;
// default:
// throw std::runtime_error("invalid field type for string");
// }
}
template <>
Field<TIMESTAMP, int64_t>::Field(std::string name):
type_(TIMESTAMP), name(name) {
// switch (type) {
// case TIMESTAMP: {
// } break;
// default:
// throw std::runtime_error("invalid field type for int64");
// }
}
template <>
Field<BOOL, bool>::Field(std::string name):
type_(BOOL), name(name) {
roar_ = new Roaring();
// switch (type) {
// case BOOL: {
// roar_ = new Roaring();
// } break;
// default:
// throw std::runtime_error("invalid field type for bool");
// }
}
template <FieldType type, typename T>
void Field<type, T>::insert(T &val) {
switch (type_) {
case TIMESTAMP:
case METRIC_INT:
case METRIC_FLOAT: {
vals.push_back(val);
} break;
case DIMENSION: {
Roaring *roar;
if (dict_.count(val) > 0) {
roar = dict_[val];
} else {
roar = new Roaring();
dict_[val] = roar;
}
roar->add(count_);
} break;
default:
throw std::runtime_error("can not insert val to field with unknown type");
}
count_++;
}
template<>
std::map<std::string, Roaring *> &Field<DIMENSION, std::string>::dict() {
return dict_;
}
class DimensionField {
public:
Field<DIMENSION, std::string> *strdim;
Field<BOOL, bool> *booldim;
bool isBoolDim;
DimensionField(Field<DIMENSION, std::string> *strdim_): strdim(strdim_), isBoolDim(false) {}
DimensionField(Field<BOOL, bool> *booldim_): booldim(booldim_), isBoolDim(true) {}
};
class Query {
private:
public:
Query();
~Query();
};
struct GroupByResult {
std::vector<std::string> key;
Roaring roaring;
};
static void genGroups(std::vector<GroupByResult> &groups, std::vector<std::string> &groupByKeys, std::map<std::string, FieldBase*> &fields, std::vector<std::string> currKey, int index) {
bool genGroup = index == (groupByKeys.size() - 1);
std::string key = groupByKeys[index];
FieldBase *fieldRef = fields[key];
Field<DIMENSION, std::string> *field = (Field<DIMENSION, std::string> *)fieldRef;
std::map<std::string, Roaring *> &dict = field->dict();
for (std::map<std::string, Roaring *>::iterator it = dict.begin(); it != dict.end(); it++) {
std::vector<std::string> groupKey = currKey;
groupKey.push_back(it->first);
if (genGroup) {
GroupByResult gres;
gres.key = groupKey;
groups.push_back(gres);
} else {
genGroups(groups, groupByKeys, fields, groupKey, index + 1);
}
}
}
std::vector<GroupByResult> genGroupByResult(std::vector<std::string> &groupByKeys, std::map<std::string, FieldBase*> &fields) {
std::vector<GroupByResult> groups;
genGroups(groups, groupByKeys, fields, std::vector<std::string>(), 0);
return groups;
}
int main(int argc, char *argv[]) {
Field<TIMESTAMP, int64_t> *timestamp = new Field<TIMESTAMP, int64_t>("timestamp");
Field<DIMENSION, std::string> *publisher = new Field<DIMENSION, std::string>("publisher");
Field<DIMENSION, std::string> *advertiser = new Field<DIMENSION, std::string>("advertiser");
Field<DIMENSION, std::string> *gender = new Field<DIMENSION, std::string>("gender");
Field<DIMENSION, std::string> *country = new Field<DIMENSION, std::string>("country");
Field<BOOL, bool> *click = new Field<BOOL, bool>("click");
Field<METRIC_FLOAT, float> *price = new Field<METRIC_FLOAT, float>("price");
std::map<std::string, FieldBase*> fields;
fields["timestamp"] = (FieldBase*)timestamp;
fields["publisher"] = (FieldBase*)publisher;
fields["advertiser"] = (FieldBase*)advertiser;
fields["gender"] = (FieldBase*)gender;
fields["country"] = (FieldBase*)country;
fields["click"] = (FieldBase*)click;
fields["price"] = (FieldBase*)price;
// select count(*) from logs where click = 1 group by country,gender
{
// generate new bitmap of all elements. so we need segment wide count variable
int count = 3;
Roaring roar(roaring_bitmap_from_range(0, count, 1));
//////////////////////////////////////////////////////////////////////
/////////// FILTERING STATE //////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// do bitwise AND with click = 1
// roar.printf();
roar &= click->roar();
// roar.printf();
//////////////////////////////////////////////////////////////////////
/////////// GROUPING STATE ///////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// generate groups for every group by term
std::vector< GroupByResult > groups;
std::vector<std::string> groupByKeys;
groupByKeys.push_back("advertiser");
groupByKeys.push_back("gender");
groupByKeys.push_back("country");
groups = genGroupByResult(groupByKeys, fields);
for (std::vector< GroupByResult >::iterator it = groups.begin(); it != groups.end(); it++) {
const GroupByResult &gres = *it;
std::vector<std::string> key = gres.key;
for (std::vector<std::string>::iterator it2 = key.begin(); it2 != key.end(); it2++) {
std::cout << *it2;
if (it2 != key.end()) {
std::cout << ", ";
}
}
std::cout << std::endl;
}
}
return 0;
}
<commit_msg>move fields to outside of main<commit_after>// g++ j.cc -o j -L/usr/local/lib -lroaring
#include <iostream>
#include <vector>
#include <string>
#include <array>
#include <map>
#include "roaring.hh"
enum FieldType {
TIMESTAMP,
DIMENSION,
BOOL,
METRIC_INT,
METRIC_FLOAT
};
class FieldBase {};
template <FieldType, typename T>
class Field : FieldBase {
private:
std::string name;
std::vector<T> vals;
std::vector< std::vector<T> > mvals;
std::map<T, Roaring *> dict_;
Roaring *roar_;
int count_;
FieldType type_;
public:
Field(std::string name);
void insert(T &val);
std::map<std::string, Roaring *> &dict();
Roaring *roar() {
return roar_;
}
};
template <FieldType type, typename T>
Field<type, T>::Field(std::string name):
type_(type), name(name) {
switch (type) {
case METRIC_INT:
case METRIC_FLOAT: {
} break;
default:
throw std::runtime_error("invalid field type for Field<>");
}
}
template <>
Field<DIMENSION, std::string>::Field(std::string name):
type_(DIMENSION), name(name) {
// switch (type) {
// case DIMENSION: {
// } break;
// default:
// throw std::runtime_error("invalid field type for string");
// }
}
template <>
Field<TIMESTAMP, int64_t>::Field(std::string name):
type_(TIMESTAMP), name(name) {
// switch (type) {
// case TIMESTAMP: {
// } break;
// default:
// throw std::runtime_error("invalid field type for int64");
// }
}
template <>
Field<BOOL, bool>::Field(std::string name):
type_(BOOL), name(name) {
roar_ = new Roaring();
// switch (type) {
// case BOOL: {
// roar_ = new Roaring();
// } break;
// default:
// throw std::runtime_error("invalid field type for bool");
// }
}
template <FieldType type, typename T>
void Field<type, T>::insert(T &val) {
switch (type_) {
case TIMESTAMP:
case METRIC_INT:
case METRIC_FLOAT: {
vals.push_back(val);
} break;
case DIMENSION: {
Roaring *roar;
if (dict_.count(val) > 0) {
roar = dict_[val];
} else {
roar = new Roaring();
dict_[val] = roar;
}
roar->add(count_);
} break;
default:
throw std::runtime_error("can not insert val to field with unknown type");
}
count_++;
}
template<>
std::map<std::string, Roaring *> &Field<DIMENSION, std::string>::dict() {
return dict_;
}
class DimensionField {
public:
Field<DIMENSION, std::string> *strdim;
Field<BOOL, bool> *booldim;
bool isBoolDim;
DimensionField(Field<DIMENSION, std::string> *strdim_): strdim(strdim_), isBoolDim(false) {}
DimensionField(Field<BOOL, bool> *booldim_): booldim(booldim_), isBoolDim(true) {}
};
class Query {
private:
public:
Query();
~Query();
};
struct GroupByResult {
std::vector<std::string> key;
Roaring roaring;
};
static void genGroups(std::vector<GroupByResult> &groups, std::vector<std::string> &groupByKeys, std::map<std::string, FieldBase*> &fields, std::vector<std::string> currKey, int index) {
bool genGroup = index == (groupByKeys.size() - 1);
std::string key = groupByKeys[index];
FieldBase *fieldRef = fields[key];
Field<DIMENSION, std::string> *field = (Field<DIMENSION, std::string> *)fieldRef;
std::map<std::string, Roaring *> &dict = field->dict();
for (std::map<std::string, Roaring *>::iterator it = dict.begin(); it != dict.end(); it++) {
std::vector<std::string> groupKey = currKey;
groupKey.push_back(it->first);
if (genGroup) {
GroupByResult gres;
gres.key = groupKey;
groups.push_back(gres);
} else {
genGroups(groups, groupByKeys, fields, groupKey, index + 1);
}
}
}
std::vector<GroupByResult> genGroupByResult(std::vector<std::string> &groupByKeys, std::map<std::string, FieldBase*> &fields) {
std::vector<GroupByResult> groups;
genGroups(groups, groupByKeys, fields, std::vector<std::string>(), 0);
return groups;
}
/// global fields
Field<TIMESTAMP, int64_t> *timestamp;
Field<DIMENSION, std::string> *publisher;
Field<DIMENSION, std::string> *advertiser;
Field<DIMENSION, std::string> *gender;
Field<DIMENSION, std::string> *country;
Field<BOOL, bool> *click;
Field<METRIC_FLOAT, float> *price;
int main(int argc, char *argv[]) {
timestamp = new Field<TIMESTAMP, int64_t>("timestamp");
publisher = new Field<DIMENSION, std::string>("publisher");
advertiser = new Field<DIMENSION, std::string>("advertiser");
gender = new Field<DIMENSION, std::string>("gender");
country = new Field<DIMENSION, std::string>("country");
click = new Field<BOOL, bool>("click");
price = new Field<METRIC_FLOAT, float>("price");
std::map<std::string, FieldBase*> fields;
fields["timestamp"] = (FieldBase*)timestamp;
fields["publisher"] = (FieldBase*)publisher;
fields["advertiser"] = (FieldBase*)advertiser;
fields["gender"] = (FieldBase*)gender;
fields["country"] = (FieldBase*)country;
fields["click"] = (FieldBase*)click;
fields["price"] = (FieldBase*)price;
// select count(*) from logs where click = 1 group by country,gender
{
// generate new bitmap of all elements. so we need segment wide count variable
int count = 3;
Roaring roar(roaring_bitmap_from_range(0, count, 1));
//////////////////////////////////////////////////////////////////////
/////////// FILTERING STATE //////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// do bitwise AND with click = 1
// roar.printf();
roar &= click->roar();
// roar.printf();
//////////////////////////////////////////////////////////////////////
/////////// GROUPING STATE ///////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// generate groups for every group by term
std::vector< GroupByResult > groups;
std::vector<std::string> groupByKeys;
groupByKeys.push_back("advertiser");
groupByKeys.push_back("gender");
groupByKeys.push_back("country");
groups = genGroupByResult(groupByKeys, fields);
for (std::vector< GroupByResult >::iterator it = groups.begin(); it != groups.end(); it++) {
const GroupByResult &gres = *it;
std::vector<std::string> key = gres.key;
for (std::vector<std::string>::iterator it2 = key.begin(); it2 != key.end(); it2++) {
std::cout << *it2;
if (it2 != key.end()) {
std::cout << ", ";
}
}
std::cout << std::endl;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <vector>
#include <stack>
#include <algorithm>
#include <memory>
namespace Frogs
{
enum class Frog { None, Brown, Green };
enum class Step { None, JumpLeft, LeapLeft, JumpRight, LeapRight };
class State
{
std::vector<Frog> lilies;
int count, blankPos;
Step movement;
public:
State(): count(0), blankPos(-1), movement(Step::None)
{
}
State(int count): lilies(2 * count + 1), count(count), blankPos(count), movement(Step::None)
{
for (int i = 0; i < count; ++i)
{
lilies[i] = Frog::Brown;
lilies[2 * count - i] = Frog::Green;
}
lilies[blankPos] = Frog::None;
}
bool operator==(const State& other) const
{
return count == other.count && lilies == other.lilies && blankPos == other.blankPos && movement == other.movement;
}
Step GetMovement() const { return movement; }
bool IsStuckJumpLeft() const { return blankPos >= (int)lilies.size() - 1 || lilies[blankPos + 1] != Frog::Green; }
bool IsStuckLeapLeft() const { return blankPos >= (int)lilies.size() - 2 || lilies[blankPos + 2] != Frog::Green; }
bool IsStuckJumpRight() const { return blankPos < 1 || lilies[blankPos - 1] != Frog::Brown; }
bool IsStuckLeapRight() const { return blankPos < 2 || lilies[blankPos - 2] != Frog::Brown; }
bool WasTargetReached() const
{
for (int i = 0; i < count; ++i)
if (lilies[i] != Frog::Green || lilies[2 * count - i] != Frog::Brown)
return false;
return lilies[count] == Frog::None;
};
void Print() const
{
for (const auto& frog: lilies)
switch (frog)
{
case Frog::Brown:
printf(">");
break;
case Frog::Green:
printf("<");
break;
case Frog::None:
printf(" ");
break;
}
printf("\n");
}
std::shared_ptr<State> Move(Step movement) const
{
bool canMove = false;
auto moved = std::make_shared<State>(*this);
moved->movement = movement;
switch (movement)
{
case Step::JumpLeft:
if (!IsStuckJumpLeft())
{
moved->lilies[moved->blankPos] = Frog::Green;
moved->blankPos++;
canMove = true;
}
break;
case Step::LeapLeft:
if (!IsStuckLeapLeft())
{
moved->lilies[moved->blankPos] = Frog::Green;
moved->blankPos += 2;
canMove = true;
}
break;
case Step::JumpRight:
if (!IsStuckJumpRight())
{
moved->lilies[moved->blankPos] = Frog::Brown;
moved->blankPos--;
canMove = true;
}
break;
case Step::LeapRight:
if (!IsStuckLeapRight())
{
moved->lilies[moved->blankPos] = Frog::Brown;
moved->blankPos -= 2;
canMove = true;
}
break;
default:
break;
}
if (canMove)
moved->lilies[moved->blankPos] = Frog::None;
return canMove ? moved : nullptr;
}
std::shared_ptr<State> UndoStep(Step prevMovement) const
{
bool canUndoStep = false;
auto undone = std::make_shared<State>(*this);
switch (movement)
{
case Step::JumpLeft:
undone->lilies[blankPos] = Frog::Green;
undone->blankPos--;
canUndoStep = true;
break;
case Step::LeapLeft:
undone->lilies[blankPos] = Frog::Green;
undone->blankPos -= 2;
canUndoStep = true;
break;
case Step::JumpRight:
undone->lilies[blankPos] = Frog::Brown;
undone->blankPos++;
canUndoStep = true;
break;
case Step::LeapRight:
undone->lilies[blankPos] = Frog::Brown;
undone->blankPos += 2;
canUndoStep = true;
break;
default:
break;
}
if (canUndoStep)
{
undone->lilies[blankPos] = Frog::None;
undone->movement = prevMovement;
}
return canUndoStep ? undone : nullptr;
};
};
}
int main()
{
int count;
scanf("%u", &count);
if (count < 0)
return 1;
std::vector<std::shared_ptr<Frogs::State> > visited;
std::stack<std::shared_ptr<Frogs::State> > trace;
std::stack<Frogs::Step> movements;
trace.push(std::make_shared<Frogs::State>(count));
while (!trace.empty() && !trace.top()->WasTargetReached())
{
auto state = trace.top();
trace.pop();
auto move = [&](Frogs::Step movement)
{
auto newState = state->Move(movement);
if (newState)
trace.push(newState);
};
while (!movements.empty() && state && state->IsStuckJumpLeft() && state->IsStuckLeapLeft() && state->IsStuckJumpRight() && state->IsStuckLeapRight())
{
state = state->UndoStep(movements.top());
movements.pop();
}
if (!state)
continue;
if (std::find(visited.crbegin(), visited.crend(), state) == visited.crend())
{
visited.push_back(state);
movements.push(state->GetMovement());
move(Frogs::Step::JumpLeft);
move(Frogs::Step::LeapLeft);
move(Frogs::Step::JumpRight);
move(Frogs::Step::LeapRight);
state->Print();
}
}
if (!trace.empty())
trace.top()->Print();
return 0;
}
<commit_msg>reordered things around<commit_after>#include <cstdio>
#include <vector>
#include <stack>
#include <algorithm>
#include <memory>
namespace Frogs
{
enum class Frog { None, Brown, Green };
enum class Step { None, JumpLeft, LeapLeft, JumpRight, LeapRight };
class State
{
std::vector<Frog> lilies;
int count, blankPos;
Step movement;
public:
State(): count(0), blankPos(-1), movement(Step::None)
{
}
State(int count): lilies(2 * count + 1), count(count), blankPos(count), movement(Step::None)
{
for (int i = 0; i < count; ++i)
{
lilies[i] = Frog::Brown;
lilies[2 * count - i] = Frog::Green;
}
lilies[blankPos] = Frog::None;
}
Step GetMovement() const { return movement; }
bool operator==(const State& other) const
{
return count == other.count && lilies == other.lilies && blankPos == other.blankPos && movement == other.movement;
}
bool IsStuckJumpLeft() const { return blankPos >= (int)lilies.size() - 1 || lilies[blankPos + 1] != Frog::Green; }
bool IsStuckLeapLeft() const { return blankPos >= (int)lilies.size() - 2 || lilies[blankPos + 2] != Frog::Green; }
bool IsStuckJumpRight() const { return blankPos < 1 || lilies[blankPos - 1] != Frog::Brown; }
bool IsStuckLeapRight() const { return blankPos < 2 || lilies[blankPos - 2] != Frog::Brown; }
bool WasTargetReached() const
{
for (int i = 0; i < count; ++i)
if (lilies[i] != Frog::Green || lilies[2 * count - i] != Frog::Brown)
return false;
return lilies[count] == Frog::None;
}
std::shared_ptr<State> Move(Step movement) const
{
bool canMove = false;
auto moved = std::make_shared<State>(*this);
moved->movement = movement;
switch (movement)
{
case Step::JumpLeft:
if (!IsStuckJumpLeft())
{
moved->lilies[moved->blankPos] = Frog::Green;
moved->blankPos++;
canMove = true;
}
break;
case Step::LeapLeft:
if (!IsStuckLeapLeft())
{
moved->lilies[moved->blankPos] = Frog::Green;
moved->blankPos += 2;
canMove = true;
}
break;
case Step::JumpRight:
if (!IsStuckJumpRight())
{
moved->lilies[moved->blankPos] = Frog::Brown;
moved->blankPos--;
canMove = true;
}
break;
case Step::LeapRight:
if (!IsStuckLeapRight())
{
moved->lilies[moved->blankPos] = Frog::Brown;
moved->blankPos -= 2;
canMove = true;
}
break;
default:
break;
}
if (canMove)
moved->lilies[moved->blankPos] = Frog::None;
return canMove ? moved : nullptr;
}
std::shared_ptr<State> UndoStep(Step prevMovement) const
{
bool canUndoStep = false;
auto undone = std::make_shared<State>(*this);
switch (movement)
{
case Step::JumpLeft:
undone->lilies[blankPos] = Frog::Green;
undone->blankPos--;
canUndoStep = true;
break;
case Step::LeapLeft:
undone->lilies[blankPos] = Frog::Green;
undone->blankPos -= 2;
canUndoStep = true;
break;
case Step::JumpRight:
undone->lilies[blankPos] = Frog::Brown;
undone->blankPos++;
canUndoStep = true;
break;
case Step::LeapRight:
undone->lilies[blankPos] = Frog::Brown;
undone->blankPos += 2;
canUndoStep = true;
break;
default:
break;
}
if (canUndoStep)
{
undone->lilies[blankPos] = Frog::None;
undone->movement = prevMovement;
}
return canUndoStep ? undone : nullptr;
}
void Print() const
{
for (const auto& frog: lilies)
switch (frog)
{
case Frog::Brown:
printf(">");
break;
case Frog::Green:
printf("<");
break;
case Frog::None:
printf(" ");
break;
}
printf("\n");
}
};
}
int main()
{
int count;
scanf("%u", &count);
if (count < 0)
return 1;
std::vector<std::shared_ptr<Frogs::State> > visited;
std::stack<std::shared_ptr<Frogs::State> > trace;
std::stack<Frogs::Step> movements;
trace.push(std::make_shared<Frogs::State>(count));
while (!trace.empty() && !trace.top()->WasTargetReached())
{
auto state = trace.top();
trace.pop();
auto move = [&](Frogs::Step movement)
{
auto newState = state->Move(movement);
if (newState)
trace.push(newState);
};
while (!movements.empty() && state && state->IsStuckJumpLeft() && state->IsStuckLeapLeft() && state->IsStuckJumpRight() && state->IsStuckLeapRight())
{
state = state->UndoStep(movements.top());
movements.pop();
}
if (!state)
continue;
if (std::find(visited.crbegin(), visited.crend(), state) == visited.crend())
{
visited.push_back(state);
movements.push(state->GetMovement());
move(Frogs::Step::JumpLeft);
move(Frogs::Step::LeapLeft);
move(Frogs::Step::JumpRight);
move(Frogs::Step::LeapRight);
state->Print();
}
}
if (!trace.empty())
trace.top()->Print();
return 0;
}
<|endoftext|>
|
<commit_before>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/*
Evaluates the conductivity of surface flow.
Authors: Ethan Coon (ecoon@lanl.gov)
*/
#include "independent_variable_field_evaluator.hh"
#include "overland_conductivity_evaluator.hh"
#include "manning_conductivity_model.hh"
namespace Amanzi {
namespace Flow {
namespace FlowRelations {
OverlandConductivityEvaluator::OverlandConductivityEvaluator(Teuchos::ParameterList& plist) :
SecondaryVariableFieldEvaluator(plist) {
depth_key_ = plist_.get<std::string>("height key", "ponded_depth");
dependencies_.insert(depth_key_);
slope_key_ = plist_.get<std::string>("slope key", "slope_magnitude");
dependencies_.insert(slope_key_);
coef_key_ = plist_.get<std::string>("coefficient key", "manning_coefficient");
dependencies_.insert(coef_key_);
dt_ = plist_.get<bool>("include dt factor", false);
if (dt_) {
factor_ = plist_.get<double>("dt factor");
}
dens_ = plist_.get<bool>("include density factor", true);
if (dens_) {
dens_key_ = plist_.get<std::string>("density key", "surface_molar_density_liquid");
dependencies_.insert(dens_key_);
}
if (my_key_ == std::string("")) {
my_key_ = plist_.get<std::string>("overland conductivity key",
"overland_conductivity");
}
// create the model, hard-coded until we have a 2nd model
ASSERT(plist_.isSublist("overland conductivity model"));
Teuchos::ParameterList sublist = plist_.sublist("overland conductivity model");
model_ = Teuchos::rcp(new ManningConductivityModel(sublist));
}
OverlandConductivityEvaluator::OverlandConductivityEvaluator(const OverlandConductivityEvaluator& other) :
SecondaryVariableFieldEvaluator(other),
depth_key_(other.depth_key_),
slope_key_(other.slope_key_),
coef_key_(other.coef_key_),
dens_key_(other.dens_key_),
dt_(other.dt_),
factor_(other.factor_),
dens_(other.dens_),
model_(other.model_) {}
Teuchos::RCP<FieldEvaluator>
OverlandConductivityEvaluator::Clone() const {
return Teuchos::rcp(new OverlandConductivityEvaluator(*this));
}
// Required methods from SecondaryVariableFieldEvaluator
void OverlandConductivityEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
const Teuchos::Ptr<CompositeVector>& result) {
Teuchos::RCP<const CompositeVector> depth = S->GetFieldData(depth_key_);
Teuchos::RCP<const CompositeVector> slope = S->GetFieldData(slope_key_);
Teuchos::RCP<const CompositeVector> coef = S->GetFieldData(coef_key_);
for (CompositeVector::name_iterator comp=result->begin();
comp!=result->end(); ++comp) {
const Epetra_MultiVector& depth_v = *depth->ViewComponent(*comp,false);
const Epetra_MultiVector& slope_v = *slope->ViewComponent(*comp,false);
const Epetra_MultiVector& coef_v = *coef->ViewComponent(*comp,false);
Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);
int ncomp = result->size(*comp, false);
if (dt_) {
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] = model_->Conductivity(factor_*depth_v[0][i], slope_v[0][i], coef_v[0][i]);
}
} else {
// double dt = *S->GetScalarData("dt");
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] = model_->Conductivity(depth_v[0][i], slope_v[0][i], coef_v[0][i]);
}
}
if (dens_) {
const Epetra_MultiVector& dens_v = *S->GetFieldData(dens_key_)->ViewComponent(*comp,false);
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] *= dens_v[0][i];
}
}
}
}
void OverlandConductivityEvaluator::EvaluateFieldPartialDerivative_(
const Teuchos::Ptr<State>& S,
Key wrt_key, const Teuchos::Ptr<CompositeVector>& result) {
Teuchos::RCP<const CompositeVector> depth = S->GetFieldData(depth_key_);
Teuchos::RCP<const CompositeVector> slope = S->GetFieldData(slope_key_);
Teuchos::RCP<const CompositeVector> coef = S->GetFieldData(coef_key_);
if (wrt_key == depth_key_) {
for (CompositeVector::name_iterator comp=result->begin();
comp!=result->end(); ++comp) {
const Epetra_MultiVector& depth_v = *depth->ViewComponent(*comp,false);
const Epetra_MultiVector& slope_v = *slope->ViewComponent(*comp,false);
const Epetra_MultiVector& coef_v = *coef->ViewComponent(*comp,false);
Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);
int ncomp = result->size(*comp, false);
if (dt_) {
// double dt = *S->GetScalarData("dt");
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] = model_->DConductivityDDepth(factor_*depth_v[0][i], slope_v[0][i], coef_v[0][i]) * factor_;
}
} else {
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] = model_->DConductivityDDepth(depth_v[0][i], slope_v[0][i], coef_v[0][i]);
}
}
if (dens_) {
const Epetra_MultiVector& dens_v = *S->GetFieldData(dens_key_)->ViewComponent(*comp,false);
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] *= dens_v[0][i];
}
}
}
} else if (wrt_key == dens_key_) {
ASSERT(dens_);
for (CompositeVector::name_iterator comp=result->begin();
comp!=result->end(); ++comp) {
const Epetra_MultiVector& depth_v = *depth->ViewComponent(*comp,false);
const Epetra_MultiVector& slope_v = *slope->ViewComponent(*comp,false);
const Epetra_MultiVector& coef_v = *coef->ViewComponent(*comp,false);
Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);
int ncomp = result->size(*comp, false);
if (dt_) {
// double dt = *S->GetScalarData("dt");
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] = model_->Conductivity(factor_*depth_v[0][i], slope_v[0][i], coef_v[0][i]);
}
} else {
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] = model_->Conductivity(depth_v[0][i], slope_v[0][i], coef_v[0][i]);
}
}
}
} else {
ASSERT(0);
}
}
} //namespace
} //namespace
} //namespace
<commit_msg>adds option for which overland conductivity model to use, as we will be adding a no-denominator version<commit_after>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
/*
Evaluates the conductivity of surface flow.
Authors: Ethan Coon (ecoon@lanl.gov)
*/
#include "independent_variable_field_evaluator.hh"
#include "overland_conductivity_evaluator.hh"
#include "manning_conductivity_model.hh"
// #include "no_denominator_conductivity_model.hh"
namespace Amanzi {
namespace Flow {
namespace FlowRelations {
OverlandConductivityEvaluator::OverlandConductivityEvaluator(Teuchos::ParameterList& plist) :
SecondaryVariableFieldEvaluator(plist) {
depth_key_ = plist_.get<std::string>("height key", "ponded_depth");
dependencies_.insert(depth_key_);
slope_key_ = plist_.get<std::string>("slope key", "slope_magnitude");
dependencies_.insert(slope_key_);
coef_key_ = plist_.get<std::string>("coefficient key", "manning_coefficient");
dependencies_.insert(coef_key_);
dt_ = plist_.get<bool>("include dt factor", false);
if (dt_) {
factor_ = plist_.get<double>("dt factor");
}
dens_ = plist_.get<bool>("include density factor", true);
if (dens_) {
dens_key_ = plist_.get<std::string>("density key", "surface_molar_density_liquid");
dependencies_.insert(dens_key_);
}
if (my_key_ == std::string("")) {
my_key_ = plist_.get<std::string>("overland conductivity key",
"overland_conductivity");
}
// create the model, hard-coded until we have a 2nd model
ASSERT(plist_.isSublist("overland conductivity model"));
Teuchos::ParameterList sublist = plist_.sublist("overland conductivity model");
std::string model_type = sublist.get<std::string>("overland conductivity type", "manning");
if (model_type == "manning") {
model_ = Teuchos::rcp(new ManningConductivityModel(sublist));
} else if (model_type == "no denominator") {
// model_ = Teuchos::rcp(new NoDenominatorConductivityModel(sublist));
} else {
ASSERT(0);
}
}
OverlandConductivityEvaluator::OverlandConductivityEvaluator(const OverlandConductivityEvaluator& other) :
SecondaryVariableFieldEvaluator(other),
depth_key_(other.depth_key_),
slope_key_(other.slope_key_),
coef_key_(other.coef_key_),
dens_key_(other.dens_key_),
dt_(other.dt_),
factor_(other.factor_),
dens_(other.dens_),
model_(other.model_) {}
Teuchos::RCP<FieldEvaluator>
OverlandConductivityEvaluator::Clone() const {
return Teuchos::rcp(new OverlandConductivityEvaluator(*this));
}
// Required methods from SecondaryVariableFieldEvaluator
void OverlandConductivityEvaluator::EvaluateField_(const Teuchos::Ptr<State>& S,
const Teuchos::Ptr<CompositeVector>& result) {
Teuchos::RCP<const CompositeVector> depth = S->GetFieldData(depth_key_);
Teuchos::RCP<const CompositeVector> slope = S->GetFieldData(slope_key_);
Teuchos::RCP<const CompositeVector> coef = S->GetFieldData(coef_key_);
for (CompositeVector::name_iterator comp=result->begin();
comp!=result->end(); ++comp) {
const Epetra_MultiVector& depth_v = *depth->ViewComponent(*comp,false);
const Epetra_MultiVector& slope_v = *slope->ViewComponent(*comp,false);
const Epetra_MultiVector& coef_v = *coef->ViewComponent(*comp,false);
Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);
int ncomp = result->size(*comp, false);
if (dt_) {
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] = model_->Conductivity(factor_*depth_v[0][i], slope_v[0][i], coef_v[0][i]);
}
} else {
// double dt = *S->GetScalarData("dt");
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] = model_->Conductivity(depth_v[0][i], slope_v[0][i], coef_v[0][i]);
}
}
if (dens_) {
const Epetra_MultiVector& dens_v = *S->GetFieldData(dens_key_)->ViewComponent(*comp,false);
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] *= dens_v[0][i];
}
}
}
}
void OverlandConductivityEvaluator::EvaluateFieldPartialDerivative_(
const Teuchos::Ptr<State>& S,
Key wrt_key, const Teuchos::Ptr<CompositeVector>& result) {
Teuchos::RCP<const CompositeVector> depth = S->GetFieldData(depth_key_);
Teuchos::RCP<const CompositeVector> slope = S->GetFieldData(slope_key_);
Teuchos::RCP<const CompositeVector> coef = S->GetFieldData(coef_key_);
if (wrt_key == depth_key_) {
for (CompositeVector::name_iterator comp=result->begin();
comp!=result->end(); ++comp) {
const Epetra_MultiVector& depth_v = *depth->ViewComponent(*comp,false);
const Epetra_MultiVector& slope_v = *slope->ViewComponent(*comp,false);
const Epetra_MultiVector& coef_v = *coef->ViewComponent(*comp,false);
Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);
int ncomp = result->size(*comp, false);
if (dt_) {
// double dt = *S->GetScalarData("dt");
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] = model_->DConductivityDDepth(factor_*depth_v[0][i], slope_v[0][i], coef_v[0][i]) * factor_;
}
} else {
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] = model_->DConductivityDDepth(depth_v[0][i], slope_v[0][i], coef_v[0][i]);
}
}
if (dens_) {
const Epetra_MultiVector& dens_v = *S->GetFieldData(dens_key_)->ViewComponent(*comp,false);
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] *= dens_v[0][i];
}
}
}
} else if (wrt_key == dens_key_) {
ASSERT(dens_);
for (CompositeVector::name_iterator comp=result->begin();
comp!=result->end(); ++comp) {
const Epetra_MultiVector& depth_v = *depth->ViewComponent(*comp,false);
const Epetra_MultiVector& slope_v = *slope->ViewComponent(*comp,false);
const Epetra_MultiVector& coef_v = *coef->ViewComponent(*comp,false);
Epetra_MultiVector& result_v = *result->ViewComponent(*comp,false);
int ncomp = result->size(*comp, false);
if (dt_) {
// double dt = *S->GetScalarData("dt");
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] = model_->Conductivity(factor_*depth_v[0][i], slope_v[0][i], coef_v[0][i]);
}
} else {
for (int i=0; i!=ncomp; ++i) {
result_v[0][i] = model_->Conductivity(depth_v[0][i], slope_v[0][i], coef_v[0][i]);
}
}
}
} else {
ASSERT(0);
}
}
} //namespace
} //namespace
} //namespace
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <stack>
#include <variant>
#include "dDNNFTreeDecompositionBuilder.h"
/* Turn a bounded-treewidth circuit c for which a tree decomposition td
* is provided into a dNNF rooted at root, following the construction in
* Section 5.1 of https://arxiv.org/pdf/1811.02944 */
dDNNF&& dDNNFTreeDecompositionBuilder::build() && {
// We make the tree decomposition friendly
td.makeFriendly(root_id);
// We look for bags responsible for each variable
for(bag_t i{0}; i<td.bags.size(); ++i) {
const auto &b = td.getBag(i);
if(td.getChildren(i).empty() && b.size()==1 && c.getGateType(*b.begin()) == BooleanGate::IN)
responsible_bag[*b.begin()] = i;
}
// A friendly tree decomposition has leaf bags for every variable
// nodes. Let's just check that to be safe.
assert(responsible_bag.size()==c.inputs.size());
// Create the input and negated input gates
for(auto g: c.inputs) {
auto gate = d.setGate(BooleanGate::IN, c.getProb(g));
auto not_gate = d.setGate(BooleanGate::NOT);
d.addWire(not_gate, gate);
input_gate[g]=gate;
negated_input_gate[g]=not_gate;
}
gate_vector_t<dDNNFGate> result_gates = builddDNNF();
auto result_id = d.setGate("root", BooleanGate::OR);
for(const auto &p: result_gates) {
if(p.suspicious.empty() && p.valuation.find(root_id)->second) {
d.addWire(result_id, p.id);
break;
}
}
return std::move(d);
}
constexpr bool isStrong(BooleanGate type, bool value)
{
switch(type) {
case BooleanGate::OR:
return value;
case BooleanGate::AND:
return !value;
case BooleanGate::IN:
return false;
default:
return true;
}
}
static bool isConnectible(const dDNNFTreeDecompositionBuilder::suspicious_t &suspicious,
const TreeDecomposition::Bag &b)
{
for(const auto &g: suspicious) {
if(b.find(g)==b.end())
return false;
}
return true;
}
dDNNFTreeDecompositionBuilder::gate_vector_t<dDNNFTreeDecompositionBuilder::dDNNFGate> dDNNFTreeDecompositionBuilder::builddDNNFLeaf(
bag_t bag)
{
// If the bag is empty, it behaves as if it was not there
if(td.getBag(bag).size()==0)
return {};
// Otherwise, since we have a friendly decomposition, we have a
// single gate
auto single_gate = *td.getBag(bag).begin();
// We check if this bag is responsible for an input variable
if(c.getGateType(single_gate)==BooleanGate::IN &&
responsible_bag.find(single_gate)->second==bag)
{
// No need to create an extra gate, just point to the variable and
// negated variable gate; no suspicious gate.
dDNNFGate pos = { input_gate.find(single_gate)->second,
{std::make_pair(single_gate,true)},
{}
};
dDNNFGate neg = { negated_input_gate.find(single_gate)->second,
{std::make_pair(single_gate,false)},
{}
};
return { std::move(pos), std::move(neg) };
} else {
gate_vector_t<dDNNFGate> result_gates;
// We create two TRUE gates (AND gates with no inputs)
for(auto v: {true, false}) {
// Optimization: we know the root is set to True, so no need to
// construct valuations incompatible with this
if(single_gate==root_id && !v)
continue;
suspicious_t suspicious;
if(isStrong(c.getGateType(single_gate), v))
suspicious.insert(single_gate);
result_gates.emplace_back(
d.setGate(BooleanGate::AND),
valuation_t{std::make_pair(single_gate, v)},
std::move(suspicious)
);
}
return result_gates;
}
}
bool dDNNFTreeDecompositionBuilder::isAlmostValuation(
const valuation_t &valuation) const
{
for(const auto &p1: valuation) {
for(const auto &p2: valuation) {
if(p1.first==p2.first)
continue;
if(!isStrong(c.getGateType(p1.first),p2.second))
continue;
if(circuitHasWire(p1.first,p2.first)) {
switch(c.getGateType(p1.first)) {
case BooleanGate::AND:
case BooleanGate::OR:
if(p1.second!=p2.second)
return false;
break;
case BooleanGate::NOT:
if(p1.second==p2.second)
return false;
default:
;
}
}
}
}
return true;
}
dDNNFTreeDecompositionBuilder::suspicious_t
dDNNFTreeDecompositionBuilder::getInnocent(
const valuation_t &valuation,
const suspicious_t &innocent) const
{
suspicious_t result = innocent;
for(const auto &[g1,val]: valuation) {
if(innocent.find(g1)!=innocent.end())
continue;
// We check if it is strong, if not it is innocent
if(!isStrong(c.getGateType(g1), valuation.find(g1)->second)) {
result.insert(g1);
continue;
}
// We have a strong gate not innocented by the children bags,
// it is only innocent if we also have in the bag an input to
// that gate which is strong for that gate
for(const auto &[g2, value]: valuation) {
if(g2==g1)
continue;
if(circuitHasWire(g1,g2)) {
if(isStrong(c.getGateType(g1), value)) {
result.insert(g1);
break;
}
}
}
}
return result;
}
std::ostream &operator<<(std::ostream &o, const dDNNFTreeDecompositionBuilder::gates_to_or_t &gates_to_or)
{
for(auto &[valuation, m]: gates_to_or) {
o << "{";
bool first=true;
for(auto &[var, val]: valuation) {
if(!first)
o << ",";
o << "(" << var << "," << val << ")";
first=false;
}
o << "}: ";
for(auto &[innocent, gates]: m) {
o << "{";
bool first=true;
for(auto &x: innocent) {
if(!first)
o << ",";
o << x;
first=false;
}
o << "} ";
o << "[";
first=true;
for(auto &x: gates) {
if(!first)
o << ",";
o << x;
first=false;
}
o << "] ";
}
o << "\n";
}
return o;
}
dDNNFTreeDecompositionBuilder::gates_to_or_t dDNNFTreeDecompositionBuilder::collectGatesToOr(
bag_t bag,
const gate_vector_t<dDNNFGate> &children_gates,
const gates_to_or_t &partial)
{
gates_to_or_t gates_to_or;
for(auto g: children_gates) {
// We check all suspicious gates are in the bag of the parent
if(!isConnectible(g.suspicious,td.getBag(bag)))
continue;
// Find all valuations in partial that are compatible with this partial
// valuation, if it exists
auto compatibleValuation = [&g](const auto &p) {
for(const auto &[var, val]: p.first) {
auto it = g.valuation.find(var);
if(it != g.valuation.end() && it->second != val)
return false;
}
return true;
};
for (auto it = std::find_if(partial.begin(), partial.end(), compatibleValuation);
it != partial.end();
it = std::find_if(std::next(it), partial.end(), compatibleValuation)) {
auto &[matching_valuation, m] = *it;
valuation_t valuation = matching_valuation;
suspicious_t extra_innocent{};
for(auto &[var, val]: g.valuation) {
if(td.getBag(bag).find(var)!=td.getBag(bag).end()) {
if(matching_valuation.find(var)==matching_valuation.end())
valuation[var]=val;
if(g.suspicious.find(var)==g.suspicious.end()) {
extra_innocent.insert(var);
}
}
}
// We check valuation is still an almost-valuation
if(!isAlmostValuation(valuation))
continue;
for(auto &[innocent, gates]: m) {
suspicious_t new_innocent = std::move(extra_innocent);
for(auto s: innocent)
new_innocent.insert(s);
new_innocent = getInnocent(valuation, new_innocent);
if(gates.empty())
gates_to_or[valuation][new_innocent].push_back(g.id);
else {
for(auto g2: gates) {
gate_t and_gate;
// We optimize a bit by avoiding creating an AND gate if there
// is only one child, or if a second child is a TRUE gate
gate_t gates_children[2];
unsigned nb = 0;
if(!(d.getGateType(g.id)==BooleanGate::AND &&
d.getWires(g.id).empty()))
gates_children[nb++]=g.id;
if(!(d.getGateType(g2)==BooleanGate::AND &&
d.getWires(g2).empty()))
gates_children[nb++]=g2;
if(nb==0) {
// We have one (or two) TRUE gates; we just reuse it -- even
// though we reuse a child gate, connections will still make
// sense as the valuation and suspicious set been correctly
// computed
and_gate = g.id;
} else if(nb==1) {
// Only one non-TRUE gate; we reuse it. Similarly as in the
// previous case, even though we reuse this gate, the connections
// made from it will still take into account the valuation and
// suspicious set
and_gate = gates_children[0];
} else {
and_gate = d.setGate(BooleanGate::AND);
for(auto x: gates_children) {
d.addWire(and_gate, x);
}
}
gates_to_or[valuation][new_innocent].push_back(and_gate);
}
}
}
}
}
return gates_to_or;
}
dDNNFTreeDecompositionBuilder::gate_vector_t<dDNNFTreeDecompositionBuilder::dDNNFGate> dDNNFTreeDecompositionBuilder::builddDNNF()
{
// Unfortunately, tree decompositions can be quite deep so we need to
// simulate recursion with a heap-based stack, to avoid exhausting the
// actual memory stack
struct RecursionParams
{
bag_t bag;
size_t children_processed;
gates_to_or_t gates_to_or;
RecursionParams(bag_t b, size_t c, gates_to_or_t g) :
bag(b), children_processed(c), gates_to_or(std::move(g)) {}
RecursionParams(bag_t b) :
bag(b), children_processed(0) {
gates_to_or_t::mapped_type m;
m[suspicious_t{}] = {};
gates_to_or[valuation_t{}] = std::move(m);
}
};
using RecursionResult = gate_vector_t<dDNNFGate>;
std::stack<std::variant<RecursionParams,RecursionResult>> stack;
stack.emplace(RecursionParams{td.root});
while(!stack.empty()) {
RecursionResult result;
if(stack.top().index()==1) { // RecursionResult
result = std::move(std::get<1>(stack.top()));
stack.pop();
if(stack.empty())
return result;
}
auto [bag, children_processed, gates_to_or] = std::move(std::get<0>(stack.top()));
stack.pop();
if(td.getChildren(bag).empty()) {
auto x = builddDNNFLeaf(bag);
stack.emplace(x);
} else {
if(children_processed>0) {
gates_to_or = collectGatesToOr(bag, result, gates_to_or);
}
if(children_processed==td.getChildren(bag).size()) {
gate_vector_t<dDNNFGate> result_gates;
for(auto &[valuation, m]: gates_to_or) {
for(auto &[innocent, gates]: m) {
gate_t result_gate;
assert(gates.size()!=0);
suspicious_t suspicious;
for(auto &[var, val]: valuation)
if(innocent.find(var)==innocent.end())
suspicious.insert(var);
if(gates.size()==1)
result_gate = *gates.begin();
else {
result_gate = d.setGate(BooleanGate::OR);
for(auto &g: gates) {
d.addWire(result_gate, g);
}
}
result_gates.emplace_back(result_gate, std::move(valuation), std::move(suspicious));
}
}
stack.emplace(std::move(result_gates));
} else {
stack.emplace(RecursionParams{bag, children_processed+1, std::move(gates_to_or)});
stack.emplace(RecursionParams{td.getChildren(bag)[children_processed]});
}
}
}
// We return from within the while loop, when we hit the last return
// value
assert(false);
}
std::ostream &operator<<(std::ostream &o, const dDNNFTreeDecompositionBuilder::dDNNFGate &g)
{
o << g.id << "; {";
bool first=true;
for(const auto &p: g.valuation) {
if(!first)
o << ",";
first=false;
o << "(" << p.first << "," << p.second << ")";
}
o << "}; {";
first=true;
for(auto x: g.suspicious) {
if(!first)
o << ",";
first=false;
o << x;
}
o << "}";
return o;
}
bool dDNNFTreeDecompositionBuilder::circuitHasWire(gate_t f, gate_t t) const
{
return wiresSet.find(std::make_pair(f,t))!=wiresSet.end();
}
<commit_msg>More explicit constructors<commit_after>#include <algorithm>
#include <stack>
#include <variant>
#include "dDNNFTreeDecompositionBuilder.h"
/* Turn a bounded-treewidth circuit c for which a tree decomposition td
* is provided into a dNNF rooted at root, following the construction in
* Section 5.1 of https://arxiv.org/pdf/1811.02944 */
dDNNF&& dDNNFTreeDecompositionBuilder::build() && {
// We make the tree decomposition friendly
td.makeFriendly(root_id);
// We look for bags responsible for each variable
for(bag_t i{0}; i<td.bags.size(); ++i) {
const auto &b = td.getBag(i);
if(td.getChildren(i).empty() && b.size()==1 && c.getGateType(*b.begin()) == BooleanGate::IN)
responsible_bag[*b.begin()] = i;
}
// A friendly tree decomposition has leaf bags for every variable
// nodes. Let's just check that to be safe.
assert(responsible_bag.size()==c.inputs.size());
// Create the input and negated input gates
for(auto g: c.inputs) {
auto gate = d.setGate(BooleanGate::IN, c.getProb(g));
auto not_gate = d.setGate(BooleanGate::NOT);
d.addWire(not_gate, gate);
input_gate[g]=gate;
negated_input_gate[g]=not_gate;
}
gate_vector_t<dDNNFGate> result_gates = builddDNNF();
auto result_id = d.setGate("root", BooleanGate::OR);
for(const auto &p: result_gates) {
if(p.suspicious.empty() && p.valuation.find(root_id)->second) {
d.addWire(result_id, p.id);
break;
}
}
return std::move(d);
}
constexpr bool isStrong(BooleanGate type, bool value)
{
switch(type) {
case BooleanGate::OR:
return value;
case BooleanGate::AND:
return !value;
case BooleanGate::IN:
return false;
default:
return true;
}
}
static bool isConnectible(const dDNNFTreeDecompositionBuilder::suspicious_t &suspicious,
const TreeDecomposition::Bag &b)
{
for(const auto &g: suspicious) {
if(b.find(g)==b.end())
return false;
}
return true;
}
dDNNFTreeDecompositionBuilder::gate_vector_t<dDNNFTreeDecompositionBuilder::dDNNFGate> dDNNFTreeDecompositionBuilder::builddDNNFLeaf(
bag_t bag)
{
// If the bag is empty, it behaves as if it was not there
if(td.getBag(bag).size()==0)
return {};
// Otherwise, since we have a friendly decomposition, we have a
// single gate
auto single_gate = *td.getBag(bag).begin();
// We check if this bag is responsible for an input variable
if(c.getGateType(single_gate)==BooleanGate::IN &&
responsible_bag.find(single_gate)->second==bag)
{
// No need to create an extra gate, just point to the variable and
// negated variable gate; no suspicious gate.
dDNNFGate pos = { input_gate.find(single_gate)->second,
{std::make_pair(single_gate,true)},
suspicious_t{}
};
dDNNFGate neg = { negated_input_gate.find(single_gate)->second,
{std::make_pair(single_gate,false)},
suspicious_t{}
};
return { std::move(pos), std::move(neg) };
} else {
gate_vector_t<dDNNFGate> result_gates;
// We create two TRUE gates (AND gates with no inputs)
for(auto v: {true, false}) {
// Optimization: we know the root is set to True, so no need to
// construct valuations incompatible with this
if(single_gate==root_id && !v)
continue;
suspicious_t suspicious;
if(isStrong(c.getGateType(single_gate), v))
suspicious.insert(single_gate);
result_gates.emplace_back(
d.setGate(BooleanGate::AND),
valuation_t{std::make_pair(single_gate, v)},
std::move(suspicious)
);
}
return result_gates;
}
}
bool dDNNFTreeDecompositionBuilder::isAlmostValuation(
const valuation_t &valuation) const
{
for(const auto &p1: valuation) {
for(const auto &p2: valuation) {
if(p1.first==p2.first)
continue;
if(!isStrong(c.getGateType(p1.first),p2.second))
continue;
if(circuitHasWire(p1.first,p2.first)) {
switch(c.getGateType(p1.first)) {
case BooleanGate::AND:
case BooleanGate::OR:
if(p1.second!=p2.second)
return false;
break;
case BooleanGate::NOT:
if(p1.second==p2.second)
return false;
default:
;
}
}
}
}
return true;
}
dDNNFTreeDecompositionBuilder::suspicious_t
dDNNFTreeDecompositionBuilder::getInnocent(
const valuation_t &valuation,
const suspicious_t &innocent) const
{
suspicious_t result = innocent;
for(const auto &[g1,val]: valuation) {
if(innocent.find(g1)!=innocent.end())
continue;
// We check if it is strong, if not it is innocent
if(!isStrong(c.getGateType(g1), valuation.find(g1)->second)) {
result.insert(g1);
continue;
}
// We have a strong gate not innocented by the children bags,
// it is only innocent if we also have in the bag an input to
// that gate which is strong for that gate
for(const auto &[g2, value]: valuation) {
if(g2==g1)
continue;
if(circuitHasWire(g1,g2)) {
if(isStrong(c.getGateType(g1), value)) {
result.insert(g1);
break;
}
}
}
}
return result;
}
std::ostream &operator<<(std::ostream &o, const dDNNFTreeDecompositionBuilder::gates_to_or_t &gates_to_or)
{
for(auto &[valuation, m]: gates_to_or) {
o << "{";
bool first=true;
for(auto &[var, val]: valuation) {
if(!first)
o << ",";
o << "(" << var << "," << val << ")";
first=false;
}
o << "}: ";
for(auto &[innocent, gates]: m) {
o << "{";
bool first=true;
for(auto &x: innocent) {
if(!first)
o << ",";
o << x;
first=false;
}
o << "} ";
o << "[";
first=true;
for(auto &x: gates) {
if(!first)
o << ",";
o << x;
first=false;
}
o << "] ";
}
o << "\n";
}
return o;
}
dDNNFTreeDecompositionBuilder::gates_to_or_t dDNNFTreeDecompositionBuilder::collectGatesToOr(
bag_t bag,
const gate_vector_t<dDNNFGate> &children_gates,
const gates_to_or_t &partial)
{
gates_to_or_t gates_to_or;
for(auto g: children_gates) {
// We check all suspicious gates are in the bag of the parent
if(!isConnectible(g.suspicious,td.getBag(bag)))
continue;
// Find all valuations in partial that are compatible with this partial
// valuation, if it exists
auto compatibleValuation = [&g](const auto &p) {
for(const auto &[var, val]: p.first) {
auto it = g.valuation.find(var);
if(it != g.valuation.end() && it->second != val)
return false;
}
return true;
};
for (auto it = std::find_if(partial.begin(), partial.end(), compatibleValuation);
it != partial.end();
it = std::find_if(std::next(it), partial.end(), compatibleValuation)) {
auto &[matching_valuation, m] = *it;
valuation_t valuation = matching_valuation;
suspicious_t extra_innocent{};
for(auto &[var, val]: g.valuation) {
if(td.getBag(bag).find(var)!=td.getBag(bag).end()) {
if(matching_valuation.find(var)==matching_valuation.end())
valuation[var]=val;
if(g.suspicious.find(var)==g.suspicious.end()) {
extra_innocent.insert(var);
}
}
}
// We check valuation is still an almost-valuation
if(!isAlmostValuation(valuation))
continue;
for(auto &[innocent, gates]: m) {
suspicious_t new_innocent = std::move(extra_innocent);
for(auto s: innocent)
new_innocent.insert(s);
new_innocent = getInnocent(valuation, new_innocent);
if(gates.empty())
gates_to_or[valuation][new_innocent].push_back(g.id);
else {
for(auto g2: gates) {
gate_t and_gate;
// We optimize a bit by avoiding creating an AND gate if there
// is only one child, or if a second child is a TRUE gate
gate_t gates_children[2];
unsigned nb = 0;
if(!(d.getGateType(g.id)==BooleanGate::AND &&
d.getWires(g.id).empty()))
gates_children[nb++]=g.id;
if(!(d.getGateType(g2)==BooleanGate::AND &&
d.getWires(g2).empty()))
gates_children[nb++]=g2;
if(nb==0) {
// We have one (or two) TRUE gates; we just reuse it -- even
// though we reuse a child gate, connections will still make
// sense as the valuation and suspicious set been correctly
// computed
and_gate = g.id;
} else if(nb==1) {
// Only one non-TRUE gate; we reuse it. Similarly as in the
// previous case, even though we reuse this gate, the connections
// made from it will still take into account the valuation and
// suspicious set
and_gate = gates_children[0];
} else {
and_gate = d.setGate(BooleanGate::AND);
for(auto x: gates_children) {
d.addWire(and_gate, x);
}
}
gates_to_or[valuation][new_innocent].push_back(and_gate);
}
}
}
}
}
return gates_to_or;
}
dDNNFTreeDecompositionBuilder::gate_vector_t<dDNNFTreeDecompositionBuilder::dDNNFGate> dDNNFTreeDecompositionBuilder::builddDNNF()
{
// Unfortunately, tree decompositions can be quite deep so we need to
// simulate recursion with a heap-based stack, to avoid exhausting the
// actual memory stack
struct RecursionParams
{
bag_t bag;
size_t children_processed;
gates_to_or_t gates_to_or;
RecursionParams(bag_t b, size_t c, gates_to_or_t g) :
bag(b), children_processed(c), gates_to_or(std::move(g)) {}
RecursionParams(bag_t b) :
bag(b), children_processed(0) {
gates_to_or_t::mapped_type m;
m[suspicious_t{}] = {};
gates_to_or[valuation_t{}] = std::move(m);
}
};
using RecursionResult = gate_vector_t<dDNNFGate>;
std::stack<std::variant<RecursionParams,RecursionResult>> stack;
stack.emplace(RecursionParams{td.root});
while(!stack.empty()) {
RecursionResult result;
if(stack.top().index()==1) { // RecursionResult
result = std::move(std::get<1>(stack.top()));
stack.pop();
if(stack.empty())
return result;
}
auto [bag, children_processed, gates_to_or] = std::move(std::get<0>(stack.top()));
stack.pop();
if(td.getChildren(bag).empty()) {
auto x = builddDNNFLeaf(bag);
stack.emplace(x);
} else {
if(children_processed>0) {
gates_to_or = collectGatesToOr(bag, result, gates_to_or);
}
if(children_processed==td.getChildren(bag).size()) {
gate_vector_t<dDNNFGate> result_gates;
for(auto &[valuation, m]: gates_to_or) {
for(auto &[innocent, gates]: m) {
gate_t result_gate;
assert(gates.size()!=0);
suspicious_t suspicious;
for(auto &[var, val]: valuation)
if(innocent.find(var)==innocent.end())
suspicious.insert(var);
if(gates.size()==1)
result_gate = *gates.begin();
else {
result_gate = d.setGate(BooleanGate::OR);
for(auto &g: gates) {
d.addWire(result_gate, g);
}
}
result_gates.emplace_back(result_gate, std::move(valuation), std::move(suspicious));
}
}
stack.emplace(std::move(result_gates));
} else {
stack.emplace(RecursionParams{bag, children_processed+1, std::move(gates_to_or)});
stack.emplace(RecursionParams{td.getChildren(bag)[children_processed]});
}
}
}
// We return from within the while loop, when we hit the last return
// value
assert(false);
}
std::ostream &operator<<(std::ostream &o, const dDNNFTreeDecompositionBuilder::dDNNFGate &g)
{
o << g.id << "; {";
bool first=true;
for(const auto &p: g.valuation) {
if(!first)
o << ",";
first=false;
o << "(" << p.first << "," << p.second << ")";
}
o << "}; {";
first=true;
for(auto x: g.suspicious) {
if(!first)
o << ",";
first=false;
o << x;
}
o << "}";
return o;
}
bool dDNNFTreeDecompositionBuilder::circuitHasWire(gate_t f, gate_t t) const
{
return wiresSet.find(std::make_pair(f,t))!=wiresSet.end();
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.