├── CMakeLists.txt
├── LICENSE
├── README.md
├── assets
├── PSO_Planner.png
├── pso_demo1.gif
├── pso_demo2.gif
├── pso_fitness.png
└── pso_ros_1.gif
├── include
├── global_planner_ros.h
├── pso.h
└── trajectoryGeneration.h
├── package.xml
├── params
└── pso_planner.yaml
├── pso_planner_plugin.xml
└── src
├── global_planner_ros.cpp
├── pso.cpp
├── pso_plan_node.cpp
└── trajectoryGeneration.cpp
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.0.2)
2 | project(pso_global_planner)
3 |
4 | add_compile_options(-std=c++11)
5 |
6 | find_package(catkin REQUIRED
7 | angles
8 | COMPONENTS
9 | costmap_2d
10 | geometry_msgs
11 | nav_msgs
12 | pluginlib
13 | tf2_geometry_msgs
14 | tf2_ros
15 | nav_core
16 | roscpp
17 | std_msgs
18 | visualization_msgs
19 | tf
20 | )
21 |
22 | catkin_package(
23 | INCLUDE_DIRS include
24 | LIBRARIES ${PROJECT_NAME}
25 | CATKIN_DEPENDS
26 | costmap_2d
27 | geometry_msgs
28 | nav_msgs
29 | pluginlib
30 | tf2_geometry_msgs
31 | tf2_ros
32 | nav_core
33 | roscpp
34 | std_msgs
35 | visualization_msgs
36 | tf
37 | )
38 |
39 | include_directories(
40 | include
41 | ${catkin_INCLUDE_DIRS}
42 | )
43 |
44 | add_library(${PROJECT_NAME}
45 | src/global_planner_ros.cpp
46 | src/trajectoryGeneration.cpp
47 | src/pso.cpp
48 | )
49 |
50 | add_dependencies(${PROJECT_NAME} ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
51 | target_link_libraries(${PROJECT_NAME} ${catkin_LIBRARIES})
52 |
53 | add_executable(pso_planner src/pso_plan_node.cpp)
54 | add_dependencies(pso_planner ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS})
55 | target_link_libraries(pso_planner ${PROJECT_NAME} ${catkin_LIBRARIES})
56 |
57 | install(TARGETS ${PROJECT_NAME}
58 | ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
59 | LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
60 | RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION})
61 |
62 | install(DIRECTORY include/${PROJECT_NAME}/
63 | DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION}
64 | PATTERN ".svn" EXCLUDE)
65 |
66 | install(FILES pso_planner_plugin.xml
67 | DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION})
68 |
69 |
70 |
--------------------------------------------------------------------------------
/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 |
635 | Copyright (C)
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 | Copyright (C)
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 | # PSO Global Path Planner for ROS
2 |
3 | 
4 |
5 |
6 |
8 |
9 |
10 |
11 | ## 1. Introduction
12 |
13 | This ROS Global Planner Plugin implements the PSO (Particle Swarm Optimization) path planning algorithm. The examples below demonstrate its usage in both static and dynamic environments:
14 |
15 | ### (1) Static Environment:
16 |
17 |
18 |

19 |
20 |
21 | ### (2) Dynamic Environment:
22 |
23 |
24 |

