├── .github
└── workflows
│ └── publish_api_docs.yml
├── .gitignore
├── FUNDING.yml
├── LICENSE
├── README.md
├── img
├── example.png
├── pycircos_patchwork.png
└── tree-example.png
├── pycircos
├── __init__.py
├── pycircos.py
└── tree.py
└── setup.py
/.github/workflows/publish_api_docs.yml:
--------------------------------------------------------------------------------
1 | name: Publish API Docs
2 |
3 | on:
4 | push:
5 | branches: [master]
6 | paths: ["pycircos/**.py"]
7 | pull_request:
8 | branches: [master]
9 | paths: ["pycircos/**.py"]
10 | workflow_dispatch:
11 |
12 | jobs:
13 | publish_api_docs:
14 | runs-on: ubuntu-20.04
15 | concurrency:
16 | group: ${{ github.workflow }}-${{ github.ref }}
17 | steps:
18 | - name: Checkout
19 | uses: actions/checkout@v3
20 |
21 | - name: Setup Python 3.9
22 | uses: actions/setup-python@v2
23 | with:
24 | python-version: 3.9
25 |
26 | - name: Install requirements & pdoc3
27 | run: |
28 | pip install .
29 | pip install pdoc3
30 |
31 | - name: Generate API docs using pdoc3
32 | run: |
33 | pdoc3 ./pycircos -o ./docs --html --force -c list_class_variables_in_index=False -c sort_identifiers=False
34 |
35 | - name: Deploy
36 | uses: peaceiris/actions-gh-pages@v3
37 | if: ${{ github.ref == 'refs/heads/master' }}
38 | with:
39 | github_token: ${{ secrets.GITHUB_TOKEN }}
40 | publish_dir: ./docs/pycircos
41 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /*/*/example_db/
2 | /*/*/*.maf
3 | /*/*/*.gbff
4 | *.pyc
5 | *.swp
6 | /.ipynb_checkpoints/
7 | /__pycache__/
8 | /build/
9 | /dist/
10 | /pycircos/tree.py
11 | /pycircos.egg-info/
12 |
--------------------------------------------------------------------------------
/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: ponnhide# Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | otechie: # Replace with a single Otechie username
12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
13 |
--------------------------------------------------------------------------------
/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 | # pyCircos
2 | Circos is one of the most popular software for visualizing genomic similarities and features. However, its execution process is complicated and requires multiple original config files for the visualizations. Additionally, Circos is written in Perl, which limits its integration with other software for biological analysis. On the other hand, Python has been applied for various biological software packages. Therefore, by combining these packages, researchers can complete most of the required analysis. Nevertheless, Python lacks a library for drawing Circos plots, even though Circos software has been developed for more than a decade. Here, we provide a python Matplotlib based circular genome visualization package '"pyCircos." Users easily and quickly visualize genomic features and comparative genome analysis results by specifying annotated sequence files such as GenBank files.
3 |
4 | ### Join Our Team: Bioinformatics Researcher Wanted.
5 | We are currently seeking a skilled researcher with expertise in bioinformatics to join our lab.
6 | For more details and to apply, please visit the following [URL](https://prime.osaka-u.ac.jp/careers/images/CREST_recruit_en_20231120.pdf).
7 |
8 | ## Gallery
9 |
10 |
11 | ## Dependencies
12 |
13 | - python 3.7later
14 |
15 | ## Installation
16 | For normal users, we recommended you to install the official release as follows.
17 | `pip install python-circos`
18 |
19 | If you want to use developmental version, it can be installed using the following single command:
20 | `pip install git+https://github.com/ponnhide/pyCircos.git`
21 |
22 | ## Usage
23 |
24 | pyCircos provides the “Gcircle class” and "Garc class". A "Gcircle" class object holds the dictionary of Garc class objefcts and provides functions to place Garc classs object on the circular map. Each Garc class object manages numeric and genomic data to be visualized on the circular map.
25 |
26 | ### News
27 | - Tutorial codes are moved to https://github.com/ponnhide/pyCircos-examples .
28 |
29 | #### Version 0.3.0 is released.
30 | - Tarc class and Tcircle class are added.
31 | Tarc class and Tcircle class is implemented as subclass of Garc and Gcircle class, respectivily.
32 | By using these class, you can draw circular phylogenetic tree as the following example.
33 |
34 |
35 |
36 | You can execute the example code to draw the circular phylogenetic tee on the [Google colab](https://colab.research.google.com/drive/140m2jpQpgSZwSlP-3u3Oj8IcJUbP2NGD?usp=sharing).
37 |
38 |
39 | Version 0.2.0 is released. The `fig` parameter is added for Gcircle.__init__, so it is now possible to specify your own figure object.
40 |
41 | If you want to arrange multiple circos plots, I reccomend to use [patchworklib](https://github.com/ponnhide/patchworklib).
42 | Please see the following example code.
43 | https://colab.research.google.com/drive/1tkn7pxRqh9By5rTFqRbVNDVws-o-ySz9?usp=sharing
44 |
45 | **Example result of multiple circos plots**
46 |
47 |
48 |
49 |
50 | ### Gcircle class
51 |
52 | A Gcircle class object provides a circle whose diameter is 1000 (a.u.) as a drawing space. Any graph (line plot, scatter plot, barplot, heatmap, and chordplot) can be placed on the space by specifying the _raxis\_range_ (from 0 to 1000) and the corresponding Garc class object.
53 |
54 | #### Parameters
55 |
56 | - **.garc_dict**: *dict* (default:None)
57 | Dictionary of the Garc class objects in *Gcircle object*. The keys of the dictionary are id values of the Garc class objects.
58 |
59 | - .**figsize**: *tuple* (dfault:)
60 | Figure size for the circular map.
61 |
62 | #### Methods
63 |
64 | - **.add_garc (garc_object=*Garc class object*)**
65 | Add a new Garc class object into *garc_dict*.
66 | - **garc_object**: *Garc class object* (default:None)
67 | Garc class object to be added.
68 |
69 | **return** *None*
70 |
71 |
72 | - **.set_garcs(start=0, end=360)**
73 | Visualize the arc rectangles of the Garc class objects in *.garc_dict* on the drawing space. After the execution of this method, a new Garc class object cannot be added to *garc_dict* and *figure* parameter representing maplotlib.pyplot.figure object will be created in *Gcircle object*.
74 | **return** *None*
75 | - **start**: *int* (defaut: *0*)
76 | Start angle of the circos plot. The value range is -360 ~ 360.
77 | - **end**: *int* (default: *360*)
78 | End angle of the circos plot. The value range is -360 ~ 360.
79 |
80 | - __.lineplot (garc_id=*str*, data=*list* or *numpy.ndarray* , positions=*list* or *numpy.ndarray*, raxis_range=*tuple*, rlim=*tuple, linestyle=*str*, linecolor=*str* or *tuple*, linewidth=*int*)__
81 | Plot a line in the sector corresponding to the arc of the Garc class object specified by *garc_id*.
82 |
83 | - **garc_id**: *str* (defaut: *None*)
84 | ID of the Garc class object. The ID shoud be in *Gcircle object.garc_dict*.
85 | - **data**: *list* or numpy.ndarray (default: *None*)
86 | Numerical data to be drawn with line.
87 | - **positions**: *list* or *numpy.ndarray* (default: None)
88 | The x coordinates of the values in *data* on the Garc class object when the plot is drawn on the rectangular coordinates. Each coordinate value should be in the range 0 to *size* of the Garc class object specified by *garc_id*. By the method execution, the coordinates are converted to proper angle coordinates. If *positions* are not given, proper coordinates values are generated according to the length of *data*.
89 | - **raxis_range**: *tuple* *(top=int, bottom=int)* (default: (550, 650))
90 | Radial axis range where line plot is drawn.
91 | - **rlim**: *tuple (top=int, bottom=int)* (default: (min(*data*), max(*data*)))
92 | The *top* and *bottom* r limits in data coordinates. If *rlim* value is not given, the maximum value and the minimum value in *data* will be set to *top* and *bottom* , respectively.
93 | - **linestyle**: *str* (default: "solid")
94 | Line style. Possible line styles can be reffered from https://matplotlib.org/stable/gallery/lines_bars_and_markers/linestyles.html
95 | - **linecolor**: *str or tuple* representing color code (default: None)
96 | Color of the line plot. If *linecolor* value is not given, the color will be set according to the default color set of matplotlib. To specify the opasity for a line color, please use (*r, g, b*, *a*) or #_XXXXXXXX_ format.
97 | - **linewidth**: *float* (default: 1)
98 | Line width.
99 |
100 | **return** *None*
101 |
102 |
103 | - **.fillplot (garc_id=*str*, data=*list* or *numpy.ndarray* , positions=*list* or *numpy.ndarray*, raxis_range=*tuple*, rlim=*tuple*, base_value=*float*, facecolor=*str* or *tuple*, linecolor=*str* or *tuple*, linewidth=*int*)**
104 | Fill a specified area in the sector corresponding to the arc of the Garc class object specified by *garc_id*.
105 |
106 | - **garc_id** :*str* (defaut: *None*)
107 | Same parameter with *garc_id* of lineplot().
108 | - **data**: *list* or numpy.ndarray (default: *None*)
109 | Same parameter with *data* of lineplot().
110 | - **positions**: *list* or *numpy.ndarray* (default: None)
111 | Same parameter with *positions* of lineplot().
112 | - **raxis_range**: *tuple* *(top=int, bottom=int)* (default: (550, 650))
113 | Same parameter with *raxis_range* of lineplot().
114 | - **rlim**: *tuple (top=int, bottom=int)* (default: (min(_data_), max(_data_))
115 | Same parameter with *rlim* of lineplot().
116 | - **base_value**: *float* (default: 0)
117 | Base line height in data coordinates. The area between the base line and the data line is filled by *facecolor*.
118 | - **facecolor**: *str or tuple* representing color code (default: None)
119 | Color for filling.
120 | - **edgecolor**: *str or tuple* representing color code (default: "#303030")
121 | Edge color of the filled area
122 | - **linewidth**: *float* (default: 0)
123 | Edge line width.
124 |
125 | **return** *None*
126 |
127 |
128 | - **.scatterplot (garc_id=*str*, data=*list* or *numpy.ndarray* , positions=*list* or *numpy.ndarray*, raxis_range=*tuple*, rlim=*tuple*, markershape=*str*, facecolor=*str* or *tuple*, edgecolor =*str* or *tuple*, linewidth=*int*, markersize=*int*)**
129 | Plot markers in the sector corresponding to the arc of the Garc class object specified by *garc_id*.
130 |
131 | - **garc_id** :*str* (defaut: *None*)
132 | Same parameter with *garc_id* of lineplot().
133 | - **data**: *list* or numpy.ndarray (default: *None*)
134 | Numerical data to be drawn by scatter plots.
135 | - **positions**: *list* or *numpy.ndarray* (default: None)
136 | Same parameter with *positions* of lineplot().
137 | - **raxis_range**: *tuple* *(top=int, bottom=int)* (default: (550, 650))
138 | Same parameter with *raxis_range* of lineplot().
139 | - **rlim**: *tuple (top=int, bottom=int)* (default: (min(_data_), max(_data_))
140 | Same parameter with *rlim* of lineplot().
141 | - **makershape**: *str* (default: "o")
142 | Marker shape. Possible marker shapes can be reffered from https://matplotlib.org/stable/gallery/lines_bars_and_markers/marker_reference.html.
143 | - **markersize**: *float* or *list* of *float* (default: *None*)
144 | Size(s) of the marker(s).
145 | - **facecolor**: *str, tuple* representing color code or *list* of color code (default: None)
146 | Face color(s) of the markers. If value type is *list*, the lenght of *facecolor* should be the same as the data length.
147 | - **edgecolor**: *str or tuple* representing color code (default: None)
148 | Edge color of the markers
149 | - **linewidth**: *float* (default: 0)
150 | Edge line width of the markers
151 |
152 | **return** *None*
153 |
154 |
155 | - **.barplot (garc_id=*str*, data=*list* or *numpy.ndarray* , positions=*list* or *numpy.ndarray*, width=*float* or *list*, raxis_range=*tuple*, rlim=*tuple*, base_value=*int*, faceolor=*str* or *tuple*, edgecolor=*str* or *tuple*)**
156 |
157 | Plot bars in the sector corresponding to the arc of the Garc class object specified by *garc_id*.
158 |
159 | - **garc_id** :*str* (defaut: *None*)
160 | Same parameter with *garc_id* of lineplot().
161 | - **data**: *list* or numpy.ndarray (default: *None*)
162 | Numerical data to be drawn by bar plots.
163 | - **positions**: *list* or *numpy.ndarray* (default: _None_)
164 | Same parameter with *positions* of lineplot(). The center of the base bases become in *positions*.
165 | - **width**: *float* or *list* of *float* (default: *garc\_object.size/len(data)*)
166 | Width(s) of the bars.
167 | - **raxis_range**: *tuple* *(top=int, bottom=int)* (default: (550, 650))
168 | Same parameter with *raxis_range* of lineplot().
169 | - **rlim**: *tuple (top=int, bottom=int)* (default: (min(_data_), max(_data_))
170 | Same parameter with *rlim* of lineplot().
171 | - **facecolor**: *str, tuple* representing color code or *list* of color code (default: None)
172 | Facecolor(s) of the bars. If value type is *list*, the lenght of *facecolor* should be the same as the data length.
173 | - **edgecolor**: *str or tuple* representing color code (default: _None_)
174 | Edge color of the bars
175 | - **linewidth**: *float* (default: 1.0)
176 | Edge line width of the bars.
177 |
178 | **return** *None*
179 |
180 |
181 | - **.heatmap (garc_id=*str*, data=*list* or *numpy.ndarray*, positions=*list* or *numpy.ndarray*, width=*float* or *list*, raxis_range=*tuple*, cmap=*str*, vmin=*float*, vmax=*float*)**
182 | Visualize magnitudes of data values by color scale in the sector corresponding to the arc of the Garc class object specified by *garc_id*.
183 |
184 | - **garc_id** :*str* (defaut: *None*)
185 | Same parameter with *garc_id* of lineplot().
186 | - **data**: *list* or numpy.ndarray (default: *None*)
187 | Numerical data to be visualized by color scale. Two dimensional array can also be taken.
188 | - **positions**: *list* or *numpy.ndarray* (default: *None*)
189 | Same parameter with *positions* of lineplot().
190 | - **width**: *float* or *list* of *float* (default: *garc\_object.size/len(data)*)
191 | Width(s) of the bars.
192 | - **raxis_range**: *tuple* *(top=int, bottom=int)* (default: (550, 650))
193 | Same parameter with *raxis_range* of lineplot()
194 | - **cmap**: *str* represeting matplotlib colormap name or *matplotlib.colors.Colormap object* (default: "Reds")
195 | The mapping from data values to color space.
196 | - **vmin**: *float* (default: min(data))
197 | Minimum data limit for color scale.
198 | - **vmax**: *float* (default: min(data))
199 | Maximum data limit for color scale.
200 |
201 | **return** *None*
202 |
203 |
204 | - **.chordplot(arc_loc1=*tuple*, arc_loc2=*tuple*, facecolor=*str* or *tuple*, edgecolor=*str* or *tuple*, linewidth=*int*)**
205 | Visualize inter-relation ships between data.
206 |
207 | - **arc_loc1**: *tuple* (defaut: *None*)
208 | First data location of linked data. The tuple is composed of four parameters: *arc_id*, *ede_position1*, *edge_position2*, *raxis_position*
209 | *edge_position*1 and *edge_position2* are the x coordinates on the Garc class object when the plot is drawn on the rectangular coordinates.
210 | *raxis_position* is base height for the drawing cord.
211 | - **arc_loc2**: *tuple* (defaut: *None*)
212 | Second data location of linked data.
213 | - **facecolor**: *str or tuple* representing color code (default: None)
214 | Face color of the link.
215 | - **edgecolor**: *str or tuple* representing color code (default: None)
216 | Edge color of the link.
217 | - **linewidth**: *float* (default: 0.0)
218 | Edge line width of the link.
219 |
220 | **return** *None*
221 |
222 |
223 | - .**featureplot (garc_id=*str*, feature_type=*str*, soruce=*list* of *Bio.SeqFeature object*, raxis_range=*tuple*, faceolor=*str* or *tuple*)**
224 | Visualize sequence features with bar plots in the sector corresponding to the arc of the Garc class object specified by *garc_id*.
225 | - **garc_id** :*str* (defaut: *None*)
226 | Same parameter with *garc_id* of lineplot().
227 | - **feature_type**: *str* (default: "all")
228 | Biological nature of the Bio.Seqfeature class objects (Any value is acceptable, but GenBank format requires registering a biological nature category for each sequence feature).
229 | If the value is "all",all features in *soruce* will be drawn in the sector of the Garc class object specified by *grac_id*.
230 | - **source**: *list* of *Bio.SeqFeature* object (default: record.features of the Garc class object specified by *grac_id* )
231 | List of Bio.Seqfeature class object. If *source* value is not given, record.features of the Garc class object specified by *grac_id* is given.
232 | - **raxis_range**: *tuple* *(top=int, bottom=int)* (default: (550, 650))
233 | Same parameter with *raxis_range* of lineplot().
234 | - **facecolor**: *str or tuple* representing color code (default: None)
235 | Face color of the feature bars.
236 |
237 | **return** *None*
238 |
239 | ### Tcircle class
240 |
241 | Tcircle class is the subclass of Gcircle. All methods implemented in the Gcircle class also can be used.
242 | Then, the two additional methods `set_tarc`, `plot_tree` and `plot_highlight` is provided in the Tcircle class.
243 |
244 | #### Methods
245 | - **.add_tarc(tarc=*str*)**:
246 | Add a new Tarc or Garc class object into tarc_dict.
247 | - tarc : _Tarc class object_ (default:None)
248 | Tarc class object to be added.
249 |
250 | **return** *None*
251 |
252 |
253 | - **.plot_tree(tarc_id=*str*, rlim=*tuple*, cladevisual_dict=*dict*, highlight_dict=*dict*, linecolor=*str*, linewidth=*float*)**:
254 | Drawa circular phylogenetic tree.
255 | - **tarc_id**: *str*
256 | ID of the Tarc class object. The ID should be in Tcircle
257 | - **object.tarc_dict**: *dict*
258 | - **rlim** : *tuple* (top=int, bottom=int)
259 | The top and bottom r limits in data coordinates. The default vlaues is (0, 700).
260 | If the first value is less than second value, tree will be outward direction.
261 | If the first value is larger than second value, tree will be inward direction.
262 | - **cladevisual_dict** : *dict*
263 | Dictionay composed of pairs of clade name and a sub-dict holding parameters
264 | to visualize the clade. A sub-dict is composed of the following key-value pairs:
265 | - **size**: *int* or *float*
266 | Size of dot. The default value is 5.
267 | - **color**: *float* or *str* replresenting color code.
268 | Face color of dot. The default value is '#303030'.
269 | - **edgecolor**: *float* or *str* replresenting color code.
270 | Edge line color of dot. The default value is '#303030'.
271 | - **linewidth**: *int* or *float*.
272 | Edge line width of dot. The default value is 0.5.
273 |
274 | **return** *None*
275 |
276 |
277 | - **.plot_tree(tarc_id=*str*, highlight_dict=*dict*)**:
278 | Add highlight for specif clade under the given internal clade.
279 | - **highlight_dict**: *dict*
280 | Dictionay composed of pairs of internal clade name and a sub-dict.
281 | Instead of clade name, tuples of teminal clade names can also be used.
282 | A sub-dict is composed of the following key-value pairs:
283 | - **color**: *str*
284 | Color of highlight for clades. The default value is "#000000".
285 | - **alpha**: *flaot*
286 | Alpha of highlight for clades. The default vlalue is 0.25.
287 | - **label**: *str*
288 | Label. The default vlalue is None.
289 | - **fontsize**: int or float
290 | Fontsize of label. The default vlalue is 10.
291 | - **y**: *int* or *float*
292 | Y location of the text. The default vlalue is the bottom edge of the highliht.
293 |
294 | **return** *None*
295 |
296 |
297 | ### Garc class
298 |
299 | A Garc class object can be created by ```Garc()``` command.
300 | The following parameters, which are mainly used for the visualization of the arc rectangle, can also be specified.
301 |
302 | **Parameters**
303 |
304 | - **arc_id**: *str* (default None)
305 | Unique identifier for the Garc class object. Suppose *id* value is not given. An original unique ID is automatically given for *Garc object*.
306 | - **record**: *Bio.SeqRecord class object* or NCBI accession number (default: None)
307 | Bio.SeqRecord class object or NCBI accession number of an annotated sequence. If a NCBI accession number is given, the GeBank reord of the accesion number will be loaded from NCBI public database.
308 | - **size**: *float* (default: 1000)
309 | Width of the arc rectangle. If *record* is given, the value is set by the sequence length of the record. The real arc rectangle width in the circle is determined by the ratio of *size* to the sum of the size and interspace values of the Garc class objects in the Gcircle class object.
310 | - **interspace**: *float* (default: 0)
311 | Distance angle to the adjacent arc rectangle on the right. The real interspace size in the circle is determined by the ratio of *size* to the sum of the size and interspace values of the Garc class objects in the Gcircle class object.
312 | - **raxis_range**: *tuple* *(top=int, bottom=int)* (default: (500, 550))
313 | Radial axis range where the arc rectangle is drawn.
314 | - **facecolor**: *str* or *tuple* representing color code (default: *None*)
315 | Face color for the arc rectangle. If *facecolor* is not given, the color will be selected from the default color set provided in the pyCircos module.
316 | - **edgecolor**: *str* or *tuple* representing color code (default: "#303030")
317 | Edge color for the arc rectangle. If *edgecolor* is not given, the color will be selected from the default color set provided in the pyCircos module.
318 | - **linewidth**: *int* (default: 0)
319 | Edge line width of the arc rectangle.
320 | - **label**: *str* (default: *arc_id*)
321 | Label of the arc rectangle.
322 | - **labelposition**: *int* (default:0)
323 | Relative label height from the center of the arc rectangle.
324 | - **labelsize**: *int* (default:0)
325 | Font size of the label.
326 | - **label_visible**: *bool* (defaule: *False*)
327 | If True, *label* of the Garc object is shown on the arc rectangle.
328 |
329 |
330 | #### Methods
331 | The Garc class object provides some analytical methods to support users analyze genomic characters.
332 | - **.calc_density(positions=*list*, window_size=*int*)**
333 | Converts *positions* consisting of x-coordinates into a list of density values scanned in a sliding window.
334 | - **positions**: *list* of *int* or *tuple*
335 | List of x corrdinate values or tuple consisting of two x coordinate values. Each coordinate value should be in the range 0 to *size* of *Garc object*.
336 | - **window_size**: *int* (default:1000)
337 | Size of the sliding window
338 |
339 | **return** *list* consisting of density values
340 |
341 | - **.calc_nnratio(n1=*str*, n2=*str*, window_size=*int*, step_size=*int*)**
342 | *n1* and *n2* are one of the nucleotide base letters of "ATGC". Calculate *n*,*m* ratiio for multiple windows along the sequence. If *Garc object.record* is None, the method will not work.
343 | - .**calc_nnskew(n1=*str*, n2=*str*, window_size=*int*, step_size=*int*)**
344 | *n1* and *n2* are one of the nucleotide base letters of "ATGC". Calculate *n*,*m* skew (n-m)/(n+m) for multiple windows along the sequence. If *Garc object.record* is None, the method will not work.
345 |
346 | ## Example code
347 | Prease see the notebooks in the 'tutorial' directrory.
348 | I also provide the executable tutorial codes in Google Colaboratory.
349 | - tutorial1: https://colab.research.google.com/drive/1xmAnv7AHWUTA2HWfjqV1lFWkFMSLJHG0?usp=sharing
350 | - tutorial2: https://colab.research.google.com/drive/1RYSo4aXpDIZlSQ9EhO2kPCeF8FOwyvXv?usp=sharing
351 | - tutorial3: https://colab.research.google.com/drive/1EPxCQCgOouVxtXcGyxu2ZqQvfucVnOJ-?usp=sharing
352 | - tutorial4 (Drawing pylogenetic tree): https://colab.research.google.com/drive/140m2jpQpgSZwSlP-3u3Oj8IcJUbP2NGD?usp=sharing
353 |
--------------------------------------------------------------------------------
/img/example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ponnhide/pyCircos/f5ef141c6af21c46a9432fce266e6c13a663edfc/img/example.png
--------------------------------------------------------------------------------
/img/pycircos_patchwork.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ponnhide/pyCircos/f5ef141c6af21c46a9432fce266e6c13a663edfc/img/pycircos_patchwork.png
--------------------------------------------------------------------------------
/img/tree-example.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ponnhide/pyCircos/f5ef141c6af21c46a9432fce266e6c13a663edfc/img/tree-example.png
--------------------------------------------------------------------------------
/pycircos/__init__.py:
--------------------------------------------------------------------------------
1 | import pycircos.pycircos as pc
2 | import pycircos.tree as pt
3 | Garc = pc.Garc
4 | Gcircle = pc.Gcircle
5 | Tarc = pt.Tarc
6 | Tcircle = pt.Tcircle
7 |
--------------------------------------------------------------------------------
/pycircos/pycircos.py:
--------------------------------------------------------------------------------
1 | import os
2 | import re
3 | import io
4 | import sys
5 | import math
6 | import urllib
7 | import tempfile
8 | import collections
9 | import numpy as np
10 | import matplotlib
11 | import matplotlib.pyplot as plt
12 | import matplotlib.path as mpath
13 | import matplotlib.patches as mpatches
14 | from Bio import SeqIO
15 | import Bio
16 |
17 | matplotlib.rcParams["figure.max_open_warning"] = 0
18 | matplotlib.rcParams['ps.fonttype'] = 42
19 | matplotlib.rcParams['pdf.fonttype'] = 42
20 | matplotlib.rcParams['font.sans-serif'] = ["Arial","Lucida Sans","DejaVu Sans","Lucida Grande","Verdana"]
21 | matplotlib.rcParams['font.family'] = 'sans-serif'
22 | matplotlib.rcParams['font.size'] = 10.0
23 | matplotlib.rcParams["axes.labelcolor"] = "#000000"
24 | matplotlib.rcParams["axes.linewidth"] = 1.0
25 | matplotlib.rcParams["xtick.major.width"] = 1.0
26 | matplotlib.rcParams["ytick.major.width"] = 1.0
27 | matplotlib.rcParams['xtick.major.pad'] = 6
28 | matplotlib.rcParams['ytick.major.pad'] = 6
29 | matplotlib.rcParams['xtick.major.size'] = 6
30 | matplotlib.rcParams['ytick.major.size'] = 6
31 |
32 | class Garc:
33 | #list100 = ["#ffcdd2","#f8bbd0","#e1bee7","#d1c4e9","#c5cae9","#bbdefb","#b3e5fc","#b2ebf2","#b2dfdb","#c8e6c9","#dcedc8","#f0f4c3","#fff9c4","#ffecb3","#ffe0b2","#ffccbc","#d7ccc8","#cfd8dc",
34 | colorlist = ["#ff8a80","#ff80ab","#ea80fc","#b388ff","#8c9eff","#82b1ff","#84ffff","#a7ffeb","#b9f6ca","#ccff90","#f4ff81","#ffff8d","#ffe57f","#ffd180","#ff9e80","#bcaaa4","#eeeeee","#b0bec5",
35 | "#ff5252","#ff4081","#e040fb","#7c4dff","#536dfe","#448aff","#18ffff","#64ffda","#69f0ae","#b2ff59","#eeff41","#ffff00","#ffd740","#ffab40","#ff6e40","#a1887f","#e0e0e0","#90a4ae"]
36 | _arcnum = 0
37 | def __setitem__(self, key, item):
38 | self.__dict__[key] = item
39 |
40 | def __getitem__(self, key):
41 | return self.__dict__[key]
42 |
43 | def __init__(self, arc_id=None, record=None, size=1000, interspace=3, raxis_range=(500, 550), facecolor=None, edgecolor="#303030", linewidth=0.75, label=None, labelposition=0, labelsize=10, label_visible=False):
44 | """
45 | Parameters
46 | ----------
47 | arc_id : str, optional
48 | Unique identifier for the Garc class object. In the event an id
49 | value is not provided, an original unique ID is automatically
50 | generated for Garc object. The default is None.
51 | record : Bio.SeqRecord class object or NCBI accession number, optional
52 | Bio.SeqRecord class object or NCBI accession number of an annotated
53 | sequence. If a NCBI accession number is given, the GenBank record of
54 | the accession number will be loaded from NCBI public database.
55 | The default is None.
56 | size : int, optional
57 | Width of the arc section. If record is provided, the value is
58 | instead set by the sequence length of the record. In reality
59 | the actual arc section width in the resultant circle is determined
60 | by the ratio of size to the combined sum of the size and interspace
61 | values of the Garc class objects in the Gcircle class object.
62 | The default is 1000.
63 | interspace : float, optional
64 | Distance angle (deg) to the adjacent arc section in clockwise
65 | sequence. The actual interspace size in the circle is determined by
66 | the actual arc section width in the resultant circle is determined
67 | by the ratio of size to the combined sum of the size and interspace
68 | values of the Garc class objects in the Gcircle class object.
69 | The default is 3.
70 | raxis_range : tuple (top=int, bottom=int), optional
71 | Radial axis range where line plot is drawn. The default is (500, 550).
72 | facecolor : str or tuple representing color code, optional
73 | Color for filling. The default color is set automatically.
74 | edgecolor : str or tuple representing color code, optional
75 | Edge color of the filled area. The default is "#303030".
76 | linewidth : float, optional
77 | Edge line width. The default is 0.75.
78 | label : str, optional
79 | Label of the arc section. The default is None.
80 | labelposition : int, optional
81 | Relative label height from the center of the arc section.
82 | The default is 0.
83 | labelsize : int, optional
84 | Font size of the label. The default is 10.
85 | label_visible : bool, optional
86 | If True, label of the Garc object is shown on the arc section.
87 | The default is False.
88 |
89 | Raises
90 | ------
91 | ValueError
92 | In the event no match for the NCBI accession number value input in
93 | the record input variable, an error is raised.
94 |
95 | Returns
96 | -------
97 | None
98 | """
99 | self._parental_gcircle = None
100 | if arc_id == None:
101 | self.arc_id = str(Garc._arcnum)
102 | else:
103 | self.arc_id = arc_id
104 |
105 | if record is None:
106 | self.record = None
107 | self.size = size
108 |
109 | elif type(record) == Bio.SeqRecord.SeqRecord:
110 | self.record = record
111 | self.size = len(str(self.record.seq))
112 |
113 | elif type(record) == str:
114 | match = re.fullmatch("[a-zA-Z]{1,2}_?[0-9]{5,6}", record)
115 | if os.path.exists(record) == True:
116 | self.record = SeqIO.read(value, format="genbank")
117 |
118 | if match is None:
119 | raise ValueError("Incorrect value for NCBI accession number.")
120 | else:
121 | url = "https://www.ncbi.nlm.nih.gov/sviewer/viewer.cgi?tool=portal&save=file&log$=seqview&db=nuccore&report=gbwithparts&id={}&withparts=on".format(record)
122 | outb = io.BytesIO()
123 | outs = io.StringIO()
124 | headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0"}
125 | request = urllib.request.Request(url, headers=headers)
126 |
127 | with urllib.request.urlopen(request) as u:
128 | outb.write(u.read())
129 | outs.write(outb.getvalue().decode())
130 |
131 | with tempfile.TemporaryFile(mode="w+") as o:
132 | content = outs.getvalue()
133 | o.write(content)
134 | o.seek(0)
135 | record = SeqIO.parse(o,"genbank")
136 | record = next(record)
137 | self.record = record
138 | self.size = len(str(self.record.seq))
139 | else:
140 | self.record = None
141 | self.size = size
142 |
143 | if facecolor is None:
144 | facecolor = Garc.colorlist[Garc._arcnum % len(Garc.colorlist)]
145 | self.interspace = 2 * np.pi * (interspace / 360)
146 | self.raxis_range = raxis_range
147 | self.facecolor = facecolor
148 | self.edgecolor = edgecolor
149 | self.linewidth = linewidth
150 |
151 | if label is None:
152 | self.label = arc_id
153 | else:
154 | self.label = label
155 |
156 | self.label_visible = label_visible
157 | self.labelposition = labelposition
158 | self.labelsize = labelsize
159 | Garc._arcnum += 1
160 |
161 | def calc_density(self, positions, window_size=1000):
162 | """
163 | Converts positions consisting of x-coordinates into a list of density
164 | values scanned in a sliding window.
165 |
166 | Parameters
167 | ----------
168 | positions : list of int or tuple
169 | List of x coordinate values or tuple consisting of two x coordinate
170 | values. Each coordinate value should be in the range 0 to the
171 | size of Garc object.
172 | window_size : int, optional
173 | Size of the sliding window. The default is 1000.
174 |
175 | Raises
176 | ------
177 | ValueError
178 | If an inappropriate value or values is input for positions, an
179 | error is raised
180 |
181 | Returns
182 | -------
183 | densities : list
184 | A list consisting of density values.
185 | """
186 | densities = []
187 | positions.sort()
188 | for i in range(0, self.size, window_size):
189 | source = tuple(range(i, i+window_size))
190 | amount = 0
191 | for pos in positions:
192 | if type(pos) == int:
193 | if pos in source:
194 | amount += 1
195 | elif type(pos) == tuple:
196 | if pos[0] <= source[-1] and pos[1] >= source[0]:
197 | amount += 1
198 | else:
199 | raise ValueError("List elements should be int type or tuple consisting of two int values")
200 | densities.append(amount)
201 |
202 | source = tuple(range(i,self.size))
203 | amount = 0
204 | for pos in positions:
205 | if type(pos) == int:
206 | if pos in source:
207 | amount += 1
208 | elif type(pos) == tuple:
209 | if pos[0] <= source[-1] and pos[1] >= source[0]:
210 | amount += 1
211 | else:
212 | raise ValueError("List elements should be int type or tuple consisting of two int values")
213 | densities.append(amount*((self.size-i)/window_size))
214 | return densities
215 |
216 | def calc_nnratio(self, n1="G", n2="C", window_size=1000, step_size=None):
217 | """
218 | Calculates the ratio of n1 and n2 base frequency for multiple windows
219 | along the sequence.
220 |
221 | Parameters
222 | ----------
223 | n1 : string corresponding to one of "ATGC", optional
224 | The first of the two nucleotide bases to be compared.
225 | The default is "G".
226 | n2 : string corresponding to one of "ATGC", optional
227 | The second of the two nucleotide bases to be compared.
228 | The default is "C".
229 | window_size : int, optional
230 | Size of the sliding window. The default is 1000.
231 | step_size : int, optional
232 | Size of the sliding step. The default is window_size.
233 |
234 | Raises
235 | ------
236 | ValueError
237 | In the event no record is provided, will return an error.
238 |
239 | Returns
240 | -------
241 | gc_amounts : np.array
242 | An array of the ratios computed by this method
243 |
244 | """
245 | if self.record is None:
246 | raise ValueError("self.record is None, please specify record value")
247 |
248 | if step_size is None:
249 | step_size = window_size
250 |
251 | seq = str(self.record.seq)
252 | gc_amounts = []
253 | for i in range(0, len(seq), step_size):
254 | if n2 is None:
255 | gc_amount = seq[i:i+window_size].upper().count(n1) * 1.0 / window_size
256 | else:
257 | gc_amount = (seq[i:i+window_size].upper().count(n1) + seq[i:i+window_size].upper().count(n2)) * 1.0 / window_size
258 | gc_amounts.append(gc_amount)
259 | if n2 is None:
260 | gc_amounts.append(seq[i:].upper().count(n1) * 1.0 / (len(seq)-i))
261 | else:
262 | gc_amounts.append((seq[i:].upper().count(n1) + seq[i:i+window_size].upper().count(n2)) * 1.0 / (len(seq)-i))
263 |
264 | self["{}{}_ratio".format(n1,n2)] = gc_amounts
265 | gc_amounts = np.array(gc_amounts)
266 | return gc_amounts
267 |
268 | def calc_nnskew(self, n1="G", n2="C", window_size=1000, step_size=None):
269 | """
270 | Calculates n1,n2 skew (n1-n2)/(n1+n2) for multiple windows along
271 | the sequence.
272 |
273 | Parameters
274 | ----------
275 | n1 : string corresponding to one of "ATGC", optional
276 | The first of the two nucleotide bases to be compared.
277 | The default is "G".
278 | n2 : string corresponding to one of "ATGC", optional
279 | The second of the two nucleotide bases to be compared.
280 | The default is "C".
281 | window_size : int, optional
282 | Size of the sliding window. The default is 1000.
283 | step_size : int, optional
284 | Size of the sliding step. The default is window_size.
285 |
286 | Raises
287 | ------
288 | ValueError
289 | In the event no record is provided, will return an error.
290 |
291 | Returns
292 | -------
293 | gc_skews : np.array
294 | An array of the skews computed by this method
295 |
296 | """
297 | #(G-C)/(G+C)
298 | if self.record is None:
299 | raise ValueError("self.record is None, please specify record value")
300 |
301 | if step_size is None:
302 | step_size = window_size
303 |
304 | seq = str(self.record.seq)
305 | gc_skews = []
306 | for i in range(0, len(seq), step_size):
307 | gc_skew = (seq[i:i+window_size].upper().count(n1) - seq[i:i+window_size].upper().count(n2)) * 1.0 / (seq[i:i+window_size].upper().count(n1) + seq[i:i+window_size].upper().count(n2)) * 1.0
308 | gc_skews.append(gc_skew)
309 |
310 | gc_skews.append((seq[i:].upper().count(n1) - seq[i:].upper().count(n2)) * 1.0 / (seq[i:].upper().count(n1) + seq[i:].upper().count(n2)) * 1.0)
311 | self["{}{}_skew".format(n1,n2)] = gc_skews
312 | gc_skews = np.array(gc_skews)
313 | return gc_skews
314 |
315 | class Gcircle:
316 | """
317 | A Gcircle class object provides a circle whose diameter is 1000 (a.u.) as a
318 | drawing space. Any graph (line plot, scatter plot, barplot, heatmap, and chordplot)
319 | can be placed on the space by specifying the raxis_range (from 0 to 1000) and
320 | the corresponding Garc class object.
321 | """
322 | colors = ["#f44336","#e91e63","#9c27b0","#673ab7","#3f51b5","#2196f3","#00bcd4","#009688","#4caf50","#8bc34a","#cddc39","#ffeb3b","#ffc107","#ff9800","#ff5722","#795548","#9e9e9e","#607d8b"]
323 | #colors = ["#4E79A7","#F2BE2B","#E15759","#76B7B2","#59A14F","#EDC948","#B07AA1","#FF9DA7","#9C755F","#BAB0AC"]
324 | cmaps = [plt.cm.Reds, plt.cm.Blues, plt.cm.Greens, plt.cm.Greys]
325 |
326 | def __getattr__(self, name):
327 | if name == "garc_dict":
328 | return self._garc_dict
329 |
330 | def __init__(self, fig=None, figsize=None):
331 | """
332 | Parameters
333 | ----------
334 | fig : matplotlib.pyplot.figure object, optional
335 | Matplotlib Figure class object
336 | figsize : tuple, optional
337 | Figure size for the circular map
338 | """
339 | self._garc_dict = {}
340 | if fig is None:
341 | if figsize is None:
342 | figsize = (8,8)
343 | self.figure = plt.figure(figsize=figsize)
344 | self.fig_is_ext = False
345 | else:
346 | if figsize is None:
347 | figsize = (6,6)
348 | self.figure = fig
349 | self.fig_is_ext = True
350 | self.figsize = figsize
351 | self.color_cycle = 0
352 |
353 | def add_garc(self, garc):
354 | """
355 | Add a new Garc class object into garc_dict.
356 |
357 | Parameters
358 | ----------
359 | garc : Garc class object
360 | Garc class object to be added.
361 |
362 | Returns
363 | -------
364 | None
365 | """
366 | self._garc_dict[garc.arc_id] = garc
367 |
368 | def set_garcs(self, start=0, end=360):
369 | """
370 | Visualize the arc rectangles of the Garc class objects in .garc_dict on
371 | the drawing space. After the execution of this method, a new Garc class
372 | object cannot be added to garc_dict and figure parameter representing
373 | maplotlib.pyplot.figure object will be created in Gcircle object.
374 |
375 | Parameters
376 | ----------
377 | start : int, optional
378 | Start angle of the circos plot. The value range is -360 ~ 360.
379 | The default is 0.
380 | end : int, optional
381 | End angle of the circos plot. The value range is -360 ~ 360.
382 | The default is 360.
383 |
384 | Returns
385 | -------
386 | None
387 | """
388 | sum_length = sum(list(map(lambda x: self._garc_dict[x]["size"], list(self._garc_dict.keys()))))
389 | sum_interspace = sum(list(map(lambda x: self._garc_dict[x]["interspace"], list(self._garc_dict.keys()))))
390 | start = 2 * np.pi * start / 360
391 | end = (2 * np.pi * end / 360) - sum_interspace
392 |
393 | s = 0
394 | sum_interspace = 0
395 | for key in self._garc_dict.keys():
396 | size = self._garc_dict[key].size
397 | self._garc_dict[key].coordinates = [None, None]
398 | self._garc_dict[key].coordinates[0] = sum_interspace + start + ((end-start) * s/sum_length) #self.theta_list[s:s+self._garc_dict[key]["size"]+1]
399 | self._garc_dict[key].coordinates[1] = sum_interspace + start + ((end-start) * (s+size)/sum_length)
400 | s = s + size
401 | sum_interspace += self._garc_dict[key].interspace
402 |
403 | #self.figure = plt.figure(figsize=self.figsize)
404 | if self.fig_is_ext:
405 | self.ax = self.figure.add_axes([0, 0, self.figsize[0], self.figsize[1]], polar=True)
406 | else:
407 | self.ax = self.figure.add_axes([0, 0, 1, 1], polar=True)
408 | self.ax.set_theta_zero_location("N")
409 | self.ax.set_theta_direction(-1)
410 | self.ax.set_ylim(0,1000)
411 | self.ax.spines['polar'].set_visible(False)
412 | self.ax.xaxis.set_ticks([])
413 | self.ax.xaxis.set_ticklabels([])
414 | self.ax.yaxis.set_ticks([])
415 | self.ax.yaxis.set_ticklabels([])
416 |
417 | for i, key in enumerate(self._garc_dict.keys()):
418 | pos = self._garc_dict[key].coordinates[0]
419 | width = self._garc_dict[key].coordinates[-1] - self._garc_dict[key].coordinates[0]
420 | height = abs(self._garc_dict[key].raxis_range[1] - self._garc_dict[key].raxis_range[0])
421 | bottom = self._garc_dict[key].raxis_range[0]
422 | facecolor = self._garc_dict[key].facecolor
423 | edgecolor = self._garc_dict[key].edgecolor
424 | linewidth = self._garc_dict[key].linewidth
425 | #print(key, pos, pos+width)
426 | self.ax.bar([pos], [height], bottom=bottom, width=width, facecolor=facecolor, linewidth=linewidth, edgecolor=edgecolor, align="edge")
427 | if self._garc_dict[key].label_visible == True:
428 | rot = (self._garc_dict[key].coordinates[0] + self._garc_dict[key].coordinates[1]) / 2
429 | rot = rot*360/(2*np.pi)
430 | if 90 < rot < 270:
431 | rot = 180-rot
432 | else:
433 | rot = -1 * rot
434 | height = bottom + height/2 + self._garc_dict[key].labelposition
435 | self.ax.text(pos + width/2, height, self._garc_dict[key].label, rotation=rot, ha="center", va="center", fontsize=self._garc_dict[key].labelsize)
436 |
437 | def setspine(self, garc_id, raxis_range=(550, 600), facecolor="#30303000", edgecolor="#303030", linewidth=0.75):
438 | """
439 | Set spines in the sector corresponding to the arc of
440 | the Garc class object specified by garc_id.
441 |
442 | Parameters
443 | ----------
444 | garc_id : str
445 | ID of the Garc class object. The ID should be in Gcircle object.garc_dict.
446 | raxis_range : tuple (top=int, bottom=int)
447 | Radial axis range where line plot is drawn. The default is (550, 600).
448 | facecolor : str or tuple representing color code, optional
449 | Color for spines area. The default is "#30303000".
450 | edgecolor : str or tuple representing color code, optional
451 | Edge color of the spines boundary area. The default is "#303030".
452 | linewidth : float, optional
453 | Edge line width of spines boundary area. The default is 0.75.
454 |
455 | Returns
456 | -------
457 | None
458 | """
459 | pos = self._garc_dict[garc_id].coordinates[0]
460 | width = self._garc_dict[garc_id].coordinates[-1] - self._garc_dict[garc_id].coordinates[0]
461 | height = abs(raxis_range[1] - raxis_range[0])
462 | bottom = raxis_range[0]
463 | self.ax.bar([pos], [height], bottom=bottom, width=width, facecolor=facecolor, linewidth=linewidth, edgecolor=edgecolor, align="edge", zorder=0)
464 |
465 | def lineplot(self, garc_id, data, positions=None, raxis_range=(550, 600), rlim=None, linestyle="solid", linecolor=None, linewidth=1.0, spine=False):
466 | """
467 | Plot a line in the sector corresponding to the arc of the Garc class
468 | object specified by garc_id.
469 |
470 | Parameters
471 | ----------
472 | garc_id : str
473 | ID of the Garc class object. The ID should be in Gcircle object.garc_dict.
474 | data : list or numpy.ndarray
475 | Numerical data to used for plot generation.
476 | positions : list or numpy.ndarray
477 | The x coordinates of the values in data on the Garc class object
478 | when the plot is drawn on the rectangular coordinates. Each
479 | coordinate value should be in the range 0 to size of the Garc class
480 | object specified by garc_id. By the method execution, the
481 | coordinates are converted to proper angle coordinates. If positions
482 | are not given, proper coordinates values are generated according to
483 | the length of data. The default is None.
484 | raxis_range : tuple (top=int, bottom=int), optional
485 | Radial axis range where line plot is drawn.
486 | The default is (550, 600).
487 | rlim : tuple (top=int, bottom=int)
488 | The top and bottom r limits in data coordinates. If rlim value is
489 | not given, the maximum value and the minimum value in data will be
490 | set to top and bottom, respectively. The default is None.
491 | linestyle : str, optional
492 | Line style. The default is "solid".
493 | Possible line styles are documented at
494 | https://matplotlib.org/stable/gallery/lines_bars_and_markers/linestyles.html
495 |
496 | linecolor : str or tuple representing color code, optional
497 | Color of the line plot. If linecolor value is not given, the color
498 | will be set according to the default color set of matplotlib. To
499 | specify the opacity for a line color, please use `(r,g,b,a)` or
500 | `#XXXXXXXX` format. The default is None.
501 | linewidth : float, optional
502 | Edge line width. The default is 1.0.
503 | spine : bool, optional
504 | If True, spines of the Garc object is shown on the arc section.
505 | The default is False.
506 |
507 | Returns
508 | -------
509 | None
510 | """
511 | start = self._garc_dict[garc_id].coordinates[0]
512 | end = self._garc_dict[garc_id].coordinates[-1]
513 | size = self._garc_dict[garc_id].size - 1
514 | positions_all = np.linspace(start, end, len(data), endpoint=True)
515 | if positions is None:
516 | positions = positions_all
517 | else:
518 | new_positions = []
519 | for p in positions:
520 | new_positions.append(start + ((end-start) * p/size))
521 | positions = new_positions
522 |
523 | if raxis_range is None:
524 | raxis_range = raxis_range[0]
525 | bottom = raxis_range[0]
526 | top = raxis_range[1]
527 |
528 | if linecolor is None:
529 | linecolor = Gcircle.colors[self.color_cycle % len(Gcircle.colors)]
530 | self.color_cycle += 1
531 |
532 | if rlim is None:
533 | rlim = (min(data) - 0.05 * abs(min(data)), max(data) + 0.05 * abs(max(data)))
534 |
535 | min_value = rlim[0]
536 | max_value = rlim[1]
537 | new_data = []
538 | new_positions = []
539 | new_data_array = []
540 | new_positions_array = []
541 | for p, v in zip(positions, data):
542 | if v > rlim[1] or v < rlim[0]:
543 | new_data_array.append(new_data)
544 | new_positions_array.append(new_positions)
545 | new_data = []
546 | new_positions = []
547 | else:
548 | new_data.append(v)
549 | new_positions.append(p)
550 | new_data_array.append(new_data)
551 | new_positions_array.append(new_positions)
552 | for data, positions in zip(new_data_array, new_positions_array):
553 | if len(positions) > 0:
554 | data = np.array(data) - min_value
555 | data = bottom + np.array(data * ((top - bottom) / (max_value - min_value)))
556 | self.ax.plot(positions, data, color=linecolor, linewidth=linewidth, linestyle=linestyle)
557 |
558 | if spine == True:
559 | self.setspine(garc_id, raxis_range)
560 |
561 | def fillplot(self, garc_id, data, positions=None, raxis_range=(550, 600), rlim=None, base_value=None, facecolor=None, edgecolor="#303030", linewidth=0.0, spine=False):
562 | """
563 | Fill a specified area in the sector corresponding to the arc of the
564 | Garc class object specified by garc_id.
565 |
566 | Parameters
567 | ----------
568 | garc_id : str
569 | ID of the Garc class object. The ID should be in Gcircle object.garc_dict.
570 | data : list or numpy.ndarray
571 | Numerical data to used for plot generation.
572 | positions : list or numpy.ndarray
573 | The x coordinates of the values in data on the Garc class object
574 | when the plot is drawn on the rectangular coordinates. Each
575 | coordinate value should be in the range 0 to size of the Garc class
576 | object specified by garc_id. By the method execution, the
577 | coordinates are converted to proper angle coordinates. If positions
578 | are not given, proper coordinates values are generated according to
579 | the length of data. The default is None.
580 | raxis_range : tuple (top=int, bottom=int), optional
581 | Radial axis range where line plot is drawn. The default is (550, 600).
582 | rlim : tuple (top=int, bottom=int)
583 | The top and bottom r limits in data coordinates. If rlim value is
584 | not given, the maximum value and the minimum value in data will be
585 | set to top and bottom, respectively.
586 | The default is `(min(data), max(data))`.
587 | base_value : float, optional
588 | Base line height in data coordinates. The area between the base
589 | line and the data line is filled by facecolor. The default is None.
590 | facecolor : str or tuple representing color code, optional
591 | Color for filling. The default is None.
592 | edgecolor : str or tuple representing color code, optional
593 | Edge color of the filled area. The default is "#303030".
594 | linewidth : float, optional
595 | Edge line width. The default is 0.0.
596 | spine : bool, optional
597 | If True, spines of the Garc object is shown on the arc section.
598 | The default is False.
599 |
600 | Returns
601 | -------
602 | None.
603 |
604 | """
605 | start = self._garc_dict[garc_id].coordinates[0]
606 | end = self._garc_dict[garc_id].coordinates[-1]
607 | size = self._garc_dict[garc_id].size - 1
608 | positions_all = np.linspace(start, end, len(data), endpoint=True)
609 | if positions is None:
610 | positions = positions_all
611 | else:
612 | new_positions = []
613 | for p in positions:
614 | new_positions.append(start + ((end-start) * p/size))
615 | positions = new_positions
616 |
617 | if raxis_range is None:
618 | raxis_range = raxis_range[0]
619 | bottom = raxis_range[0]
620 | top = raxis_range[1]
621 |
622 | if facecolor is None:
623 | facecolor = Gcircle.colors[self.color_cycle % len(Gcircle.colors)]
624 | self.color_cycle += 1
625 |
626 | if rlim is None:
627 | rlim = (min(data) - 0.05 * abs(min(data)), max(data) + 0.05 * abs(max(data)))
628 |
629 | min_value = rlim[0]
630 | max_value = rlim[1]
631 | if base_value is None:
632 | base_value = min_value
633 | new_data = []
634 | new_positions = []
635 | new_data_array = []
636 | new_positions_array = []
637 | for p, v in zip(positions, data):
638 | if v > rlim[1] or v < rlim[0]:
639 | new_data_array.append(new_data)
640 | new_positions_array.append(new_positions)
641 | new_data = []
642 | new_positions = []
643 | else:
644 | new_data.append(v)
645 | new_positions.append(p)
646 | new_data_array.append(new_data)
647 | new_positions_array.append(new_positions)
648 | for data, positions in zip(new_data_array, new_positions_array):
649 | if len(positions) > 0:
650 | base_value = base_value - min_value
651 | base_value = bottom + base_value * ((top - bottom) / (max_value - min_value))
652 | data = np.array(data) - min_value
653 | data = bottom + np.array(data * ((top - bottom) / (max_value - min_value)))
654 | self.ax.fill_between(positions, data, base_value, facecolor=facecolor, linewidth=linewidth, edgecolor=edgecolor)
655 |
656 | if spine == True:
657 | self.setspine(garc_id, raxis_range)
658 |
659 | def scatterplot(self, garc_id, data, positions=None, raxis_range=(550, 600), rlim=None, markershape="o", markersize=5, facecolor=None, edgecolor="#303030", linewidth=0.0, spine=False):
660 | """
661 | Plot markers in the sector corresponding to the arc of the Garc class
662 | object specified by garc_id.
663 |
664 | Parameters
665 | ----------
666 | garc_id : str
667 | ID of the Garc class object. The ID should be in Gcircle object.garc_dict.
668 | data : list or numpy.ndarray
669 | Numerical data to used for plot generation.
670 | positions : list or numpy.ndarray
671 | The x coordinates of the values in data on the Garc class object
672 | when the plot is drawn on the rectangular coordinates. Each
673 | coordinate value should be in the range 0 to size of the Garc class
674 | object specified by garc_id. By the method execution, the
675 | coordinates are converted to proper angle coordinates. If positions
676 | are not given, proper coordinates values are generated according to
677 | the length of data. The default is None.
678 | raxis_range : tuple (top=int, bottom=int), optional
679 | Radial axis range where line plot is drawn. The default is (550, 600).
680 | rlim : tuple (top=int, bottom=int)
681 | The top and bottom r limits in data coordinates. If rlim value is
682 | not given, the maximum value and the minimum value in data will be
683 | set to top and bottom, respectively.
684 | The default is `(min(data), max(data))`.
685 | markershape : str, optional
686 | Marker shape. The default is "o".
687 | Possible marker are listed at
688 | https://matplotlib.org/stable/gallery/lines_bars_and_markers/marker_reference.html
689 | markersize : float or list of float, optional
690 | Size(s) of the marker(s). The default is 5.
691 | facecolor : str or tuple representing color code or list thereof, optional
692 | Face color(s) of the markers. If value type is list, the length of
693 | facecolor should be the same as the data length.
694 | The default is None.
695 | edgecolor : str or tuple representing color code, optional
696 | Edge color of the markers. The default is "#303030".
697 | linewidth : float, optional
698 | Edge line width of the markers. The default is 0.0.
699 | spine : bool, optional
700 | If True, spines of the Garc object is shown on the arc section.
701 | The default is False.
702 |
703 | Returns
704 | -------
705 | None
706 | """
707 | start = self._garc_dict[garc_id].coordinates[0]
708 | end = self._garc_dict[garc_id].coordinates[-1]
709 | size = self._garc_dict[garc_id].size - 1
710 | positions_all = np.linspace(start, end, len(data), endpoint=True)
711 | if positions is None:
712 | positions = positions_all
713 | else:
714 | new_positions = []
715 | for p in positions:
716 | new_positions.append(start + ((end-start) * p/size))
717 | positions = new_positions
718 |
719 | if raxis_range is None:
720 | raxis_range = raxis_range[0]
721 | bottom = raxis_range[0]
722 | top = raxis_range[1]
723 |
724 | if facecolor is None:
725 | facecolor = Gcircle.colors[self.color_cycle % len(Gcircle.colors)]
726 | self.color_cycle += 1
727 |
728 | if rlim is None:
729 | rlim = (min(data) - 0.05 * abs(min(data)), max(data) + 0.05 * abs(max(data)))
730 |
731 | min_value = rlim[0]
732 | max_value = rlim[1]
733 | new_data = []
734 | new_positions = []
735 | new_data_array = []
736 | new_positions_array = []
737 | for p, v in zip(positions, data):
738 | if v > rlim[1] or v < rlim[0]:
739 | new_data_array.append(new_data)
740 | new_positions_array.append(new_positions)
741 | new_data = []
742 | new_positions = []
743 | else:
744 | new_data.append(v)
745 | new_positions.append(p)
746 |
747 | new_data_array.append(new_data)
748 | new_positions_array.append(new_positions)
749 | for positions, data in zip(new_positions_array, new_data_array):
750 | if len(positions) > 0:
751 | data = np.array(data) - min_value
752 | data = bottom + np.array(data * ((top - bottom) / (max_value - min_value)))
753 | self.ax.scatter(positions, data, c=facecolor, s=markersize, linewidth=linewidth, edgecolor=edgecolor, marker=markershape)
754 |
755 | if spine == True:
756 | self.setspine(garc_id, raxis_range)
757 |
758 | def barplot(self, garc_id, data, positions=None, width=None, raxis_range=(550, 600), rlim=None, base_value=None, facecolor=None, edgecolor="#303030", linewidth=0.0, spine=False):
759 | """
760 | Plot bars in the sector corresponding to the arc of the Garc class
761 | object specified by garc_id.
762 |
763 | Parameters
764 | ----------
765 | garc_id : str
766 | ID of the Garc class object. The ID should be in Gcircle object.garc_dict.
767 | data : list or numpy.ndarray
768 | Numerical data to used for plot generation.
769 | positions : list or numpy.ndarray
770 | The x coordinates of the values in data on the Garc class object
771 | when the plot is drawn on the rectangular coordinates. Each
772 | coordinate value should be in the range 0 to size of the Garc class
773 | object specified by garc_id. By the method execution, the
774 | coordinates are converted to proper angle coordinates. If positions
775 | are not given, proper coordinates values are generated according to
776 | the length of data. The default is None.
777 | width : float or list of float
778 | Width(s) of the bars. The default is `garc_object.size / len(data)`.
779 | raxis_range : tuple (top=int, bottom=int), optional
780 | Radial axis range where line plot is drawn. The default is (550, 600).
781 | rlim : tuple (top=int, bottom=int)
782 | The top and bottom r limits in data coordinates. If rlim value is
783 | not given, the maximum value and the minimum value in data will be
784 | set to top and bottom, respectively.
785 | The default is (min(data), max(data).
786 | base_value : float, optional
787 | Base line height in data coordinates. The area between the base
788 | line and the data line is filled by facecolor. The default is None.
789 | facecolor : str or tuple representing color code or list thereof, optional
790 | Facecolor(s) of the bars. If value type is list, the length of
791 | facecolor should be the same as the data length.
792 | The default is None.
793 | edgecolor : str or tuple representing color code, optional
794 | Edge color of the bars. The default is "#303030".
795 | linewidth : float, optional
796 | Edge line width of the bars. The default is 0.0.
797 | spine : bool, optional
798 | If True, spines of the Garc object is shown on the arc section.
799 | The default is False.
800 |
801 | Returns
802 | -------
803 | None
804 | """
805 | start = self._garc_dict[garc_id].coordinates[0]
806 | end = self._garc_dict[garc_id].coordinates[-1]
807 | size = self._garc_dict[garc_id].size
808 | positions_all = np.linspace(start, end, len(data), endpoint=False)
809 | if positions is None:
810 | positions = positions_all
811 | else:
812 | new_positions = []
813 | for p in positions:
814 | new_positions.append(start + ((end-start) * p/size))
815 | positions = new_positions
816 |
817 | if width is None:
818 | width = [positions[1] - positions[0]] * len(data)
819 | elif type(width) == float or type(width) == int:
820 | width = [(end-start) * width/size] * len(data)
821 | else:
822 | new_width = []
823 | for w in width:
824 | new_w = (end-start) * w/size
825 | new_width.append(new_w)
826 | width = new_width
827 |
828 | if raxis_range is None:
829 | raxis_range = raxis_range[0]
830 | bottom = raxis_range[0]
831 | top = raxis_range[1]
832 |
833 | if facecolor is None:
834 | facecolor = Gcircle.colors[self.color_cycle % len(Gcircle.colors)]
835 | self.color_cycle += 1
836 |
837 | if rlim is None:
838 | if min(data) != max(data):
839 | rlim = (min(data) - 0.05 * abs(min(data)), max(data) + 0.05 * abs(max(data)))
840 | else:
841 | rlim = (min(data), max(data))
842 |
843 | min_value = rlim[0] if rlim[0] is not None else min(data)
844 | max_value = rlim[1] if rlim[1] is not None else max(data)
845 | if base_value is None:
846 | base_value = min_value
847 |
848 | new_data = []
849 | new_positions = []
850 | new_width = []
851 | new_data_array = []
852 | new_positions_array = []
853 | new_width_array = []
854 | for p, v, w in zip(positions, data, width):
855 | if v > rlim[1] or v < rlim[0]:
856 | new_data_array.append(new_data)
857 | new_positions_array.append(new_positions)
858 | new_width_array.append(new_width)
859 | new_data = []
860 | new_width = []
861 | new_positions = []
862 | else:
863 | new_data.append(v)
864 | new_positions.append(p)
865 | new_width.append(w)
866 |
867 | new_data_array.append(new_data)
868 | new_positions_array.append(new_positions)
869 | new_width_array.append(new_width)
870 | for data, positions, width in zip(new_data_array, new_positions_array, new_width_array):
871 | if len(positions) > 0:
872 | base_value = base_value - min_value
873 | if min_value != max_value:
874 | base_value = bottom + base_value * ((top - bottom) / (max_value - min_value))
875 | else:
876 | base_value = raxis_range[0]
877 |
878 | data = np.array(data) - min_value
879 | if min_value != max_value:
880 | data = np.array(data) * ((top - bottom) / (max_value - min_value))
881 | data = np.array(data) - (base_value - raxis_range[0])
882 | else:
883 | data = [raxis_range[1]-raxis_range[0]] * len(data)
884 | self.ax.bar(positions, data, width=width, bottom=base_value, color=facecolor, linewidth=linewidth, edgecolor=edgecolor, align="edge")
885 |
886 | if spine == True:
887 | self.setspine(garc_id, raxis_range)
888 |
889 | def heatmap(self, garc_id, data, positions=None, width=None, raxis_range=(550, 600), cmap=None, vmin=None, vmax=None, edgecolor="#303030", linewidth=0.0, spine=False):
890 | """
891 | Visualize magnitudes of data values by color scale in the sector
892 | corresponding to the arc of the Garc class object specified by garc_id.
893 |
894 | Parameters
895 | ----------
896 | garc_id : str
897 | ID of the Garc class object. The ID should be in Gcircle object.garc_dict.
898 | data : list or numpy.ndarray
899 | Numerical data to used for plot generation.
900 | positions : list or numpy.ndarray
901 | The x coordinates of the values in data on the Garc class object
902 | when the plot is drawn on the rectangular coordinates. Each
903 | coordinate value should be in the range 0 to size of the Garc class
904 | object specified by garc_id. By the method execution, the
905 | coordinates are converted to proper angle coordinates. If positions
906 | are not given, proper coordinates values are generated according to
907 | the length of data. The default is None.
908 | width : float or list of float, optional
909 | Width(s) of the bars. The default is `garc_object.size / len(data)`.
910 | raxis_range : tuple (top=int, bottom=int), optional
911 | Radial axis range where heatmap is drawn. The default is (550, 600).
912 | cmap : str representing matplotlib colormap name or
913 | matplotlib.colors.Colormap object, optional
914 | The mapping from data values to color space. The default is 'Reds'.
915 | vmin : float, optional
916 | Minimum data threshold for color scale. The default is min(data).
917 | vmax : TYPE, optional
918 | Maximum data threshold for color scale. The default is max(data).
919 | edgecolor : str or tuple representing color code, optional
920 | Edge color of the bars. The default is "#303030".
921 | linewidth : float, optional
922 | Edge line width of the bars. The default is 0.0.
923 | spine : bool, optional
924 | If True, spines of the Garc object is shown on the arc section.
925 | The default is False.
926 |
927 | Returns
928 | -------
929 | None
930 | """
931 | start = self._garc_dict[garc_id].coordinates[0]
932 | end = self._garc_dict[garc_id].coordinates[-1]
933 | size = self._garc_dict[garc_id].size
934 | positions_all = np.linspace(start, end, len(data), endpoint=False)
935 | if positions is None:
936 | positions = positions_all
937 | else:
938 | new_positions = []
939 | for p in positions:
940 | new_positions.append(start + ((end-start) * p/size))
941 | positions = new_positions
942 |
943 | if width is None:
944 | width = [positions[1] - positions[0]] * len(data)
945 | elif type(width) == float or type(width) == int:
946 | width = [(end-start) * width/size] * len(data)
947 | else:
948 | new_width = []
949 | for w in width:
950 | new_w = (end-start) * w/size
951 | new_width.append(new_w)
952 | width = new_width
953 |
954 | if raxis_range is None:
955 | raxis_range = raxis_range[0]
956 | bottom = raxis_range[0]
957 | top = raxis_range[1]
958 | height = top - bottom
959 |
960 | if cmap is None:
961 | cmap = Gcircle.cmaps[self.cmap_cycle % len(Gcircle.cmaps)]
962 | self.cmap_cycle += 1
963 |
964 | if vmax is None:
965 | max_value = max(data)
966 | else:
967 | max_value = vmax
968 |
969 | if vmin is None:
970 | min_value = min(data)
971 | else:
972 | min_value = vmin
973 |
974 | facecolors = []
975 | for d in data:
976 | facecolors.append(cmap(d/(max_value-min_value)))
977 | self.ax.bar(positions, height=[height] * len(positions), width=width, bottom=bottom, color=facecolors, edgecolor=edgecolor, linewidth=linewidth, align="edge")
978 |
979 | if spine == True:
980 | self.setspine(garc_id, raxis_range)
981 |
982 | def featureplot(self, garc_id, feature_type=None, source=None, raxis_range=(550, 600), facecolor=None, edgecolor="#303030", linewidth=0.0, spine=False):
983 | """
984 | Visualize sequence features with bar plots in the sector corresponding
985 | to the arc of the Garc class object specified by garc_id.
986 |
987 | Parameters
988 | ----------
989 | garc_id : str
990 | ID of the Garc class object. The ID should be in Gcircle object.garc_dict.
991 | feature_type : str, optional
992 | Biological nature of the Bio.Seqfeature class objects (Any value is
993 | acceptable, but GenBank format requires registering a biological
994 | nature category for each sequence feature). If the value is "all",
995 | all features in source will be drawn in the sector of the Garc
996 | class object specified by grac_id. The default is 'all'.
997 | source : list of Bio.SeqFeature object, optional
998 | List of Bio.Seqfeature class object. If source value is not given,
999 | record.features of the Garc class object specified by grac_id is
1000 | used. The default is record.features of the Garc class object
1001 | specified by grac_id.
1002 | raxis_range : tuple (top=int, bottom=int), optional
1003 | Radial axis range where feature plot is drawn. The default is (550, 600).
1004 | facecolor : str or tuple representing color code or list thereof, optional
1005 | Facecolor(s) of the bars. If value type is list, the length of
1006 | facecolor should be the same as the data length.
1007 | The default is None.
1008 | edgecolor : str or tuple representing color code, optional
1009 | Edge color of the bars. The default is "#303030".
1010 | linewidth : float, optional
1011 | Edge line width of the bars. The default is 0.0.
1012 | spine : bool, optional
1013 | If True, spines of the Garc object is shown on the arc section.
1014 | The default is False.
1015 |
1016 | Returns
1017 | -------
1018 | None
1019 | """
1020 | start = self._garc_dict[garc_id].coordinates[0]
1021 | end = self._garc_dict[garc_id].coordinates[-1]
1022 | size = self._garc_dict[garc_id].size - 1
1023 |
1024 | if source is None:
1025 | source = self.record.features
1026 |
1027 | if feature_type is None:
1028 | feature_list = source
1029 | else:
1030 | feature_list = [feat for feat in source if feat.type == feature_type]
1031 |
1032 | positions = []
1033 | widths = []
1034 | for feat in feature_list:
1035 | if feat.location.strand >= 0:
1036 | s = int(feat.location.parts[0].start.position)
1037 | e = int(feat.location.parts[-1].end.position)
1038 | pos = start + ((end-start) * s/size)
1039 | width = start + ((end-start) * e/size) - pos
1040 | positions.append(pos)
1041 | widths.append(width)
1042 | else:
1043 | s = int(feat.location.parts[-1].start.position)
1044 | e = int(feat.location.parts[0].end.position)
1045 | pos = start + ((end-start) * s/size)
1046 | width = start + ((end-start) * e/size) - pos
1047 | positions.append(pos)
1048 | widths.append(width)
1049 |
1050 | bottom = raxis_range[0]
1051 | top = raxis_range[1]
1052 |
1053 | if facecolor is None:
1054 | facecolor = Gcircle.colors[self.color_cycle % len(Gcircle.colors)]
1055 | self.color_cycle += 1
1056 | self.ax.bar(positions, [abs(top-bottom)] * len(positions) , width=widths, bottom=bottom, color=facecolor, edgecolor=edgecolor, linewidth=linewidth, align="edge")
1057 | if spine == True:
1058 | self.setspine(garc_id, raxis_range)
1059 |
1060 | def chord_plot(self, start_list, end_list, facecolor=None, edgecolor=None, linewidth=0.0):
1061 | """
1062 | Visualize interrelationships between data.
1063 |
1064 | Parameters
1065 | ----------
1066 | start_list : tuple
1067 | Start data location of linked data.
1068 | The tuple is composed of four parameters:
1069 |
1070 | - `arc_id` : `str`
1071 | The ID of the first Garc class object to be compared.
1072 | The ID should be in Gcircle object.garc_dict.
1073 | - `edge_position1` : `int`
1074 | The minimal x coordinates on the Garc class object
1075 | when the plot is drawn on the rectangular coordinates.
1076 | - `edge_position2` : `int`
1077 | The maximal x coordinates on the Garc class object
1078 | when the plot is drawn on the rectangular coordinates.
1079 | - `raxis_position` : `int`
1080 | The base height for the drawing chord.
1081 |
1082 | end_list : tuple
1083 | End data location of linked data.
1084 | The tuple is composed of four parameters:
1085 |
1086 | - `arc_id` : `str`
1087 | The ID of the second Garc class object to be compared.
1088 | The ID should be in Gcircle object.garc_dict.
1089 | - `edge_position1` : `int`
1090 | The minimal x coordinates on the Garc class object
1091 | when the plot is drawn on the rectangular coordinates.
1092 | - `edge_position2` : `int`
1093 | The maximal x coordinates on the Garc class object
1094 | when the plot is drawn on the rectangular coordinates.
1095 | - `raxis_position` : `int`
1096 | The base height for the drawing chord.
1097 |
1098 | facecolor : str or tuple representing color code, optional
1099 | Facecolor of the link. The default is None.
1100 | edgecolor : str or tuple representing color code, optional
1101 | Edge color of the link. The default is "#303030".
1102 | linewidth : float, optional
1103 | Edge line width of the link. The default is 0.0.
1104 |
1105 | Returns
1106 | -------
1107 | None
1108 | """
1109 | garc_id1 = start_list[0]
1110 | garc_id2 = end_list[0]
1111 | center = 0
1112 |
1113 | start1 = self._garc_dict[garc_id1].coordinates[0]
1114 | end1 = self._garc_dict[garc_id1].coordinates[-1]
1115 | size1 = self._garc_dict[garc_id1].size
1116 | sstart = start1 + ((end1-start1) * start_list[1]/size1)
1117 | send = start1 + ((end1-start1) * start_list[2]/size1)
1118 | stop = start_list[3]
1119 |
1120 | start2 = self._garc_dict[garc_id2].coordinates[0]
1121 | end2 = self._garc_dict[garc_id2].coordinates[-1]
1122 | size2 = self._garc_dict[garc_id2].size
1123 | ostart = start2 + ((end2-start2) * end_list[1]/size2)
1124 | oend = start2 + ((end2-start2) * end_list[2]/size2)
1125 | etop = end_list[3]
1126 |
1127 | if facecolor is None:
1128 | facecolor = Gcircle.colors[self.color_cycle % len(Gcircle.colors)] + "80"
1129 | self.color_cycle += 1
1130 |
1131 | z1 = stop - stop * math.cos(abs((send-sstart) * 0.5))
1132 | z2 = etop - etop * math.cos(abs((oend-ostart) * 0.5))
1133 | if sstart == ostart:
1134 | pass
1135 | else:
1136 | Path = mpath.Path
1137 | path_data = [(Path.MOVETO, (sstart, stop)),
1138 | (Path.CURVE3, (sstart, center)),
1139 | (Path.CURVE3, (oend, etop)),
1140 | (Path.CURVE3, ((ostart+oend)*0.5, etop+z2)),
1141 | (Path.CURVE3, (ostart, etop)),
1142 | (Path.CURVE3, (ostart, center)),
1143 | (Path.CURVE3, (send, stop)),
1144 | (Path.CURVE3, ((sstart+send)*0.5, stop+z1)),
1145 | (Path.CURVE3, (sstart, stop)),
1146 | ]
1147 | codes, verts = list(zip(*path_data))
1148 | path = mpath.Path(verts, codes)
1149 | patch = mpatches.PathPatch(path, facecolor=facecolor, linewidth=linewidth, edgecolor=edgecolor, zorder=0)
1150 | self.ax.add_patch(patch)
1151 |
1152 | def tickplot(self, garc_id, raxis_range=None, tickinterval=1000, tickpositions=None, ticklabels=None, tickwidth=1, tickcolor="#303030", ticklabelsize=10, ticklabelcolor="#303030", ticklabelmargin=10, tickdirection="outer", ticklabelorientation="vertical"):
1153 | """
1154 | Plot ticks on the arc of the Garc class object
1155 |
1156 | Parameters
1157 | ----------
1158 | garc_id : str
1159 | ID of the Garc class object. The ID should be in Gcircle object.garc_dict.
1160 | raxis_range : tuple (top=int, bottom=int)
1161 | Radial axis range where tick plot is drawn.
1162 | If direction is "inner", the default is `(r0 - 0.5 * abs(r1 -r0), r0)`.
1163 | If direction is "outer", the default is `(r1, r1 + 0.5 * abs(r1 -r0))`.
1164 | `r0, r1 = Garc_object.raxis_range[0], Garc_object.raxis_range[1]`
1165 | tickinterval : int
1166 | Tick interval.
1167 | The default is 1000. If `tickpositions` value is given, this value will be ignored.
1168 | tickpositions : list of int
1169 | Positions on the arc of the Garc class object.
1170 | If you set ticks on your specified positions, please use this parameter instead of tickinterval
1171 | The values should be less than `Garc_object.size`.
1172 | ticklabels : list of int or list or str
1173 | Labels for ticks on the arc of the Garc class object.
1174 | The default is same with tickpositions.
1175 | tickwidth : float
1176 | Tick width. The default is 1.0.
1177 | tickcolor : str or float representing color code
1178 | Tick color. The default is "#303030"
1179 | ticklabelsize : float
1180 | Tick label fontsize. The default is 10.
1181 | ticklabelcolor : str
1182 | Tick label color, The default is "#303030".
1183 | ticklabelmargin : float
1184 | Tick label margin. The default is 10.
1185 | tickdirection : str ("outer" or "inner")
1186 | Tick direction. The default is "outer".
1187 | ticklabelorientation : str ("vertical" or "horizontal")
1188 | Tick label orientation. The default is "vertical".
1189 |
1190 | Returns
1191 | -------
1192 | None
1193 | """
1194 | start = self._garc_dict[garc_id].coordinates[0]
1195 | end = self._garc_dict[garc_id].coordinates[-1]
1196 | size = self._garc_dict[garc_id].size + 1
1197 | positions_all = np.linspace(start, end, size, endpoint=True)
1198 |
1199 | if raxis_range is None:
1200 | r0, r1 = self._garc_dict[garc_id].raxis_range
1201 | tickheight = 0.5 * abs(r1 - r0)
1202 | if tickdirection == "outer":
1203 | raxis_range = (r1, r1 + tickheight)
1204 | elif tickdirection == "inner":
1205 | raxis_range = (r0 - tickheight, r0)
1206 |
1207 | if tickpositions is None:
1208 | tickpositions = [pos for pos in range(0, size, tickinterval)]
1209 |
1210 | if ticklabels is None:
1211 | ticklabels = [None] * len(tickpositions)
1212 |
1213 | elif ticklabels == "None":
1214 | ticklabels = tickpositions
1215 |
1216 | for pos, label in zip(tickpositions, ticklabels):
1217 | self.ax.plot([positions_all[pos], positions_all[pos]], raxis_range, linewidth=tickwidth, color=tickcolor)
1218 | if label is None:
1219 | pass
1220 | else:
1221 | ticklabel_rot = self._get_label_rotation(start + ((end - start) * (pos / size)), ticklabelorientation)
1222 | if ticklabelorientation == "horizontal":
1223 | label_width = ticklabelsize * 2
1224 | elif ticklabelorientation == "vertical":
1225 | label_width = ticklabelsize * len(str(label))
1226 |
1227 | if tickdirection == "outer":
1228 | y_pos = raxis_range[1] + (label_width + ticklabelmargin)
1229 | elif tickdirection == "inner":
1230 | y_pos = raxis_range[0] - (label_width + ticklabelmargin)
1231 |
1232 | self.ax.text(positions_all[pos], y_pos, str(label), rotation=ticklabel_rot, ha="center", va="center", fontsize=ticklabelsize, color=ticklabelcolor)
1233 |
1234 | def _get_label_rotation(self, position, orientation="horizontal"):
1235 | """
1236 | Get label rotation from label radian position
1237 |
1238 | Parameters
1239 | ----------
1240 | position : float
1241 | Label radian position (-2 * np.pi <= position <= 2 * np.pi)
1242 | orientation : str ("vertical" or "horizontal")
1243 | Label orientation, The default is "horizontal"
1244 |
1245 | Returns
1246 | -------
1247 | rotation : float
1248 | Label rotation
1249 | """
1250 | position_degree = position * (180 / np.pi) #-360 <= position_degree <= 360
1251 | if orientation == "horizontal":
1252 | rotation = 0 - position_degree
1253 | if -270 <= position_degree < -90 or 90 <= position_degree < 270:
1254 | rotation += 180
1255 | elif orientation == "vertical":
1256 | rotation = 90 - position_degree
1257 | if -180 <= position_degree < 0 or 180 <= position_degree < 360:
1258 | rotation += 180
1259 | return rotation
1260 |
1261 | def save(self, file_name="test", format="pdf", dpi=None):
1262 | """
1263 | Save image of Gcircle class figure object
1264 |
1265 | Parameters
1266 | ----------
1267 | file_name : str, optional
1268 | File name of figure. The default is "test".
1269 | format : str, optional
1270 | File format of figure. The default is "pdf"
1271 | dpi : int, optional
1272 | Dpi of figure. The default is None.
1273 |
1274 | Returns
1275 | -------
1276 | None
1277 | """
1278 | self.figure.patch.set_alpha(0.0)
1279 | if format == "pdf" and dpi is None:
1280 | self.figure.savefig(file_name + ".pdf", bbox_inches="tight")
1281 | else:
1282 | if dpi is None:
1283 | dpi = 600
1284 | self.figure.savefig(file_name + "." + format, bbox_inches="tight", dpi=dpi)
1285 | return self.figure
1286 |
1287 | if __name__ == "__main__":
1288 | pass
1289 |
--------------------------------------------------------------------------------
/pycircos/tree.py:
--------------------------------------------------------------------------------
1 | import math
2 | import numpy as np
3 | from Bio import Phylo
4 | from pycircos.pycircos import Garc
5 | from pycircos.pycircos import Gcircle
6 |
7 | class Tarc(Garc):
8 | def __init__(self, arc_id=None, tree=None, format="newick", interspace=3, raxis_range=(900, 950), facecolor=None, edgecolor="#303030", linewidth=0, label=None, labelposition=0, labelsize=10, label_visible=False):
9 | """
10 | Parameters
11 | ----------
12 | arc_id : str, optional
13 | Unique identifier for the Garc class object. In the event an id
14 | value is not provided, an original unique ID is automatically
15 | generated for Garc object. The default is None.
16 | tree : str
17 | File name of phylogenetic tree
18 | format : str
19 | Format of phylogenetic tree. The default is "newick".
20 | interspace : float, optional
21 | Distance angle (deg) to the adjacent arc section in clockwise
22 | sequence. The actual interspace size in the circle is determined by
23 | the actual arc section width in the resultant circle is determined
24 | by the ratio of size to the combined sum of the size and interspace
25 | values of the Garc class objects in the Gcircle class object.
26 | The default is 3.
27 | raxis_range : tuple (top=int, bottom=int), optional
28 | Radial axis range where line plot is drawn. The default is (900, 950).
29 | facecolor : str or tuple representing color code, optional
30 | Color for filling. The default is None.
31 | edgecolor : str or tuple representing color code, optional
32 | Edge color of the filled area. The default is "#303030".
33 | linewidth : float, optional
34 | Edge line width. The default is 0.
35 | label : str, optional
36 | Label of the arc section. The default is None.
37 | labelposition : int, optional
38 | Relative label height from the center of the arc section.
39 | The default is 0.
40 | labelsize : int, optional
41 | Font size of the label. The default is 10.
42 | label_visible : bool, optional
43 | If True, label of the Garc object is shown on the arc section.
44 | The default is False.
45 |
46 | Returns
47 | -------
48 | None
49 | """
50 | self.tree = Phylo.read(tree, format)
51 | self.size = len(self.tree.get_terminals())
52 | self._tree_plotted = 0
53 | self._parental_gcircle = None
54 | if arc_id == None:
55 | self.arc_id = str(Garc._arcnum)
56 | else:
57 | self.arc_id = arc_id
58 |
59 | self.interspace = 2 * np.pi * (interspace / 360)
60 | self.raxis_range = raxis_range
61 | self.facecolor = facecolor
62 | self.edgecolor = edgecolor
63 | self.linewidth = linewidth
64 |
65 | if label is None:
66 | self.label = arc_id
67 | else:
68 | self.label = label
69 |
70 | self.label_visible = label_visible
71 | self.labelposition = labelposition
72 | self.labelsize = labelsize
73 |
74 | self._get_col_positions()
75 | self._get_row_positions()
76 |
77 | Garc._arcnum += 1
78 |
79 | def _get_col_positions(self):
80 | taxa = self.tree.get_terminals()
81 | depths = self.tree.depths()
82 | max_label_width = max(len(str(taxon)) for taxon in taxa)
83 | drawing_width = 100 - max_label_width - 1
84 | if max(depths.values()) == 0:
85 | depths = self.tree.depths(unit_branch_lengths=True)
86 | fudge_margin = math.log(len(taxa), 2)
87 | cols_per_branch_unit = (drawing_width - fudge_margin) / float(max(depths.values()))
88 | positions = {clade: blen * cols_per_branch_unit + 1.0 for clade, blen in depths.items()}
89 | self._col_positions = positions
90 |
91 | def _get_row_positions(self):
92 | taxa = self.tree.get_terminals()
93 | positions = {taxon: 2 * idx for idx, taxon in enumerate(taxa)}
94 | def calc_row(clade):
95 | for subclade in clade:
96 | if subclade not in positions:
97 | calc_row(subclade)
98 | positions[clade] = (
99 | positions[clade.clades[0]] + positions[clade.clades[-1]]
100 | ) // 2
101 | calc_row(self.tree.root)
102 | self._row_positions = positions
103 |
104 | self.clade_dict = {}
105 | self.terminal_dict = {}
106 | self.nonterminal_dict = {}
107 | keys = list(self._row_positions.keys())
108 | keys.sort(key=lambda x: self._row_positions[x])
109 | for key in keys:
110 | if key in taxa:
111 | self.terminal_dict[key.name] = key
112 | else:
113 | self.nonterminal_dict[key.name] = key
114 | self.clade_dict[key.name] = key
115 |
116 | def _convert(self, thetalim, rlim):
117 | col_values = list(self._col_positions.values())
118 | row_values = list(self._row_positions.values())
119 | row_min, row_max = np.min(row_values), np.max(row_values)
120 | col_min, col_max = np.min(col_values), np.max(col_values)
121 |
122 | theta_positions = [thetalim[0] + (v * abs(thetalim[1]-thetalim[0])/abs(row_min-row_max)) for v in row_values]
123 | if rlim[0] < rlim[1]:
124 | r_positions = [rlim[0] + (v * abs(rlim[1]-rlim[0])/abs(col_min-col_max)) for v in col_values]
125 | else:
126 | r_positions = [rlim[0] - (v * abs(rlim[1]-rlim[0])/abs(col_min-col_max)) for v in col_values]
127 | self._theta_dict = dict(zip(list(self._row_positions.keys()) ,theta_positions))
128 | self._r_dict = dict(zip(list(self._col_positions.keys()) ,r_positions))
129 |
130 | def _plot_tree(self, ax, thetalim=None, rlim=None, cladevisual_dict=None, highlight_dict=None, linewidth=None, linecolor=None):
131 | if linewidth is None:
132 | linewidth = 0.5
133 |
134 | if linecolor is None:
135 | linecolor = "k"
136 |
137 | if cladevisual_dict is None:
138 | cladevisual_dict = {}
139 |
140 | self._tree_rlim = rlim
141 | if rlim[0] < rlim[1]:
142 | self._tree_direction = "inner"
143 | else:
144 | self._tree_direction = "outer"
145 |
146 | self._convert(thetalim, rlim)
147 | s = []
148 | c = []
149 | ecs = []
150 | lws = []
151 | for clade in self._theta_dict:
152 | if clade.name not in cladevisual_dict:
153 | cladevisual_dict[clade.name] = {}
154 | cladevisual_dict[clade.name].setdefault("size",0)
155 | cladevisual_dict[clade.name].setdefault("color","k")
156 | cladevisual_dict[clade.name].setdefault("edgecolor","k")
157 | cladevisual_dict[clade.name].setdefault("linewidth",0.1)
158 | s.append(cladevisual_dict[clade.name]["size"])
159 | c.append(cladevisual_dict[clade.name]["color"])
160 | ecs.append(cladevisual_dict[clade.name]["edgecolor"])
161 | lws.append(cladevisual_dict[clade.name]["linewidth"])
162 | ax.scatter(self._theta_dict.values(), [self._r_dict[clade] for clade in self._theta_dict], s=s, c=c, edgecolors=ecs, linewidths=lws, zorder=1100)
163 | for clade in self._theta_dict:
164 | subclades = clade.clades
165 | if len(subclades) > 0:
166 | sc_thetas = [self._theta_dict[sc] for sc in subclades]
167 | minsc_theta = min(sc_thetas)
168 | maxsc_theta = max(sc_thetas)
169 | thetas = np.linspace(minsc_theta, maxsc_theta, 100)
170 | rs = [self._r_dict[clade]] * len(thetas)
171 | ax.plot(thetas, rs, lw=linewidth, color=linecolor, zorder=0)
172 | for sc, sc_theta in zip(subclades, sc_thetas):
173 | ax.plot([sc_theta, sc_theta], [self._r_dict[sc], self._r_dict[clade]], lw=linewidth, color=linecolor, zorder=0)
174 |
175 | if highlight_dict is not None:
176 | self.plot_highlight(ax, highlight_dict)
177 | self._tree_plotted = 1
178 |
179 | def _plot_highlight(self, ax, highlight_dict=None):
180 | if self._tree_plotted == 0:
181 | raise ValueError("Please run `plot_tree` before running `plot_highlight`")
182 |
183 | for clade_names in highlight_dict:
184 | highlight_dict[clade_names].setdefault("color", "#000000")
185 | highlight_dict[clade_names].setdefault("alpha", 0.25)
186 | highlight_dict[clade_names].setdefault("label", None)
187 | highlight_dict[clade_names].setdefault("y", None)
188 | highlight_dict[clade_names].setdefault("fontsize", self.labelsize)
189 |
190 | color = highlight_dict[clade_names]["color"]
191 | alpha = highlight_dict[clade_names]["alpha"]
192 | label = highlight_dict[clade_names]["label"]
193 | fontsize = highlight_dict[clade_names]["fontsize"]
194 | yloc = highlight_dict[clade_names]["y"]
195 |
196 | if type(clade_names) is tuple:
197 | ca = self.tree.common_ancestor([self.clade_dict[name] for name in clade_names])
198 | clades = [self.clade_dict[name] for name in clade_names]
199 | else:
200 | ca = self.clade_dict[clade_names]
201 | clades = ca.get_terminals()
202 |
203 | c_thetas = [self._theta_dict[c] for c in clades]
204 | minc_theta = min(c_thetas)
205 | maxc_theta = max(c_thetas)
206 |
207 | if self._tree_direction == "inner":
208 | c_rs = [self._r_dict[c] for c in clades]
209 | maxc_r = max(c_rs)
210 | width = minc_theta - maxc_theta
211 | loc = (minc_theta + maxc_theta) / 2
212 | ax.bar([loc], [self._tree_rlim[1] - self._r_dict[ca]], bottom=self._r_dict[ca], width=width, color=color, alpha=alpha, linewidth=0, zorder=1000 + maxc_r)
213 | if highlight_dict[clade_names]["label"] is None:
214 | pass
215 | else:
216 | rot = loc*360/(2*np.pi)
217 | if 90 < rot < 270:
218 | rot = 180-rot
219 | else:
220 | rot = -1 * rot
221 | if yloc is None:
222 | yloc = self._tree_rlim[1] - abs(self._tree_rlim[1]-self._tree_rlim[0]) * 0.1
223 | ax.text(loc, yloc, str(label), rotation=rot, ha="center", va="center", fontsize=fontsize, zorder=1000 + maxc_r + 0.1)
224 |
225 | else:
226 | c_rs = [self._r_dict[c] for c in clades]
227 | minc_r = min(c_rs)
228 | width = minc_theta - maxc_theta
229 | loc = (minc_theta + maxc_theta) / 2
230 | ax.bar([loc], [self._r_dict[ca] - self._tree_rlim[1]], bottom=self._tree_rlim[1], width=width, color=color, alpha=alpha, linewidth=0, zorder=1000 + (-1 * minc_r))
231 | if highlight_dict[clade_names]["label"] is None:
232 | pass
233 | else:
234 | rot = loc*360/(2*np.pi)
235 | if 90 < rot < 270:
236 | rot = 180-rot
237 | else:
238 | rot = -1 * rot
239 | if yloc is None:
240 | yloc = self._tree_rlim[1] + abs(self._tree_rlim[1]-self._tree_rlim[0]) * 0.1
241 | ax.text(loc, yloc, str(label), rotation=rot, ha="center", va="center", fontsize=fontsize, zorder=1000 + (-1 * minc_r) + 0.1)
242 |
243 | class Tcircle(Gcircle):
244 | """
245 | Tcircle class is the subclass of Gcircle. All methods implemented in the
246 | Gcircle class also can be used. Then, the two additional methods set_tarc,
247 | plot_tree and plot_highlight is provided in the Tcircle class.
248 | """
249 | def __init__(self, fig=None, figsize=None):
250 | """
251 | Parameters
252 | ----------
253 | fig : matplotlib.pyplot.figure object, optional
254 | Matplotlib Figure class object
255 | figsize : tuple, optional
256 | Figure size for the circular map
257 | """
258 | super().__init__(fig=fig, figsize=figsize)
259 |
260 | def __getattr__(self, name):
261 | if name == "tarc_dict":
262 | return self._garc_dict
263 |
264 | def add_tarc(self, tarc):
265 | """
266 | Add a new Tarc or Garc class object into tarc_dict.
267 |
268 | Parameters
269 | ----------
270 | tarc : Tarc or Garc class object
271 | Tarc or Garc class object to be added.
272 |
273 | Returns
274 | -------
275 | None
276 | """
277 | self._garc_dict[tarc.arc_id] = tarc
278 |
279 | def set_tarcs(self, start=0, end=360):
280 | """
281 | Visualize the arc rectangles of the Tarc class objects in .garc_dict on
282 | the drawing space. After the execution of this method, a new Tarc class
283 | object cannot be added to garc_dict and figure parameter representing
284 | matplotlib.pyplot.figure object will be created in Tcircle object.
285 |
286 | Parameters
287 | ----------
288 | start : int, optional
289 | Start angle of the circos plot. The value range is -360 ~ 360.
290 | The default is 0.
291 | end : int, optional
292 | End angle of the circos plot. The value range is -360 ~ 360.
293 | The default is 360.
294 |
295 | Returns
296 | -------
297 | None
298 | """
299 | sum_length = sum(list(map(lambda x: self._garc_dict[x]["size"], list(self._garc_dict.keys()))))
300 | sum_interspace = sum(list(map(lambda x: self._garc_dict[x]["interspace"], list(self._garc_dict.keys()))))
301 | start = 2 * np.pi * start / 360
302 | end = (2 * np.pi * end / 360) - sum_interspace
303 |
304 | s = 0
305 | sum_interspace = 0
306 | for key in self._garc_dict.keys():
307 | size = self._garc_dict[key].size
308 | self._garc_dict[key].coordinates = [None, None]
309 | self._garc_dict[key].coordinates[0] = sum_interspace + start + ((end-start) * s/sum_length)
310 | self._garc_dict[key].coordinates[1] = sum_interspace + start + ((end-start) * (s+size)/sum_length)
311 | s = s + size
312 | sum_interspace += self._garc_dict[key].interspace
313 |
314 | if self.fig_is_ext:
315 | self.ax = self.figure.add_axes([0, 0, self.figsize[0], self.figsize[1]], polar=True)
316 | else:
317 | self.ax = self.figure.add_axes([0, 0, 1, 1], polar=True)
318 | self.ax.set_theta_zero_location("N")
319 | self.ax.set_theta_direction(-1)
320 | self.ax.set_ylim(0,1000)
321 | self.ax.spines['polar'].set_visible(False)
322 | self.ax.xaxis.set_ticks([])
323 | self.ax.xaxis.set_ticklabels([])
324 | self.ax.yaxis.set_ticks([])
325 | self.ax.yaxis.set_ticklabels([])
326 |
327 | for i, key in enumerate(self._garc_dict.keys()):
328 | pos = self._garc_dict[key].coordinates[0]
329 | width = self._garc_dict[key].coordinates[-1] - self._garc_dict[key].coordinates[0]
330 | height = abs(self._garc_dict[key].raxis_range[1] - self._garc_dict[key].raxis_range[0])
331 | bottom = self._garc_dict[key].raxis_range[0]
332 | facecolor = self._garc_dict[key].facecolor
333 | edgecolor = self._garc_dict[key].edgecolor
334 | linewidth = self._garc_dict[key].linewidth
335 | if facecolor is None:
336 | facecolor = (0, 0, 0, 0)
337 |
338 | if facecolor == (0, 0, 0, 0) and linewidth == 0:
339 | pass
340 | else:
341 | self.ax.bar([pos], [height], bottom=bottom, width=width, facecolor=facecolor, linewidth=linewidth, edgecolor=edgecolor, align="edge")
342 |
343 | if self._garc_dict[key].label_visible == True:
344 | rot = (self._garc_dict[key].coordinates[0] + self._garc_dict[key].coordinates[1]) / 2
345 | rot = rot*360/(2*np.pi)
346 | if 90 < rot < 270:
347 | rot = 180-rot
348 | else:
349 | rot = -1 * rot
350 | height = bottom + height/2 + self._garc_dict[key].labelposition
351 | self.ax.text(pos + width/2, height, self._garc_dict[key].label, rotation=rot, ha="center", va="center", fontsize=self._garc_dict[key].labelsize)
352 |
353 | def plot_tree(self, tarc_id, rlim=(0,700), cladevisual_dict=None, highlight_dict=None, linecolor="#303030", linewidth=0.5):
354 | """
355 | Draw circular phylogenetic tree
356 |
357 | Parameters
358 | ---------
359 | tarc_id : str
360 | ID of the Tarc class object. The ID should be in Tcircle object.tarc_dict.
361 | rlim : tuple (top=int, bottom=int)
362 | The top and bottom r limits in data coordinates. The default is (0, 700).
363 | cladevisual_dict : dict
364 | Dictionary composed of pairs of clade name and a sub-dict holding
365 | parameters to visualize the clade. A sub-dict is composed of
366 | the following key-value pairs:
367 |
368 | - `size` : `float`
369 | Size of dot. The default is 5.
370 | - `color` : `float or str` representing color code.
371 | Face color of dot. The default is "#303030".
372 | - `edgecolor` : `float or str` representing color code.
373 | Edge line color of dot. The default is "#303030".
374 | - `linewidth` : `float`
375 | Edge line width of dot. The default is 0.5.
376 |
377 | highlight_dict : dict
378 | Dictionary composed of pairs of internal clade name and a sub-dict.
379 | Instead of clade name, tuples of terminal clade names can also be
380 | A sub-dict is composed of the following key-value pairs:
381 |
382 | - `color` : `str`
383 | Color of highlight for clades. The default is "#000000".
384 | - `alpha` : `float`
385 | Alpha of highlight for clades. The default is 0.25.
386 | - `label` : `str`
387 | Label. The default is None.
388 | - `fontsize` : `float`
389 | Fontsize of label. The default is 10.
390 | - `y` : `float`
391 | Y location of the text. The default is the bottom edge of the highlight.
392 |
393 | linecolor : str or tuple representing color code, optional
394 | Color of the tree line. The default is "#303030".
395 | linewidth : float
396 | Line width of tree. The default is 0.5.
397 |
398 | Returns
399 | -------
400 | None
401 | """
402 | start = self._garc_dict[tarc_id].coordinates[0]
403 | end = self._garc_dict[tarc_id].coordinates[-1]
404 | positions = np.linspace(start, end, self._garc_dict[tarc_id].size, endpoint=False)
405 | positions = positions + abs(positions[1]-positions[0]) * 0.5
406 | start, end = positions[0], positions[-1]
407 | self._garc_dict[tarc_id]._plot_tree(self.ax, thetalim=(start, end), rlim=rlim, cladevisual_dict=cladevisual_dict, highlight_dict=highlight_dict, linecolor=linecolor, linewidth=linewidth)
408 |
409 | def plot_highlight(self, tarc_id, highlight_dict=None):
410 | """
411 | Add highlight for specific clade under the given internal clade
412 |
413 | Parameters
414 | ----------
415 | tarc_id : str
416 | ID of the Tarc class object. The ID should be in Tcircle object.tarc_dict.
417 | highlight_dict : dict
418 | Dictionary composed of pairs of internal clade name and a sub-dict.
419 | Instead of clade name, tuples of terminal clade names can also be used.
420 | A sub-dict is composed of the following key-value pairs:
421 |
422 | - `color` : `str`
423 | Color of highlight for clades. The default is "#000000".
424 | - `alpha` : `float`
425 | Alpha of highlight for clades. The default is 0.25.
426 | - `label` : `str`
427 | Label. The default is None.
428 | - `fontsize` : `float`
429 | Fontsize of label. The default is 10.
430 | - `y` : `float`
431 | Y location of the text. The default is the bottom edge of the highlight.
432 |
433 | Returns
434 | -------
435 | None
436 | """
437 | self._garc_dict[tarc_id]._plot_highlight(self.ax, highlight_dict=highlight_dict)
438 |
439 | if __name__ == "__main__":
440 | pass
441 | """
442 | tree = next(Phylo.parse("../tutorial/sample_data/hmptree.xml", "phyloxml"))
443 | col_positions = get_col_positions(tree)
444 | row_positions = get_row_positions(tree)
445 |
446 | import numpy as np
447 | import matplotlib.pyplot as plt
448 | fig = plt.figure(figsize=(5,5))
449 | ax = fig.add_axes([0, 0, 1, 1], polar=True)
450 | theta_dict, r_dict = convert(tree, col_positions, row_positions, (0, np.pi), (0,10))
451 |
452 | #ax.scatter(theta_dict.values(), [r_dict[clade] for clade in theta_dict], s=1, color="k")
453 |
454 | plot_lines(ax, theta_dict, r_dict)
455 |
456 | ax.set_ylim([0,10])
457 | fig.savefig("test.pdf", bbox_inches="tight")
458 | """
459 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | #
3 | # Copyright (C) Hideto Mori
4 |
5 |
6 | DESCRIPTION = "circosplot for matplotlib"
7 | LONG_DESCRIPTION = ""
8 |
9 | DISTNAME = 'python-circos'
10 | MAINTAINER = 'Hideto Mori'
11 | MAINTAINER_EMAIL = 'hidto7592@gmail.com'
12 | URL = 'https://github.com/ponnhide/pyCircos'
13 | LICENSE = 'GNU General Public License v3.0'
14 | DOWNLOAD_URL = 'https://github.com/ponnhide/pyCircos'
15 | VERSION = '0.3.0'
16 | PYTHON_REQUIRES = ">=3.7"
17 |
18 | INSTALL_REQUIRES = [
19 | 'matplotlib>=3.4',
20 | 'biopython>=1.78',
21 | ]
22 |
23 | PACKAGES = [
24 | 'pycircos'
25 | ]
26 |
27 | CLASSIFIERS = [
28 | 'Intended Audience :: Science/Research',
29 | 'Programming Language :: Python :: 3.7',
30 | 'Programming Language :: Python :: 3.8',
31 | 'Programming Language :: Python :: 3.9',
32 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',
33 | ]
34 |
35 |
36 | if __name__ == "__main__":
37 | from setuptools import setup
38 | import sys
39 | if sys.version_info[:2] < (3, 7):
40 | raise RuntimeError("pycircos requires python >= 3.7.")
41 |
42 | setup(
43 | name=DISTNAME,
44 | author=MAINTAINER,
45 | author_email=MAINTAINER_EMAIL,
46 | maintainer=MAINTAINER,
47 | maintainer_email=MAINTAINER_EMAIL,
48 | description=DESCRIPTION,
49 | long_description=LONG_DESCRIPTION,
50 | license=LICENSE,
51 | url=URL,
52 | version=VERSION,
53 | download_url=DOWNLOAD_URL,
54 | python_requires=PYTHON_REQUIRES,
55 | install_requires=INSTALL_REQUIRES,
56 | packages=PACKAGES,
57 | classifiers=CLASSIFIERS
58 | )
59 |
--------------------------------------------------------------------------------