├── LICENSE
├── README.md
├── Script 1. Pre_processing_AIS.R
├── Script 2. Merging statistics.R
├── Script 3. Shiplist from AIS monthly files.R
├── Script 4. Generate_events.R
├── Script 5. Produce lines id.R
├── Script 6. TrackBuilderFromCSV_multiprocessing.py
├── Script 7. SplitTracksByShipType_multiprocessing.py
├── Script 8. CreateRastersYear_multiprocessing.py
└── Script 8. CreateRasters_multiprocessing.py
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | The script are available in R and Python languages and were developed by the HELCOM Secretariat between 2015 and 2018.
3 | The aims of the scripts are to cleaning the AIS data (pre-processing) as well as to generate maps and statistics of the traffic in the Baltic Sea Region.
4 |
5 | The scripts available are:
6 | - Script 1. Pre_processing_AIS.R: the first one is to pre-process decoded AIS data using divisions. The mother file of data (yearly file of a given year) is divided in small divisions and each of these divisions are preprocessed and statistics (called reports) are generated for each divisions (number of duplicated signals, wrong IMO numbers, etc.). The script is finally merging the cleaned AIS data into monthly files.
7 |
8 | - Script 2. Merging statistics.R: the second one aims to merge the statistics produced by the first script for a given year. It gives monthly statistics as well as yearly statistics.
9 |
10 | - Script 3. Shiplist from AIS monthly files.R: the third script will produce shiplist for a certain year based on the AIS monthly files for the script #1.
11 |
12 | - Script 4. Generate_events.R: this fourth script will generate events: it will produce the events such as the trips between ports, the calls in ports, the entrance and the exit of the Baltic Sea. For this script, a shape file is needed with the ports polygons.
13 | - Script 5. Produce lines id.R: this script aims to generate the trips between the ports used in in the next script to produce the density maps. A shape file is also needed for this script, it contains the ports polygons (same as for the Script 4).
14 |
15 | - Script 6. TrackBuilderFromCSV_multiprocessing.py: It converts monthly AIS point data, the result of the previous operation, to lines features in shapefile format for each month. It assumes that there is a folder 01_trips and 02_lines under each year and thateach file contains the name of the month.
16 |
17 | - Script 7. SplitTracksByShipType_multiprocessing.py: It divides the lines shapefiles according to the 8 ship types. It assumes that there is a folder 03_lines_by_shiptype. The script makes a folder for each ship type.
18 |
19 | - Script 8. CreateRastersYear_multiprocessing.py: It creates a raster file for each ship type in multiprocessing. It assumes that there is a folder with the line shapefiles for each ship type; a folder 04_rasters and a grid Grid1km_BalticSea.shp with the 1x1 km INSPIRE compliant grid.
20 |
21 | The underlying AIS data processing work has been co-financed by EU projects Baltic Scope (2015-2017 EASME/EMFF/2014/1.2.1.5) and Baltic Lines (2016-2019, Interreg Baltic Sea Region). For more information, please check the HELCOM Maritime Assessment on Maritime Activities published in 2018 at http://www.helcom.fi/Lists/Publications/BSEP152.pdf. The methodology is available in the annexes.
22 |
23 | License: GNU General Public License V3
24 |
--------------------------------------------------------------------------------
/Script 1. Pre_processing_AIS.R:
--------------------------------------------------------------------------------
1 | #####################################################################
2 | #
3 | # R Script to pre-process AIS data
4 | # Developped by Florent NICOLAS, HELCOM Secretariat - 2017
5 | # R Version 3.4.3
6 | #
7 | # Input data: yearly file of AIS signals / all messages
8 | # Required data: shape file defining the limits of the Baltic Sea and the list of Maritime Identification Digits
9 | # Ouput data: monthly files of pre-processed AIS data and quality assessment
10 | #
11 | # !! The current script is processing the year XXXX To produce the same data for the year XXXX, replace XXXX by XXXX (CTRL + A and CTRL + F)
12 | #
13 | #####################################################################
14 |
15 | # packages needed
16 | install.packages("sp")
17 | install.packages("rgdal")
18 | install.packages("maps")
19 | install.packages("maps")
20 | install.packages("rworldmap")
21 | install.packages("RgoogleMaps")
22 | install.packages("plyr")
23 | install.packages("dplyr")
24 | install.packages("tidyr")
25 | install.packages("data.table")
26 | install.packages("lubridate")
27 | install.packages("zoo")
28 | install.packages("geosphere")
29 | install.packages("base")
30 |
31 | # packages needed
32 | library("sp")
33 | library("rgdal")
34 | install.packages("maps")
35 | library("maps")
36 | library("rworldmap")
37 | library("RgoogleMaps")
38 | library("plyr")
39 | library("dplyr")
40 | library("tidyr")
41 | library("data.table")
42 | library("lubridate")
43 | library("zoo")
44 | library("geosphere")
45 | library("base")
46 |
47 | ##### the otput are produced in the directory E:/test_division/division_finale2013/
48 | # this one has to be changed manually (CTRL+F) to adjust the script to your directories
49 |
50 |
51 | # Steps 1, 2 and 3 : Division mother file / cleaning the divisions / selection of relevant parameters ------------------------------------
52 | rm(list = ls()) # clean environment
53 |
54 | # start time to have time time needed for producing the AIS monthly files:
55 | start.time <- Sys.time()
56 |
57 | # import the polygons defining the Baltic Sea
58 | exit_baltic <-readOGR("//10.10.10.210/e$/AIS_on_github/Baltic Sea limits","Limits_Baltic_Sea_AIS")
59 |
60 | #Divide file in smaller text files and cleaning / selecting relevant data
61 | conn=file("E:/helcom-log-2013.csv", open="r")
62 |
63 | ###########################################################################################################################################
64 | # Enter the number of records (rows) per divisions:
65 | n_rows= as.numeric(1000000)
66 | ###########################################################################################################################################
67 |
68 | #read the first XXX rows:
69 | data<-read.csv(conn, nrows=n_rows, head=T, fill=T,na.strings=c(""," ", "null", "NA"))
70 | #add column name to the first file
71 | colnames(data)<-c( "timestamp_pretty","timestamp","targetType","mmsi","msgid","posacc","lat","long","sog","cog","draught","name","dimBow",
72 | "dimPort","dimStarboard","dimStern","shipTypeCargoTypeCode","shipType","shipCargo","destination","eta","imo","callsign")
73 |
74 | dir.create(file.path("E:/test_division/division_finale2013/"), showWarnings=F)
75 |
76 | i=1
77 | while (length(data)>0) {
78 | #unique name file for each divisions:
79 | fn=paste("E:/test_division/division_finale2013/division_ais_2013.", i,sep=",", ".csv" )
80 | out_con=file(fn, open="w")
81 | #Remove the double quote sign in the division
82 | data$name <- gsub("\"","",data$name)
83 | data$destination <- gsub("\"","",data$destination)
84 | data$callsign <- gsub("\"","",data$callsign)
85 | data$msgid <- gsub("\"","",data$msgid )
86 | data$targetType <- gsub("\"","",data$targetType )
87 | data$mmsi <- gsub("\"","",data$mmsi )
88 | data$lat <- gsub("\"","",data$lat )
89 | data$long <- gsub("\"","",data$long )
90 | data$sog <- gsub("\"","",data$sog )
91 | data$cog <- gsub("\"","",data$cog )
92 | data$shipType <- gsub("\"","",data$shipType )
93 | data$dimBow <- gsub("\"","",data$dimBow )
94 | data$draught <- gsub("\"","",data$draught )
95 | data$dimPort <- gsub("\"","",data$dimPort )
96 | data$dimStarboard <- gsub("\"","",data$dimStarboard )
97 | data$dimStern <- gsub("\"","",data$dimStern )
98 | data$imo <- gsub("\"","",data$imo )
99 |
100 | #cleaning AIS data begins here
101 |
102 | #remove signals that are not from 2013
103 | data$year <- substr(data$timestamp_pretty,7,10)
104 | data<-subset(data,data$year==2013)
105 |
106 | #remove duplication
107 | all_data_with_duplication<-nrow(data)
108 | data <- data[!duplicated(data), ]
109 | all_data_without_duplication<-nrow(data)
110 |
111 | all_AIS<-nrow(data)
112 |
113 | ###
114 | # 1. Select the message ID
115 | data$msgid<-as.factor(data$msgid)
116 | data<-subset(data, msgid == 1 | msgid == 2 | msgid == 3 | msgid == 18 | msgid == 19 )
117 |
118 | Messages_for_shipping<-nrow(data)
119 |
120 | ####
121 | # 2. MMSI and imo
122 | data$mmsi<-as.numeric(as.character(data$mmsi))
123 | data <- subset(data, mmsi > 99999999 & mmsi < 999999999)
124 | wrongMMSI= c(000000000,111111111,222222222,333333333,444444444,555555555, 666666666, 777777777, 888888888,
125 | 999999999,123456789,0,12345, 1193046) ############################################################# list to be updated
126 | wrongMMSI<-as.numeric(wrongMMSI)
127 | data<-subset(data, mmsi!="wrongMMSI")
128 |
129 | data$imo<-as.numeric(as.character(data$imo))
130 |
131 |
132 | not_clean_imo<-sum(is.na(data$imo))
133 | data$imo[is.na(data$imo)] <- NA
134 | #for too big IMO numbers:
135 | data$imo[data$imo < 999999] <- NA
136 | #for too small IMO numbers:
137 | data$imo[data$imo >9999999] <- NA
138 | clean_imo<-sum(is.na(data$imo))
139 |
140 | wrong_imo<- clean_imo-not_clean_imo
141 | MMSI_registered<-nrow(data)
142 |
143 | # remove special characters from strings
144 | data$msgid <- gsub("([\\])","", data$msgid)
145 | data$msgid <- gsub("[][!#$%()*.:;<=>@^_`|~.{}]", "", data$msgid)
146 |
147 | data$targetType <- gsub("([\\])","", data$targetType)
148 | data$targetType <- gsub("[][!#$%()*.:;<=>@^_`|~.{}]", "", data$targetType)
149 |
150 | data$posacc <- gsub("([\\])","", data$posacc)
151 | data$posacc <- gsub("[][!#$%()*:;<=>@^_`|~.{}]", "", data$posacc)
152 |
153 | data$dimBow <- gsub("([\\])","", data$dimBow)
154 | data$dimBow <- gsub("[][!#$%()*:;<=>@^_`|~{}]", "", data$dimBow)
155 |
156 | data$dimPort <- gsub("([\\])","", data$dimPort)
157 | data$dimPort <- gsub("[][!#$%()*:;<=>@^_`|.{}]", "", data$dimPort)
158 |
159 | data$draught <- gsub("([\\])","", data$draught)
160 | data$draught <- gsub("[][!#$%()*:;<=>@^_`|~{}]", "", data$draught)
161 |
162 | data$dimStarboard <- gsub("([\\])","", data$dimStarboard)
163 | data$dimStarboard <- gsub("[][!#$%()*:;<=>@^_`|~{}]", "", data$dimStarboard)
164 |
165 | data$dimStern <- gsub("([\\])","", data$dimStern)
166 | data$dimStern <- gsub("[][!#$%()*:;<=>@^_`|~{}]", "", data$dimStern)
167 |
168 | ###
169 | # 3. add MID and flag
170 | data$MID <- substr(data$mmsi,1,3)
171 | MID <- read.csv("//hcvhost01/data/MID.csv", sep=";", quote="")
172 | data<-merge(data, MID, by="MID")
173 |
174 | #remove special characters
175 | data$country <- gsub("([\\])","", data$country)
176 | data$country <- gsub("[][!#$%()*.:;<=>@^_`|~.{}]", "", data$country)
177 |
178 | ###
179 | # 4. Addition of the columns month and week
180 | # addition on the month number in new column called month
181 | data$month <- substr(data$timestamp_pretty,4,5)
182 | data$month <- as.numeric(data$month)
183 |
184 | # addition of column week
185 | library("ISOweek")
186 | data$date <- substr((as.factor(data$timestamp_pretty)),1,10)
187 | data$date <- as.Date(data$date,format = "%d/%m/%Y")
188 | data$week<-ISOweek(data$date)
189 | data$week<-substr((as.factor(data$week)),7,8)
190 |
191 |
192 | ###
193 | # 5. Selection of Baltic Sea
194 | library(ggplot2)
195 | library(sp)
196 | library(rgdal)
197 |
198 | ###
199 | # Prepare lat/long
200 | data <- subset(data, !(is.na(lat) ))
201 | data <- subset(data, !(is.na(long) ))
202 | data$lat<-as.numeric(as.character(data$lat))
203 | data$long<-as.numeric(as.character(data$long))
204 | data <- subset(data, lat >= -90 & lat < 90)
205 | data <- subset(data, long > -180 & long < 180)
206 |
207 | coordinates(data) <- c("long", "lat")
208 |
209 |
210 | # to confirm the same reference system
211 | proj4string(data) <- proj4string(exit_baltic)
212 |
213 | # combine is.na() with over() to do the containment test; note that we
214 | # need to "demote" parks to a SpatialPolygons object first
215 | InsideBalticSea <- !is.na(over(data, as(exit_baltic, "SpatialPolygons")))
216 | mean(InsideBalticSea)
217 |
218 | data <- as.data.frame(data)
219 | data$InsideBalticSea <- InsideBalticSea
220 |
221 | InsideBalticSea <- nrow(subset(data, InsideBalticSea == 1))
222 | OutsideBalticSea <- nrow(subset(data, InsideBalticSea == 0))
223 |
224 |
225 | #plot to check
226 | #data<- subset(data, data$into_baltic==TRUE)
227 | #newmap <- getMap(resolution = "low")
228 | #plot(newmap, xlim = c(5.39, 30), ylim = c(52, 65.5), asp = 1, col="grey")
229 | #points(data$long, data$lat, col = "red", cex = 1)
230 |
231 |
232 | #old function::
233 | #definition of Baltic Sea
234 | # read coordinates of the polygon around the Baltic Sea
235 | # baltic <- read.csv("E:/test_division/DeleteAreaOutsideBaltic_Coordinates.txt", sep=";")
236 | # long=c(baltic $POINT_X)
237 | # lat=c(baltic $POINT_Y)
238 | # create df with 2 digits
239 | # baltic<- data.frame( lat, long)
240 | # baltic$lat <- round(lat, digits = 2)
241 | # baltic$long <- round(long, digits = 2)
242 | # data$long<-as.numeric(as.character(data$long))
243 | # data$lat<-as.numeric(as.character(data$lat))
244 |
245 | # point in polygon
246 | # data$InsideBalticSea <- factor(point.in.polygon(data$long, data$lat, baltic$long, baltic$lat))
247 | #InsideBalticSea <- nrow(subset(data, InsideBalticSea == 1))
248 | #OutsideBalticSea <- nrow(subset(data, InsideBalticSea == 0))
249 |
250 | ###
251 | # 6. SOG
252 | data$sog <- as.numeric(as.character(data$sog))
253 | data <- subset(data, sog >= 0 & sog < 800 )
254 | #summary(data$sog)
255 |
256 | clean_SOG<-nrow(data)
257 |
258 | ###
259 | # 7. COG
260 | data$cog <- as.numeric(as.character(data$cog))
261 | data <- subset(data, cog >= 0 & cog < 360 )
262 | #summary(data$cog)
263 |
264 | clean_COG<-nrow(data)
265 |
266 | ########## STEP III
267 | #subsetting the data
268 |
269 | ####
270 | # 1. IMO
271 | #data <- subset(data, !(is.na(imo) ))
272 | data$imo <- as.numeric(as.character(data$imo))
273 | #data <- subset(data, imo > 999999 & imo < 9999999)
274 | #summary(data$imo)
275 | Imo_and_non_imo<-nrow(data)
276 |
277 | ####
278 | # 2. Baltic Sea
279 | data<-subset(data, InsideBalticSea == 1)
280 | InsideBalticSea<-nrow(data)
281 |
282 | # Selection of relevant information and export of data in csv files
283 |
284 |
285 | # as.characters and Selection of parameters
286 | data$dimBow<-as.character(data$dimBow)
287 | data$dimPort<-as.character(data$dimPort)
288 | data$dimStarboard<-as.character(data$dimStarboard)
289 | data$dimStern<-as.character(data$dimStern)
290 | data<- data[,c("timestamp_pretty","timestamp","msgid","targetType","mmsi", "lat","long", "posacc", "sog", "cog", "shipType", "dimBow", "draught","dimPort","dimStarboard","dimStern","month", "week", "imo", "country", "name", "callsign" )]
291 |
292 | #stats report
293 | signals<-c(all_data_with_duplication,all_data_without_duplication ,Messages_for_shipping,MMSI_registered,wrong_imo,Imo_and_non_imo,clean_SOG,clean_COG, InsideBalticSea,OutsideBalticSea)
294 | parameters<-c("all_data_with_duplication","all_data_without_duplication","Messages_for_shipping","MMSI_registered","wrong_imo","Imo_and_non_imo","clean_SOG","clean_COG", "InsideBalticSea","OutsideBalticSea")
295 | stats<-data.frame(parameters,signals)
296 |
297 |
298 | # end cleaning AIS data
299 |
300 | #write tables
301 | stats_directory=paste("E:/test_division/division_finale2013/stats_ais_2013_", i, sep=",", ".csv" )
302 | write.table(stats, stats_directory, sep=",", col.names = T, row.names=F, quote=F)
303 |
304 |
305 |
306 | #### filter the signals / month: 1 file in a monthly folder
307 |
308 | data_2013_january<-data[data$month == 1, ]
309 | data_2013_january <- subset(data_2013_january, !(is.na(timestamp_pretty) ))
310 | dir.create(file.path("E:/test_division/division_finale2013/january"), showWarnings=F)
311 | nrow<-as.numeric(nrow(data_2013_january))
312 | if(nrow>0){
313 | directory_divisions=paste("E:/test_division/division_finale2013/january/data_2013_januaryfinal", sep="_",i, ".csv")
314 | write.table (data_2013_january, directory_divisions, row.names=F, sep=",")
315 | i=i+1
316 | } else {
317 | }
318 |
319 |
320 | data_2013_february<-data[data$month == 2, ]
321 | data_2013_february <- subset(data_2013_february, !(is.na(timestamp_pretty) ))
322 | dir.create(file.path("E:/test_division/division_finale2013/february"), showWarnings=F)
323 | nrow<-as.numeric(nrow(data_2013_february))
324 | if(nrow>0){
325 | directory_divisions=paste("E:/test_division/division_finale2013/february/data_2013_februaryfinal", sep="_",i, ".csv")
326 | write.table (data_2013_february, directory_divisions, row.names=F, sep=",")
327 | i=i+1
328 | } else {
329 | }
330 |
331 |
332 | ###march 03
333 | data_2013_march<-data[data$month == 3, ]
334 | data_2013_march <- subset(data_2013_march, !(is.na(timestamp_pretty) ))
335 | dir.create(file.path("E:/test_division/division_finale2013/march"), showWarnings=F)
336 | nrow<-as.numeric(nrow(data_2013_march))
337 | if(nrow>0){
338 | directory_divisions=paste("E:/test_division/division_finale2013/march/data_2013_marchfinal", sep="_",i, ".csv")
339 | write.table (data_2013_march, directory_divisions, row.names=F, sep=",")
340 | i=i+1
341 | } else {
342 | }
343 |
344 |
345 | ###april 04
346 | data_2013_april<-data[data$month == 4, ]
347 | dir.create(file.path("E:/test_division/division_finale2013/april"), showWarnings=F)
348 | nrow<-as.numeric(nrow(data_2013_april))
349 | if(nrow>0){
350 | directory_divisions=paste("E:/test_division/division_finale2013/april/data_2013_aprilfinal", sep="_",i, ".csv")
351 | write.table (data_2013_april, directory_divisions, row.names=F, sep=",")
352 | i=i+1
353 | } else {
354 | }
355 |
356 |
357 | ###may 05
358 | data_2013_may<-data[data$month == 5, ]
359 | data_2013_may <- subset(data_2013_may, !(is.na(timestamp_pretty) ))
360 | dir.create(file.path("E:/test_division/division_finale2013/may"), showWarnings=F)
361 | nrow<-as.numeric(nrow(data_2013_may))
362 | if(nrow>0){
363 | directory_divisions=paste("E:/test_division/division_finale2013/may/data_2013_mayfinal", sep="_",i, ".csv")
364 | write.table (data_2013_may, directory_divisions, row.names=F, sep=",")
365 | i=i+1
366 | } else {
367 | }
368 |
369 |
370 |
371 | ###june 06
372 | data_2013_june<-data[data$month == 6, ]
373 | data_2013_june <- subset(data_2013_june, !(is.na(timestamp_pretty) ))
374 | dir.create(file.path("E:/test_division/division_finale2013/june"), showWarnings=F)
375 | nrow<-as.numeric(nrow(data_2013_june))
376 | if(nrow>0){
377 | directory_divisions=paste("E:/test_division/division_finale2013/june/data_2013_junefinal", sep="_",i, ".csv")
378 | write.table (data_2013_june, directory_divisions, row.names=F, sep=",")
379 | i=i+1
380 | } else {
381 | }
382 |
383 |
384 | ###july 07
385 | data_2013_july<-data[data$month == 7, ]
386 | data_2013_july <- subset(data_2013_july, !(is.na(timestamp_pretty) ))
387 | dir.create(file.path("E:/test_division/division_finale2013/july"), showWarnings=F)
388 | nrow<-as.numeric(nrow(data_2013_july))
389 | if(nrow>0){
390 | directory_divisions=paste("E:/test_division/division_finale2013/july/data_2013_julyfinal", sep="_",i, ".csv")
391 | write.table (data_2013_july, directory_divisions, row.names=F, sep=",")
392 | i=i+1
393 | } else {
394 | }
395 |
396 |
397 | ###august 08
398 | data_2013_august<-data[data$month == 8, ]
399 | data_2013_august <- subset(data_2013_august, !(is.na(timestamp_pretty) ))
400 | dir.create(file.path("E:/test_division/division_finale2013/august"), showWarnings=F)
401 | nrow<-as.numeric(nrow(data_2013_august))
402 | if(nrow>0){
403 | directory_divisions=paste("E:/test_division/division_finale2013/august/data_2013_augustfinal", sep="_",i, ".csv")
404 | write.table (data_2013_august, directory_divisions, row.names=F, sep=",")
405 | i=i+1
406 | } else {
407 | }
408 |
409 |
410 |
411 |
412 | ###september 09
413 | data_2013_september<-data[data$month == 9, ]
414 | data_2013_september <- subset(data_2013_september, !(is.na(timestamp_pretty) ))
415 | dir.create(file.path("E:/test_division/division_finale2013/september"), showWarnings=F)
416 | nrow<-as.numeric(nrow(data_2013_september))
417 | if(nrow>0){
418 | directory_divisions=paste("E:/test_division/division_finale2013/september/data_2013_septemberfinal", sep="_",i, ".csv")
419 | write.table (data_2013_september, directory_divisions, row.names=F, sep=",")
420 | i=i+1
421 | } else {
422 | }
423 |
424 |
425 |
426 | ###october 10
427 | data_2013_october<-data[data$month == 10, ]
428 | data_2013_october <- subset(data_2013_october, !(is.na(timestamp_pretty) ))
429 | dir.create(file.path("E:/test_division/division_finale2013/october"), showWarnings=F)
430 | nrow<-as.numeric(nrow(data_2013_october))
431 | if(nrow>0){
432 | directory_divisions=paste("E:/test_division/division_finale2013/october/data_2013_octoberfinal", sep="_",i, ".csv")
433 | write.table (data_2013_october, directory_divisions, row.names=F, sep=",")
434 | i=i+1
435 | } else {
436 | }
437 |
438 |
439 | ###november 11
440 | data_2013_november<-data[data$month == 11, ]
441 | data_2013_november <- subset(data_2013_november, !(is.na(timestamp_pretty) ))
442 | dir.create(file.path("E:/test_division/division_finale2013/november"), showWarnings=F)
443 | nrow<-as.numeric(nrow(data_2013_november))
444 | if(nrow>0){
445 | directory_divisions=paste("E:/test_division/division_finale2013/november/data_2013_novemberfinal", sep="_",i, ".csv")
446 | write.table (data_2013_november, directory_divisions, row.names=F, sep=",")
447 | i=i+1
448 | } else {
449 | }
450 |
451 |
452 | ###december 12
453 | data_2013_december<-data[data$month == 12, ]
454 | data_2013_december <- subset(data_2013_december, !(is.na(timestamp_pretty) ))
455 | dir.create(file.path("E:/test_division/division_finale2013/december"), showWarnings=F)
456 | nrow<-as.numeric(nrow(data_2013_december))
457 | if(nrow>0){
458 | directory_divisions=paste("E:/test_division/division_finale2013/december/data_2013_decemberfinal", sep="_",i, ".csv")
459 | write.table (data_2013_december, directory_divisions, row.names=F, sep=",")
460 | i=i+1
461 | } else {
462 | }
463 |
464 |
465 | ### going to the next division
466 |
467 |
468 |
469 | #ais_directory=paste("E:/test_division/division_finale2013/division_ais_2013.", i,sep=",", ".csv" )
470 | #write.table(data, ais_directory, row.names=F, sep=",", col.names=T)
471 | #close(out_con)
472 |
473 | #read the next files of n_rows rows
474 | data<-read.csv(conn, nrows=n_rows,fill=T,na.strings=c(""," ", "null", "NA"))
475 | #add column names for these divisions
476 | colnames(data)<-c( "timestamp_pretty","timestamp","targetType","mmsi","msgid","posacc","lat","long","sog","cog","draught","name","dimBow",
477 | "dimPort","dimStarboard","dimStern","shipTypeCargoTypeCode","shipType","shipCargo","destination","eta","imo","callsign")
478 | i=i+1
479 | }
480 | close(conn)
481 |
482 | #mail notification
483 | library(mail)
484 | ##sendmail("your_email@domain.domain", "2013 is divided and CLEAN with new method", "2013 is divided and CLEAN", password="rmail")
485 |
486 |
487 |
488 |
489 |
490 |
491 | # Steps 4: Sorting and merging the division into monthly files -----------------------------------------------
492 |
493 | ###January 01 Merging all files in each month_folder to have 1 file per month
494 | rm(list = ls()[!ls() %in% c("start.time")])
495 | setwd("E:/test_division/division_finale2013/january")
496 | fileList <- list.files(pattern="data_2013_januaryfinal*", recursive=FALSE)
497 | library(plyr)
498 | data <- ldply(fileList, read.table, header=T, sep = ",", fill=T)
499 | data <- subset(data, !(is.na(timestamp_pretty) ))
500 |
501 | data$imo<-as.numeric(as.character(data$imo))
502 | not_clean_imo<-sum(is.na(data$imo))
503 | data$imo[is.na(data$imo)] <- NA
504 | #for too big IMO numbers:
505 | data$imo[data$imo < 999999] <- NA
506 | #for too small IMO numbers:
507 | data$imo[data$imo >9999999] <- NA
508 |
509 | rows_data_duplicate<-nrow(data)
510 | data <- unique(data)
511 | rows_no_duplication<-nrow(data)
512 | difference<-(rows_data_duplicate-rows_no_duplication)
513 | month<-c("january")
514 | duplication<-data.frame(rows_data_duplicate,rows_no_duplication,difference, month, row.names = NULL)
515 | dir.create(file.path("E:/test_division/division_finale2013/file_list_months_weeks"), showWarnings=F)
516 | directory_stats_duplications=paste("E:/test_division/division_finale2013/file_list_months_weeks/duplication_january.csv")
517 | write.table (duplication, directory_stats_duplications , row.names=F, sep=";")
518 |
519 | data$timestamp_pretty<-as.character(data$timestamp_pretty)
520 | data$shipType<-as.character(data$shipType)
521 |
522 | directory_final=paste("E:/test_division/division_finale2013/file_list_months_weeks/ais_january_2013.csv")
523 | write.table (data, directory_final, row.names=F, sep=",")
524 |
525 | library(mail)
526 | ###sendmail("florent.nicolas@helcom.fi", "AIS january 2013 is merged", " AIS january 2013 is merged", password="rmail")
527 |
528 |
529 | ###february 02 Merging all files in each month_folder to have 1 file per month
530 | rm(list = ls()[!ls() %in% c("start.time")])
531 | setwd("E:/test_division/division_finale2013/february")
532 | fileList <- list.files(pattern="data_2013_februaryfinal*", recursive=FALSE)
533 | library(plyr)
534 | data <- ldply(fileList, read.table, header=T, sep = ",", fill=T)
535 | data <- subset(data, !(is.na(timestamp_pretty) ))
536 |
537 | data$imo<-as.numeric(data$imo)
538 | not_clean_imo<-sum(is.na(data$imo))
539 | data$imo[is.na(data$imo)] <- NA
540 | #for too big IMO numbers:
541 | data$imo[data$imo < 999999] <- NA
542 | #for too small IMO numbers:
543 | data$imo[data$imo >9999999] <- NA
544 |
545 | rows_data_duplicate<-nrow(data)
546 | data <- unique(data)
547 | rows_no_duplication<-nrow(data)
548 | difference<-(rows_data_duplicate-rows_no_duplication)
549 | month<-c("february")
550 | duplication<-data.frame(rows_data_duplicate,rows_no_duplication,difference, month, row.names = NULL)
551 | dir.create(file.path("E:/test_division/division_finale2013/file_list_months_weeks"), showWarnings=F)
552 | directory_stats_duplications=paste("E:/test_division/division_finale2013/file_list_months_weeks/duplication_february.csv")
553 | write.table (duplication, directory_stats_duplications , row.names=F, sep=";")
554 |
555 | data$timestamp_pretty<-as.character(data$timestamp_pretty)
556 | data$shipType<-as.character(data$shipType)
557 |
558 | directory_final=paste("E:/test_division/division_finale2013/file_list_months_weeks/ais_february_2013.csv")
559 | write.table (data, directory_final, row.names=F, sep=",")
560 |
561 | ###march 03 Merging all files in each month_folder to have 1 file per month
562 | rm(list = ls()[!ls() %in% c("start.time")])
563 | setwd("E:/test_division/division_finale2013/march")
564 | fileList <- list.files(pattern="data_2013_marchfinal*", recursive=FALSE)
565 | library(plyr)
566 | data <- ldply(fileList, read.table, header=T, sep = ",", fill=T)
567 | data <- subset(data, !(is.na(timestamp_pretty) ))
568 |
569 | data$imo<-as.numeric(data$imo)
570 | not_clean_imo<-sum(is.na(data$imo))
571 | data$imo[is.na(data$imo)] <- NA
572 | #for too big IMO numbers:
573 | data$imo[data$imo < 999999] <- NA
574 | #for too small IMO numbers:
575 | data$imo[data$imo >9999999] <- NA
576 |
577 | rows_data_duplicate<-nrow(data)
578 | data <- unique(data)
579 | rows_no_duplication<-nrow(data)
580 | difference<-(rows_data_duplicate-rows_no_duplication)
581 | month<-c("march")
582 | duplication<-data.frame(rows_data_duplicate,rows_no_duplication,difference, month, row.names = NULL)
583 | dir.create(file.path("E:/test_division/division_finale2013/file_list_months_weeks"), showWarnings=F)
584 | directory_stats_duplications=paste("E:/test_division/division_finale2013/file_list_months_weeks/duplication_march.csv")
585 | write.table (duplication, directory_stats_duplications , row.names=F, sep=";")
586 |
587 | data$timestamp_pretty<-as.character(data$timestamp_pretty)
588 | data$shipType<-as.character(data$shipType)
589 |
590 | directory_final=paste("E:/test_division/division_finale2013/file_list_months_weeks/ais_march_2013.csv")
591 | write.table (data, directory_final, row.names=F, sep=",")
592 |
593 | library(mail)
594 | ###sendmail("florent.nicolas@helcom.fi", "AIS march 2013 is merged", " AIS march 2013 is merged", password="rmail")
595 |
596 | ###april 04 Merging all files in each month_folder to have 1 file per month
597 | rm(list = ls()[!ls() %in% c("start.time")])
598 | setwd("E:/test_division/division_finale2013/april")
599 | fileList <- list.files(pattern="data_2013_aprilfinal*", recursive=FALSE)
600 | library(plyr)
601 | data <- ldply(fileList, read.table, header=T, sep = ",", fill=T)
602 | data <- subset(data, !(is.na(timestamp_pretty) ))
603 |
604 | data$imo<-as.numeric(data$imo)
605 | not_clean_imo<-sum(is.na(data$imo))
606 | data$imo[is.na(data$imo)] <- NA
607 | #for too big IMO numbers:
608 | data$imo[data$imo < 999999] <- NA
609 | #for too small IMO numbers:
610 | data$imo[data$imo >9999999] <- NA
611 |
612 | rows_data_duplicate<-nrow(data)
613 | data <- unique(data)
614 | rows_no_duplication<-nrow(data)
615 | difference<-(rows_data_duplicate-rows_no_duplication)
616 | month<-c("april")
617 | duplication<-data.frame(rows_data_duplicate,rows_no_duplication,difference, month, row.names = NULL)
618 | dir.create(file.path("E:/test_division/division_finale2013/file_list_months_weeks"), showWarnings=F)
619 | directory_stats_duplications=paste("E:/test_division/division_finale2013/file_list_months_weeks/duplication_april.csv")
620 | write.table (duplication, directory_stats_duplications , row.names=F, sep=";")
621 |
622 | data$timestamp_pretty<-as.character(data$timestamp_pretty)
623 | data$shipType<-as.character(data$shipType)
624 |
625 | directory_final=paste("E:/test_division/division_finale2013/file_list_months_weeks/ais_april_2013.csv")
626 | write.table (data, directory_final, row.names=F, sep=",")
627 |
628 |
629 | ###may 05 Merging all files in each month_folder to have 1 file per month
630 | rm(list = ls()[!ls() %in% c("start.time")])
631 | setwd("E:/test_division/division_finale2013/may")
632 | fileList <- list.files(pattern="data_2013_mayfinal*", recursive=FALSE)
633 | library(plyr)
634 | data <- ldply(fileList, read.table, header=T, sep = ",", fill=T)
635 | data <- subset(data, !(is.na(timestamp_pretty) ))
636 |
637 | data$imo<-as.numeric(data$imo)
638 | not_clean_imo<-sum(is.na(data$imo))
639 | data$imo[is.na(data$imo)] <- NA
640 | #for too big IMO numbers:
641 | data$imo[data$imo < 999999] <- NA
642 | #for too small IMO numbers:
643 | data$imo[data$imo >9999999] <- NA
644 |
645 | rows_data_duplicate<-nrow(data)
646 | data <- unique(data)
647 | rows_no_duplication<-nrow(data)
648 | difference<-(rows_data_duplicate-rows_no_duplication)
649 | month<-c("may")
650 | duplication<-data.frame(rows_data_duplicate,rows_no_duplication,difference, month, row.names = NULL)
651 | dir.create(file.path("E:/test_division/division_finale2013/file_list_months_weeks"), showWarnings=F)
652 | directory_stats_duplications=paste("E:/test_division/division_finale2013/file_list_months_weeks/duplication_may.csv")
653 | write.table (duplication, directory_stats_duplications , row.names=F, sep=";")
654 |
655 | data$timestamp_pretty<-as.character(data$timestamp_pretty)
656 | data$shipType<-as.character(data$shipType)
657 |
658 | directory_final=paste("E:/test_division/division_finale2013/file_list_months_weeks/ais_may_2013.csv")
659 | write.table (data, directory_final, row.names=F, sep=",")
660 |
661 | library(mail)
662 | ###sendmail("florent.nicolas@helcom.fi", "AIS may 2013 is merged", " AIS may 2013 is merged", password="rmail")
663 |
664 |
665 |
666 | ###june 06 Merging all files in each month_folder to have 1 file per month
667 | rm(list = ls()[!ls() %in% c("start.time")])
668 | setwd("E:/test_division/division_finale2013/june")
669 | fileList <- list.files(pattern="data_2013_junefinal*", recursive=FALSE)
670 | library(plyr)
671 | data <- ldply(fileList, read.table, header=T, sep = ",", fill=T)
672 | data <- subset(data, !(is.na(timestamp_pretty) ))
673 |
674 | data$imo<-as.numeric(data$imo)
675 | not_clean_imo<-sum(is.na(data$imo))
676 | data$imo[is.na(data$imo)] <- NA
677 | #for too big IMO numbers:
678 | data$imo[data$imo < 999999] <- NA
679 | #for too small IMO numbers:
680 | data$imo[data$imo >9999999] <- NA
681 |
682 | rows_data_duplicate<-nrow(data)
683 | data <- unique(data)
684 | rows_no_duplication<-nrow(data)
685 | difference<-(rows_data_duplicate-rows_no_duplication)
686 | month<-c("june")
687 | duplication<-data.frame(rows_data_duplicate,rows_no_duplication,difference, month, row.names = NULL)
688 | dir.create(file.path("E:/test_division/division_finale2013/file_list_months_weeks"), showWarnings=F)
689 | directory_stats_duplications=paste("E:/test_division/division_finale2013/file_list_months_weeks/duplication_june.csv")
690 | write.table (duplication, directory_stats_duplications , row.names=F, sep=";")
691 |
692 | data$timestamp_pretty<-as.character(data$timestamp_pretty)
693 | data$shipType<-as.character(data$shipType)
694 |
695 | directory_final=paste("E:/test_division/division_finale2013/file_list_months_weeks/ais_june_2013.csv")
696 | write.table (data, directory_final, row.names=F, sep=",")
697 |
698 |
699 |
700 | ###july 07 Merging all files in each month_folder to have 1 file per month
701 | rm(list = ls()[!ls() %in% c("start.time")])
702 | setwd("E:/test_division/division_finale2013/july")
703 | fileList <- list.files(pattern="data_2013_julyfinal*", recursive=FALSE)
704 | library(plyr)
705 | data <- ldply(fileList, read.table, header=T, sep = ",", fill=T)
706 | data <- subset(data, !(is.na(timestamp_pretty) ))
707 |
708 | data$imo<-as.numeric(data$imo)
709 | not_clean_imo<-sum(is.na(data$imo))
710 | data$imo[is.na(data$imo)] <- NA
711 | #for too big IMO numbers:
712 | data$imo[data$imo < 999999] <- NA
713 | #for too small IMO numbers:
714 | data$imo[data$imo >9999999] <- NA
715 |
716 | rows_data_duplicate<-nrow(data)
717 | data <- unique(data)
718 | rows_no_duplication<-nrow(data)
719 | difference<-(rows_data_duplicate-rows_no_duplication)
720 | month<-c("july")
721 | duplication<-data.frame(rows_data_duplicate,rows_no_duplication,difference, month, row.names = NULL)
722 | dir.create(file.path("E:/test_division/division_finale2013/file_list_months_weeks"), showWarnings=F)
723 | directory_stats_duplications=paste("E:/test_division/division_finale2013/file_list_months_weeks/duplication_july.csv")
724 | write.table (duplication, directory_stats_duplications , row.names=F, sep=";")
725 |
726 | data$timestamp_pretty<-as.character(data$timestamp_pretty)
727 | data$shipType<-as.character(data$shipType)
728 |
729 | directory_final=paste("E:/test_division/division_finale2013/file_list_months_weeks/ais_july_2013.csv")
730 | write.table (data, directory_final, row.names=F, sep=",")
731 |
732 |
733 |
734 | ###august 08
735 | rm(list = ls()[!ls() %in% c("start.time")])
736 | setwd("E:/test_division/division_finale2013/august")
737 | fileList <- list.files(pattern="data_2013_augustfinal*", recursive=FALSE)
738 | library(plyr)
739 | data <- ldply(fileList, read.table, header=T, sep = ",", fill=T)
740 | data <- subset(data, !(is.na(timestamp_pretty) ))
741 |
742 | data$imo<-as.numeric(data$imo)
743 | not_clean_imo<-sum(is.na(data$imo))
744 | data$imo[is.na(data$imo)] <- NA
745 | #for too big IMO numbers:
746 | data$imo[data$imo < 999999] <- NA
747 | #for too small IMO numbers:
748 | data$imo[data$imo >9999999] <- NA
749 |
750 | rows_data_duplicate<-nrow(data)
751 | data <- unique(data)
752 | rows_no_duplication<-nrow(data)
753 | difference<-(rows_data_duplicate-rows_no_duplication)
754 | month<-c("august")
755 | duplication<-data.frame(rows_data_duplicate,rows_no_duplication,difference, month, row.names = NULL)
756 | dir.create(file.path("E:/test_division/division_finale2013/file_list_months_weeks"), showWarnings=F)
757 | directory_stats_duplications=paste("E:/test_division/division_finale2013/file_list_months_weeks/duplication_august.csv")
758 | write.table (duplication, directory_stats_duplications , row.names=F, sep=";")
759 |
760 | data$timestamp_pretty<-as.character(data$timestamp_pretty)
761 | data$shipType<-as.character(data$shipType)
762 |
763 | directory_final=paste("E:/test_division/division_finale2013/file_list_months_weeks/ais_august_2013.csv")
764 | write.table (data, directory_final, row.names=F, sep=",")
765 |
766 | library(mail)
767 | ###sendmail("florent.nicolas@helcom.fi", "AIS august 2013 is merged", " AIS august 2013 is merged", password="rmail")
768 |
769 |
770 |
771 | ###september 09 Merging all files in each month_folder to have 1 file per month
772 | rm(list = ls()[!ls() %in% c("start.time")])
773 | setwd("E:/test_division/division_finale2013/september")
774 | fileList <- list.files(pattern="data_2013_septemberfinal*", recursive=FALSE)
775 | library(plyr)
776 | data <- ldply(fileList, read.table, header=T, sep = ",", fill=T)
777 | data <- subset(data, !(is.na(timestamp_pretty) ))
778 |
779 | data$imo<-as.numeric(data$imo)
780 | not_clean_imo<-sum(is.na(data$imo))
781 | data$imo[is.na(data$imo)] <- NA
782 | #for too big IMO numbers:
783 | data$imo[data$imo < 999999] <- NA
784 | #for too small IMO numbers:
785 | data$imo[data$imo >9999999] <- NA
786 |
787 | rows_data_duplicate<-nrow(data)
788 | data <- unique(data)
789 | rows_no_duplication<-nrow(data)
790 | difference<-(rows_data_duplicate-rows_no_duplication)
791 | month<-c("september")
792 | duplication<-data.frame(rows_data_duplicate,rows_no_duplication,difference, month, row.names = NULL)
793 | dir.create(file.path("E:/test_division/division_finale2013/file_list_months_weeks"), showWarnings=F)
794 | directory_stats_duplications=paste("E:/test_division/division_finale2013/file_list_months_weeks/duplication_september.csv")
795 | write.table (duplication, directory_stats_duplications , row.names=F, sep=";")
796 |
797 | data$timestamp_pretty<-as.character(data$timestamp_pretty)
798 | data$shipType<-as.character(data$shipType)
799 |
800 | directory_final=paste("E:/test_division/division_finale2013/file_list_months_weeks/ais_september_2013.csv")
801 | write.table (data, directory_final, row.names=F, sep=",")
802 |
803 |
804 |
805 |
806 | ###october 10 Merging all files in each month_folder to have 1 file per month
807 | rm(list = ls()[!ls() %in% c("start.time")])
808 | setwd("E:/test_division/division_finale2013/october")
809 | fileList <- list.files(pattern="data_2013_octoberfinal*", recursive=FALSE)
810 | library(plyr)
811 | data <- ldply(fileList, read.table, header=T, sep = ",", fill=T)
812 | data <- subset(data, !(is.na(timestamp_pretty) ))
813 |
814 | data$imo<-as.numeric(data$imo)
815 | not_clean_imo<-sum(is.na(data$imo))
816 | data$imo[is.na(data$imo)] <- NA
817 | #for too big IMO numbers:
818 | data$imo[data$imo < 999999] <- NA
819 | #for too small IMO numbers:
820 | data$imo[data$imo >9999999] <- NA
821 |
822 | rows_data_duplicate<-nrow(data)
823 | data <- unique(data)
824 | rows_no_duplication<-nrow(data)
825 | difference<-(rows_data_duplicate-rows_no_duplication)
826 | month<-c("october")
827 | duplication<-data.frame(rows_data_duplicate,rows_no_duplication,difference, month, row.names = NULL)
828 | dir.create(file.path("E:/test_division/division_finale2013/file_list_months_weeks"), showWarnings=F)
829 | directory_stats_duplications=paste("E:/test_division/division_finale2013/file_list_months_weeks/duplication_october.csv")
830 | write.table (duplication, directory_stats_duplications , row.names=F, sep=";")
831 |
832 | data$timestamp_pretty<-as.character(data$timestamp_pretty)
833 | data$shipType<-as.character(data$shipType)
834 |
835 | directory_final=paste("E:/test_division/division_finale2013/file_list_months_weeks/ais_october_2013.csv")
836 | write.table (data, directory_final, row.names=F, sep=",")
837 |
838 | ###sendmail("florent.nicolas@helcom.fi", "AIS october 2013 is merged", " AIS october 2013 is merged", password="rmail")
839 |
840 |
841 | ###november 11 Merging all files in each month_folder to have 1 file per month
842 | rm(list = ls()[!ls() %in% c("start.time")])
843 | setwd("E:/test_division/division_finale2013/november")
844 | fileList <- list.files(pattern="data_2013_novemberfinal*", recursive=FALSE)
845 | library(plyr)
846 | data <- ldply(fileList, read.table, header=T, sep = ",", fill=T)
847 | data <- subset(data, !(is.na(timestamp_pretty) ))
848 |
849 | data$imo<-as.numeric(data$imo)
850 | not_clean_imo<-sum(is.na(data$imo))
851 | data$imo[is.na(data$imo)] <- NA
852 | #for too big IMO numbers:
853 | data$imo[data$imo < 999999] <- NA
854 | #for too small IMO numbers:
855 | data$imo[data$imo >9999999] <- NA
856 |
857 | rows_data_duplicate<-nrow(data)
858 | data <- unique(data)
859 | rows_no_duplication<-nrow(data)
860 | difference<-(rows_data_duplicate-rows_no_duplication)
861 | month<-c("november")
862 | duplication<-data.frame(rows_data_duplicate,rows_no_duplication,difference, month, row.names = NULL)
863 | dir.create(file.path("E:/test_division/division_finale2013/file_list_months_weeks"), showWarnings=F)
864 | directory_stats_duplications=paste("E:/test_division/division_finale2013/file_list_months_weeks/duplication_november.csv")
865 | write.table (duplication, directory_stats_duplications , row.names=F, sep=";")
866 |
867 | data$timestamp_pretty<-as.character(data$timestamp_pretty)
868 | data$shipType<-as.character(data$shipType)
869 |
870 | directory_final=paste("E:/test_division/division_finale2013/file_list_months_weeks/ais_november_2013.csv")
871 | write.table (data, directory_final, row.names=F, sep=",")
872 |
873 |
874 |
875 |
876 | ###december 12 Merging all files in each month_folder to have 1 file per month
877 | rm(list = ls()[!ls() %in% c("start.time")])
878 | setwd("E:/test_division/division_finale2013/december")
879 | fileList <- list.files(pattern="data_2013_decemberfinal*", recursive=FALSE)
880 | library(plyr)
881 | data <- ldply(fileList, read.table, header=T, sep = ",", fill=T)
882 | data <- subset(data, !(is.na(timestamp_pretty) ))
883 |
884 | data$imo<-as.numeric(data$imo)
885 | not_clean_imo<-sum(is.na(data$imo))
886 | data$imo[is.na(data$imo)] <- NA
887 | #for too big IMO numbers:
888 | data$imo[data$imo < 999999] <- NA
889 | #for too small IMO numbers:
890 | data$imo[data$imo >9999999] <- NA
891 |
892 | rows_data_duplicate<-nrow(data)
893 | data <- unique(data)
894 | rows_no_duplication<-nrow(data)
895 | difference<-(rows_data_duplicate-rows_no_duplication)
896 | month<-c("december")
897 | duplication<-data.frame(rows_data_duplicate,rows_no_duplication,difference, month, row.names = NULL)
898 | dir.create(file.path("E:/test_division/division_finale2013/file_list_months_weeks"), showWarnings=F)
899 | directory_stats_duplications=paste("E:/test_division/division_finale2013/file_list_months_weeks/duplication_december.csv")
900 | write.table (duplication, directory_stats_duplications , row.names=F, sep=";")
901 |
902 | data$timestamp_pretty<-as.character(data$timestamp_pretty)
903 | data$shipType<-as.character(data$shipType)
904 |
905 | directory_final=paste("E:/test_division/division_finale2013/file_list_months_weeks/ais_december_2013.csv")
906 | write.table (data, directory_final, row.names=F, sep=",")
907 |
908 | library(mail)
909 | ###sendmail("florent.nicolas@helcom.fi", "AIS december 2013 is merged", " AIS december 2013 is merged", password="rmail")
910 | rm(list = ls()[!ls() %in% c("start.time")])
911 |
912 |
913 |
914 |
915 |
916 |
917 | # Step 5: division of monthly files in weekly files (optional) -----------------------
918 |
919 | ### table per week new test (14082013):
920 | # taking lot of time to generate, not efficient
921 |
922 |
923 | #rm(list = ls())
924 | #setwd("E:/test_division/division_finale2013/file_list_months_weeks")
925 | #fileList <- list.files(pattern="scope_ais_.*\\.csv", recursive=FALSE)
926 | #for (i in 1:52){
927 | # for (file in fileList){
928 | #data_2013<-read.table(file, header=T, fill=T, sep=",")
929 | #data_2013<-data_2013[data_2013$week == i, ]
930 | #nrow<-as.numeric(nrow(data_2013))
931 | #if(nrow>0){
932 | #data_2013 <- data_2013[order(data_2013$timestamp_pretty) , ]
933 | #dir.create(file.path("E:/test_division/division_finale2013/file_list_months_weeks"), showWarnings=F)
934 |
935 | #time in UTC GMT seconds in the filename to avoir overwritting
936 | #install.packages("stringr")
937 | #a<-Sys.time()
938 | #library(stringr)
939 | #a<-str_replace_all(a, fixed(" "), "_")
940 | #a<-str_replace_all(a, fixed(":"), "_")
941 | #a<-str_replace_all(a, fixed("-"), "_")
942 |
943 | #directory_divisions=paste("E:/test_division/division_finale2013/file_list_months_weeks/data_2013_scope_week",i, sep="_", a, ".csv")
944 | #write.table (data_2013, directory_divisions, row.names=F, sep=",")
945 | #} else {
946 | #} } }
947 |
948 | #library(mail)
949 | ###sendmail("florent.nicolas@helcom.fi", "AIS monthly and weekly files ready", "The final step is done: weekly files are ready (I hope so...). weekly and monthly files WITHOUT DUPLICATION are available", password="rmail")
950 |
951 | # Empty the environment and close R ---------------------------------------
952 |
953 | # delete temp files (divisions)
954 | setwd("E:/test_division/division_finale2013/")
955 | #fileList <- list.files(pattern="division_ais_2013.*\\.csv", recursive=FALSE)
956 | #for (file in fileList) {
957 | #unlink(file)
958 | #}
959 |
960 |
961 | # time taken to process
962 | end.time <- Sys.time()
963 | time.taken <- end.time - start.time
964 | time.taken
965 | str(time.taken)
966 | unit <- attr(time.taken, "units")
967 | time.taken <- paste(time.taken,unit,"")
968 |
969 | start.time
970 | end.time
971 | time.taken
972 |
973 | #save time taken
974 | year <- 2013
975 |
976 | dir.create(file.path("E:/test_division/time to process"), showWarnings=F)
977 | directory_time.taken <- paste("E:/test_division/time to process/time_to_pre_process_" , year, sep="", ".csv" )
978 | write.table(time.taken, directory_time.taken, sep=";", col.names = F, row.names=F)
979 |
980 |
981 | #empty temp memory and close R
982 | #rm(list = ls())
983 | #rm(list = ls())
984 | #quit(save = "yes")
--------------------------------------------------------------------------------
/Script 2. Merging statistics.R:
--------------------------------------------------------------------------------
1 | ##### Script 2
2 | # Developped by Florent NICOLAS, HELCOM Secretariat - 2017
3 | # R Version 3.4.3
4 |
5 |
6 |
7 | ##Merging descriptive statistics for the year 2013
8 | ##For another year, replace 2013 by the year wanted
9 |
10 | # Part 1: merging the monthly statistics (total and duplicated signals_ to be done only after the monthly files are done)
11 | # Part 2: merging the statistics for the year 2013 (to be done when the divisions are ready)
12 |
13 |
14 | # Part 1 : Merging the monthly statistics files (Number of signals and duplication) ------------------------------------
15 | rm(list = ls())
16 | setwd("E:/test_division/division_finale2013/file_list_months_weeks")
17 |
18 | fileList <- list.files(pattern="duplication_*", recursive=FALSE)
19 | library(plyr)
20 | duplication_2013 <- ldply(fileList, read.table, header=T, sep = ";", fill=T)
21 |
22 | directory_stats_duplications=paste("E:/test_division/division_finale2013/file_list_months_weeks/signals_2013.csv")
23 | #directory_stats_duplications=paste("E:/test_division/division_finale2013/180seconds/file_list_months_weeks/signals_2013.csv")
24 |
25 | write.table (duplication_2013, directory_stats_duplications , row.names=F, sep=";", quote=F)
26 | library(mail)
27 | #sendmail("your_email@domain.domain", "monthly statistics files 2013 (Number of signals and duplication) are merged", "monthly statistics files 2013 (Number of signals and duplication) are merged", password="rmail")
28 | rm(list = ls())
29 |
30 |
31 | # Part 2 : Merging the statistics for the year 2013 ------------------------------------
32 | rm(list = ls())
33 | setwd("E:/test_division/division_finale2013/")
34 | fileList <- list.files(pattern="stats_.*\\,.csv", recursive=TRUE)
35 | lenghtlist<-as.numeric(length(fileList))
36 | for (file in fileList) {
37 |
38 | library(plyr)
39 | data <- ldply(fileList, read.table, header=T, sep = ",")
40 | #data$Errors<-as.numeric(data$Errors)
41 | dir.create(file.path("E:/test_division/division_finale2013/statistics_2013"), showWarnings=F)
42 | directory_final=paste("E:/test_division/division_finale2013/statistics_2013/temp_statistics_2013", ".csv")
43 | write.table (data, directory_final, row.names=F, sep=";", quote=F)
44 |
45 | }
46 |
47 | temp <- read.csv("E:/test_division/division_finale2013/statistics_2013/temp_statistics_2013 .csv", sep=";")
48 | temp$signals<-as.numeric(temp$signals)
49 | test_merge_statistics <- ddply(temp, c("parameters"), summarise,
50 | signals = sum(signals))
51 |
52 | write.table (test_merge_statistics, "E:/test_division/division_finale2013/statistics_2013/statistics_2013.csv", row.names=F, sep=";")
53 |
54 | library(mail)
55 | #sendmail("your_email@domain.domain", "all statistics 2013 merged", "all statistics 2013 merged", password="rmail")
56 |
57 | rm(list = ls())
58 | rm(list = ls())
59 |
60 |
--------------------------------------------------------------------------------
/Script 3. Shiplist from AIS monthly files.R:
--------------------------------------------------------------------------------
1 | #####################################################################
2 | #
3 | # R Script to produce yearly ship list
4 | # Developped by Florent NICOLAS, HELCOM Secretariat - 2017
5 | # R Version 3.4.3
6 | #
7 | # Input data : AIS monthly files for the year XXXX (script 1)
8 | # Ouput data: Shiplist for the year XXXX with upgraded ship information from a commercial provider
9 | #
10 | # You have to replace (CTR A + CTR F) the year 2013 with the year wanted
11 | #
12 | #####################################################################
13 |
14 | rm(list = ls())
15 |
16 |
17 | # Step 1: create ship list of ships from AIS monthly files ------------------------------------
18 |
19 | ###### file list to select monthly files AIS data
20 | setwd("E:/test_division/division_finale2013/file_list_months_weeks")
21 | #setwd("E:/test_division/division_finale2013/180seconds/file_list_months_weeks")
22 | fileList <- list.files(pattern="ais_.*\\.csv", recursive=FALSE )
23 |
24 | i=1
25 | for (file in fileList) {
26 |
27 | ###### read the AIS table
28 | data<-read.table(file, header=T, fill=T, sep=",")
29 | data$imo<-as.numeric(as.character(data$imo))
30 | data$mmsi<-as.numeric(as.character(data$mmsi))
31 |
32 | ######apply your script to each of the AIS tables (monthly tableS)
33 |
34 | ##chose variables
35 | data <- data[,c("mmsi","imo","targetType", "shipType","dimBow","dimPort","dimStarboard","draught","dimStern", "callsign", "country", "name")]
36 |
37 | #remove same signals
38 | data <- data[!duplicated(data),]
39 |
40 | ###### write (= export) the 12 tables
41 | dir.create(file.path("E:/test_division/division_finale2013/ship_list/"), showWarnings=F)
42 | dir.create(file.path("E:/test_division/division_finale2013/ship_list/ship_list_temp/"), showWarnings=F)
43 | directory_PRF_2013=paste("E:/test_division/division_finale2013/ship_list/ship_list_temp/AIS_shipList_", i,sep=",", ".csv")
44 | write.table (data, directory_PRF_2013, row.names=F, sep=";")
45 | i=i+1
46 | }
47 |
48 |
49 | ####### to merge the 12 files to have one single file_list
50 | rm(list = ls())
51 | rm(list = ls())
52 | #set your working directory where the 12 files are
53 | setwd("E:/test_division/division_finale2013/ship_list/ship_list_temp/")
54 |
55 | #create the file list with the patter small_ship_list,....
56 | fileList <- list.files(pattern="AIS_shipList_,*", recursive=FALSE)
57 | library(plyr)
58 |
59 | # ldply to merge the files:
60 | data <- ldply(fileList, read.table, header=T, sep = ";", fill=T)
61 |
62 | #remove duplication in the files:
63 | data <- data[!duplicated(data),]
64 |
65 | #data <- unique(data)
66 |
67 | #remove the duplication if the dimensions of the ship are different but same mmsi
68 | # we keep the signal with the IMO number (if available) and the bigger draught
69 | data$mmsi<-as.numeric(as.character(data$mmsi))
70 | data$imo<-as.numeric(as.character(data$imo))
71 | data$draught<-as.numeric(as.character(data$draught))
72 | data <- data[order(-data$mmsi,-data$imo,-data$draught),]
73 |
74 | # separate imo and non imo
75 | data_non_imo <- subset(data, is.na(data$imo))
76 | data_imo <- subset(data, !is.na(data$imo))
77 |
78 | # remove duplicated imo
79 | data_imo<- data_imo[!duplicated(data_imo$imo),]
80 |
81 | # remerge imo and non imo
82 | data <- rbind(data_non_imo,data_imo)
83 |
84 | #t <- subset(data, data$imo == 7432202)
85 |
86 |
87 | #write final shipList_2013
88 | directory_final=paste("E:/test_division/division_finale2013/ship_list/ship_list_2013_final.csv")
89 | write.table (data, directory_final, row.names=F, sep=";", quote=T)
90 |
91 | #write final shipList_2013 to be merged with VF
92 | directory_final=paste("E:/ship_list/temp_AIS/ship_list_2013_final.csv")
93 | write.table (data, directory_final, row.names=F, sep=";", quote=T)
94 |
95 | # send mail notification and empty environment ------------------------------------
96 | library(mail)
97 | #sendmail("florent.nicolas@helcom.fi", "Shiplist 2013 done", " Shiplist 2013 done", password="rmail")
98 | rm(list = ls())
99 | rm(list = ls())
100 | rm(list = ls())
101 |
102 |
103 |
104 | # Step 2: FINAL TABLE 2 : merging ship list AIS with ship provider information ------------------------------------
105 | rm(list = ls())
106 | rm(list = ls())
107 |
108 | setwd("E:/ship_list/temp_AIS")
109 | #ship_list_2013 <- read.csv("ship_list_2013_final.csv", sep=";")
110 | ship_list_2013 <- read.csv("E:/ship_list/temp_AIS/ship_list_2013_final.csv", sep=";")
111 |
112 | ship_list_2013$year <- 2013
113 |
114 | #add country (following the MID from the MMSI)
115 | # 3. add MID and flag
116 | #ship_list_2013$MID <- substr(ship_list_2013$mmsi,1,3)
117 | #MID <- read.csv("//hcvhost01/data/MID.csv", sep=";", quote="")
118 | #ship_list_2013<-merge(ship_list_2013, MID, by="MID")
119 | #remove special characters
120 | #ship_list_2013$country <- gsub("([\\])","", ship_list_2013$country)
121 | #ship_list_2013$country <- gsub("[][!#$%()*.:;<=>@^_`|~.{}]", "", ship_list_2013$country)
122 |
123 | ship_list <- read.csv("HELCOM-Maritime-Database_ALL.csv", sep=";", na.strings =c("", "--", "NA") )
124 | ship_list[ship_list == 0] <- NA
125 | # rename column for tonnage
126 | colnames(ship_list)[which(colnames(ship_list) == 'GROSS.TONNAGE')] <- 'VF_GROSS_TONNAGE'
127 | colnames(ship_list)[which(colnames(ship_list) == 'NET.TONNAGE')] <- 'VF_NET_TONNAGE'
128 |
129 | #merging to have final shiplist
130 | year_2013 <- merge(ship_list_2013,ship_list,by.x='imo',by.y='imo',all.x=TRUE)
131 |
132 | no_year<-as.numeric(nrow(subset(year_2013,(is.na(year) ))))
133 | #year_2013 <-subset(year_2013, imo == "6814128" | imo == "1234567" | imo == "5338555" | imo == "5104253" )
134 |
135 | #add lenght and width to the AIS information
136 | year_2013$dimStern <- as.numeric(year_2013$dimStern)
137 | year_2013$dimBow <- as.numeric(year_2013$dimBow)
138 | year_2013$dimPort <- as.numeric(year_2013$dimPort)
139 | year_2013$dimStarboard <- as.numeric(year_2013$dimStarboard)
140 | year_2013$draught <- as.numeric(year_2013$draught)
141 |
142 | year_2013$length_AIS <- year_2013$dimBow + year_2013$dimStern
143 | year_2013$width_AIS <- year_2013$dimPort + year_2013$dimStarboard
144 |
145 | year_2013$length_AIS [year_2013$length_AIS == 0 & is.numeric(year_2013$length_AIS )] <- NA
146 | year_2013$width_AIS [year_2013$width_AIS == 0 & is.numeric(year_2013$width_AIS )] <- NA
147 | year_2013$draught [year_2013$draught == 0 & is.numeric(year_2013$draught )] <- NA
148 |
149 | #replace the shiptype, dimensions, etc. if == NA from VF
150 | year_2013$shipType_final<- ifelse(is.na(year_2013$VF_SHIP_TYPE), as.character(year_2013$shipType), as.character(year_2013$VF_SHIP_TYPE))
151 | #year_2013$shipType_final<-as.factor(year_2013$shipType_final)
152 | year_2013$name_final<- ifelse(is.na(year_2013$VF_NAME), as.character(year_2013$name), as.character(year_2013$VF_NAME))
153 |
154 | year_2013$length_final <- ifelse(is.na(year_2013$VF_LENGTH), as.numeric(year_2013$length_AIS), as.numeric(year_2013$VF_LENGTH))
155 | year_2013$width_final <- ifelse(is.na(year_2013$VF_WIDTH), as.numeric(year_2013$width_AIS),as.numeric(year_2013$VF_WIDTH))
156 | year_2013$draught_final <- ifelse(is.na(year_2013$VF_DRAUGHT), as.numeric(year_2013$draught), as.numeric(year_2013$VF_DRAUGHT))
157 |
158 | # select relevant parameters
159 | #year_2013<- year_2013[,c("imo","mmsi","callsign","country","targetType","year","name_final","length_final","width_final","draught_final", "shipType_final")]
160 |
161 | # add the HELCOM gross shiptype and detail shiptype
162 | gross_detail_shiptype <- read.csv("HELCOM_gross_detail_shiptypes.csv", sep=";")
163 | colnames(gross_detail_shiptype)[1] <- "shipType_final"
164 | colnames(gross_detail_shiptype)[2] <- "HELCOM_Gross_ShipType"
165 | colnames(gross_detail_shiptype)[3] <- "HELCOM_Detail_ShipType"
166 |
167 |
168 |
169 | # merge
170 | library(plyr)
171 | year_2013 <- join(year_2013, gross_detail_shiptype, by = "shipType_final")
172 | #remove white spaces and change upper case (only first letter is uppercase) and the slash for Gross_ShipType
173 | year_2013$HELCOM_Gross_ShipType <- gsub(" ", "", year_2013$HELCOM_Gross_ShipType, fixed = TRUE)
174 | year_2013$HELCOM_Gross_ShipType <- gsub("/", "", year_2013$HELCOM_Gross_ShipType, fixed = TRUE)
175 | year_2013$HELCOM_Detail_ShipType <- gsub(" ", "", year_2013$HELCOM_Detail_ShipType, fixed = TRUE)
176 |
177 | year_2013$HELCOM_Gross_ShipType <- tolower(year_2013$HELCOM_Gross_ShipType)
178 | year_2013$HELCOM_Detail_ShipType <- tolower(year_2013$HELCOM_Detail_ShipType)
179 | proper=function(x) paste0(toupper(substr(x, 1, 1)), tolower(substring(x, 2)))
180 | year_2013$HELCOM_Gross_ShipType <- proper(year_2013$HELCOM_Gross_ShipType)
181 | year_2013$HELCOM_Detail_ShipType <- proper(year_2013$HELCOM_Detail_ShipType)
182 |
183 | # test data (imo without shiptype)
184 | no_gross<- year_2013[is.na(year_2013$HELCOM_Gross_ShipType),]
185 | summary(no_gross$imo)
186 | no_detail<- year_2013[is.na(year_2013$HELCOM_Detail_ShipType),]
187 | summary(no_detail$imo)
188 |
189 | # rename column for tonnage
190 | colnames(year_2013)[which(colnames(year_2013) == 'VF_GROSS_TONNAGE')] <- 'Gross_tonnage'
191 | colnames(year_2013)[which(colnames(year_2013) == 'VF_NET_TONNAGE')] <- 'Net_tonnage'
192 |
193 | #### export data
194 | # select relevant parameters
195 | year_2013<- year_2013[,c("imo","mmsi","callsign","targetType","country","year","name_final","length_final","width_final","draught_final", "Gross_tonnage","Net_tonnage", "HELCOM_Gross_ShipType","HELCOM_Detail_ShipType")]
196 |
197 | # replace NANA with NA
198 | year_2013$HELCOM_Gross_ShipType<- as.character(year_2013$HELCOM_Gross_ShipType)
199 | year_2013$HELCOM_Detail_ShipType<- as.character(year_2013$HELCOM_Detail_ShipType)
200 | year_2013$HELCOM_Gross_ShipType[year_2013$HELCOM_Gross_ShipType == "NANA"] <- "Unknown"
201 | year_2013$HELCOM_Detail_ShipType[year_2013$HELCOM_Detail_ShipType == "NANA"] <- "Unknown"
202 |
203 | # replace Vehiclecarrierrorocargo to ROROcargo
204 | year_2013$HELCOM_Gross_ShipType[year_2013$HELCOM_Gross_ShipType == "Vehiclecarrierrorocargo"] <- "Rorocargo"
205 |
206 | t <- subset(year_2013, year_2013$imo == 7432202)
207 |
208 |
209 |
210 | # remove duplicated imo numbers (due to the last merging to dimensions and shiptypes):
211 | # we keep the signal with the IMO number (if available) and the bigger draught
212 | # separate imo and non imo
213 | year_2013_non_imo <- subset(year_2013, is.na(year_2013$imo))
214 | year_2013_imo <- subset(year_2013, !is.na(year_2013$imo))
215 |
216 | # sort by imo and draught
217 | #year_2013_imo$imo <- as.numeric(year_2013_imo$imo)
218 | year_2013_imo <- year_2013_imo[order(-year_2013_imo$imo,-year_2013_imo$draught),]
219 |
220 | # remove duplicated imo
221 | year_2013_imo<- year_2013_imo[!duplicated(year_2013_imo$imo),]
222 |
223 | # remerge imo and non imo
224 | year_2013_all <- rbind(year_2013_imo,year_2013_non_imo)
225 |
226 |
227 |
228 |
229 |
230 |
231 |
232 | #write table and dbf to produce density maps
233 | write.table(year_2013_all, "E:/ship_list/shiplist_2013_final.csv", row.names=F, sep=";")
234 |
235 |
236 | # send mail notification and empty environment ------------------------------------
237 | library(mail)
238 | #sendmail("your_email@domain.domain", "Shiplist 2013 merged with VF done", "Shiplist 2013 merged with VF done", password="rmail")
239 |
240 | #to do a final check of the shiptypes
241 | year_2013$HELCOM_Gross_ShipType <- as.factor(year_2013$HELCOM_Gross_ShipType)
242 | summary(year_2013$HELCOM_Gross_ShipType)
243 |
244 | year_2013$HELCOM_Detail_ShipType <- as.factor(year_2013$HELCOM_Detail_ShipType)
245 | summary(year_2013$HELCOM_Detail_ShipType)
246 |
247 | rm(list = ls())
248 | rm(list = ls())
249 | rm(list = ls())
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 |
--------------------------------------------------------------------------------
/Script 4. Generate_events.R:
--------------------------------------------------------------------------------
1 | #####################################################################
2 | #
3 | # R Script to generate events statistics using AIS data (trips, stops, enters, exits, etc.)
4 | # Developped by Florent NICOLAS, HELCOM Secretariat - 2017
5 | # R Version 3.4.3
6 | #
7 | # Input data : AIS monthly files
8 | # Ouput data: Events yearly files (E:/Events_V2/Events_YEAR.csv)
9 | #
10 | # !! you have to enter the year that you want to process in the field below (row 17)
11 | #
12 | #####################################################################
13 |
14 | rm(list = ls())
15 | rm(list = ls())
16 |
17 | year = 2007
18 |
19 | # packages needed
20 |
21 | # to undo (from 6/12)
22 | #install.packages("maps")
23 |
24 | library("sp")
25 | library("rgdal")
26 | library("maps")
27 | library("rworldmap")
28 | library("RgoogleMaps")
29 | library("plyr")
30 | library("dplyr")
31 | library("tidyr")
32 | library("data.table")
33 | library("lubridate")
34 |
35 | # time for producing the files:
36 | start.time <- Sys.time()
37 |
38 | #prepare directory for exporting the outcome
39 | dir.to.create <- "E:/Events_V2/"
40 | dir.create(file.path(dir.to.create), showWarnings=F)
41 |
42 | dir.to.create <- paste(dir.to.create,year,sep="")
43 | dir.create(file.path(dir.to.create), showWarnings=F)
44 |
45 | dir.to.create <- paste(dir.to.create,"/", "monthly", sep="")
46 | dir.create(file.path(dir.to.create), showWarnings=F)
47 |
48 |
49 | # 1. input data: AIS monthly files with a filelist
50 | working.dir <- paste("E:/test_division/division_finale", year, "/file_list_months_weeks", sep="")
51 | #setwd("D:/HELCOM AIS data/division_finale2016/file_list_months_weeks") #if data on D drive
52 | setwd(working.dir) # auto setwd with year as variable
53 | fileList <- list.files(pattern="ais_.*\\.csv", recursive=FALSE)
54 |
55 | for (file in fileList) {
56 | df <- read.table(file, header=T, fill=T, sep=",", na.strings=c(""," ","null", "NA"))
57 |
58 | ###### TEST ONLY
59 | #df <- read.csv("D:/HELCOM AIS data/division_finale2014/file_list_months_weeks/ais_june_2014.csv", header=T, fill=T, nrows=100000)
60 |
61 | ########## add column names (parameters) and select relevant parameters FOR YEARS 2016, 2016 and 2016 ONLY
62 |
63 |
64 | #colnames(df)<-c( "timestamp_pretty","timestamp","msgid","targetType","mmsi","lat","long","posacc","sog","cog","shipType","dimBow",
65 | # "dimport","dimStarboard","dimStern","shipTypeCargoTypeCode","shipType","destination","imo","eta")
66 | #################
67 | #################
68 | #################
69 | ################# PREPARE DATA
70 | #################
71 | #################
72 | #################
73 | #################
74 |
75 | df<- df[,c("timestamp_pretty","timestamp","mmsi", "lat","long", "sog", "cog", "imo")]
76 | #df = df[-1,]
77 |
78 | # 2. prepare the timestamp
79 | Sys.setlocale("LC_TIME", "C")
80 | date <- strptime(df$timestamp_pretty, "%d/%m/%Y %H:%M:%S")
81 | month <- unique(months(as.Date(date)))
82 |
83 | # 3. removing wrong mmsi 111111111 and wrong imo
84 | df <- subset(df,df$mmsi != "111111111")
85 | df <- subset(df,df$imo != "1111111")
86 | df <- subset(df,df$imo != "2222222")
87 | df <- subset(df,df$imo != "3333333")
88 | df <- subset(df,df$imo != "4444444")
89 | df <- subset(df,df$imo != "5555555")
90 | df <- subset(df,df$imo != "6666666")
91 | df <- subset(df,df$imo != "7777777")
92 | df <- subset(df,df$imo != "8888888")
93 | df <- subset(df,df$imo != "9999999")
94 | #for too big IMO numbers:
95 | df$imo <- as.numeric(as.character(df$imo))
96 | df$imo[df$imo < 999999] <- NA
97 | #for too small IMO numbers:
98 | df$imo[df$imo >9999999] <- NA
99 |
100 | # 4. select only IMO ships and relevant parameters
101 | df<-subset(df, (!is.na(imo)))
102 | df<- df[,c("timestamp_pretty","imo", "sog", "cog", "lat","long")]
103 | df$imo<- as.numeric(df$imo)
104 |
105 | # 5. sort data by ship and time
106 | df <- df[order(df$imo, df$timestamp_pretty),]
107 |
108 | # 6 . positions as numerical values
109 | df$lat <- as.numeric(as.character(df$lat))
110 | df$long <- as.numeric(as.character(df$long))
111 |
112 | #################
113 | #################
114 | #################
115 | ################# GENERATE IN/OUT EVENTS
116 | #################
117 | #################
118 | #################
119 | #################
120 |
121 | # df is data
122 | # df is data
123 | # df is data
124 | data <- df
125 |
126 | ######################### ######################### ######################### A. Definition of the signals inside the polygons
127 | ######################### ######################### #########################
128 |
129 | # 7. definition of signals in exits and add port name
130 | coordinates(data) <- c("long", "lat")
131 | exit_baltic <-readOGR("W:/Florentdrafts","Exit_Baltic_Sea")
132 | #plot(exit_baltic)
133 | proj4string(data) <- proj4string(exit_baltic) # to confirm the same reference system
134 | into_exit_baltic <- !is.na(over(data, as(exit_baltic, "SpatialPolygons"))) # combine is.na() with over() to do the containment test; note that we
135 | mean(into_exit_baltic)
136 | data2<-as.data.frame(data) # build data frame called data2
137 | data2$into_exit_baltic <-into_exit_baltic *1
138 | into_exit_baltic <- over(data, exit_baltic[,"Name"]) # get the name of the exit: Skagen / Kiel Canal / Lappeenranta / Neva
139 | data2$Name_exit <- NA
140 | data2$Name_exit <- into_exit_baltic$Name # add the name
141 | summary(data2$Name_exit)
142 |
143 | #t <- subset(data2, data2$into_exit_baltic==TRUE)
144 | #newmap <- getMap(resolution = "low")
145 | #plot(newmap, xlim = c(5.39, 30), ylim = c(52, 65.5), asp = 1, col="grey") # plot to check
146 | #points(t$long, t$lat, col = "red", cex = 1)
147 |
148 | summary(data2$into_exit_baltic)
149 |
150 | data2$opp_into_exit_baltic <- ifelse(data2$into_exit_baltic== 1,0,1) # if not in the baltic, then outside or vice versa
151 |
152 | #t <- subset(data2, data2$opp_into_exit_baltic==0)
153 | #newmap <- getMap(resolution = "low")
154 | #plot(newmap, xlim = c(5.39, 30), ylim = c(52, 65.5), asp = 1, col="grey")
155 | #points(t$long, t$lat, col = "red", cex = 1) # plot to check
156 |
157 | # 8 . identify signals outside the Baltic Sea to be make sure to create new enter / exit if the ship is using the same location
158 | coordinates(data2) <- c("long", "lat")
159 | outside_exits_polygons <-readOGR("W:/Florentdrafts","Outside_Exits")
160 | #plot(outside_exits_polygons)
161 | proj4string(data2) <- proj4string(outside_exits_polygons) # to confirm the same reference system
162 |
163 | outside_exist_signals <- !is.na(over(data2, as(outside_exits_polygons, "SpatialPolygons"))) # combine is.na() with over() to do the containment test; note that we
164 | mean(outside_exist_signals)
165 |
166 | data2<-as.data.frame(data2) # build data frame
167 | data2$outside_exist_signals <-outside_exist_signals *1 # id the signals
168 |
169 |
170 | #data <- subset(data,outside_exist_signals==0 ) # select only signals that not in the polygons (so inside the Baltic Sea)
171 |
172 |
173 | ######################### ######################### ######################### B. Skagen
174 | ######################### ######################### #########################
175 | data <- subset(data2,data2$Name_exit == "Skagen" | (is.na(Name_exit)) )
176 | data <- data[order(data$imo, data$timestamp_pretty),]
177 | summary(data$Name_exit)
178 | #newmap <- getMap(resolution = "low")
179 | #plot(newmap, xlim = c(5.39, 30), ylim = c(52, 65.5), asp = 1, col="grey")
180 | #points(data$long, data$lat, col = "red", cex = 1)
181 |
182 | # 9. Count of passage in Skagen
183 | data$Passage <- setDT(data)[, v1 := if(all(!opp_into_exit_baltic)) c(TRUE, imo[-1]!= imo[-.N])
184 | else rep(FALSE, .N), .(grp = rleid(opp_into_exit_baltic))][,cumsum(v1)*(!opp_into_exit_baltic)]
185 |
186 | # 10. bearing N == 0 or South == 90
187 | data$cog2 <- NA
188 | data$cog<-as.numeric(data$cog)
189 | data$cog2 <- ifelse(80% # drop rows with Stop == 0
205 | unite(dates, timestamp_pretty, sep = " ") %>% #create date object
206 | mutate(dates = as.POSIXct(strptime(dates, format = "%d/%m/%Y %H:%M:%S"))) %>%
207 | group_by(Passage) %>% # for each stop
208 | filter(dates == min(dates) | dates == max(dates)) %>% #select rows with min and max dates
209 | dplyr::summarise(minTime = min(dates),
210 | maxTime = max(dates),
211 | duration_minutes = round(difftime(max(dates), min(dates), units="mins")),
212 | mean_COG= mean(cog),
213 | mean_COG2= mean(cog2),
214 | Ship = imo[1])
215 |
216 | # 12. Definition if exit or enter
217 | #summary(data_passage$mean_COG)
218 | #entering_Skagen <- subset(data_passage, data_passage$mean_COG < 260 & data_passage$mean_COG > 80 )
219 | #exiting_Skagen <- subset(data_passage, data_passage$mean_COG > 260 | data_passage$mean_COG < 80 )
220 | entering_Skagen <- subset(data_passage, data_passage$mean_COG2 ==180 )
221 | exiting_Skagen <- subset(data_passage, data_passage$mean_COG2 ==0 )
222 |
223 | rows_entering <- as.numeric(nrow(entering_Skagen))
224 | if (rows_entering !=0) entering_Skagen$event <- "enter" #add column event = enter or exit if there are observations
225 |
226 | rows_exiting <- as.numeric(nrow(exiting_Skagen))
227 | if (rows_exiting !=0) exiting_Skagen$event <- "exit" #add column event = enter or exit if there are observations
228 |
229 | # 13. merge all passages
230 | data_Skagen <- rbind(entering_Skagen,exiting_Skagen)
231 |
232 | # 14. add location name if there are observations
233 | rows_Skagen <- as.numeric(nrow(data_Skagen))
234 | if (rows_Skagen !=0) data_Skagen$name <- "Skagen"
235 |
236 | ######################### ######################### ######################### C. Kiel
237 | ######################### ######################### #########################
238 |
239 | data <- subset(data2,data2$Name_exit == "Kiel" | (is.na(Name_exit)) )
240 | summary(data$Name_exit)
241 | data <- data[order(data$imo, data$timestamp_pretty),]
242 |
243 | # 15. Count of passage in Kiel
244 | data$Passage <- setDT(data)[, v1 := if(all(!opp_into_exit_baltic)) c(TRUE, imo[-1]!= imo[-.N])
245 | else rep(FALSE, .N), .(grp = rleid(opp_into_exit_baltic))][,cumsum(v1)*(!opp_into_exit_baltic)]
246 |
247 | # 16. bearing N == 0 or South == 90
248 | data$cog2 <- NA
249 | data$cog<-as.numeric(data$cog)
250 | data$cog2 <- ifelse(180% # drop rows with Stop == 0
263 | unite(dates, timestamp_pretty, sep = " ") %>% #create date object
264 | mutate(dates = as.POSIXct(strptime(dates, format = "%d/%m/%Y %H:%M:%S"))) %>%
265 | group_by(Passage) %>% # for each stop
266 | filter(dates == min(dates) | dates == max(dates)) %>% #select rows with min and max dates
267 | summarise(minTime = min(dates),
268 | maxTime = max(dates),
269 | duration_minutes = round(difftime(max(dates), min(dates), units="mins")),
270 | mean_COG= mean(cog),
271 | mean_COG2= mean(cog2),
272 | Ship = imo[1])
273 |
274 | # 18. Definition if exit or enter
275 | #summary(data_passage$mean_COG)
276 | exiting_Kiel <- subset(data_passage, data_passage$mean_COG2 ==270 )
277 | entering_Kiel <- subset(data_passage, data_passage$mean_COG2 == 90 )
278 |
279 | rows_entering <- as.numeric(nrow(entering_Kiel)) #add column event = enter or exit if there are observations
280 | if (rows_entering !=0) entering_Kiel$event <- "enter"
281 |
282 | rows_exiting <- as.numeric(nrow(exiting_Kiel))
283 | if (rows_exiting !=0) exiting_Kiel$event <- "exit"
284 |
285 | # 19. merge all passages
286 | data_Kiel <- rbind(entering_Kiel,exiting_Kiel)
287 |
288 | # 20. add location name if there are observations
289 | rows_Kiel <- as.numeric(nrow(data_Kiel))
290 | if (rows_Kiel !=0) data_Kiel$name <- "Kiel"
291 |
292 |
293 | ######################### ######################### ######################### D. Neva River
294 | ######################### ######################### #########################
295 |
296 | data <- subset(data2,data2$Name_exit == "Neva_River" | (is.na(Name_exit)) )
297 | summary(data$Name_exit)
298 | data <- data[order(data$imo, data$timestamp_pretty),]
299 |
300 |
301 | # 21. Count of passage in Neva
302 | data$Passage <- setDT(data)[, v1 := if(all(!opp_into_exit_baltic)) c(TRUE, imo[-1]!= imo[-.N])
303 | else rep(FALSE, .N), .(grp = rleid(opp_into_exit_baltic))][,cumsum(v1)*(!opp_into_exit_baltic)]
304 |
305 | # 22. bearing N == 0 or South == 90
306 | data$cog2 <- NA
307 | data$cog<-as.numeric(data$cog)
308 | data$cog2 <- ifelse(270>data$cog & data$cog>90, "180", "0")
309 | data$cog2<- as.numeric(data$cog2)
310 | summary(data$cog2)
311 |
312 |
313 | detach(package:plyr)
314 | detach(package:dplyr)
315 | detach(package:tidyr)
316 | #detach(package:lubridate)
317 | library(plyr)
318 | library(tidyr)
319 | library(dplyr)
320 |
321 | # 23. Computer information about the passages in Skagen (time, cog, etc.)
322 | data_passage <- filter(data, Passage != 0) %>% # drop rows with Stop == 0
323 | unite(dates, timestamp_pretty, sep = " ") %>% #create date object
324 | mutate(dates = as.POSIXct(strptime(dates, format = "%d/%m/%Y %H:%M:%S"))) %>%
325 | group_by(Passage) %>% # for each stop
326 | filter(dates == min(dates) | dates == max(dates)) %>% #select rows with min and max dates
327 | dplyr::summarise(minTime = min(dates),
328 | maxTime = max(dates),
329 | duration_minutes = round(difftime(max(dates), min(dates), units="mins")),
330 | mean_COG= mean(cog),
331 | mean_COG2= mean(cog2),
332 | Ship = imo[1])
333 |
334 | # 24. Definition if exit or enter
335 | entering_Neva <- subset(data_passage, data_passage$mean_COG2 ==0 )
336 | exiting_Neva <- subset(data_passage, data_passage$mean_COG2 ==180 )
337 |
338 | rows_entering <- as.numeric(nrow(entering_Neva))
339 | if (rows_entering !=0) entering_Neva$event <- "enter"
340 |
341 | rows_exiting <- as.numeric(nrow(exiting_Neva))
342 | if (rows_exiting !=0) exiting_Neva$event <- "exit"
343 |
344 | # 25. merge all passages
345 | data_Neva <- rbind(entering_Neva,exiting_Neva)
346 |
347 | # 26. add location name if there are observations
348 | rows_Neva <- as.numeric(nrow(data_Neva))
349 | if (rows_Neva !=0) data_Neva$name <- "Neva"
350 |
351 |
352 | ######################### ######################### ######################### E. Lappeenranta
353 | ######################### ######################### #########################
354 |
355 | data <- subset(data2,data2$Name_exit == "Lappeenranta" | (is.na(Name_exit)) )
356 | summary(data$Name_exit)
357 | data <- data[order(data$imo, data$timestamp_pretty),]
358 |
359 | # 27. Count of passage in Lappeenranta
360 | data$Passage <- setDT(data)[, v1 := if(all(!opp_into_exit_baltic)) c(TRUE, imo[-1]!= imo[-.N])
361 | else rep(FALSE, .N), .(grp = rleid(opp_into_exit_baltic))][,cumsum(v1)*(!opp_into_exit_baltic)]
362 |
363 |
364 | # 28. bearing N == 0 or South == 90
365 | data$cog2 <- NA
366 | data$cog<-as.numeric(data$cog)
367 | data$cog2 <- ifelse(27090, "0", "180")
368 | data$cog2<- as.numeric(data$cog2)
369 | summary(data$cog2)
370 | #check_passage <- subset(data, data$Passage == 2 )
371 | #mean(check_passage$cog2)
372 |
373 | detach(package:plyr)
374 | detach(package:dplyr)
375 | detach(package:tidyr)
376 | #detach(package:lubridate)
377 | library(plyr)
378 | library(tidyr)
379 | library(dplyr)
380 |
381 | # 29. Computer information about the passages in Lappeenranta (time, cog, etc.)
382 | data_passage <- filter(data, Passage != 0) %>% # drop rows with Stop == 0
383 | unite(dates, timestamp_pretty, sep = " ") %>% #create date object
384 | mutate(dates = as.POSIXct(strptime(dates, format = "%d/%m/%Y %H:%M:%S"))) %>%
385 | group_by(Passage) %>% # for each stop
386 | filter(dates == min(dates) | dates == max(dates)) %>% #select rows with min and max dates
387 | dplyr::summarise(minTime = min(dates),
388 | maxTime = max(dates),
389 | duration_minutes = round(difftime(max(dates), min(dates), units="mins")),
390 | mean_COG= mean(cog),
391 | mean_COG2= mean(cog2),
392 | Ship = imo[1])
393 |
394 | # 30. Definition if exit or enter
395 | entering_Lappeenranta <- subset(data_passage, data_passage$mean_COG2 ==180 )
396 | exiting_Lappeenranta <- subset(data_passage, data_passage$mean_COG2 ==0 )
397 | entering_Lappeenranta <- subset(data_passage, data_passage$mean_COG2 ==0 )
398 | exiting_Lappeenranta <- subset(data_passage, data_passage$mean_COG2 ==180 )
399 |
400 |
401 | rows_entering <- as.numeric(nrow(entering_Lappeenranta)) #add column event = enter or exit if there are observations
402 | if (rows_entering !=0) entering_Lappeenranta$event <- "enter"
403 |
404 | rows_exiting <- as.numeric(nrow(exiting_Lappeenranta))
405 | if (rows_exiting !=0) exiting_Lappeenranta$event <- "exit"
406 |
407 | # 31. merge all passages
408 | data_Lappeenranta <- rbind(entering_Lappeenranta,exiting_Lappeenranta)
409 |
410 | # 32. add location name if there are observations
411 | rows_Lappeenranta <- as.numeric(nrow(data_Lappeenranta))
412 | if (rows_Lappeenranta !=0) data_Lappeenranta$name <- "Lappeenranta"
413 |
414 |
415 |
416 |
417 |
418 |
419 | ######################### ######################### ######################### F. Goteborg
420 | ######################### ######################### #########################
421 |
422 | data <- subset(data2,data2$Name_exit == "Goteborg" | (is.na(Name_exit)) )
423 | summary(data$Name_exit)
424 | data <- data[order(data$imo, data$timestamp_pretty),]
425 |
426 | #newmap <- getMap(resolution = "low")
427 | #plot(newmap, xlim = c(5.39, 30), ylim = c(52, 65.5), asp = 1, col="grey")
428 | #points(data$long, data$lat, col = "red", cex = 1)
429 |
430 | # 33. Count of passage in Goteborg
431 | data$Passage <- setDT(data)[, v1 := if(all(!opp_into_exit_baltic)) c(TRUE, imo[-1]!= imo[-.N])
432 | else rep(FALSE, .N), .(grp = rleid(opp_into_exit_baltic))][,cumsum(v1)*(!opp_into_exit_baltic)]
433 |
434 | # 34. bearing N == 0 or South == 90
435 | data$cog2 <- NA
436 | data$cog<-as.numeric(data$cog)
437 | data$cog2 <- ifelse(270>data$cog & 90% # drop rows with Stop == 0
451 | unite(dates, timestamp_pretty, sep = " ") %>% #create date object
452 | mutate(dates = as.POSIXct(strptime(dates, format = "%d/%m/%Y %H:%M:%S"))) %>%
453 | group_by(Passage) %>% # for each stop
454 | filter(dates == min(dates) | dates == max(dates)) %>% #select rows with min and max dates
455 | dplyr::summarise(minTime = min(dates),
456 | maxTime = max(dates),
457 | duration_minutes = round(difftime(max(dates), min(dates), units="mins")),
458 | mean_COG= mean(cog),
459 | mean_COG2= mean(cog2),
460 | Ship = imo[1])
461 |
462 | # 36. Definition if exit or enter
463 | entering_Goteborg <- subset(data_passage, data_passage$mean_COG2 ==180 )
464 | exiting_Goteborg <- subset(data_passage, data_passage$mean_COG2 ==0 )
465 |
466 | rows_entering <- as.numeric(nrow(entering_Goteborg))
467 | if (rows_entering !=0) entering_Goteborg$event <- "enter" #add column event = enter or exit if there are observations
468 |
469 |
470 | rows_exiting <- as.numeric(nrow(exiting_Goteborg))
471 | if (rows_exiting !=0) exiting_Goteborg$event <- "exit"
472 |
473 | # 37. merge all passages
474 | data_Goteborg <- rbind(entering_Goteborg,exiting_Goteborg)
475 |
476 | # 38. add location name if there are observations
477 | rows_goteborg <- as.numeric(nrow(data_Goteborg))
478 | if (rows_goteborg !=0) data_Goteborg$name <- "Goteborg"
479 |
480 |
481 | # 39. Merge Skagen, Kiel, Neva_river, Lappeenranta and Goteborg
482 | total_in_out <- rbind(data_Skagen,data_Kiel)
483 | total_in_out <- rbind(total_in_out,data_Neva)
484 | total_in_out <- rbind(total_in_out,data_Lappeenranta)
485 | total_in_out <- rbind(total_in_out,data_Goteborg)
486 | colnames(total_in_out)[4] <- "duration.minutes"
487 | total_in_out$duration.minutes <- NA
488 | colnames(total_in_out)[9] <- "Location"
489 | total_in_out$duration.hours <- round(total_in_out$duration.minutes/60,digits=2)
490 |
491 | total_in_out$Location <- as.factor(total_in_out$Location)
492 | summary(total_in_out$Location)
493 |
494 |
495 | ls()
496 | library(gdata)
497 |
498 | keep(df,total_in_out,date, exit_baltic, month, year, start.time, sure = TRUE)
499 |
500 |
501 |
502 | #################
503 | #################
504 | #################
505 | ################# trips_stops
506 | #################
507 | #################
508 | #################
509 | #################
510 |
511 | # 40. remove signals outside Skagen and inside Kiel
512 | data <- df
513 | coordinates(data) <- c("long", "lat")
514 | outside_exits_polygons <-readOGR("W:/Florentdrafts","Outside_Exits")
515 | #plot(outside_exits_polygons)
516 |
517 | # 41. confirm the same reference system
518 | proj4string(data) <- proj4string(outside_exits_polygons)
519 |
520 | # 42. overlap outside / exits and AIS data
521 | outside_exist_signals <- !is.na(over(data, as(outside_exits_polygons, "SpatialPolygons")))
522 | mean(outside_exist_signals)
523 |
524 | # 43. build data frame
525 | data<-as.data.frame(data)
526 | data$outside_exist_signals <-outside_exist_signals *1 # adjust format
527 |
528 | # 44. select only signals that are not in the polygons (so inside the Baltic Sea)
529 | data <- subset(data,outside_exist_signals==0 )
530 |
531 | ######################### ######################### ######################### A. Definition of the signals
532 | ######################### ######################### #########################
533 |
534 | # 45. definition of signals in ports and add port name
535 | coordinates(data) <- c("long", "lat")
536 | ports_polygons <-readOGR("W:/PROJECTS/Maritime Assessment 2016/Ports","Ports_V3")
537 | #plot(ports_polygons)
538 | proj4string(data) <- proj4string(ports_polygons) # confirm the same reference system
539 |
540 | inside.port <- !is.na(over(data, as(ports_polygons, "SpatialPolygons"))) # combine is.na() with over() to do the containment test
541 | mean(inside.port)
542 | inside.port2 <- over(data, ports_polygons[,"port"])
543 |
544 |
545 | # 46. add column to assess if the signal is in the exit polygons of the Baltic Sea
546 | #(to be sure that exiting / entering the Baltic Sea is creating a new trip)
547 | exit_baltic <-readOGR("W:/Florentdrafts","Exit_Baltic_Sea")
548 | #plot(exit_baltic)
549 | proj4string(data) <- proj4string(exit_baltic) # to confirm the same reference system
550 | into_exit_baltic <- !is.na(over(data, as(exit_baltic, "SpatialPolygons")))
551 | mean(into_exit_baltic)
552 | data$into_exit_baltic <-into_exit_baltic *1
553 |
554 | data2<-as.data.frame(data) #build data frame
555 | data2$inside.port <-inside.port *1
556 | #data2$outside.port[data2$inside.port== 1] <- 0
557 | #data2$outside.port[data2$inside.port== 0] <- 1
558 | data2$trips_data2 <- data2$inside.port
559 | data2$trips_data2[data2$into_exit_baltic== 1] <- 1
560 |
561 |
562 | # 47. for the signals in the port, if SOG < 0.5 KN (0.926 km/h) then SOG = 0
563 | summary(data2$sog)
564 | data2$sog <- data2$sog
565 | data2$sog <- as.numeric(data2$sog)
566 | data2$sog <- ifelse( data2$sog < 0.5 & data2$inside.port == "1" , "0", data2$sog)
567 | data2$sog <- as.numeric(data2$sog)
568 | summary(data2$sog)
569 | mean(data2$inside.port)
570 |
571 | # 48. Def of STOPS: if the SOG is = 0 and the ship is in the port polygon, so it is a stop
572 | data2$inside.port <-inside.port *1
573 | #summary(data2$inside.port)
574 | data2$Stops <- NA
575 | summary(data2$sog)
576 | data2$Stops <- ifelse( data2$sog== 0 & data2$inside.port == "1", "1", "0")
577 | data2$Stops <- as.numeric(data2$Stops)
578 | mean(data2$Stops)
579 |
580 | # 49. add name of the port
581 | data2$Port <- inside.port2$port
582 | data2$Stops<-as.numeric(data2$Stops)
583 | data2$Stops<-as.factor(data2$Stops)
584 |
585 | #plot to check
586 | #t <- subset(data2, data2$Stops==TRUE)
587 | #newmap <- getMap(resolution = "low")
588 | #plot(newmap, xlim = c(5.39, 30), ylim = c(52, 65.5), asp = 1, col="grey")
589 | #points(t$long, t$lat, col = "red", cex = 1)
590 |
591 | #select only signals in the ports and plot
592 | #t <- subset(data2, data2$Stops==1)
593 | #newmap <- getMap(resolution = "low")
594 | #plot(newmap, xlim = c(5.39, 30), ylim = c(52, 65.5), asp = 1)
595 | #points(t$long, t$lat, col = "red", cex = 1)
596 |
597 | # only sog=0
598 | #data<-subset(data, data$sog==0)
599 | # only in ports_selected
600 | #data<-subset(data, data$port==1)
601 |
602 | # 50. Def of Trips: if signal outside the ports = trips and rename dataframe
603 | data2$Trips <- NA
604 | data2$Trips <- ifelse( data2$inside.port == "0", "1", "0")
605 | #If not stop, then trip:
606 | #data$Trips[data$Stops== 1] <- 0
607 | #data$Trips[data$Stops== 0] <- 1
608 | #data$Trips <- as.factor(data$Trips)
609 |
610 | data <- data2 # rename data2 in data
611 |
612 | #plot to check the stops
613 | #t <- subset(data, data$Stops==1)
614 | #newmap <- getMap(resolution = "low")
615 | #plot(newmap, xlim = c(5.39, 30), ylim = c(52, 65.5), asp = 1, col="grey")
616 | #points(t$long, t$lat, col = "red", cex = 1)
617 | data$Stops <- as.numeric(as.character(data$Stops))
618 | data$Trips <- as.numeric(as.character(data$Trips))
619 |
620 | # 51. check the new variables and order by ship and time
621 | summary(data$Trips)
622 | summary(data$Stops)
623 | #summary(data$in_port)
624 | data <- data[order(data$imo, data$timestamp_pretty),]
625 |
626 | #imo_test <- subset(data, data$imo == 207015000)
627 | #newmap <- getMap(resolution = "low")
628 | #plot(newmap, xlim = c(5.39, 30), ylim = c(52, 65.5), asp = 1, col="grey")
629 | #points(imo_test$long, imo_test$lat, col = "red", cex = 1)
630 |
631 |
632 | ########################## ######################## ######################### B. PRODUCE EVENTS STOPS
633 | ######################### ######################### #########################
634 |
635 | # 52. counting number of stops
636 | #data$Stops2 <- setDT(data)[, v1 := if(all(!Trips)) c(TRUE, imo[-1]!= imo[-.N]) #not working, taking into account the passages in the ports without stopping
637 | #else rep(FALSE, .N), .(grp = rleid(Trips))][,cumsum(v1)*(!Trips)]
638 | data$Stops2 <- as.numeric(ifelse( data$Stop == "1", "0", "1"))
639 | data$Stops2 <- setDT(data)[, v1 := if(all(!Stops2)) c(TRUE, imo[-1]!= imo[-.N])
640 | else rep(FALSE, .N), .(grp = rleid(Stops2))][,cumsum(v1)*(!Stops2)]
641 |
642 | # 53. correction of strange trips: if signals are only in ports: it has to create a new stop if the port is different
643 | setDT(data)[, `:=`(Stops2 = as.character(Stops2), Idindx = rleid(Port))]
644 | indx <- unique(data, by = "Idindx")[, counter := (1:.N) - 1L, by = Stops2]
645 | data[indx[counter > 0], Stops2 := paste(Stops2, i.counter, sep = "-"), on = "Idindx"]
646 |
647 | data$Idindx[data$Trips== 1] <- 0
648 | data$Stops2 <- data$Idindx
649 | data$Stops2[data$Stops== 0] <- 0
650 | summary(data$Stops2)
651 |
652 | # 54. duration of the stops
653 | data_stops <- filter(data, Stops2 != 0) %>% # drop rows with Stop == 0
654 | unite(dates, timestamp_pretty, sep = " ") %>% #create date object
655 | mutate(dates = as.POSIXct(strptime(dates, format = "%d/%m/%Y %H:%M:%S"))) %>%
656 | group_by(Idindx) %>% # for each stop
657 | filter(dates == min(dates) | dates == max(dates)) %>% #select rows with min and max dates
658 | summarise(minTime = min(dates),
659 | maxTime = max(dates),
660 | duration_minutes = round(difftime(max(dates), min(dates), units="mins")),
661 | Ship = imo[1],
662 | Port = Port[1])
663 |
664 | # 55. calcul of Lat Long of the stops (average)
665 | cal <- function(x, y){ # A custom function for calculating the mean Lat/Long
666 | latToRadians <- x * pi / 180
667 | longToRadians <- y * pi / 180
668 |
669 | x_cartesian <- cos(latToRadians) * cos(longToRadians)
670 | y_cartesian <- cos(latToRadians) * sin(longToRadians)
671 | z_cartesian <- sin(latToRadians)
672 |
673 | aveX <- sum(x_cartesian) / length(x_cartesian)
674 | aveY <- sum(y_cartesian) / length(y_cartesian)
675 | aveZ <- sum(z_cartesian) / length(z_cartesian)
676 |
677 | hyp <- sqrt(aveX * aveX + aveY * aveY)
678 | lat <- atan2(aveZ, hyp)
679 | long <- atan2(aveY, aveX)
680 |
681 | latMean <- lat * 180 / pi
682 | longMean <- long * 180 / pi
683 |
684 | return(as.data.frame(cbind(latMean, longMean)))
685 | }
686 |
687 | #plot the stops
688 | #newmap <- getMap(resolution = "low")
689 | #plot(newmap, xlim = c(5.39, 30), ylim = c(52, 65.5), asp = 1, col="grey")
690 | #points(t$long , t$lat , col = "blue", cex = 1)
691 | data$Stops <- as.numeric(data$Stops)
692 | LatLong <- data %>% # create the LatLong of the stop (data)
693 | filter(Stops2 != 0) %>%
694 | group_by(Idindx) %>%
695 | do(cal(.$lat, .$long))
696 |
697 | #plot LatLong
698 | #newmap <- getMap(resolution = "low")
699 | #plot(newmap, xlim = c(5.39, 30), ylim = c(52, 65.5), asp = 1, col="grey")
700 | #points(LatLong$longMean, LatLong$latMean, col = "red", cex = 1)
701 | LatLong <- as.data.table(LatLong)
702 | data_stops <- as.data.table(data_stops)
703 |
704 | # 56. Join durations of the stops and LatLong
705 | data_stops <- full_join(data_stops, LatLong, by="Idindx" )
706 |
707 |
708 | # 57. filter the stops more than 10 min
709 | data_stops <- filter(data_stops, duration_minutes >10)
710 |
711 | ######################### ######################### ######################### C. TRIPS
712 | ######################### ######################### #########################
713 |
714 | # 58. Counting number of trips
715 | data$Trips_rle <- setDT(data)[, v1 := if(all(!trips_data2)) c(TRUE, imo[-1]!= imo[-.N])
716 | else rep(FALSE, .N), .(grp = rleid(trips_data2))][,cumsum(v1)*(!trips_data2)]
717 |
718 | # old versions of rle, does not work
719 | #data$Trips_rle <- setDT(data)[, v1 := if(all(!Stops)) c(TRUE, imo[-1]!= imo[-.N])
720 | #else rep(FALSE, .N), .(grp = rleid(Stops))][,cumsum(v1)*(!Stops)]
721 |
722 | #data$Trips_rle <- setDT(data)[, v1 := if(all(!inside.port)) c(TRUE, imo[-1]!= imo[-.N])
723 | #else rep(FALSE, .N), .(grp = rleid(inside.port))][,cumsum(v1)*(!inside.port)]
724 |
725 | #plot the trips to check
726 | #t <- subset(data, data$Trips_rle > 0)
727 | #library("RgoogleMaps")
728 | #newmap <- getMap(resolution = "low")
729 | #plot(newmap, xlim = c(5.39, 30), ylim = c(52, 65.5), asp = 1, col="grey")
730 | #points(t$long, t$lat, col = "blue", cex = 1)
731 |
732 | # 59. Duration of the trips
733 | duration_trips <- filter(data, Trips_rle !=0) %>%
734 | unite(dates, timestamp_pretty, sep = " ") %>% # create date object
735 | mutate(dates = as.POSIXct(strptime(dates, format = "%d/%m/%Y %H:%M:%S"))) %>%
736 | group_by(Trips_rle) %>%
737 | filter(dates == min(dates) | dates == max(dates)) %>% # select rows with min and max dates
738 | summarise(minTime = min(dates),
739 | maxTime = max(dates),
740 | duration_minutes = round(difftime(max(dates), min(dates), units="mins")),
741 | Ship = imo[1])
742 |
743 | # 60. Duration of the trips
744 | data_for_distance <- data # create data for distance only
745 | data_for_distance <- as.data.frame(data_for_distance) # as data frame
746 |
747 | # 61. select relevant parameters
748 | data_for_distance <- data_for_distance[,c("timestamp_pretty", "imo","lat", "long", "Trips_rle")]
749 |
750 | # 62. remove the stops to keep only the trips
751 | data_for_distance <- subset(data_for_distance, data_for_distance$Trips_rle !=0)
752 |
753 |
754 | #data_for_distance <- ddply(data_for_distance,.(Trips_rle),function(x){ # remove unique Trips_rle
755 | #if(nrow(x)==1){
756 | #return(NULL)}
757 | #else{
758 | #return(x)
759 | #}
760 | #})
761 |
762 | # 63. Distance sailed in meters
763 | library(geosphere)
764 | library(base)
765 | data_for_distance$Trips_rle <- as.numeric(data_for_distance$Trips_rle)
766 | distance <- data_for_distance %>%
767 | group_by(Trips_rle) %>%
768 | mutate(longlead = lead(long), latlead = lead(lat)) %>%
769 | na.omit() %>%
770 | rowwise() %>%
771 | mutate(dist = distCosine(c(long,lat), c(longlead, latlead)))
772 |
773 | # 64. Cumulative sum of distance sailed in meters
774 | options(scipen = 50)
775 | #t <- subset(distance, distance$dist.sailed == "NaN")
776 | distance <- transform(distance, dist.sailed = ave(dist, Trips_rle, FUN = cumsum))
777 | distance <- distance[,c("Trips_rle", "dist", "dist.sailed")]
778 | distance <- distance[,c("Trips_rle", "dist.sailed")]
779 |
780 | # 65. Keep longest cumulative distance for each Ids (trips)
781 | distance.sum <- distance %>%
782 | group_by(Trips_rle) %>%
783 | slice(which.max(dist.sailed))
784 |
785 | # 66. Join duration and distance of the trip
786 | trips <- full_join(distance.sum, duration_trips, by="Trips_rle" )
787 | #filter the stops more than 10 min
788 | trips <- filter(trips, duration_minutes >10)
789 |
790 | # 67. prepare the final tables (stops and then trips) for merging
791 | colnames(data_stops)[4] <- "duration.minutes" # for stops rename the column number 4
792 | data_stops$event <- "stop"
793 | colnames(data_stops)[6] <- "Location" # for stops rename the column number 6
794 | #data_stops <- data_stops[,c("Idindx", "minTime","maxTime","duration.minutes", "Ship", "Location", "event")]
795 |
796 | trips$event <- "trip" # for trips
797 | colnames(trips)[1] <- "Trips.rle"
798 | colnames(trips)[5] <- "duration.minutes"
799 |
800 | # 68. Join stops and trips in same table
801 | total_trips_stops <- rbind.fill(data_stops, trips) # join
802 | total_trips_stops <- total_trips_stops[,c("Ship", "minTime","maxTime","duration.minutes", "event", "dist.sailed", "Location", "Trips.rle", "Idindx")] # select relevant parameters
803 |
804 | total_trips_stops$duration.hours <- round(total_trips_stops$duration.minutes/60,digits=2) # duration in hours
805 | total_trips_stops <- total_trips_stops[order(total_trips_stops$Ship, total_trips_stops$minTime),] # order by ship and time of event
806 |
807 | # 69. Merge all final data together (total_trips_stops and total_in_out from the first step)
808 | total <- rbind.fill( total_in_out, total_trips_stops)
809 | total <- total[!duplicated(total), ] # remove duplicates
810 | total <- total[,c("Ship", "minTime","maxTime","duration.minutes", "event", "dist.sailed", "Location","Trips.rle", "Idindx", "mean_COG",
811 | "mean_COG2")] # select relevant parameters
812 | total <- total[order(total$Ship, total$minTime),] # order by ship and time of event
813 |
814 | # 70. merge the consecutive trips together: ships can not have consecutive trips without stops or exit.
815 | library(dplyr)
816 | total_final <- total %>%
817 | group_by(Ship) %>%
818 | mutate(new_id = data.table::rleid(event)) %>%
819 | group_by(event, new_id, Ship) %>%
820 | mutate(duration.minutes = ifelse(event %in% c('trip', 'stop'), sum(duration.minutes), duration.minutes), maxTime = tail(maxTime, 1)) %>%
821 | mutate(dist.sailed = ifelse(event == 'trip', sum(dist.sailed), dist.sailed), dist.sailed = tail(dist.sailed, 1)) %>%
822 | filter(!duplicated(new_id)) %>%
823 | select(-new_id)
824 |
825 | # 71. Export the final monthly files events
826 | dir.create(file.path("E:/Events_V2/"), showWarnings=F)
827 | dir.to.create1 <- paste("E:/Events_V2/", year, sep="") #level 1 in directory using year as variable
828 | dir.create(file.path(dir.to.create1), showWarnings=F)
829 | dir.to.create2 <- paste(dir.to.create1,"/monthly", sep="") # dir.to.create level 2 using year as variable
830 | dir.create(file.path(dir.to.create2), showWarnings=F)
831 |
832 | directory=paste(dir.to.create2, "/Events_", year, "_", month, sep="", ".csv" )
833 | write.table(total_final, directory, sep=";", col.names = T, row.names=F)
834 |
835 | }
836 |
837 | #library(mail)
838 | #sendmail("florent.nicolas@helcom.fi", "AIS monthly events for 2016 ready", "AIS monthly events for 2016 ready", password="rmail")
839 |
840 | #################
841 | #################
842 | #################
843 | ################# WRITE YEARLY FILES
844 | #################
845 | #################
846 | #################
847 | #################
848 |
849 | rm(list = ls()[!ls() %in% c("start.time", "year","dir.to.create2", "time")])
850 | #library(plyr)
851 | #library(dplyr)
852 |
853 | # 72. Read monthly events files using file list
854 | setwd(dir.to.create2)
855 | #filelist with pattern of the monthly events files
856 | pattern <- paste("Events_", year, "_.*\\.csv", sep="")
857 | fileList <- list.files(pattern=pattern, recursive=FALSE)
858 |
859 | # 73. Merging the monthly files
860 | df <- ldply(fileList, read.table, header=T, sep = ";", fill=T)
861 |
862 | # 74. Order by ship and time
863 | df <- df[order(df$Ship, df$minTime),]
864 |
865 | # 75. select relevant parameters and change their formats
866 | df <- df[,c("Ship", "minTime","maxTime","duration.minutes", "event", "dist.sailed", "Location","Trips.rle", "mean_COG")]
867 | #data<- subset(df, df$Ship==209276000)
868 |
869 | #change formats of some parameters
870 | df$minTime <- as.POSIXct(as.character(df$minTime), format = "%Y-%m-%d %H:%M:%S") # change their formats
871 | df <- df[order(df$Ship, df$minTime),] # sort again by ship and time
872 | df$duration.minutes <- as.numeric(df$duration.minutes)
873 | df$Ship <- as.factor(df$Ship)
874 |
875 | # 76. Merge events that are divided between 2 consecutive months
876 | library(dplyr)
877 | total_final <- df %>%
878 | group_by(Ship) %>%
879 | mutate(new_id = data.table::rleid(event)) %>%
880 | group_by(event, new_id, Ship) %>%
881 | mutate(duration.minutes = ifelse(event %in% c('trip', 'stop'), sum(duration.minutes), duration.minutes), maxTime = tail(maxTime, 1)) %>%
882 | mutate(dist.sailed = ifelse(event == 'trip', sum(dist.sailed), dist.sailed), dist.sailed = tail(dist.sailed, 1)) %>%
883 | filter(!duplicated(new_id)) %>%
884 | select(-new_id)
885 |
886 | # 77. select again relevant parameters (not needed)
887 | total_final <- total_final[,c("Ship", "minTime","maxTime","duration.minutes", "event", "dist.sailed", "Location","Trips.rle", "mean_COG")]
888 |
889 |
890 | # 78. writing the yearly event file
891 |
892 | directory <- paste("E:/Events_V2/Events_", year, ".csv", sep="")
893 | write.table(total_final, directory, sep=";", col.names = T, row.names=F)
894 |
895 |
896 | #################
897 | #################
898 | #################
899 | ################# PRODUCE SUMMARY OF THE EVENTS
900 | #################
901 | #################
902 | #################
903 | #################
904 |
905 | # 79. Prepare data
906 | data_stops <- subset(total_final, total_final$event=="stop") # for stops
907 | dt <- data.table(data_stops)
908 | data_stops_summary <- dt[,list(duration.minutes=sum(duration.minutes)),by= Ship]
909 | data_stops_summary$stop <- 1
910 |
911 | data_trips <- subset(total_final, total_final$event=="trip") # for trips
912 | dt <- data.table(data_trips)
913 |
914 | # 80. Produce summary (SUM of distance for trips and duration for trips and stops)
915 | data_trips_summary <- dt[,list(distance=sum(dist.sailed),duration.minutes=sum(duration.minutes)),by=Ship] # for trips
916 | data_trips_summary$trip <- 1
917 |
918 | data_exit_enter <- subset(total_final, total_final$event=="exit" |total_final$event=="enter" ) # for enters and exits
919 |
920 | # 81. Prepare ship related information
921 | shiplist <- paste("E:/ship_list/shiplist_", year,"_final.csv", sep="")
922 | shiptype <- read.csv(shiplist, sep=";")
923 | shiptype <- shiptype[,c("imo", "country","length_final","width_final", "draught_final", "Gross_tonnage", "Net_tonnage", "HELCOM_Gross_ShipType", "HELCOM_Detail_ShipType")]
924 | colnames(shiptype)[1] <- "Ship"
925 |
926 | data_stops_summary$Ship <- as.factor(data_stops_summary$Ship)
927 | data_trips_summary$Ship <- as.factor(data_trips_summary$Ship)
928 | data_exit_enter$Ship <- as.factor(data_exit_enter$Ship)
929 | shiptype$Ship <- as.factor(shiptype$Ship)
930 |
931 | # 82. Add ship related information
932 | summary_stops <- merge(data_stops_summary,shiptype, by= "Ship" )
933 | summary_trips <- merge(data_trips_summary,shiptype, by= "Ship" )
934 | summary_exit_enter <- merge(data_exit_enter,shiptype, by= "Ship" )
935 |
936 |
937 | # 83. writing summary tables
938 | directory=paste("E:/Events_V2/Summary_stops_", year,".csv", sep="")
939 | write.table(summary_stops, directory, sep=";", col.names = T, row.names=F)
940 |
941 | directory=paste("E:/Events_V2/Summary_trips_", year,".csv", sep="")
942 | write.table(summary_trips, directory, sep=";", col.names = T, row.names=F)
943 |
944 | directory=paste("E:/Events_V2/Summary_exit_enter_", year,".csv", sep="")
945 | write.table(summary_exit_enter, directory, sep=";", col.names = T, row.names=F)
946 |
947 | #library(mail)
948 | #sendmail("florent.nicolas@helcom.fi", "AIS Events for 2016 ready", " AIS Events for 2016 ready", password="rmail")
949 |
950 |
951 | # time taken to process
952 | end.time <- Sys.time()
953 | time.taken <- end.time - start.time
954 | time.taken
955 | str(time.taken)
956 | unit <- attr(time.taken, "units")
957 | time.taken <- paste(time.taken,unit,"")
958 | start.time
959 | end.time
960 | time.taken
961 |
962 | #save time taken
963 | directory_time.taken=paste("E:/Events_V2/time.taken_for_events_", year, sep="", ".csv" )
964 | write.table(time.taken, directory_time.taken, sep=";", col.names = F, row.names=F)
965 |
966 |
--------------------------------------------------------------------------------
/Script 5. Produce lines id.R:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/helcomsecretariat/AIS-data-processing-for-statistics-and-maps/614b969527218610d5b449e89dbe2ded581b5b30/Script 5. Produce lines id.R
--------------------------------------------------------------------------------
/Script 6. TrackBuilderFromCSV_multiprocessing.py:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------
2 | # Name: Track Builder From CSV
3 | # Purpose: Creates lines features from the monthly csv files
4 | # Author: Andzej Milos
5 | # Created: 2017
6 | # Copyright: GNU General Public License V3
7 | # ArcGIS Version: 10.2
8 | # Python Version: 2.7
9 | #-------------------------------------------------------------
10 |
11 | import os
12 | import csv
13 | import arcpy
14 | import multiprocessing
15 | from datetime import datetime
16 |
17 | # Change input values according to the data you want to process
18 | year = "2011"
19 | inFolder = r"E:/DensityMaps_V3/" + year + "/01_trips"
20 | outFolder = r"E:/DensityMaps_V3/" + year + "/02_lines"
21 |
22 | # Check if file name contains "tracks", name of month and year
23 | def getMonthFromFileName(filename):
24 | monthsList = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
25 | result = False
26 | for month in monthsList:
27 | #if filename.find(month) > -1:
28 | if ((filename.find(month) > -1) and (filename.find(year) > -1) and (filename.find("tracks") > -1)):
29 | result = month
30 | break
31 | return result
32 |
33 | def readCSV(filename):
34 | month = getMonthFromFileName(filename)
35 | if not month:
36 | print "Cannot process file " + filename
37 | else:
38 | print "--- Started processing " + month + " at: " + str(datetime.now()) + "\n"
39 |
40 | #attrnames = ["imo", "trip_id", "lat", "long"]
41 | inCSV = open(inFolder + "\\" + filename, 'r')
42 | csvreader = csv.reader(inCSV, delimiter = ';')
43 |
44 | headers = csvreader.next()
45 | #print str(headers)
46 | attrnameindexes = {"imo": headers.index("imo"), "trip_id": headers.index("trip_id"), "new_trip_id": headers.index("new_trip_id"), "lat": headers.index("lat"), "long": headers.index("long") }
47 |
48 | i = 0
49 | point = arcpy.Point()
50 | pointsarray = arcpy.Array()
51 |
52 |
53 | firstrow = csvreader.next()
54 | #print str(firstrow)
55 | trip_id = firstrow[attrnameindexes["trip_id"]]
56 | new_trip_id = firstrow[attrnameindexes["new_trip_id"]]
57 | imo = firstrow[attrnameindexes["imo"]]
58 | point.X = float(firstrow[attrnameindexes["long"]])
59 | point.Y = float(firstrow[attrnameindexes["lat"]])
60 | pointsarray.add(point)
61 |
62 | #filenameparts = filename.split(".")[0].split("_")
63 | #outputfilename = "ais_"+filenameparts[2]+"_"+filenameparts[1]+"_lines.shp"
64 | outputfilename = "lines_" + year + "_" + month + ".shp"
65 | outputfilepath = outFolder + "\\" + outputfilename
66 |
67 | arcpy.CreateFeatureclass_management(outFolder, outputfilename, "POLYLINE", None, None, None, arcpy.SpatialReference(4326))
68 | arcpy.AddField_management(outputfilepath, "trip_id", "LONG")
69 | arcpy.AddField_management(outputfilepath, "new_tr_id", "LONG")
70 | arcpy.AddField_management(outputfilepath, "imo", "LONG")
71 |
72 | insertcursor = arcpy.da.InsertCursor(outputfilepath, ["imo", "trip_id", "new_tr_id", "SHAPE@"])
73 |
74 | for row in csvreader:
75 |
76 | if i % 50000 == 0:
77 | print "processing row " + str(i) + " " + month
78 | #print str(row)
79 | #if i > 500000:
80 | # print str(row)
81 |
82 | #print "imo: " + str(row[attrnameindexes["imo"]]) + ", new_tr_id: " + str(row[attrnameindexes["new_trip_id"]])
83 | #print str(row) + " " + month
84 | if new_trip_id == row[attrnameindexes["new_trip_id"]]:
85 | point.X = float(row[attrnameindexes["long"]])
86 | point.Y = float(row[attrnameindexes["lat"]])
87 | pointsarray.add(point)
88 | else:
89 | polyline = arcpy.Polyline(pointsarray)
90 | try:
91 | insertcursor.insertRow([imo, trip_id, new_trip_id, polyline])
92 | except:
93 | print "error insertcursor.insertRow " + str(row) + " " + month
94 | break
95 | pointsarray.removeAll()
96 | trip_id = row[attrnameindexes["trip_id"]]
97 | new_trip_id = row[attrnameindexes["new_trip_id"]]
98 | imo = row[attrnameindexes["imo"]]
99 | point.X = float(row[attrnameindexes["long"]])
100 | point.Y = float(row[attrnameindexes["lat"]])
101 | pointsarray.add(point)
102 | i += 1
103 |
104 | polyline = arcpy.Polyline(pointsarray)
105 | insertcursor.insertRow([imo, trip_id, new_trip_id, polyline])
106 | pointsarray.removeAll()
107 |
108 | del insertcursor
109 | print "--- Ended processing " + month + " at: " + str(datetime.now()) + "\n"
110 |
111 | if __name__ == '__main__':
112 | startTime_script = datetime.now()
113 | print "Started Track Builder at: " + str(startTime_script)
114 | filenames = []
115 | for filename in os.listdir(inFolder):
116 | if filename.endswith(".csv"):
117 | filenames.append(filename)
118 |
119 | pool = multiprocessing.Pool(6)
120 | pool.map(readCSV, filenames)
121 | pool.close()
122 | pool.join()
123 | print "Ended Track Builder at: " + str(datetime.now())
124 | print "Duration: " + str(datetime.now() - startTime_script) + "\n"
125 |
--------------------------------------------------------------------------------
/Script 7. SplitTracksByShipType_multiprocessing.py:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------
2 | # Name: Split tracks by ship type
3 | # Purpose: Split lines features into different ship type categories
4 | # Authors: Manuel Frias, Andzej Milos
5 | # Created: 2017
6 | # Copyright: GNU General Public License V3
7 | # ArcGIS Version: 10.2
8 | # Python Version: 2.7
9 | #-------------------------------------------------------------
10 | import arcpy
11 | import time
12 | from arcpy.sa import *
13 | import os
14 | import multiprocessing
15 | from datetime import datetime
16 |
17 | spatialRef = arcpy.SpatialReference(3035)
18 | year = "2011"
19 | shipTypes = ["CARGO", "CONTAINER", "FISHING", "OTHER", "PASSENGER", "SERVICE", "TANKER", "UNKNOWN", "ROROCARGO"]
20 | shipList = r"E:/DensityMaps_V3/ship_list_dbf/imo/" + year + ".dbf"
21 | fields = ["HELCOM_Gro"]
22 |
23 | in_folder = r"E:/DensityMaps_V3/" + year + "/02_lines"
24 | out_folder = r"E:/DensityMaps_V3/" + year + "/03_lines_by_shiptype"
25 |
26 | def getMonthFromFileName(filename):
27 | monthsList = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
28 | result = False
29 | for month in monthsList:
30 | if ((filename.find(month) > -1) and (filename.find(year) > -1) and (filename.find("lines") > -1)):
31 | result = month
32 | break
33 | return result
34 |
35 | def checkDefineProjection(data_, spatialRef_):
36 | data_desc = arcpy.Describe(data_)
37 | if data_desc.spatialReference.name != spatialRef_.name:
38 | print "--- Projecting " + data_desc.file + " in " + spatialRef_.name + "..."
39 | arcpy.Project_management(data_, in_folder + "\\pr_" + data_desc.file, spatialRef_)
40 | arcpy.Delete_management(data_)
41 | arcpy.Rename_management(in_folder + "\\pr_" + data_desc.file, in_folder + "\\" + data_desc.file)
42 |
43 | def checkAddFields(data_, fields_):
44 | data_desc = arcpy.Describe(data_)
45 | data_fieldList = arcpy.ListFields(data_)
46 | data_fieldListNames = [field.name for field in data_fieldList]
47 | fieldsToAdd = [field for field in fields_ if field not in data_fieldListNames]
48 |
49 | if ((len(fieldsToAdd) > 0) and ("imo" in data_fieldListNames)):
50 | print "--- Adding fields " + str(fieldsToAdd) + " " + data_desc.file + "..."
51 | month = getMonthFromFileName(data_desc.file)
52 | arcpy.MakeTableView_management(shipList, "shipList_view_" + month)
53 | try:
54 | arcpy.JoinField_management(data_, "imo", "shipList_view_" + month, "imo", fieldsToAdd)
55 | except:
56 | print "error processing join " + "shipList_view_" + month
57 | arcpy.Delete_management("shipList_view_" + month)
58 |
59 | def splitDataByType(data_, shipTypes_):
60 | data_desc = arcpy.Describe(data_)
61 | print "--- Extracting ship types out of " + data_desc.file + "..."
62 | for shipType in shipTypes_:
63 | shipTypeFolder = out_folder + "\\" + shipType
64 | if not arcpy.Exists(shipTypeFolder):
65 | arcpy.CreateFolder_management(out_folder, shipType)
66 | shipTypeData = shipTypeFolder + "\\" + shipType + "_" + data_desc.file
67 | if not arcpy.Exists(shipTypeData):
68 | query = "HELCOM_Gro = '" + shipType.title() + "'"
69 | arcpy.FeatureClassToFeatureClass_conversion(data_, shipTypeFolder, shipType + "_" + data_desc.file, query)
70 | else:
71 | print "--- WARNING: " + shipType + " " + getMonthFromFileName(data_desc.file) + " " + year + " already exists..."
72 |
73 | def multiProcessing_function(data):
74 | month = getMonthFromFileName(data)
75 | if not month:
76 | print "Cannot process file " + data
77 | else:
78 | print "Start processing " + month + " at: " + str(datetime.now()) + "\n"
79 | checkDefineProjection(data, spatialRef)
80 | checkAddFields(data, fields)
81 | splitDataByType(data, shipTypes)
82 | print "End processing " + month + " at: " + str(datetime.now()) + "\n"
83 |
84 | if __name__ == '__main__':
85 | startTime_script = datetime.now()
86 | print "Started at: " + str(startTime_script) + "\n"
87 |
88 | #monthsList = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
89 | linesfiles = []
90 | for filename in os.listdir(in_folder):
91 | if filename.endswith(".shp"):
92 | #m = getMonthFromFileName(filename)
93 | #print "+++ " + str(m) + " " + filename
94 | if getMonthFromFileName(filename):
95 | linesfiles.append(in_folder + "\\" + filename)
96 | else:
97 | print "WARNING: " + in_folder + "\\" + filename + " is not included in analysis...\n"
98 |
99 | if len(linesfiles) == 0:
100 | print "WARNING: No files for the analysis..."
101 | else:
102 | pool = multiprocessing.Pool(6)
103 | pool.map(multiProcessing_function, linesfiles)
104 | pool.close()
105 | pool.join()
106 |
107 | print "Ended at: " + str(datetime.now()) + ".\nDuration: " + str(datetime.now() - startTime_script) + "\n"
108 |
109 |
110 |
--------------------------------------------------------------------------------
/Script 8. CreateRastersYear_multiprocessing.py:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------
2 | # Name: Split tracks by ship type
3 | # Purpose:
4 | # Authors: Andzej Milos
5 | # Created: 2017
6 | # Copyright: (c) HELCOM Secretariat
7 | # ArcGIS Version: 10.2
8 | # Python Version: 2.7
9 | #-------------------------------------------------------------
10 |
11 | import arcpy
12 | import time
13 | from arcpy.sa import *
14 | import os
15 | import multiprocessing
16 | from datetime import datetime
17 |
18 | year = "2019"
19 | # CARGO CONTAINER PASSENGER TANKER ROROCARGO SERVICE FISHING OTHER UNKNOWN
20 | shipType = "ROROCARGO"
21 | grids_folder = r"E:/DensityMaps_V3/grid"
22 | grid = r"E:/DensityMaps_V3/grid/BSII_grid.shp"
23 | #clippingArea = r"E:\DensityMaps\DensityMaps1Km_GRIDSandTables.gdb\BalticScope_StudyArea"
24 |
25 | in_folder = r"E:/DensityMaps_V3/" + year + "/03_lines_by_shiptype/" + shipType
26 | out_folder = r"E:/DensityMaps_V3/" + year + "/04_rasters"
27 |
28 | def getMonthFromFileName(filename):
29 | monthsList = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
30 | result = False
31 | for month in monthsList:
32 | if ((filename.find(month) > -1) and (filename.find(year) > -1) and (filename.find(shipType) > -1)):
33 | result = month
34 | break
35 | return result
36 |
37 | def multiProcessing_function(data):
38 | month = getMonthFromFileName(data)
39 | print "Start processing " + month + " at: " + str(datetime.now()) + "\n"
40 | #worktempfolder = out_folder + "\\" + shipType + "\\temp_" + month
41 | worktempfolder = out_folder + "\\DensityMaps1Km_" + year + "_IMO_" + shipType + "\\temp_" + month
42 | if not arcpy.Exists(worktempfolder):
43 | #arcpy.CreateFolder_management(out_folder + "\\" + shipType, "temp_" + month)
44 | arcpy.CreateFolder_management(out_folder + "\\DensityMaps1Km_" + year + "_IMO_" + shipType, "temp_" + month)
45 |
46 | grid_inverse_sel_lyrs = []
47 | for i in range(1, 6):
48 | print "--- Started Spatial join " + month + " gridDivision " + str(i) + " at: " + str(datetime.now()) + "\n"
49 |
50 | # Choose next grid division
51 | gridDivision = grids_folder + "\\grid_division" + str(i) + ".shp"
52 |
53 | arcpy.MakeFeatureLayer_management(gridDivision, "gridDivision_lyr_" + month)
54 | arcpy.MakeFeatureLayer_management(grid, "grid_lyr_" + month + "_" + str(i))
55 | arcpy.MakeFeatureLayer_management(data, "line_lyr")
56 |
57 | # Select grids in grid division
58 | arcpy.SelectLayerByLocation_management("grid_lyr_" + month + "_" + str(i), "WITHIN", "gridDivision_lyr_" + month)
59 | arcpy.MakeFeatureLayer_management("grid_lyr_" + month + "_" + str(i), "grid_lyr_" + month)
60 |
61 | # Select lines in grid division
62 | arcpy.SelectLayerByLocation_management("line_lyr", "INTERSECT", "gridDivision_lyr_" + month, "", "NEW_SELECTION")
63 | arcpy.MakeFeatureLayer_management("line_lyr", "selected_line_lyr")
64 |
65 | # Select grids intersecting lines
66 | arcpy.SelectLayerByLocation_management("grid_lyr_" + month, "INTERSECT", "line_lyr", "", "NEW_SELECTION")
67 | arcpy.MakeFeatureLayer_management("grid_lyr_" + month, "selected_grid_lyr_" + month)
68 |
69 | # Spatial join selected lines and grids
70 | arcpy.SpatialJoin_analysis("selected_grid_lyr_" + month, "selected_line_lyr", worktempfolder + "\\" + month + "_SpJoin_" + str(i) + ".shp", "JOIN_ONE_TO_MANY", "", "", "INTERSECT")
71 |
72 | # Select grids not intersecting lines and store them for later raster creation. 1 grid layer per grid division
73 | arcpy.SelectLayerByAttribute_management("grid_lyr_" + month, "SWITCH_SELECTION")
74 | arcpy.MakeFeatureLayer_management("grid_lyr_" + month, "grid_inverse_sel_lyr_" + month + "_" + str(i))
75 | grid_inverse_sel_lyrs.append("grid_inverse_sel_lyr_" + month + "_" + str(i))
76 |
77 | arcpy.Delete_management("gridDivision_lyr_" + month)
78 | arcpy.Delete_management("grid_lyr_" + month + "_" + str(i))
79 | arcpy.Delete_management("grid_lyr_" + month)
80 | arcpy.Delete_management("selected_grid_lyr_" + month)
81 | arcpy.Delete_management("line_lyr")
82 | arcpy.Delete_management("selected_line_lyr")
83 |
84 | print "--- Ended Spatial join " + month + " gridDivision " + str(i) + " at: " + str(datetime.now()) + "\n"
85 |
86 | # Store spatial join from 2 to 5
87 | spjoinList = []
88 | for i in range(2, 6):
89 | if arcpy.Exists(worktempfolder + "\\" + month + "_SpJoin_" + str(i) + ".shp"):
90 | spjoinList.append(worktempfolder + "\\" + month + "_SpJoin_" + str(i) + ".shp")
91 |
92 | if len(spjoinList) > 0:
93 | # Append 2 - 5 spatial joins to 1
94 | print "+++ Started spjoin Append " + month + " at: " + str(datetime.now()) + "\n"
95 | arcpy.Append_management(spjoinList, worktempfolder + "\\" + month + "_SpJoin_1.shp", "TEST","","")
96 | print "+++ Ended spjoin Append " + month + " at: " + str(datetime.now()) + "\n"
97 |
98 | # Dissolve spatial join 1
99 | print "+++ Started dissolve " + month + " at: " + str(datetime.now()) + "\n"
100 | arcpy.Dissolve_management(worktempfolder + "\\" + month + "_SpJoin_1.shp", worktempfolder + "\\" + month + "_Dissolve.shp", "TARGET_FID", [["Join_Count", "SUM"]])
101 | print "+++ Ended dissolve " + month + " at: " + str(datetime.now()) + "\n"
102 |
103 | # Create shp of 1 grid division grids not intersecting lines layer
104 | print "+++ Started CopyFeatures " + month + " at: " + str(datetime.now()) + "\n"
105 | arcpy.CopyFeatures_management(grid_inverse_sel_lyrs[0], worktempfolder + "\\" + month + "_Inv_Merged.shp")
106 | del grid_inverse_sel_lyrs[0]
107 | print "+++ Ended CopyFeatures " + month + " at: " + str(datetime.now()) + "\n"
108 |
109 | # Append rest grids not intersecting lines layers to first division layer
110 | print "+++ Started inverse Append " + month + " at: " + str(datetime.now()) + "\n"
111 | arcpy.Append_management(grid_inverse_sel_lyrs, worktempfolder + "\\" + month + "_Inv_Merged.shp", "TEST","","")
112 | print "+++ Ended inverse Append " + month + " at: " + str(datetime.now()) + "\n"
113 |
114 | # Merge Dissolve result and grids not intersecting lines
115 | print "+++ Started Merge dissolve + inverse " + month + " at: " + str(datetime.now()) + "\n"
116 | arcpy.Merge_management([worktempfolder + "\\" + month + "_Dissolve.shp", worktempfolder + "\\" + month + "_Inv_Merged.shp"], worktempfolder + "\\" + month + "_ForRaster.shp")
117 | print "+++ Ended Merge dissolve + inverse " + month + " at: " + str(datetime.now()) + "\n"
118 |
119 | # Create raster out of merged grids
120 | print "+++ Started FeatureToRaster " + month + " at: " + str(datetime.now()) + "\n"
121 | #arcpy.FeatureToRaster_conversion(worktempfolder + "\\" + month + "_ForRaster.shp","SUM_Join_C", out_folder + "\\" + shipType + "\\" + shipType + "_" + year + "_" + month + "_Raster" + ".tif", 1000)
122 | arcpy.FeatureToRaster_conversion(worktempfolder + "\\" + month + "_ForRaster.shp","SUM_Join_C", out_folder + "\\DensityMaps1Km_" + year + "_IMO_" + shipType + "\\" + shipType + "_" + year + "_" + month + "_Raster" + ".tif", 1000)
123 | print "+++ Ended FeatureToRaster " + month + " at: " + str(datetime.now()) + "\n"
124 |
125 | arcpy.Delete_management(worktempfolder)
126 | print "End processing " + month + " at: " + str(datetime.now()) + "\n"
127 |
128 | if __name__ == '__main__':
129 | startTime_script = datetime.now()
130 | print "Started script for year " + year + " " + shipType + " at: " + str(startTime_script)
131 | print "Started create months rasters at: " + str(datetime.now()) + "\n"
132 |
133 | linesfiles = []
134 | for filename in os.listdir(in_folder):
135 | if filename.endswith(".shp"):
136 | linesfiles.append(in_folder + "\\" + filename)
137 |
138 | if len(linesfiles) == 0:
139 | print "WARNING: No files for the analysis..."
140 | else:
141 | starTime_task = datetime.now()
142 | #shipTypeFolder = out_folder + "\\" + shipType
143 | shipTypeFolder = out_folder + "\\DensityMaps1Km_" + year + "_IMO_" + shipType
144 | if not arcpy.Exists(shipTypeFolder):
145 | #arcpy.CreateFolder_management(out_folder, shipType)
146 | arcpy.CreateFolder_management(out_folder, "DensityMaps1Km_" + year + "_IMO_" + shipType)
147 |
148 | pool = multiprocessing.Pool(6)
149 | pool.map(multiProcessing_function, linesfiles)
150 | pool.close()
151 | pool.join()
152 |
153 | print "Ended create months rasters at: " + str(datetime.now())
154 |
155 | #Join all months rasters into one year raster
156 | print "Started create year " + year + " " + shipType + " raster at: " + str(datetime.now()) + "\n"
157 | if arcpy.CheckExtension("Spatial") == "Available":
158 | arcpy.CheckOutExtension("Spatial")
159 | #arcpy.env.workspace = out_folder + "\\" + shipType
160 | arcpy.env.workspace = out_folder + "\\DensityMaps1Km_" + year + "_IMO_" + shipType
161 | rasterList = arcpy.ListRasters("*_Raster.tif")
162 | sumRasters = arcpy.sa.CellStatistics(rasterList, "SUM", "NODATA")
163 | #sumRasters.save(out_folder + "\\" + shipType + "\\" + shipType + "_" + year + "_Year_Raster" + ".tif")
164 | sumRasters.save(out_folder + "\\DensityMaps1Km_" + year + "_IMO_" + shipType + "\\" + shipType + "_" + year + "_Year_Raster" + ".tif")
165 | arcpy.CheckInExtension("Spatial")
166 | else:
167 | print("Spatial Analyst license is unavailable")
168 | print "Ended create year " + year + " " + shipType + " raster at: " + str(datetime.now())
169 | print "Ended script for year " + year + " " + shipType + " at: " + str(datetime.now())
170 | print "Duration: " + str(datetime.now() - startTime_script) + "\n"
171 |
--------------------------------------------------------------------------------
/Script 8. CreateRasters_multiprocessing.py:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------
2 | # Name: Create rasters in multiprocessing
3 | # Purpose: Creates a raster file for each ship type category
4 | # Authors: Manuel Frias, Andzej Milos
5 | # Copyright: GNU General Public License V3
6 | # ArcGIS Version: 10.2
7 | # Python Version: 2.7
8 | #-------------------------------------------------------------
9 |
10 | import arcpy
11 | import time
12 | from arcpy.sa import *
13 | import os
14 | import multiprocessing
15 | from datetime import datetime
16 |
17 | year = "2010"
18 | shipType = "TANKER"
19 | grids_folder = r"E:\DensityMaps_V2\grid"
20 | grid = r"E:\DensityMaps_V2\grid\Grid1km_BalticSea.shp"
21 | #clippingArea = r"E:\DensityMaps\DensityMaps1Km_GRIDSandTables.gdb\BalticScope_StudyArea"
22 |
23 | in_folder = r"E:\DensityMaps_V2\2013\03_lines_by_shiptype" + "\\" + shipType
24 | out_folder = r"E:\DensityMaps_V2\2013\04_rasters"
25 |
26 | def getMonthFromFileName(filename):
27 | monthsList = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
28 | result = False
29 | for month in monthsList:
30 | if ((filename.find(month) > -1) and (filename.find(year) > -1) and (filename.find(shipType) > -1)):
31 | result = month
32 | break
33 | return result
34 |
35 | def multiProcessing_function(data):
36 | month = getMonthFromFileName(data)
37 | print "Start processing " + month + " at: " + str(datetime.now()) + "\n"
38 | worktempfolder = out_folder + "\\" + shipType + "\\temp_" + month
39 | if not arcpy.Exists(worktempfolder):
40 | arcpy.CreateFolder_management(out_folder + "\\" + shipType, "temp_" + month)
41 |
42 | for i in range(1, 6):
43 | print "--- Spatial join " + month + " gridDivision " + str(i) + "..."
44 |
45 | gridDivision = grids_folder + "\\grid_division" + str(i) + ".shp"
46 |
47 | arcpy.MakeFeatureLayer_management(gridDivision, "gridDivision_lyr_" + month)
48 | arcpy.MakeFeatureLayer_management(grid, "grid_lyr_" + month + "_" + str(i))
49 | arcpy.MakeFeatureLayer_management(data, "line_lyr")
50 |
51 | arcpy.SelectLayerByLocation_management("grid_lyr_" + month + "_" + str(i), "WITHIN", "gridDivision_lyr_" + month)
52 | arcpy.MakeFeatureLayer_management("grid_lyr_" + month + "_" + str(i), "grid_lyr_" + month)
53 |
54 |
55 | #result = arcpy.GetCount_management("line_lyr")
56 | #count = int(result.getOutput(0))
57 | #print " lines total count: " + str(count) + " " + month
58 |
59 | # Select lines in grid division
60 | arcpy.SelectLayerByLocation_management("line_lyr", "INTERSECT", "gridDivision_lyr_" + month, "", "NEW_SELECTION")
61 |
62 | #if count > 0:
63 | # Select grids intersecting lines
64 | arcpy.SelectLayerByLocation_management("grid_lyr_" + month, "INTERSECT", "line_lyr", "", "NEW_SELECTION")
65 |
66 | # Spatial join selected lines and grids
67 | arcpy.SpatialJoin_analysis("grid_lyr_" + month, "line_lyr", worktempfolder + "\\" + month + "_SpJoin_" + str(i) + ".shp", "JOIN_ONE_TO_MANY", "", "", "INTERSECT")
68 |
69 | arcpy.Delete_management("gridDivision_lyr_" + month)
70 | arcpy.Delete_management("grid_lyr_" + month + "_" + str(i))
71 | arcpy.Delete_management("grid_lyr_" + month)
72 | arcpy.Delete_management("line_lyr")
73 |
74 | print "--- End spatial join: " + month + " gridDivision " + str(i) + "..."
75 |
76 | spjoinList = []
77 | for spjoin in os.listdir(worktempfolder):
78 | if spjoin.endswith(".shp"):
79 | spjoinList.append(worktempfolder + "\\" + spjoin)
80 |
81 | if len(spjoinList) > 0:
82 | # Merge Spatial Joins
83 | print "--- Merge " + month + "..."
84 | arcpy.Merge_management(spjoinList, worktempfolder + "\\" + month + "_Merged.shp")
85 | print "--- End merge " + month + "..."
86 |
87 | # Dissolve merged
88 | print "--- Dissolve " + month + "..."
89 | arcpy.Dissolve_management(worktempfolder + "\\" + month + "_Merged.shp", worktempfolder + "\\" + month + "_Dissolve.shp", "TARGET_FID", [["Join_Count", "SUM"]])
90 | print "--- End dissolve " + month + "..."
91 |
92 | # Make raster out of dissolved
93 | print "--- FeatureToRaster " + month + "..."
94 | arcpy.FeatureToRaster_conversion(worktempfolder + "\\" + month + "_Dissolve.shp","SUM_Join_C", out_folder + "\\" + shipType + "\\" + month + "_" + year + "_" + shipType + "_Raster" + ".tif", 1000)
95 | print "--- End FeatureToRaster " + month + "..."
96 |
97 | arcpy.Delete_management(worktempfolder)
98 | print "End processing " + month + " at: " + str(datetime.now()) + "\n"
99 |
100 | if __name__ == '__main__':
101 | startTime_script = datetime.now()
102 | print "Started at: " + str(startTime_script) + "\n"
103 |
104 | linesfiles = []
105 | for filename in os.listdir(in_folder):
106 | if filename.endswith(".shp"):
107 | linesfiles.append(in_folder + "\\" + filename)
108 |
109 | if len(linesfiles) == 0:
110 | print "WARNING: No files for the analysis..."
111 | else:
112 | starTime_task = datetime.now()
113 | shipTypeFolder = out_folder + "\\" + shipType
114 | if not arcpy.Exists(shipTypeFolder):
115 | arcpy.CreateFolder_management(out_folder, shipType)
116 |
117 |
118 | pool = multiprocessing.Pool(6)
119 | pool.map(multiProcessing_function, linesfiles)
120 | pool.close()
121 | pool.join()
122 |
123 | print "Ended at: " + str(datetime.now()) + ".\nDuration: " + str(datetime.now() - startTime_script) + "\n"
124 |
125 |
--------------------------------------------------------------------------------