25 |
26 |
27 | ## 2. How to Use
28 |
29 | ### (1) Method One: Utilized as a ROS Global Planner Plugin.
30 |
31 | You can employ this plugin within the ROS navigation package by configuring the global path planner plugin to `pso_planner/globalMotionPlannerROS` in the launch file where the 'move_base' node is situated. Additionally, load the parameter configuration file `pso_planner.yaml`. An example is provided below:
32 |
33 | ```bash
34 |
35 |
36 |
37 | ...
38 | ...
39 | ...
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 | ...
49 | ...
50 | ...
51 |
52 |
53 | ```
54 |
55 | ### (2) Method Two: Employing through the ros_motion_planning library.
56 |
57 | In addition to the method described above, which involves using it as an independent ROS global path planner plugin, we also offer an alternative approach. We have integrated the PSO global path planner into the ROS-based motion planning library, [ros_motion_planning](https://github.com/ai-winter/ros_motion_planning). You can easily utilize it by setting the 'robot1_global_planner' parameter in the ['user_config.yaml'](https://github.com/ai-winter/ros_motion_planning/blob/master/src/user_config/user_config.yaml) file of this motion planning library to 'pso'. An example is provided below:
58 |
59 | ```bash
60 | map: "warehouse"
61 | world: "warehouse"
62 | rviz_file: "sim_env.rviz"
63 |
64 | robots_config:
65 | - robot1_type: "turtlebot3_waffle"
66 | robot1_global_planner: "pso"
67 | robot1_local_planner: "dwa"
68 |
69 |
70 | ...
71 | ...
72 | ...
73 |
74 | plugins:
75 |
76 |
77 | ...
78 | ...
79 | ...
80 |
81 | ```
82 |
83 | The demonstration of the results is as follows:
84 |
85 |
86 |

87 |

88 |
--------------------------------------------------------------------------------
/assets/PSO_Planner.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JZX-MY/pso_global_planner/f1e8286c9908721af4ba52cdd889084b53550867/assets/PSO_Planner.png
--------------------------------------------------------------------------------
/assets/pso_demo1.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JZX-MY/pso_global_planner/f1e8286c9908721af4ba52cdd889084b53550867/assets/pso_demo1.gif
--------------------------------------------------------------------------------
/assets/pso_demo2.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JZX-MY/pso_global_planner/f1e8286c9908721af4ba52cdd889084b53550867/assets/pso_demo2.gif
--------------------------------------------------------------------------------
/assets/pso_fitness.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JZX-MY/pso_global_planner/f1e8286c9908721af4ba52cdd889084b53550867/assets/pso_fitness.png
--------------------------------------------------------------------------------
/assets/pso_ros_1.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/JZX-MY/pso_global_planner/f1e8286c9908721af4ba52cdd889084b53550867/assets/pso_ros_1.gif
--------------------------------------------------------------------------------
/include/global_planner_ros.h:
--------------------------------------------------------------------------------
1 | /***********************************************************
2 | *
3 | * @file: global_planner_ros.cpp
4 | * @breif: ROS related framework for global path planner
5 | * @author: Jing Zongxin
6 | * @update: 2023-12-13
7 | * @version: 1.0
8 | *
9 | * Copyright (c) 2023,Jing Zongxin
10 | * All rights reserved.
11 | * --------------------------------------------------------
12 | *
13 | **********************************************************/
14 |
15 | #ifndef GLOBAL_PLANNER_ROS_H
16 | #define GLOBAL_PLANNER_ROS_H
17 |
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 |
28 | #include "pso.h"
29 |
30 |
31 | namespace global_motion_planner
32 | {
33 |
34 | class globalMotionPlannerROS : public nav_core::BaseGlobalPlanner
35 | {
36 |
37 | public:
38 | /**
39 | * @brief Default constructor of the plugin
40 | */
41 | globalMotionPlannerROS();
42 |
43 | globalMotionPlannerROS(std::string name, costmap_2d::Costmap2DROS* costmap_ros);
44 |
45 | ~globalMotionPlannerROS();
46 |
47 | /**
48 | * @brief Initialization function for the PlannerCore object
49 | * @param name The name of this planner
50 | * @param costmap_ros A pointer to the ROS wrapper of the costmap to use for planning
51 | */
52 | void initialize(std::string name, costmap_2d::Costmap2DROS* costmap_ros);
53 |
54 | /**
55 | * @brief Given a goal pose in the world, compute a plan
56 | * @param start The start pose
57 | * @param goal The goal pose
58 | * @param plan The plan... filled by the planner
59 | * @return True if a valid plan was found, false otherwise
60 | */
61 | bool makePlan(const geometry_msgs::PoseStamped& start,
62 | const geometry_msgs::PoseStamped& goal,
63 | std::vector& plan);
64 |
65 | /**
66 | * @brief Generates a plan from a given path.
67 | * @param path Vector of pairs representing the path in (x, y) coordinates.
68 | * @param plan Vector of PoseStamped messages representing the generated plan.
69 | * @return bool True if the plan is successfully generated, false otherwise.
70 | */
71 | bool getPlanFromPath(std::vector< std::pair >& path, std::vector& plan);
72 |
73 |
74 | /**
75 | * @brief Compute the euclidean distance (straight-line distance) between two points
76 | * @param px1 point 1 x
77 | * @param py1 point 1 y
78 | * @param px2 point 2 x
79 | * @param py2 point 2 y
80 | * @return the distance computed
81 | */
82 | double distance(double px1, double py1, double px2, double py2);
83 |
84 | /**
85 | * @brief Check if there is a collision.
86 | * @param x coordinate (cartesian system)
87 | * @param y coordinate (cartesian system)
88 | * @return True is the point collides and false otherwise
89 | */
90 | bool collision(double x, double y); //是否为障碍物
91 |
92 | /**
93 | * @brief Checks if the specified world coordinates are in the vicinity of a free space.
94 | * @param wx The world x-coordinate to be checked.
95 | * @param wy The world y-coordinate to be checked.
96 | * @return bool True if the specified coordinates are around a free space, false otherwise.
97 | */
98 | bool isAroundFree(double wx, double wy);
99 |
100 | /**
101 | * @brief Checks for collision between two points in a circular region.
102 | * @param x1 The x-coordinate of the first point.
103 | * @param y1 The y-coordinate of the first point.
104 | * @param x2 The x-coordinate of the second point.
105 | * @param y2 The y-coordinate of the second point.
106 | * @param radius The radius of the circular region for collision checking.
107 | * @return bool True if there is a collision, false otherwise.
108 | */
109 | bool pointCircleCollision(double x1, double y1, double x2, double y2, double radius);
110 |
111 | /**
112 | * @brief Optimizes the orientation of poses in a given plan.
113 | * @param plan Vector of PoseStamped messages representing the plan to be optimized.
114 | */
115 | void optimizationOrientation(std::vector &plan);
116 |
117 | /**
118 | * @brief Checks if the line segment between two points is free from obstacles.
119 | * @param p1 Pair representing the coordinates (x, y) of the first point.
120 | * @param p2 Pair representing the coordinates (x, y) of the second point.
121 | * @return bool True if the line segment is free from obstacles, false otherwise.
122 | */
123 | bool isLineFree(const std::pair p1,const std::pair p2);
124 |
125 | protected:
126 |
127 | costmap_2d::Costmap2D* costmap_; // costmap
128 | costmap_2d::Costmap2DROS* costmap_ros_; // costmap ros
129 | global_motion_planner::PSO* g_planner_; // planner
130 | unsigned int nx_, ny_; // costmap size
131 | double origin_x_, origin_y_; // costmap origin
132 | double resolution_; // costmap resolution
133 | std::string frame_id_;
134 | ros::Publisher plan_pub_;
135 |
136 | private:
137 |
138 | bool initialized_;
139 |
140 | };
141 | } // global_motion_planner namespace
142 | #endif
143 |
--------------------------------------------------------------------------------
/include/pso.h:
--------------------------------------------------------------------------------
1 | /***********************************************************
2 | *
3 | * @file: pso.h
4 | * @breif: Contains the Particle Swarm Optimization(PSO) planner class
5 | * @author: Jing Zongxin
6 | * @update: 2023-12-12
7 | * @version: 1.1
8 | *
9 | * Copyright (c) 2023,Jing Zongxin
10 | * All rights reserved.
11 | * --------------------------------------------------------
12 | *
13 | **********************************************************/
14 |
15 | #ifndef PSO_H
16 | #define PSO_H
17 |
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include "trajectoryGeneration.h"
23 | #include
24 | #include
25 |
26 | using PositionSequence = std::vector>>;
27 |
28 | namespace global_motion_planner
29 | {
30 | struct Particle
31 | {
32 | std::vector> position; // Particle position
33 | std::vector> velocity; // Particle velocity
34 | double fitness; // Particle fitness
35 | std::vector> personal_best_pos; // Personal best position in iteration
36 | double personal_best_fitness; // Personal best fitness in iteration
37 |
38 | Particle() = default;
39 |
40 | Particle(const std::vector>& initial_position,
41 | const std::vector>& initial_velocity,
42 | double initial_fitness)
43 | : position(initial_position),
44 | velocity(initial_velocity),
45 | fitness(initial_fitness),
46 | personal_best_pos(initial_position),
47 | personal_best_fitness(initial_fitness)
48 | {
49 | }
50 | };
51 |
52 | /**
53 | * @brief Class for objects that plan using the PSO algorithm
54 | */
55 |
56 | class PSO
57 | {
58 | public:
59 | /**
60 | * @brief Construct a new PSO object
61 | * @param nx pixel number in costmap x direction
62 | * @param ny pixel number in costmap y direction
63 | * @param resolution costmap resolution
64 | * @param origin_x origin coordinate in the x direction.
65 | * @param origin_y origin coordinate in the y direction.
66 | * @param n_particles number of particles
67 | * @param n_inherited number of inherited particles
68 | * @param pointNum number of position points contained in each particle
69 | * @param w_inertial inertia weight
70 | * @param w_social social weight
71 | * @param w_cognitive cognitive weight
72 | * @param obs_factor obstacle factor(greater means obstacles)
73 | * @param max_speed The maximum movement speed of particles
74 | * @param initposmode Set the generation mode for the initial position points of the particle swarm
75 | * @param pub_particles Boolean flag to publish particles.
76 | * @param max_iter maximum iterations
77 | */
78 | PSO(int nx, int ny, double resolution, double origin_x, double origin_y, int n_particles,int n_inherited, int pointNum , double w_inertial, double w_social, double w_cognitive, double obs_factor,int max_speed,int initposmode ,bool pub_particles,int max_iter);
79 | ~PSO();
80 |
81 | /**
82 | * @brief PSO implementation
83 | * @param global_costmap global costmap
84 | * @param start start node
85 | * @param goal goal node
86 | * @param path optimal path consists of Node
87 | * @return true if path found, else false
88 | */
89 | bool plan(const unsigned char* global_costmap, const std::pair& start, const std::pair& goal, std::vector< std::pair>& path);
90 |
91 | /**
92 | * @brief Generate n particles with pointNum_ positions each within the map range
93 | * @param initialPositions The initial position sequence of particle swarm
94 | * @param start_d starting point
95 | * @param goal_d Target point
96 | */
97 | void generateRandomInitialPositions(PositionSequence &initialPositions,const std::pair start_d,const std::pair goal_d);
98 |
99 | /**
100 | * @brief Generate an initial position point sequence within a circular area, located within the map range
101 | * @param initialPositions The initial position sequence of particle swarm
102 | * @param start_d starting point
103 | * @param goal_d Target point
104 | */
105 | void generateCircularInitialPositions(PositionSequence &initialPositions,const std::pair start_d,const std::pair goal_d);
106 |
107 | /**
108 | * @brief Calculate Obstacle avoidance cost
109 | * @param global_costmap global costmap
110 | * @param pso_path Path to perform collision detection
111 | * @return The collision cost of the path
112 | */
113 | double ObstacleCost(const unsigned char* global_costmap,const std::vector>& pso_path);
114 |
115 | /**
116 | * @brief A function to update the particle velocity
117 | * @param particle Particles to be updated for velocity
118 | * @param global_best Global optimal particle
119 | * @param gen randomizer
120 | */
121 | void updateParticleVelocity(Particle& particle,const Particle& global_best,std::mt19937& gen);
122 |
123 | /**
124 | * @brief A function to update the particle position
125 | * @param particle Particles to be updated for velocity
126 | */
127 | void updateParticlePosition(Particle& particle);
128 |
129 |
130 | /**
131 | * @brief Particle update optimization iteration
132 | * @param particle Particles to be updated for velocity
133 | * @param best_particle Global optimal particle
134 | * @param start_d starting point
135 | * @param goal_d Target point
136 | * @param index_i Particle ID
137 | * @param global_costmap global costmap
138 | * @param gen randomizer
139 | */
140 | void optimizeParticle(Particle& particle, Particle& best_particle, const unsigned char* global_costmap,
141 | const std::pair& start_d, const std::pair& goal_d,
142 | const int& index_i,std::mt19937& gen) ;
143 |
144 | /**
145 | * @brief Clamps a value within a specified range.
146 | * @tparam T The type of the values to be clamped.
147 | * @param value The value to be clamped.
148 | * @param low The lower bound of the range.
149 | * @param high The upper bound of the range.
150 | * @return const T& The clamped value within the specified range.
151 | */
152 | template
153 | const T& clamp(const T& value, const T& low, const T& high) {return std::max(low, std::min(value, high));}
154 |
155 | /**
156 | * @brief Custom comparison function for ascending order.
157 | * @param a The first element to be compared.
158 | * @param b The second element to be compared.
159 | * @return bool True if 'a' is less than 'b', indicating ascending order; otherwise, false.
160 | */
161 | static bool ascendingOrder(int a, int b) { return a < b;}
162 |
163 | /**
164 | * @brief Custom comparison function for descending order.
165 | * @param a The first element to be compared.
166 | * @param b The second element to be compared.
167 | * @return bool True if 'a' is greater than 'b', indicating descending order; otherwise, false.
168 | */
169 | static bool descendingOrder(int a, int b){ return a > b;}
170 |
171 |
172 | /**
173 | * @brief Publishes particle markers based on given positions and index.
174 | * @param positions Vector of pairs representing positions (x, y) of particles.
175 | * @param index Index identifier for the particles.
176 | */
177 | void publishParticleMarkers(const std::vector>& positions, const int& index);
178 |
179 | /**
180 | * @brief Transform from grid map(x, y) to grid index(i)
181 | * @param x grid map x
182 | * @param y grid map y
183 | * @return index
184 | */
185 | int grid2Index (int x, int y);
186 |
187 |
188 | protected:
189 | int nx_,ny_,ns_; // the number of grids on the x-axis and y-axis of the map, as well as the total number of grids
190 | double resolution_; // map resolution
191 | double origin_x_,origin_y_; // origin coordinate in the x、y direction.
192 | bool pub_particles_; // boolean flag to publish particles.
193 | int max_iter_; // maximum iterations
194 | int n_particles_; // number of particles
195 | int n_inherited_; // number of inherited particles
196 | int pointNum_; // number of position points contained in each particle
197 | double w_inertial_, w_social_, w_cognitive_; // Weight coefficients for fitness calculation: inertia weight, social weight, cognitive weight
198 | double obs_factor_; // obstacle factor(greater means obstacles)
199 | int max_speed_; // The maximum velocity of particle motion
200 | int initposmode_; // Set the generation mode for the initial position points of the particle swarm
201 |
202 |
203 | private:
204 | unsigned char lethal_cost_=253; //lethal cost
205 | ros::Publisher particle_pub; //The publisher of real-time particle visualization
206 | int GlobalBest_particle_; //The ID of the globally optimal particle
207 | std::mutex particles_lock_; //thread lock
208 | std::vector inherited_particles_; //inherited particles
209 | trajectoryGeneration path_generation; //Path generation
210 | };
211 |
212 | } // namespace global_planner
213 | #endif
214 |
--------------------------------------------------------------------------------
/include/trajectoryGeneration.h:
--------------------------------------------------------------------------------
1 | /***********************************************************
2 | *
3 | * @file: trajectoryGeneration.h
4 | * @breif: Contains trajectory generation class
5 | * @author: Jing Zongxin
6 | * @update: 2023-12-4
7 | * @version: 1.0
8 | *
9 | * Copyright (c) 2023,Jing Zongxin
10 | * All rights reserved.
11 | * --------------------------------------------------------
12 | *
13 | **********************************************************/
14 |
15 | #ifndef TRAJECTORY_GENERATION_H
16 | #define TRAJECTORY_GENERATION_H
17 |
18 | #include
19 | #include
20 |
21 | class trajectoryGeneration
22 | {
23 | public:
24 | trajectoryGeneration();
25 | ~trajectoryGeneration();
26 |
27 | static int splineOrder; //Set the order of the B-spline curve
28 |
29 | /**
30 | * @brief Using quasi uniform B-spline curves for trajectory generation
31 | * @param plan Key points&generated trajectories
32 | * @param k Order of B-spline curve
33 | */
34 | void B_spline_curve(std::vector> &plan, int k);
35 |
36 |
37 | /**
38 | * @brief Generate B-spline curve control points
39 | * @param start_d starting point
40 | * @param goal_d Target point
41 | * @param initial_position Intermediate control point
42 | * @param initial_point B-spline control points
43 | */
44 | void GenerateControlPoints(const std::pair& start_d, const std::pair& goal_d,
45 | const std::vector>& initial_position,
46 | std::vector>& initial_point);
47 |
48 | /**
49 | * @brief Calculate the distance between two points
50 | * @param point1 First point
51 | * @param point2 Second point
52 | * @return the distance between two points
53 | */
54 | double calculateDistance(const std::pair& point1, const std::pair& point2);
55 |
56 | /**
57 | * @brief Calculate path length
58 | * @param path The path to be calculated
59 | * @return path length
60 | */
61 | double calculatePathLength(const std::vector>& path);
62 |
63 |
64 | private:
65 | double BaseFun(int i, int k, double u, std::vector NodeVector);
66 | };
67 |
68 | #endif // TRAJECTORY_GENERATION_H
69 |
--------------------------------------------------------------------------------
/package.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | pso_global_planner
4 | 0.0.0
5 | The pso_global_planner package
6 |
7 | JZX-MY
8 |
9 | GPLv3
10 |
11 | catkin
12 |
13 | pluginlib
14 | roscpp
15 | std_msgs
16 | nav_core
17 | geometry_msgs
18 | costmap_2d
19 | nav_msgs
20 | tf2_geometry_msgs
21 | tf2_ros
22 | visualization_msgs
23 | tf
24 | angles
25 |
26 | pluginlib
27 | roscpp
28 | costmap_2d
29 | geometry_msgs
30 | nav_msgs
31 | tf2_geometry_msgs
32 | nav_core
33 | std_msgs
34 | visualization_msgs
35 | tf
36 | angles
37 |
38 | pluginlib
39 | roscpp
40 | std_msgs
41 | nav_core
42 | costmap_2d
43 | geometry_msgs
44 | nav_msgs
45 | tf2_geometry_msgs
46 | tf2_ros
47 | visualization_msgs
48 | tf
49 | angles
50 |
51 |
52 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/params/pso_planner.yaml:
--------------------------------------------------------------------------------
1 | globalMotionPlannerROS:
2 |
3 | ## Particle Swarm Optimization(PSO) planner
4 | # number of particles
5 | n_particles: 50
6 | # number of inherited particles (Note: Need to be less than parameter n_ Particles)
7 | n_inherited: 20
8 | # number of position points contained in each particle
9 | pointNum: 5
10 | # The maximum velocity of particle motion
11 | max_speed: 40
12 | # inertia weight
13 | w_inertial: 1.0
14 | # social weight
15 | w_social: 2.0
16 | # cognitive weight
17 | w_cognitive: 1.2
18 | # obstacle factor(greater means obstacles)
19 | obs_factor: 0.39
20 | # Set the generation mode for the initial position points of the particle swarm
21 | # 1: Randomly generate initial positions of particle swarm within the map range
22 | # 2: Randomly generate initial particle swarm positions within the circular area of the starting and target points
23 | initposmode: 2
24 | # Whether to publish particles
25 | pub_particles: false
26 | # maximum iterations
27 | pso_max_iter: 5
28 |
29 |
--------------------------------------------------------------------------------
/pso_planner_plugin.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | This is PSO Global Planner Plugin by Jing Zongxin.
4 |
5 |
6 |
--------------------------------------------------------------------------------
/src/global_planner_ros.cpp:
--------------------------------------------------------------------------------
1 | /***********************************************************
2 | *
3 | * @file: global_planner_ros.cpp
4 | * @breif: ROS related framework for global path planner
5 | * @author: Jing Zongxin
6 | * @update: 2023-12-13
7 | * @version: 1.0
8 | *
9 | * Copyright (c) 2023,Jing Zongxin
10 | * All rights reserved.
11 | * --------------------------------------------------------
12 | *
13 | **********************************************************/
14 |
15 | #include
16 | #include
17 | #include
18 |
19 | #include "global_planner_ros.h"
20 |
21 | PLUGINLIB_EXPORT_CLASS(global_motion_planner::globalMotionPlannerROS, nav_core::BaseGlobalPlanner)
22 |
23 | namespace global_motion_planner
24 | {
25 |
26 | globalMotionPlannerROS::globalMotionPlannerROS() : costmap_(nullptr), initialized_(false){}
27 |
28 | globalMotionPlannerROS::globalMotionPlannerROS(std::string name, costmap_2d::Costmap2DROS* costmap_ros) :costmap_ros_(costmap_ros),initialized_(false)
29 | {
30 | initialize(name, costmap_ros);
31 | }
32 |
33 | globalMotionPlannerROS::~globalMotionPlannerROS()
34 | {
35 | if (g_planner_)
36 | {
37 | delete g_planner_;
38 | g_planner_ = NULL;
39 | }
40 | }
41 |
42 | // Variable initialization
43 | void globalMotionPlannerROS::initialize(std::string name, costmap_2d::Costmap2DROS* costmap_ros)
44 | {
45 | if (!initialized_)
46 | {
47 | // Initialize map
48 | costmap_ros_ = costmap_ros;
49 | costmap_ = costmap_ros->getCostmap();
50 | frame_id_ = costmap_ros->getGlobalFrameID();
51 | // get costmap properties
52 | nx_ = costmap_->getSizeInCellsX(), ny_ = costmap_->getSizeInCellsY();
53 | origin_x_ = costmap_->getOriginX(), origin_y_ = costmap_->getOriginY();
54 | resolution_ = costmap_->getResolution();
55 |
56 | ros::NodeHandle private_nh("~/" + name);
57 | plan_pub_ = private_nh.advertise("plan",1); //发布全局计算
58 |
59 | bool pub_particles;
60 | int n_particles,n_inherited,pointNum,max_speed,initposmode,pso_max_iter;
61 | double obs_factor, w_inertial, w_social, w_cognitive;
62 | private_nh.param("n_particles", n_particles, 50); // number of particles
63 | private_nh.param("n_inherited", n_inherited, 20); // number of inherited particles
64 | private_nh.param("pointNum", pointNum, 5); // number of position points contained in each particle
65 | private_nh.param("obs_factor", obs_factor, 0.39); // obstacle factor(greater means obstacles)
66 | private_nh.param("max_speed", max_speed,40); // The maximum velocity of particle motion
67 | private_nh.param("w_inertial", w_inertial,1.0); // inertia weight
68 | private_nh.param("w_social", w_social, 2.0); // social weight
69 | private_nh.param("w_cognitive", w_cognitive, 1.2); // cognitive weight
70 | private_nh.param("initposmode", initposmode, 2); // Set the generation mode for the initial position points of the particle swarm
71 | private_nh.param("pub_particles", pub_particles, false); // Whether to publish particles
72 | private_nh.param("pso_max_iter", pso_max_iter, 5); // maximum iterations
73 |
74 | g_planner_ = new PSO(nx_, ny_, resolution_ ,origin_x_,origin_y_, n_particles,n_inherited, pointNum, w_inertial, w_social, w_cognitive, obs_factor, max_speed ,initposmode ,pub_particles,pso_max_iter);
75 |
76 | ROS_INFO("PSO planner initialized successfully");
77 | initialized_ = true;
78 | }
79 | else
80 | {
81 | ROS_WARN("This planner has already been initialized... doing nothing");
82 | }
83 | }
84 |
85 | // Path planning
86 | bool globalMotionPlannerROS::makePlan(const geometry_msgs::PoseStamped& start,
87 | const geometry_msgs::PoseStamped& goal,
88 | std::vector& plan)
89 | {
90 | if (!initialized_)
91 | {
92 | ROS_ERROR("This planner has not been initialized yet, but it is being used, please call initialize() before use");
93 | return false;
94 | }
95 |
96 | std::pair start_node, goal_node;
97 | unsigned int mx = 0,my = 0;
98 |
99 | if(this->collision(start.pose.position.x, start.pose.position.y))
100 | {
101 | ROS_WARN("failed to get a path.start point is obstacle.");
102 | return false;
103 | }
104 | else
105 | {
106 | this->costmap_->worldToMap(start.pose.position.x,start.pose.position.y,mx,my);
107 | start_node.first =static_cast(mx);
108 | start_node.second=static_cast(my);
109 | }
110 |
111 | if(this->collision(goal.pose.position.x, goal.pose.position.y))
112 | {
113 | ROS_WARN("failed to get a path.goal point is obstacle.");
114 | return false;
115 | }
116 | else
117 | {
118 | this->costmap_->worldToMap(goal.pose.position.x,goal.pose.position.y,mx,my);
119 | goal_node.first =static_cast(mx);
120 | goal_node.second=static_cast(my);
121 | }
122 |
123 | std::vector< std::pair> path;
124 | plan.clear();
125 |
126 | double start_time = ros::Time::now().toSec();
127 |
128 | bool path_found = g_planner_->plan(costmap_->getCharMap(), start_node, goal_node, path);
129 |
130 | if (path_found)
131 | {
132 | if (getPlanFromPath(path, plan))
133 | {
134 | geometry_msgs::PoseStamped goal_copy = goal;
135 | goal_copy.header.stamp = ros::Time::now();
136 | plan.push_back(goal_copy);
137 | }
138 | else
139 | {
140 | ROS_ERROR("Failed to get a plan from path when a legal path was found. This shouldn't happen.");
141 | }
142 | }
143 | else
144 | {
145 | ROS_ERROR("Failed to get a path.");
146 | }
147 |
148 | // path point attitude correction
149 | optimizationOrientation(plan);
150 |
151 | // publish visulization plan
152 | nav_msgs::Path path_pose;
153 | path_pose.header.frame_id = this->frame_id_;
154 | path_pose.header.stamp = ros::Time::now();
155 | path_pose.poses = plan;
156 | plan_pub_.publish(path_pose);
157 |
158 | return !plan.empty();
159 | }
160 |
161 | bool globalMotionPlannerROS::getPlanFromPath(std::vector< std::pair >& path, std::vector& plan)
162 | {
163 | plan.clear();
164 | unsigned int mx = 0,my = 0;
165 | double wx, wy;
166 |
167 | for (int i = 0; i < path.size(); i++)
168 | {
169 | mx=static_cast(path[i].first);
170 | my=static_cast(path[i].second);
171 | this->costmap_->mapToWorld(mx,my,wx,wy);
172 | // coding as message type
173 | geometry_msgs::PoseStamped pose;
174 | pose.header.stamp = ros::Time::now();
175 | pose.header.frame_id = frame_id_;
176 | pose.pose.position.x = wx;
177 | pose.pose.position.y = wy;
178 | pose.pose.position.z = 0.0;
179 | pose.pose.orientation.x = 0.0;
180 | pose.pose.orientation.y = 0.0;
181 | pose.pose.orientation.z = 0.0;
182 | pose.pose.orientation.w = 1.0;
183 | plan.push_back(pose);
184 | }
185 |
186 | return !plan.empty();
187 | }
188 |
189 | // Optimizes the orientation of poses in a given plan.
190 | void globalMotionPlannerROS::optimizationOrientation(std::vector &plan)
191 | {
192 | size_t num = plan.size()-1;
193 | if(num < 1)
194 | return;
195 | for(size_t i=0;i p1, const std::pair p2)
213 | {
214 | std::pair ptmp;
215 | ptmp.first = 0.0;
216 | ptmp.second = 0.0;
217 |
218 | double dist = sqrt( (p2.second-p1.second) * (p2.second-p1.second) +
219 | (p2.first-p1.first) * (p2.first-p1.first) );
220 | if (dist < this->resolution_)
221 | {
222 | return true;
223 | }
224 | else
225 | {
226 | int value = int(floor(dist/this->resolution_));
227 | double theta = atan2(p2.second - p1.second,
228 | p2.first - p1.first);
229 | int n = 1;
230 | for (int i = 0;i < value; i++)
231 | {
232 | ptmp.first = p1.first + this->resolution_*cos(theta) * n;
233 | ptmp.second = p1.second + this->resolution_*sin(theta) * n;
234 | if (collision(ptmp.first, ptmp.second))
235 | return false;
236 | n++;
237 | }
238 | return true;
239 | }
240 | }
241 |
242 | // Calculate the distance between two points
243 | double globalMotionPlannerROS::distance(double px1, double py1, double px2, double py2)
244 | {
245 | return sqrt((px1 - px2)*(px1 - px2) + (py1 - py2)*(py1 - py2));
246 | }
247 |
248 | // Check if the checkpoint is an obstacle
249 | bool globalMotionPlannerROS::collision(double x, double y)
250 | {
251 | unsigned int mx,my;
252 | if(!this->costmap_->worldToMap(x,y,mx,my))
253 | return true;
254 | if ((mx >= costmap_->getSizeInCellsX()) || (my >= costmap_->getSizeInCellsY()))
255 | return true;
256 | if (costmap_->getCost(mx, my) >= costmap_2d::INSCRIBED_INFLATED_OBSTACLE)
257 | return true;
258 | return false;
259 | }
260 |
261 | // Check if there are any obstacles around the checkpoint
262 | bool globalMotionPlannerROS::isAroundFree(double wx, double wy)
263 | {
264 | unsigned int mx, my;
265 | if(!this->costmap_->worldToMap(wx,wy,mx,my))
266 | return false;
267 | if(mx <= 1 || my <= 1 || mx >= this->costmap_->getSizeInCellsX()-1 || my >= this->costmap_->getSizeInCellsY()-1)
268 | return false;
269 | int x,y;
270 | for(int i=-1;i<=1;i++)
271 | {
272 | for(int j=-1;j<=1;j++)
273 | {
274 | x = static_cast(mx) + i;
275 | y = static_cast(my) + j;
276 | if(this->costmap_->getCost(static_cast(x),static_cast(y)) >= costmap_2d::INSCRIBED_INFLATED_OBSTACLE)
277 | return false;
278 | }
279 | }
280 | return true;
281 | }
282 |
283 |
284 | }; // global_motion_planner
285 |
--------------------------------------------------------------------------------
/src/pso.cpp:
--------------------------------------------------------------------------------
1 | /***********************************************************
2 | *
3 | * @file: pso.cpp
4 | * @breif: Contains the Particle Swarm Optimization(PSO) planner class
5 | * @author: Jing Zongxin
6 | * @update: 2023-12-12
7 | * @version: 1.1
8 | *
9 | * Copyright (c) 2023, Jing Zongxin
10 | * All rights reserved.
11 | * --------------------------------------------------------
12 | *
13 | **********************************************************/
14 | #include
15 | #include
16 | #include
17 | #include
18 | #include
19 | #include "pso.h"
20 |
21 |
22 | namespace global_motion_planner
23 | {
24 | /**
25 | * @brief Construct a new PSO object
26 | * @param nx pixel number in costmap x direction
27 | * @param ny pixel number in costmap y direction
28 | * @param resolution costmap resolution
29 | * @param origin_x origin coordinate in the x direction.
30 | * @param origin_y origin coordinate in the y direction.
31 | * @param n_particles number of particles
32 | * @param n_inherited number of inherited particles
33 | * @param pointNum number of position points contained in each particle
34 | * @param w_inertial inertia weight
35 | * @param w_social social weight
36 | * @param w_cognitive cognitive weight
37 | * @param obs_factor obstacle factor(greater means obstacles)
38 | * @param max_speed The maximum movement speed of particles
39 | * @param initposmode Set the generation mode for the initial position points of the particle swarm
40 | * @param pub_particles Boolean flag to publish particles.
41 | * @param max_iter maximum iterations
42 | */
43 | PSO::PSO(int nx, int ny, double resolution, double origin_x, double origin_y,int n_particles,int n_inherited,int pointNum , double w_inertial, double w_social, double w_cognitive, double obs_factor ,int max_speed, int initposmode, bool pub_particles,int max_iter)
44 | : nx_(nx)
45 | , ny_(ny)
46 | , ns_(nx*ny)
47 | , resolution_(resolution)
48 | , origin_x_(origin_x)
49 | , origin_y_(origin_y)
50 | , n_particles_(n_particles)
51 | , n_inherited_(n_inherited)
52 | , pointNum_(pointNum)
53 | , w_inertial_(w_inertial)
54 | , w_social_(w_social)
55 | , w_cognitive_(w_cognitive)
56 | , obs_factor_(obs_factor)
57 | , max_speed_(max_speed)
58 | , initposmode_(initposmode)
59 | , pub_particles_(pub_particles)
60 | , max_iter_(max_iter)
61 | {
62 | inherited_particles_.emplace_back(std::vector>(pointNum, std::make_pair(1, 1)),
63 | std::vector>(pointNum, std::make_pair(0, 0)),
64 | 0.0);
65 | // Initialize ROS publisher
66 | ros::NodeHandle nh;
67 | particle_pub = nh.advertise("particle_swarm_markers", 10);
68 | }
69 |
70 | PSO::~PSO()
71 | {
72 | }
73 |
74 | /**
75 | * @brief PSO implementation
76 | * @param global_costmap global costmap
77 | * @param start start node
78 | * @param goal goal node
79 | * @param path optimal path consists of Node
80 | * @return true if path found, else false
81 | */
82 | bool PSO::plan(const unsigned char* global_costmap, const std::pair& start, const std::pair& goal, std::vector< std::pair>& path)
83 | {
84 |
85 | std::cout<<" PSO planning started..."< particles;
94 | std::vector> initial_point;
95 | std::pair start_d(static_cast(start.first), static_cast(start.second));
96 | std::pair goal_d(static_cast(goal.first), static_cast(goal.second));
97 |
98 | //Generate initial position of particle swarm
99 | if(initposmode_==1){generateRandomInitialPositions(initialPositions,start_d,goal_d);}
100 | else{generateCircularInitialPositions(initialPositions,start_d,goal_d);}
101 |
102 | std::cout<<"PSO: Successfully generated initial position of particle swarm"<> initial_position;
108 |
109 | if ((i> initial_velocity(pointNum_, std::make_pair(0, 0));
119 | //Generate B-spline curve control points
120 | path_generation.GenerateControlPoints(start_d,goal_d,initial_position,initial_point);
121 | //Generate B-spline curves
122 | path_generation.B_spline_curve(initial_point, path_generation.splineOrder);
123 | //Calculate path length
124 | pathLength = path_generation.calculatePathLength(initial_point);
125 | //collision detection
126 | obstacle_cost=ObstacleCost(global_costmap,initial_point);
127 | //Calculate particle fitness
128 | initial_fitness = 100000.0 / (pathLength + 1000*obstacle_cost);
129 |
130 | if ((i==0)||(initial_fitness>Best_particle.fitness))
131 | {
132 | GlobalBest_particle_=i;
133 | Best_particle.fitness=initial_fitness;
134 | }
135 | //Create and add particle objects to containers
136 | particles.emplace_back(initial_position, initial_velocity, initial_fitness);
137 |
138 | }
139 |
140 | Best_particle.position=particles[GlobalBest_particle_].position;
141 |
142 | std::cout<<"PSO: Successfully generated initial particle swarm"< particle_list = std::vector(n_particles_);
156 | for (size_t i = 0; i < n_particles_; ++i)
157 | particle_list[i] = std::thread(&PSO::optimizeParticle, this, std::ref(particles[i]), std::ref(Best_particle), std::cref(global_costmap), std::cref(start_d), std::cref(goal_d), i, std::ref(gen));
158 | for (size_t i = 0; i < n_particles_; ++i)
159 | particle_list[i].join();
160 |
161 | Best_particle.position=particles[GlobalBest_particle_].personal_best_pos;
162 | }
163 |
164 | //Generating Paths from Optimal Particles
165 | path_generation.GenerateControlPoints(start_d,goal_d,Best_particle.position,initial_point);
166 | path_generation.B_spline_curve(initial_point, path_generation.splineOrder);
167 |
168 | std::cout<<"PSO: Iteration completed, optimal fitness is: "<(initial_point[0].first), static_cast(initial_point[0].second));
177 |
178 | for (int p = 1; p (initial_point[p].first);
181 | int y = static_cast(initial_point[p].second);
182 | // Check if the current point is different from the last point
183 | if (x != path.back().first || y != path.back().second)
184 | {
185 | path.emplace_back(x, y);
186 | }
187 | }
188 | }
189 |
190 | //Update inheritance particles based on optimal fitness
191 | std::sort(particles.begin(), particles.end(), [](const Particle& a, const Particle& b) { return a.personal_best_fitness > b.personal_best_fitness;});
192 | inherited_particles_.clear();
193 |
194 | for (size_t inherit = 0; inherit < n_inherited_; ++inherit)
195 | {
196 | inherited_particles_.emplace_back(particles[inherit]);
197 | }
198 |
199 | if(!path.empty()){std::cout<<"PSO: Planning Successful ! "< start_d,const std::pair goal_d)
210 | {
211 | // Use a random device and engine to generate random numbers
212 | std::random_device rd;
213 | std::mt19937 gen(rd());
214 | int x[pointNum_], y[pointNum_];
215 | int point_id;
216 |
217 | //Calculate sequence direction
218 | bool xorder = (goal_d.first > start_d.first);
219 | bool yorder = (goal_d.second > start_d.second);
220 |
221 | for (int i = 0; i < n_particles_; ++i)
222 | {
223 | std::unordered_set visited;
224 | std::vector> particlePositions;
225 | point_id=0;
226 | // Generate pointNum_ unique coordinates
227 | while (point_id < pointNum_)
228 | {
229 | x[point_id] = std::uniform_int_distribution(0, nx_-1)(gen);
230 | y[point_id] = std::uniform_int_distribution(0, ny_-1)(gen);
231 | int uniqueId = x[point_id] * (ny_ + 1) + y[point_id]; // Represent coordinates by a unique ID
232 |
233 | // Check if the coordinates have already been used
234 | if (visited.find(uniqueId) == visited.end())
235 | {
236 | point_id=point_id+1;
237 | visited.insert(uniqueId);
238 | }
239 | }
240 |
241 | //sort
242 | if(xorder){std::sort(x, x + pointNum_, &PSO::ascendingOrder);}
243 | else{std::sort(x, x + pointNum_, &PSO::descendingOrder);}
244 |
245 | if(yorder){std::sort(y, y + pointNum_, &PSO::ascendingOrder);}
246 | else{std::sort(y, y + pointNum_, &PSO::descendingOrder);}
247 |
248 | // Store elements from x and y in particlePositions
249 | for (int ii = 0; ii < pointNum_; ++ii)
250 | {
251 | particlePositions.emplace_back(x[ii], y[ii]);
252 | }
253 |
254 | initialPositions.push_back(particlePositions);
255 | }
256 | }
257 |
258 | // Generate n particles with pointNum_ positions each within the map range
259 | void PSO::generateCircularInitialPositions(PositionSequence &initialPositions,const std::pair start_d,const std::pair goal_d)
260 | {
261 | // Use a random device and engine to generate random numbers
262 | std::random_device rd;
263 | std::mt19937 gen(rd());
264 | int x[pointNum_], y[pointNum_];
265 | int point_id;
266 | //Calculate sequence direction
267 | bool xorder = (goal_d.first > start_d.first);
268 | bool yorder = (goal_d.second > start_d.second);
269 | // Calculate the center of the circle (midpoint between start and goal)
270 | int centerX = (start_d.first + goal_d.first) / 2;
271 | int centerY = (start_d.second + goal_d.second) / 2;
272 | // Calculate the radius of the circle (half of the distance between start and goal)
273 | double radius = path_generation.calculateDistance(start_d,goal_d) / 2.0;
274 |
275 | if (radius<5){radius=5;}
276 |
277 | for (int i = 0; i < n_particles_; ++i)
278 | {
279 | std::unordered_set visited;
280 | std::vector> particlePositions;
281 | point_id=0;
282 | // Generate pointNum_ unique coordinates
283 | while (point_id < pointNum_)
284 | {
285 | // Generate random angle in radians
286 | double angle = std::uniform_real_distribution(0, 2 * M_PI)(gen);
287 | // Generate random distance from the center within the circle
288 | double r = std::sqrt(std::uniform_real_distribution(0, 1)(gen)) * radius;
289 | // Convert polar coordinates to Cartesian coordinates
290 | x[point_id] = static_cast(std::round(centerX + r * std::cos(angle)));
291 | y[point_id] = static_cast(std::round(centerY + r * std::sin(angle)));
292 |
293 | // Check if the coordinates are within the map range
294 | if (x[point_id] >= 0 && x[point_id] < nx_ && y[point_id] >= 0 && y[point_id] < ny_)
295 | {
296 | int uniqueId = x[point_id] * (ny_ + 1) + y[point_id];
297 | // Check if the coordinates have already been used
298 | if (visited.find(uniqueId) == visited.end())
299 | {
300 | point_id = point_id + 1;
301 | visited.insert(uniqueId);
302 | }
303 | }
304 |
305 | }
306 |
307 | //sort
308 | if(xorder){std::sort(x, x + pointNum_, &PSO::ascendingOrder);}
309 | else{std::sort(x, x + pointNum_, &PSO::descendingOrder);}
310 |
311 | if(yorder){std::sort(y, y + pointNum_, &PSO::ascendingOrder);}
312 | else{std::sort(y, y + pointNum_, &PSO::descendingOrder);}
313 |
314 | // 将 x 和 y 中的元素存放到 particlePositions 中
315 | for (int ii = 0; ii < pointNum_; ++ii)
316 | {
317 | particlePositions.emplace_back(x[ii], y[ii]);
318 | }
319 |
320 | initialPositions.push_back(particlePositions);
321 | }
322 | }
323 |
324 | //Calculate Obstacle avoidance cost
325 | double PSO::ObstacleCost(const unsigned char* global_costmap,const std::vector>& pso_path)
326 | {
327 | int point_index;
328 | double Obscost=1;
329 |
330 | for (size_t i = 1; i < pso_path.size(); ++i)
331 | {
332 | point_index=grid2Index(static_cast(pso_path[i].first), static_cast(pso_path[i].second));
333 | // next node hit the boundary or obstacle
334 | if ((point_index < 0) || (point_index >= ns_) || (global_costmap[point_index] >= lethal_cost_ * obs_factor_))
335 | {
336 | Obscost=Obscost+1;
337 | }
338 | }
339 |
340 | return Obscost;
341 |
342 | }
343 |
344 | // A function to update the particle velocity
345 | void PSO::updateParticleVelocity(Particle& particle,const Particle& global_best,std::mt19937& gen)
346 | {
347 | //The random numbers are distributed between [0, 1).
348 | std::uniform_real_distribution dist(0.0, 1.0);
349 |
350 | // update Velocity
351 | for (size_t i = 0; i < pointNum_; ++i)
352 | {
353 | double rand1 = dist(gen);
354 | double rand2 = dist(gen);
355 |
356 | particle.velocity[i].first = static_cast( w_inertial_ * particle.velocity[i].first +
357 | w_social_ * rand1 * (particle.personal_best_pos[i].first - particle.position[i].first) +
358 | w_cognitive_ * rand2 * (global_best.position[i].first - particle.position[i].first));
359 |
360 | particle.velocity[i].second = static_cast(w_inertial_ * particle.velocity[i].second +
361 | w_social_ * rand1 * (particle.personal_best_pos[i].second - particle.position[i].second) +
362 | w_cognitive_ * rand2 * (global_best.position[i].second - particle.position[i].second));
363 |
364 | // Velocity limit
365 | particle.velocity[i].first =clamp(particle.velocity[i].first , -1*max_speed_, max_speed_);
366 | particle.velocity[i].second=clamp(particle.velocity[i].second, -1*max_speed_, max_speed_);
367 | }
368 | }
369 |
370 | // A function to update the particle position
371 | void PSO::updateParticlePosition(Particle& particle)
372 | {
373 | // update Position
374 | for (size_t i = 0; i < pointNum_; ++i)
375 | {
376 | particle.position[i].first = particle.position[i].first + particle.velocity[i].first;
377 | particle.position[i].second = particle.position[i].second+ particle.velocity[i].second;
378 |
379 | // Position limit
380 | particle.position[i].first =clamp(particle.position[i].first , 1, nx_-1);
381 | particle.position[i].second=clamp(particle.position[i].second, 1, ny_-1);
382 | }
383 | }
384 |
385 | // Particle update optimization iteration
386 | void PSO::optimizeParticle(Particle& particle, Particle& best_particle, const unsigned char* global_costmap, const std::pair& start_d, const std::pair& goal_d,const int& index_i,std::mt19937& gen)
387 | {
388 |
389 | std::vector> process_path;
390 |
391 | //update speed
392 | updateParticleVelocity(particle,best_particle,gen);
393 | //update position
394 | updateParticlePosition(particle);
395 |
396 | //Generate B-spline curve control points
397 | path_generation.GenerateControlPoints(start_d,goal_d,particle.position,process_path);
398 | //Generate B-spline curves
399 | path_generation.B_spline_curve(process_path, path_generation.splineOrder);
400 | //Calculate path length
401 | double pathLength = path_generation.calculatePathLength(process_path);
402 | //collision detection
403 | double obstacle_cost=ObstacleCost(global_costmap,process_path);
404 | //Calculate particle fitness
405 | particle.fitness = 100000.0 / (pathLength + 1000*obstacle_cost);
406 |
407 | // Update individual optima
408 | if (particle.fitness>particle.personal_best_fitness)
409 | {
410 | particle.personal_best_fitness=particle.fitness;
411 | particle.personal_best_pos=particle.position;
412 | }
413 |
414 | // Publish particle markers
415 | if(pub_particles_){publishParticleMarkers(particle.position, index_i);}
416 |
417 | //Update global optimal particles
418 | particles_lock_.lock();
419 |
420 | if (particle.personal_best_fitness>best_particle.fitness)
421 | {
422 | best_particle.fitness=particle.personal_best_fitness;
423 | GlobalBest_particle_=index_i;
424 | }
425 |
426 | particles_lock_.unlock();
427 |
428 | }
429 |
430 |
431 | void PSO::publishParticleMarkers(const std::vector>& positions, const int& index)
432 | {
433 | visualization_msgs::Marker marker;
434 | marker.header.frame_id = "map";
435 | marker.header.stamp = ros::Time::now();
436 | marker.ns = "particle_swarm";
437 | marker.id = index;
438 | marker.type = visualization_msgs::Marker::POINTS;
439 | marker.action = visualization_msgs::Marker::ADD;
440 | marker.pose.orientation.w = 1.0;
441 | marker.scale.x = 0.1;
442 | marker.scale.y = 0.1;
443 | marker.color.r = 1.0;
444 | marker.color.a = 1.0;
445 |
446 | // Convert particle positions to geometry_msgs::Point
447 | for (const auto& position : positions) {
448 | geometry_msgs::Point p;
449 | p.x = origin_x_ + position.first * resolution_;
450 | p.y = origin_y_ + position.second * resolution_;
451 | p.z = 0.0;
452 | marker.points.push_back(p);
453 | }
454 |
455 | // Set the lifetime of the marker (e.g., 1 second)
456 | marker.lifetime = ros::Duration(1.0);
457 |
458 | particle_pub.publish(marker);
459 | }
460 |
461 |
462 |
463 | } // namespace global_planner
--------------------------------------------------------------------------------
/src/pso_plan_node.cpp:
--------------------------------------------------------------------------------
1 | /***********************************************************
2 | *
3 | * @file: pso_plan_node.cpp
4 | * @breif: PSO Global Path Planner ROS Node
5 | * @author: Jing Zongxin
6 | * @update: 2023-12-13
7 | * @version: 1.0
8 | *
9 | * Copyright (c) 2023,Jing Zongxin
10 | * All rights reserved.
11 | * --------------------------------------------------------
12 | *
13 | **********************************************************/
14 |
15 |
16 | #include
17 | #include
18 | #include
19 | #include
20 | #include
21 | #include
22 |
23 | namespace global_motion_planner
24 | {
25 |
26 | class globalMotionPlannerWithCostmap : public globalMotionPlannerROS
27 | {
28 | public:
29 | globalMotionPlannerWithCostmap(std::string name, costmap_2d::Costmap2DROS* cmap);
30 | ~globalMotionPlannerWithCostmap();
31 |
32 | private:
33 | void poseCallback(const geometry_msgs::PoseStamped::ConstPtr& goal);
34 | costmap_2d::Costmap2DROS* cmap_;
35 | ros::Subscriber pose_sub_;
36 | };
37 |
38 |
39 | void globalMotionPlannerWithCostmap::poseCallback(const geometry_msgs::PoseStamped::ConstPtr& goal)
40 | {
41 | geometry_msgs::PoseStamped robot_pose;
42 | cmap_->getRobotPose(robot_pose);
43 | std::vector path;
44 | unsigned int mx = 0,my = 0;
45 | if(!this->costmap_->worldToMap(goal->pose.position.x,goal->pose.position.y,mx,my))
46 | {
47 | std::cout << "worldToMap error" << std::endl;
48 | return;
49 | }
50 | if(this->costmap_->getCost(mx,my) != costmap_2d::FREE_SPACE)
51 | {
52 | std::cout << "The target point is unreachable." << std::endl;
53 | return;
54 | }
55 | makePlan(robot_pose, *goal, path);
56 | }
57 |
58 | globalMotionPlannerWithCostmap::globalMotionPlannerWithCostmap(std::string name, costmap_2d::Costmap2DROS* cmap) :
59 | globalMotionPlannerROS(name, cmap)
60 | {
61 | ros::NodeHandle private_nh("move_base_simple");
62 | cmap_ = cmap;
63 | pose_sub_ = private_nh.subscribe("goal", 1, &globalMotionPlannerWithCostmap::poseCallback, this);
64 | }
65 |
66 | globalMotionPlannerWithCostmap::~globalMotionPlannerWithCostmap()
67 | {}
68 |
69 | } // namespace
70 |
71 | int main(int argc, char** argv)
72 | {
73 | ros::init(argc, argv, "pso_planner");
74 | tf2_ros::Buffer buffer(ros::Duration(10));
75 | tf2_ros::TransformListener tf(buffer);
76 | costmap_2d::Costmap2DROS gcm("global_costmap", buffer);
77 | global_motion_planner::globalMotionPlannerWithCostmap pppp("globalMotionPlannerROS", &gcm);
78 | ros::spin();
79 | return 0;
80 | }
81 |
82 |
--------------------------------------------------------------------------------
/src/trajectoryGeneration.cpp:
--------------------------------------------------------------------------------
1 | /***********************************************************
2 | *
3 | * @file: trajectoryGeneration.cpp
4 | * @breif: Contains trajectory generation class
5 | * @author: Jing Zongxin
6 | * @update: 2023-12-4
7 | * @version: 1.0
8 | *
9 | * Copyright (c) 2023,Jing Zongxin
10 | * All rights reserved.
11 | * --------------------------------------------------------
12 | *
13 | **********************************************************/
14 |
15 | #include
16 | #include
17 | #include "trajectoryGeneration.h"
18 |
19 | trajectoryGeneration::trajectoryGeneration()
20 | {
21 | }
22 |
23 | trajectoryGeneration::~trajectoryGeneration()
24 | {
25 | }
26 |
27 | int trajectoryGeneration::splineOrder = 3; //Set the order of the B-spline curve
28 |
29 | //Generate B-spline curve control points
30 | void trajectoryGeneration::GenerateControlPoints(const std::pair& start_d,
31 | const std::pair& goal_d,
32 | const std::vector>& initial_position,
33 | std::vector>& initial_point)
34 | {
35 | initial_point.clear(); // Clear the vector to start fresh
36 | initial_point.push_back(start_d);
37 | std::pair last_point = start_d;
38 |
39 | for (const auto& position : initial_position)
40 | {
41 | double x = static_cast(position.first);
42 | double y = static_cast(position.second);
43 | // Check if the current point is different from the last point
44 | if (x != last_point.first || y != last_point.second)
45 | {
46 | initial_point.emplace_back(x, y);
47 | last_point = {x, y};
48 | }
49 | }
50 | // Check if the goal point is different from the last point
51 | if (goal_d != last_point)
52 | {
53 | initial_point.push_back(goal_d);
54 | }
55 | }
56 |
57 | // Use De Boor-Cox recursion to calculate Bik(u)
58 | double trajectoryGeneration::BaseFun(int i, int k, double u, std::vector NodeVector)
59 | {
60 | // 1st order B-spline
61 | if (k == 0)
62 | {
63 | if ((u >= NodeVector[i]) && (u < NodeVector[i + 1]))
64 | {
65 | return 1.0;
66 | }
67 | else
68 | {
69 | return 0;
70 | }
71 | }
72 | // 2nd order and higher B-spline
73 | else
74 | {
75 | double Length1 = double(NodeVector[i + k]) - NodeVector[i];
76 | double Length2 = double(NodeVector[i + k + 1]) - NodeVector[i + 1];
77 |
78 | // Handle the case where the denominator is 0 by replacing it with 1, defining 0/0 as 0
79 | if (Length1 == 0)
80 | {
81 | Length1 = 1.0;
82 | }
83 | if (Length2 == 0)
84 | {
85 | Length2 = 1.0;
86 | }
87 |
88 | return ((double((u - NodeVector[i])) / Length1) * BaseFun(i, k - 1, u, NodeVector) +
89 | (double((NodeVector[i + k + 1] - u)) / Length2) * BaseFun(i + 1, k - 1, u, NodeVector));
90 | }
91 | }
92 |
93 | // B-spline curve for trajectory smoothing, where K is the order
94 | void trajectoryGeneration::B_spline_curve(std::vector> &plan, int k)
95 | {
96 | // Rough estimate of the path length
97 | double plan_length = 0;
98 |
99 | for (int i = 1; i < plan.size(); i++)
100 | {
101 | plan_length = plan_length + std::sqrt((plan[i].first - plan[i - 1].first) * (plan[i].first - plan[i - 1].first) +
102 | (plan[i].second - plan[i - 1].second) * (plan[i].second - plan[i - 1].second));
103 | }
104 |
105 | double d;
106 | std::pair new_control_point;
107 | // Extrapolate control points at the starting point
108 | d = std::sqrt((plan[1].first - plan[0].first) * (plan[1].first - plan[0].first) +
109 | (plan[1].second - plan[0].second) * (plan[1].second - plan[0].second));
110 | new_control_point.first = plan[0].first - (0.1 / d) * (plan[1].first - plan[0].first);
111 | new_control_point.second = plan[0].second - (0.1 / d) * (plan[1].second - plan[0].second);
112 | plan.insert(plan.begin(), new_control_point);
113 | // Get the current number of control points
114 | int n = plan.size();
115 | // Extrapolate control points at the end point
116 | d = std::sqrt((plan[n - 2].first - plan[n - 1].first) * (plan[n - 2].first - plan[n - 1].first) +
117 | (plan[n - 2].second - plan[n - 1].second) * (plan[n - 2].second - plan[n - 1].second));
118 | new_control_point.first = plan[n - 1].first - (0.1 / d) * (plan[n - 2].first - plan[n - 1].first);
119 | new_control_point.second = plan[n - 1].second - (0.1 / d) * (plan[n - 2].second - plan[n - 1].second);
120 | plan.push_back(new_control_point);
121 | // Update the number of control points
122 | n = plan.size();
123 |
124 | // Set up the node vector
125 | std::vector NodeVector;
126 |
127 | for (int i = 0; i < k + 1; i++)
128 | {
129 | NodeVector.push_back(0.0);
130 | }
131 |
132 | for (int i = 1; i <= (n - k - 1); i++)
133 | {
134 | NodeVector.push_back(double(i) / (n - k));
135 | }
136 |
137 | for (int i = 0; i < k + 1; i++)
138 | {
139 | NodeVector.push_back(1.0);
140 | }
141 |
142 | // Set up u
143 | std::vector u;
144 |
145 | double temp_u = 0.0;
146 | double end_u = 1.0;
147 |
148 | // Calculate the interval of temp_u based on the rough estimate of the path length and 0.05m precision
149 | double temp_dt = 1 / plan_length;
150 |
151 | while (temp_u < end_u)
152 | {
153 | u.push_back(temp_u);
154 | temp_u = temp_u + temp_dt;
155 | }
156 |
157 | // Initialize Bik
158 | std::vector Bik;
159 | for (int i = 0; i < n; i++)
160 | {
161 | Bik.push_back(0);
162 | }
163 |
164 | // Initialize B-spline curve
165 | std::vector> B_plan;
166 | // Clever use of vector swap to release memory; the principle is to define a new empty container and then swap the contents of the two containers
167 | std::vector>().swap(B_plan);
168 |
169 | for (int i = 0; i < u.size(); i++)
170 | {
171 | double B_plan_x = 0;
172 | double B_plan_y = 0;
173 | std::pair temp_B_plan;
174 |
175 | for (int j = 0; j < n; j++)
176 | {
177 | Bik[j] = BaseFun(j, k - 1, u[i], NodeVector);
178 | }
179 |
180 | for (int m = 0; m < n; m++)
181 | {
182 | B_plan_x = B_plan_x + plan[m].first * Bik[m];
183 | B_plan_y = B_plan_y + plan[m].second * Bik[m];
184 | }
185 | temp_B_plan.first = B_plan_x;
186 | temp_B_plan.second = B_plan_y;
187 | B_plan.push_back(temp_B_plan);
188 | }
189 |
190 | // std::cout << B_plan.size()<& point1, const std::pair& point2)
198 | {
199 | double dx = point1.first - point2.first;
200 | double dy = point1.second - point2.second;
201 | return std::sqrt(dx * dx + dy * dy);
202 | }
203 |
204 | //Calculate path length
205 | double trajectoryGeneration::calculatePathLength(const std::vector>& path)
206 | {
207 | double length = 0.0;
208 | for (size_t i = 1; i < path.size(); ++i)
209 | {
210 | length += calculateDistance(path[i - 1], path[i]);
211 | }
212 | return length;
213 | }
214 |
215 |
--------------------------------------------------------------------------------