├── LICENSE
├── MANIFEST.in
├── README.md
├── mcsolver with GUI run on Windows platform.zip
├── mcsolver
├── Lattice.py
├── WannierKit.py
├── __init__.py
├── auxiliary.py
├── fileio.py
├── guiMain.py
├── heisenbergLib.c
├── input.py
├── interface2swt.py
├── isingLib.c
├── mcMain.py
├── toolbox.py
├── win.py
└── xyLib.c
├── samples
├── CrI3With2NNCoupling
├── SkyrmionOnHexLattice
├── SkyrmionOnSqaureLattice
├── Square_XY_isotropic
├── sim_XYmodel_under_Linux.py
└── sim_XYmodel_under_Windows.py
└── setup.py
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
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 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include ./mcsolver/*.py ./mcsolver/*.c ./mcsolver/*.so LICENSE README.md
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # mcsolver
2 | A user friendly and efficient tool implementing Monte Carlo simulations to estimate Curie/Neel temperature
3 |
4 | Support multiple ocassions, e.g. standard ferromangetic/anti-ferromagnetic systems, DMI, Kiteav non-diagonal exchange interactions, dipole-dipole long-range couplings, with external fields.
5 |
6 | The newest version is 3, which supports the calculations on topological charges (the number of (anti-)Skyrmions and (anti-)Merons).
7 |
8 | Original version contributor: Dr. Liang Liu* 1.Shenzheng University 2.Shandong University
9 | Email: liangliu@mail.sdu.edu.cn
10 |
11 | You can download the packed .exe (only tested in Windows 10 platform) from the following link. Wish it can find something helpful for you. And if it was used for publication, please cite:
12 | [1] Magnetic switches via electric field in BN nanoribbons. Applied Surface Science 480(2019)
13 |
14 | Link for exe: https://pan.baidu.com/s/1kRtvPFXDBANga1StRxG7Wg?pwd=1234
15 |
16 |
17 | Brief tutorial:
18 |
19 | A. using mcsolver via .exe, e.g., in Windows platform
20 |
21 | NOTE: the mcsolver.exe maybe reported to be virus and removed by some anti-virus software. I still have no ideal about this and maybe you need add it into white list. Otherwise you can use mcsolver as a python package (see Section B below).
22 |
23 | Download and extract file from upper link (or download the .zip from https://github.com/golddoushi/mcsolver/raw/master/mcsolver.20.10.10update.zip), then open .exe (maybe wait 10+ sec.), fill out all parameters, click startMC Btn, then wait for the results.
24 |
25 | How to define parameters?
26 |
27 | Style I Define parameters via GUI:
28 |
29 | 1. Define the three lattice vectors of primitive cell.
30 |
31 | 2. Define all basic spins in primitive cell, note that the fractional coordinates are supposed. Ani represents the single-ion anisotropies in xyz directions (It is useless in Ising model, and only former two are used in XY model). As well as, note that the units of anisotropies are in Kelvin.
32 |
33 | 3. Define all exchange interactions (bonds). There are nine matrix elements for one J including Jxx, Jyy, Jzz, Jxy, Jxz, Jyz, Jyx, Jzx, Jzy, respectively. Each element discribes the coupling between two components of spins. For example, a basic bond term can be expressed as
34 | $$S1\dot J\dot S2 = S_{1x}J_{xx}S_{2x} + S_{1y}J_{yy}S_{2y} + S_{1z}J_{zz}S_{2z} + S_{1x}J_{xy}S_{2y} + ...$$
35 | For Ising model, since only one component is available for each spin, only the first element Jxx is used. As well as for XY model, only Jxx, Jyy, Jxy, Jyz are used.
36 | In this step, you can click one of the bonds to review the actual linking in lattice on view pannel. Activated bond is depicted with bold and yellow line while others are green. You may drag left/right mouse Btn to rotate and expand/shrink the model shown in view pannel.
37 | By the way, these parameters can be obtained via fitting experimental spin-wave spectra or DFT calculations. One of the general method for calculating anisotropic bonds and orbitals was introduced in dio: 10.1021/acs.jpclett.0c01911.
38 |
39 | 4. Define other parameters, including
40 | the start and end temperatures, number of temperature interpolations (for the temperature scanning)
41 | the start, end and number of samplings for external field (for the magnetic field scanning)
42 | nthermal is the total steps to make system enter balanced states, nsweep is the total steps involved in mesearing, tau denotes the MC updates for each step
43 | xAxis denote the physical quantity put in x-axis of right-hand Result viewer, it can be either T(for illustration of M-T curv) or H (for illustration of hysteresis loop).
44 | model type, algorithm (only Metropolis and Wolff are supported now)
45 | nFrame is the num. of output spin configurations, using for illustrating spin configurations in equilibrium or non-equilibrium states.
46 |
47 | 5. Set spin_i and spin_j and the lattice vector between them, for correlation mesearments. (if spin_i=spin_j and overLat=0 0 0, then you will get susceptibility for spin_i)
48 |
49 | 6. Set the core resources for parallel calc.
50 |
51 | 7. (Optional) Save current parameters into file.
52 |
53 | 8. Click startMC Btn to start.
54 |
55 | 9. Wait for the diagram update in right pannel. Afterwards, you can find a file result.txt in the root directory of mcsolver, there are many useful informations including the averaged spin (on spin_i and j defined in step 5), correlation between spin_i and j, internal energy, specific heat capacith, and Binder cumulant U4, etc. If you handle the sims with more than one cores then the results may not be ordered according to temperature, however, the correspondences in every line are ok.
56 |
57 | Style II Define parameters via loading file
58 |
59 | 1. click load Btn to load settings, and here I prepared the setting for CrI3 with exchanges up to 2nd nearest neiboring. You can modify the sample file for your own purposes, with any txt editor.
60 |
61 | 2. You can define the Topological section to compute the (thermally averaged) topological charges. Every circuits are made by three orbitals enclosing the triangle anti-clockwisely. And all the circuits should cover the zone with exactly the same area of unit cell.
62 |
63 | 3. Click startMC Btn to start.
64 |
65 | B. using mcsolver as a python package
66 |
67 | Style I Build form binary file in Windows platform
68 |
69 | Install the package via command:
70 |
71 | pip install mcsolver
72 |
73 | Note that python>=3, matplotlib, numpy, tkinter are prerequisite
74 |
75 | Afterwards, you can import mcsolver into your own python code and use function:
76 |
77 | mcsolver.loadMC("parameterfile")
78 |
79 | to start simulation. Preparation of parameterfile is the same as in section A.
80 |
81 | There are one sample file sim_XYmodel_under_Windows.py in sample folder. To use this, change your current path (in console) into sample folder, and type command: python sim_XYmodel_under_Windows.py
82 |
83 | NOTE: since mcsolver employ python-parallel you have to use freeze_support() before calling loadMC(...).
84 |
85 | Style II Build from source in Linux platform
86 |
87 | Download all codes presented here, use install command:
88 |
89 | python setup.py install
90 |
91 | Afterwards, you can import mcsolver into your own python code and use function:
92 |
93 | mcsolver.loadMC("parameterfile")
94 |
95 | to start simulation. Preparation of parameterfile is the same as in section A.
96 |
97 | There are one sample file sim_XYmodel_under_Linux.py in sample folder. To use this, cd to sample folder, and type command: python sim_XYmodel_under_Linux.py
98 |
99 | Note that the parallelization of mcsolver is not perfect. Now it cannot parallelize between multiple machines but amongst mutiple cores in a single machine (that is, only SMP mode is efficient). Therefore submit the job into one node if you are working with clusters.
100 |
101 | C. using code mode (not recommend)
102 |
103 | Download all codes, compile all .c files inito .so files the dynamic libraries. And run cmd: "python win.py" to load GUI and go on.
104 |
--------------------------------------------------------------------------------
/mcsolver with GUI run on Windows platform.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/golddoushi/mcsolver/671a44d8275839ea453147db129ae35b84f46d8a/mcsolver with GUI run on Windows platform.zip
--------------------------------------------------------------------------------
/mcsolver/Lattice.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from matplotlib.figure import Figure
3 | try:
4 | from .auxiliary import improveTheMatrixRankToThree
5 | except:
6 | from auxiliary import improveTheMatrixRankToThree
7 |
8 | class Orbital:
9 | '''
10 | represent the orbital, it is linked to many other orbitals
11 | '''
12 | def __init__(self,id,spin=1.,D=[],x=0.,y=0.,z=0.,R=np.array([0,0,0])):
13 | self.id=id
14 | self.linkedOrb=[]
15 | self.linkStrength=[]
16 | self.linkDistance=[]
17 | self.spin=spin
18 | self.D=D
19 | self.inBlock=False
20 |
21 | #use to plot on screen
22 | self.x=x
23 | self.y=y
24 | self.z=z
25 |
26 | self.r=np.array([x,y,z])
27 |
28 | # mark for renormalization
29 | self.chosen=False
30 | self.orb_cluster=[]
31 | self.linkedOrb_rnorm=[]
32 | self.linkStrength_rnorm=[]
33 |
34 | def addLinking(self,targetOrb,strength,distance,quiet=False,forceAdd=False):
35 | # check redundancy
36 | for iorb, orb in enumerate(self.linkedOrb):
37 | if forceAdd:
38 | break
39 | if targetOrb.id==orb.id:
40 | if not quiet: print('Warning: maybe redundant bonding between orb: %d and %d'%(self.id, orb.id))
41 | # check if they are equal
42 | existed_bond_strength=self.linkStrength[iorb]
43 | diff_bond_strength=abs(existed_bond_strength-strength)
44 | if type(strength) is float and diff_bond_strength<1e-5:
45 | if not quiet: print("the difference between this bond and existed bond is negligible (<1e-5), therefore we skip it")
46 | return
47 | if type(strength) is np.ndarray and sum(diff_bond_strength)<1e-5:
48 | if not quiet: print("the difference between this bond and existed bond is negligible (<1e-5), therefore we skip it")
49 | return
50 | if not quiet: print('Since the two bond strength is different, now try to add the strength to existed one')
51 | self.linkStrength[iorb]+=strength
52 | return
53 | self.linkedOrb.append(targetOrb)
54 | self.linkStrength.append(strength)
55 | self.linkDistance.append(distance)
56 | #print(strength)
57 | #exit()
58 |
59 |
60 | def addLinking_rnorm(self,targetOrb,strength):
61 | for orb in self.linkedOrb_rnorm:
62 | if targetOrb.id==orb.id:
63 | print('Warning: redundant renormalizing bonding between orb: %d and %d'%(self.id, orb.id))
64 | return
65 | self.linkedOrb_rnorm.append(targetOrb)
66 | self.linkStrength_rnorm.append(strength)
67 |
68 | def classifyTheLinking(self,On=False):
69 | initialType=-1
70 | self.classStrength=[]
71 | self.linkedOrbType=[]
72 | for linkStrength in self.linkStrength:
73 | #print(linkStrength)
74 | findType=False
75 | for itype, StrengthType in enumerate(self.classStrength):
76 | condition=sum(abs(linkStrength-StrengthType)) if On else abs(linkStrength-StrengthType)
77 | if condition<0.0001:#abs(linkStrength-StrengthType).all()<0.0001:
78 | self.linkedOrbType.append(itype)
79 | findType=True
80 | break
81 | if not findType:
82 | initialType+=1
83 | self.linkedOrbType.append(initialType)
84 | self.classStrength.append(linkStrength)
85 | self.totLinkingTypes=initialType+1
86 |
87 | def getCorrEnergy(self,corrList=[]):
88 | corr=0.
89 | for targetOrb, bondStrengh in zip(self.linkedOrb,self.linkStrength):
90 | excluded=True
91 | for corrOrb in corrList:
92 | if targetOrb.id==corrOrb.id:
93 | excluded=False
94 | break
95 | if excluded:
96 | continue
97 | corr+=self.spin*targetOrb.spin*bondStrengh
98 | return corr
99 |
100 | def getCorrEnergyDirect(self):
101 | corr=0.
102 | for targetOrb, bondStrengh in zip(self.linkedOrb,self.linkStrength):
103 | corr+=self.spin*targetOrb.spin*bondStrengh
104 | return corr
105 |
106 | def getCorrEnergyWithBlock(self):
107 | corr=0.
108 | for targetOrb, bondStrengh in zip(self.linkedOrb,self.linkStrength):
109 | if targetOrb.inBlock:
110 | corr+=self.spin*targetOrb.spin*bondStrengh
111 | return corr
112 |
113 | def addOrbIntoCluster(self,orb_trial):
114 | newOrb=True
115 | for orb in self.orb_cluster:
116 | if orb.id==orb_trial.id:
117 | newOrb=False
118 | break
119 | if newOrb:
120 | self.orb_cluster.append(orb_trial)
121 | return
122 |
123 | class Bond:
124 | '''
125 | represent the bond
126 | '''
127 | def __init__(self,source,target,overLat,Jxx,Jyy=0,Jzz=0,Jxy=0,Jxz=0,Jyz=0,Jyx=0,Jzx=0,Jzy=0,On=False):
128 | self.source=source
129 | self.target=target
130 | self.overLat=overLat
131 | self.strength=Jxx
132 | self.invStrength=Jxx
133 |
134 | self.On=On
135 | if On:
136 | self.strength=np.array([Jxx,Jyy,Jzz,Jxy,Jxz,Jyz,Jyx,Jzx,Jzy])
137 | self.invStrength=np.array([Jxx,Jyy,Jzz,Jyx,Jzx,Jzy,Jxy,Jxz,Jyz])
138 | #print('new bond')
139 | #print(self.invStrength)
140 |
141 | def renormWithT(self,T):
142 | if T<1e-4:
143 | print("Error: Lattice::Bond::renormWithT: Temperature is too low (<1e-4)")
144 | exit()
145 | #print(T,self.strength)
146 | self.strength=(1/T)*self.strength
147 | self.invStrength=(1/T)*self.invStrength
148 |
149 | def copy(self):
150 | bond=Bond(self.source,self.target,self.overLat,0,0,0,self.On)
151 | bond.strength=np.array(list(self.strength)) if self.On else self.strength
152 | bond.invStrength=np.array(list(self.invStrength)) if self.On else self.invStrength
153 | return bond
154 |
155 | def establishLattice(Lx=1,Ly=1,Lz=1,norb=1,
156 | Lmatrix=np.array([[1,0,0],[0,1,0],[0,0,1]]),bmatrix=[np.array([0.,0.,0.])],
157 | SpinList=[1],DList=[0.,0.,0.],orbGroupList=[],groupInSC=False,
158 | localCircuitList=[]):
159 | '''
160 | create a Lx X Ly X Lz lattice, and create norb orbitals
161 | for each cell
162 | '''
163 | # pre-checking if bmatrix is not consistent with norb
164 | if len(bmatrix)>>>>>")
215 | for orb in lattice_flatten:
216 | if orb.chosen:
217 | print("orb%d is chosen, involving:"%orb.id)
218 | for sub_orb in orb.orb_cluster:
219 | print(" orb%d"%sub_orb.id)
220 | print("<<<<<<")'''
221 |
222 | # construct circuits
223 | circuitList=[]
224 | for x in range(Lx):
225 | for y in range(Ly):
226 | for z in range(Lz):
227 | for circuit in localCircuitList:
228 | s1Info, s2Info, s3Info= circuit
229 | orb1, lat1= s1Info
230 | orb2, lat2= s2Info
231 | orb3, lat3= s3Info
232 | circuitList.append((lattice[(x+lat1[0])%Lx][(y+lat1[1])%Ly][(z+lat1[2])%Lz][orb1],
233 | lattice[(x+lat2[0])%Lx][(y+lat2[1])%Ly][(z+lat2[2])%Lz][orb2],
234 | lattice[(x+lat3[0])%Lx][(y+lat3[1])%Ly][(z+lat3[2])%Lz][orb3]))
235 | return lattice, lattice_flatten, orbGroup, circuitList
236 |
237 | def establishLinking(lattice,bondList,ki_s=0,ki_t=0,ki_overLat=[0,0,0],
238 | Lmatrix=np.array([[1,0,0],[0,1,0],[0,0,1]]),bmatrix=[np.array([0.,0.,0.])],
239 | dipoleAlpha=0,periodic=True):
240 | Lx=len(lattice)
241 | Ly=len(lattice[0])
242 | Lz=len(lattice[0][0])
243 | Lo=len(lattice[0][0][0])
244 |
245 | correlatedOrbitalPair=[]
246 | # uncode every orbitals
247 | for x in range(Lx):
248 | for y in range(Ly):
249 | for z in range(Lz):
250 | for o in range(Lo):
251 | # start linking type1: normal bond
252 | sourceOrb=lattice[x][y][z][o]
253 | for bond in bondList:
254 | if o==bond.source:
255 | if not periodic:
256 | if (x+bond.overLat[0])%Lx!=x+bond.overLat[0] or (y+bond.overLat[1])%Ly!=y+bond.overLat[1] or (z+bond.overLat[2])%Lz!=z+bond.overLat[2]:
257 | continue
258 | targetOrb=lattice[(x+bond.overLat[0])%Lx][(y+bond.overLat[1])%Ly][(z+bond.overLat[2])%Lz][bond.target]
259 | distance=(bond.overLat+bmatrix[bond.target]-bmatrix[o])@Lmatrix
260 | sourceOrb.addLinking(targetOrb,bond.strength,distance)
261 | if sourceOrb.id!=targetOrb.id:
262 | targetOrb.addLinking(sourceOrb,bond.invStrength,-distance)
263 | # type2: bond in renormalized system
264 |
265 | if sourceOrb.chosen:
266 | for bond in bondList:
267 | if o==bond.source:
268 | targetOrb=lattice[(x+bond.overLat[0]*2)%Lx][(y+bond.overLat[1]*2)%Ly][(z+bond.overLat[2]*2)%Lz][bond.target]
269 | sourceOrb.addLinking_rnorm(targetOrb,bond.strength)
270 | if sourceOrb.id!=targetOrb.id:
271 | targetOrb.addLinking_rnorm(sourceOrb,bond.invStrength)
272 | # save the correlated orbital pairs
273 | correlatedOrbitalPair.append([lattice[x][y][z][ki_s].id, lattice[(x+ki_overLat[0])%Lx][(y+ki_overLat[1])%Ly][(z+ki_overLat[2])%Lz][ki_t].id])
274 |
275 | # after process
276 | '''
277 | On=bondList[0].On
278 | for x in range(Lx):
279 | for y in range(Ly):
280 | for z in range(Lz):
281 | for o in range(Lo):
282 | lattice[x][y][z][o].classifyTheLinking(On=On)
283 | '''
284 | return correlatedOrbitalPair
285 |
286 | def generateDipoleBondings(lattice,dipoleAlpha,On=1):
287 | # long-range dipole coupling
288 | print("Dipole interaction factor %.6f larger than 1e-5, try to construct dipole couplings, note open border condition is employed for dipole interactions"%dipoleAlpha)
289 | for sourceOrb in lattice:
290 | for targetOrb in lattice:
291 | if sourceOrb.id==targetOrb.id:
292 | continue
293 | r12=sourceOrb.r-targetOrb.r
294 | r12_len=np.sqrt(np.dot(r12,r12))
295 | r12_n=r12/r12_len
296 | if On==1: # Ising type only AFM part
297 | dipole_AFM=dipoleAlpha/r12_len**3
298 | sourceOrb.addLinking(targetOrb,dipole_AFM,forceAdd=True)
299 | continue
300 | x,y,z=r12_n
301 | dipole_AFM=(dipoleAlpha/r12_len**3)*np.eye(3)
302 | dipole_FM=(-3*dipoleAlpha/r12_len**3)*np.array([[x*x,x*y,x*z],
303 | [y*x,y*y,y*z],
304 | [z*x,z*y,z*z]])
305 | sourceOrb.addLinking(targetOrb,dipole_AFM+dipole_FM,forceAdd=True)
306 | print("Error reported by Lattice.py::establishLinking Now dipole interaction for On(2/3) model consists of non-diagonal coupling elements, which is still in development. Therefore, let's stop here.")
307 | exit()
308 | print("dipole coupling established")
309 |
310 | def plotLattice(lattice):
311 | '''
312 | uncode the lattice pack and print each orbital on screen
313 | '''
314 | f=Figure()
315 | ax=f.add_subplot(111)
316 | for x in lattice:
317 | for y in x:
318 | for z in y:
319 | for o in z:
320 | ax.scatter(o.x,o.y,color='blue')
321 | ax.annotate(o.id,(o.x,o.y),size=10.5)
322 | for target in o.linkedSite:
323 | ax.plot([o.x,target.x],[o.y,target.y],color='red')
324 | f.show()
325 |
326 |
--------------------------------------------------------------------------------
/mcsolver/WannierKit.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018 12 8
3 |
4 | @author: Andrew
5 | '''
6 | import numpy as np
7 | from time import time
8 | from matplotlib.figure import Figure
9 | import matplotlib.pyplot as plt
10 | try:
11 | from . import auxiliary as aux
12 | except:
13 | import auxiliary as aux
14 |
15 | class TBmodel(object):
16 | Ham=[]
17 | Ham_k=[]
18 | lattice=[]
19 | reci_lattice=[]
20 | norbital=0
21 | orbital_coor=[]
22 | spin_list=[]
23 | onsite_energy=[]
24 |
25 | nhoppings=0
26 | hopping=[]
27 |
28 | kpath=[]
29 | kmesh=[]
30 |
31 | wcc_path=[]
32 | wcc_polar_direction=-1
33 | nelectrons=-1
34 |
35 | def __init__(self):
36 | pass
37 |
38 | def make_supercell(self,sc_dir0=[1.,1.,0.],sc_dir1=[1.,-1.,0.],sc_dir2=[0.,0.,1.],toHome=True):
39 | '''
40 | construct a supercell model.
41 | often used with slab fun. to get slab model with chosen border.
42 | '''
43 | Tmatrix=np.array([sc_dir0,sc_dir1,sc_dir2]) # sc_lat = T dot lat
44 | invTmatrix=np.linalg.inv(Tmatrix) # lat = invT dot sc_lat
45 | # construct lattice matrix for supercell
46 | sc_lattice=np.dot(Tmatrix,self.lattice)
47 |
48 | # construct orbitals for supercell
49 | R0max=int(np.max(abs(Tmatrix[:,0])))
50 | R1max=int(np.max(abs(Tmatrix[:,1])))
51 | R2max=int(np.max(abs(Tmatrix[:,2])))
52 |
53 | ### find which sub-cell is interior, just check the origins
54 | interior_cell_list=[]
55 | interior_cell_coor=[]
56 | for a0 in range(-R0max,R0max+1):
57 | for a1 in range(-R1max,R1max+1):
58 | for a2 in range(-R2max,R2max+1):
59 | ori_lat=np.array([a0,a1,a2])
60 | ori_sc_lat=np.dot(ori_lat,invTmatrix)
61 | interior=True
62 | for ori_coor in ori_sc_lat:
63 | if(ori_coor<0 or ori_coor>=1):
64 | interior=False
65 | if(interior):
66 | interior_cell_list.append(ori_lat)
67 | interior_cell_coor.append(ori_sc_lat)
68 |
69 | ### now add every orbs and their attributes
70 | sc_orbital_coor=[]
71 | onsite_energy=[]
72 | norbital=0
73 |
74 | hopping=[]
75 | nhoppings=0
76 | for iinter_cell, interior_cell in enumerate(interior_cell_list):
77 | for iorb0, orb0 in enumerate(self.orbital_coor):
78 | # add coordinates
79 | orb_sc=np.dot(orb0[0]+interior_cell,invTmatrix)
80 | sc_orbital_coor.append([orb_sc,orb0[1],orb0[2],orb0[3]])
81 | norbital+=1
82 | # add hopping
83 | for hopping_ele in self.hopping:
84 | if(hopping_ele[0]==iorb0):
85 | iorb0_sc=iinter_cell*self.norbital+iorb0
86 | #hopping_orb0=[iorb0_sc]
87 | iorb1, aug_vec, amplify, color, linewidth= hopping_ele[1], hopping_ele[2], hopping_ele[3], hopping_ele[4], hopping_ele[5]
88 | #print('iorb0, iorb1:', iorb0, iorb1, 'aug_vec:',aug_vec)
89 | orb1_cell_ori=interior_cell+aug_vec # the origin coordinates (a1,a2,a3 lattice)
90 | orb1_cell_ori_sc=np.dot(orb1_cell_ori,invTmatrix) # in supercell lattice
91 | orb1_cell_ori_sc_reduced=orb1_cell_ori_sc%1 # reduced by 1
92 | aug_vec_sc=orb1_cell_ori_sc-orb1_cell_ori_sc_reduced # aug vector in supercell frame
93 | # check which level is reached
94 | for iori_coor, ori_coor in enumerate(interior_cell_coor):
95 | if(ori_coor==orb1_cell_ori_sc_reduced).all():
96 | iorb1_sc=iori_coor*self.norbital+iorb1
97 | break
98 | #print('SC: iorb0, iorb1:', iorb0_sc, iorb1_sc, 'aug_vec:',aug_vec_sc)
99 | hopping_orb0=[iorb0_sc, iorb1_sc, aug_vec_sc, amplify, color, linewidth]
100 | hopping.append(hopping_orb0)
101 | nhoppings+=1
102 |
103 | self.lattice=sc_lattice
104 | self.orbital_coor=sc_orbital_coor
105 | self.norbital=norbital
106 | self.onsite_energy=onsite_energy
107 | self.nhoppings=nhoppings
108 | self.hopping=hopping
109 | if toHome:
110 | self.toHome()
111 |
112 | def toHome(self):
113 | '''move all coordinates to the home cell'''
114 | for iorb, orb in enumerate(self.orbital_coor):
115 | orb_reduced=orb[0]%1
116 | orb_shift=orb_reduced-orb[0]
117 | if (orb_shift).any():
118 | #print(orb,orb_shift)
119 | # update orb
120 | orb[0]%=1
121 | # update the hoppings
122 | for hopping in self.hopping:
123 | # hopping start with orb
124 | if(hopping[0]==iorb):
125 | hopping[2]+=orb_shift
126 | if(hopping[1]==iorb):
127 | hopping[2]-=orb_shift
128 |
129 | def viewStructure(self):
130 | '''visualize the orbital and bonding's spatial configuration'''
131 | f=Figure(figsize=(3,3))
132 | ax=f.add_subplot(111,projection='3d')
133 |
134 | def dragLineWithTwoPoints(pt0, pt1, c='black', linewidth=2):
135 | ax.plot([pt0[0],pt1[0]],[pt0[1],pt1[1]],[pt0[2],pt1[2]],c=c, linewidth=linewidth)
136 |
137 | # draw the boder of unit cell
138 | pt0=np.zeros(3)
139 | a1,a2,a3=self.lattice[0],self.lattice[1],self.lattice[2]
140 | ax.text(a1[0],a1[1],a1[2],'$a_1$')
141 | ax.text(a2[0],a2[1],a2[2],'$a_2$')
142 | ax.text(a3[0],a3[1],a3[2],'$a_3$')
143 |
144 | dragLineWithTwoPoints(pt0,a1)
145 | #dragLineWithTwoPoints(a1,a1+a2)
146 | #dragLineWithTwoPoints(a1+a2,a2)
147 | dragLineWithTwoPoints(pt0,a2)
148 |
149 | #dragLineWithTwoPoints(a3,a1+a3)
150 | #dragLineWithTwoPoints(a1+a3,a1+a2+a3)
151 | #dragLineWithTwoPoints(a1+a2+a3,a2+a3)
152 | #dragLineWithTwoPoints(a3,a2+a3)
153 |
154 | dragLineWithTwoPoints(pt0,a3)
155 | #dragLineWithTwoPoints(a1,a1+a3)
156 | #dragLineWithTwoPoints(a2,a2+a3)
157 | #dragLineWithTwoPoints(a1+a2,a1+a2+a3)
158 |
159 | for iorb, orb in enumerate(self.orbital_coor):
160 | if iorb>=50:
161 | print('num. of orb >=50, some orbs will not be illustrated')
162 | break
163 | orb_xyz=np.dot(orb[0],self.lattice)
164 | ax.scatter(orb_xyz[0],orb_xyz[1],orb_xyz[2],c=orb[2],s=orb[1])
165 | #ax.text(orb_xyz[0],orb_xyz[1],orb_xyz[2],str(iorb))
166 |
167 | for ihopping, hopping in enumerate(self.hopping):
168 | if ihopping>=200:
169 | print('num. of hopping >=200, some hoppings will not be illustrated')
170 | break
171 | iorb0, iorb1, Rextra, amp, color, linewidth=hopping[0], hopping[1], hopping[2], hopping[3], hopping[4], hopping[5]
172 | if np.dot(Rextra,Rextra)>0:
173 | continue
174 | orb0_xyz=np.dot(self.orbital_coor[iorb0][0],self.lattice)
175 | orb1_xyz=np.dot((self.orbital_coor[iorb1][0]+Rextra),self.lattice)
176 | dragLineWithTwoPoints(orb0_xyz,orb1_xyz,c=color,linewidth=linewidth)
177 |
178 | ax.set_xticks([])
179 | ax.set_yticks([])
180 | ax.set_zticks([])
181 | ax.grid(False)
182 | ax.axis('off')
183 | return f, ax
184 |
185 | def viewStructure_maya(self,ax):
186 | '''visualize the orbital and bonding's spatial configuration'''
187 |
188 | def dragLineWithTwoPoints(pt0, pt1, c=(0,0,0), linewidth=None):
189 | ax.plot3d([pt0[0],pt1[0]],[pt0[1],pt1[1]],[pt0[2],pt1[2]], color=c, tube_radius=linewidth)
190 |
191 | # draw the boder of unit cell
192 | pt0=np.zeros(3)
193 | a1,a2,a3=self.lattice[0],self.lattice[1],self.lattice[2]
194 |
195 | ax.quiver3d(*pt0,*a1,color=(0,0,0),line_width=20,mode='2darrow')
196 | ax.quiver3d(*pt0,*a2,color=(0,0,0),line_width=20,mode='2darrow')
197 | ax.quiver3d(*pt0,*a3,color=(0,0,0),line_width=20,mode='2darrow')
198 | time0=time()
199 | for iorb, orb in enumerate(self.orbital_coor):
200 | #if iorb>=50:
201 | # print('num. of orb >=50, some orbs will not be illustrated')
202 | # break
203 | orb_xyz=orb[0]@self.lattice
204 | ax.points3d(orb_xyz[0],orb_xyz[1],orb_xyz[2],color=orb[2],scale_factor=orb[1],mode='sphere')#,s=orb[1])
205 | ax.quiver3d(*orb_xyz,*orb[3],color=(0,0,1),mode='arrow')
206 | #ax.text(orb_xyz[0],orb_xyz[1],orb_xyz[2],str(iorb))
207 | print("Draw orbitals and mag.moms.: %.3fs"%(time()-time0))
208 | time0=time()
209 | for ihopping, hopping in enumerate(self.hopping):
210 | #if ihopping>=200:
211 | # print('num. of hopping >=200, some hoppings will not be illustrated')
212 | # break
213 | iorb0, iorb1, Rextra, amp, color, linewidth=hopping[0], hopping[1], hopping[2], hopping[3], hopping[4], hopping[5]
214 | if np.dot(Rextra,Rextra)>0:
215 | continue
216 | orb0_xyz=np.dot(self.orbital_coor[iorb0][0],self.lattice)
217 | orb1_xyz=np.dot((self.orbital_coor[iorb1][0]+Rextra),self.lattice)
218 | dragLineWithTwoPoints(orb0_xyz,orb1_xyz,c=color,linewidth=linewidth)
219 | print("Draw couplings: %.3fs"%(time()-time0))
220 |
221 | def genReciLattice(self):
222 | # generate the 3rd lattice vector if input 2D model
223 | def antiSymmMatrix(a):
224 | return np.array([
225 | [ 0 ,-a[2], a[1]],
226 | [ a[2], 0 ,-a[0]],
227 | [-a[1], a[0], 0 ]
228 | ])
229 |
230 | if(len(self.lattice)==2):
231 | a1=np.concatenate((self.lattice[0],[0.]))
232 | a2=np.concatenate((self.lattice[1],[0.]))
233 | a3=np.array([0.,0.,1.])
234 | self.lattice=np.array([a1,a2,a3])
235 | a1=self.lattice[0]
236 | a2=self.lattice[1]
237 | a3=self.lattice[2]
238 |
239 | V=np.abs(np.dot(np.dot(antiSymmMatrix(a1),a2),a3))
240 |
241 | b1=np.dot(antiSymmMatrix(a2),a3)
242 | b2=np.dot(antiSymmMatrix(a3),a1)
243 | b3=np.dot(antiSymmMatrix(a1),a2)
244 |
245 | b1*=2*np.pi/V
246 | b2*=2*np.pi/V
247 | b3*=2*np.pi/V
248 | self.reci_lattice=np.array([b1,b2,b3])
249 |
250 | def fixHopping(self):
251 | '''
252 | throw redundant hoppings and add hoppings accordingto time-reversal-symmetry (TRS)
253 | '''
254 | perfect_hoppings=[]
255 | def redundantless(hop_check):
256 | for hop_ref in perfect_hoppings:
257 | if(hop_check[0]==hop_ref[0] and hop_check[1]==hop_ref[1] and\
258 | (hop_check[2]==hop_ref[2]).all()):
259 | if(abs(hop_check[3]-hop_ref[3])>0.01):
260 | print ('WARNING: hoppings brreaks time-reversal symmetry!')
261 | return False
262 | return True
263 | for hopping in self.hopping:
264 | if redundantless(hopping):
265 | perfect_hoppings.append(hopping)
266 | # TRS
267 | hasTRS=False
268 | if(hopping[0]!=hopping[1]):
269 | hasTRS=True
270 | elif(np.dot(hopping[2],hopping[2])>0.01):
271 | hasTRS=True
272 | if(hasTRS):
273 | tr_hopping=[hopping[1],hopping[0],-hopping[2],hopping[3]]
274 | if redundantless(tr_hopping):
275 | perfect_hoppings.append(tr_hopping)
276 | self.hopping=perfect_hoppings
277 |
278 | def constructHam(self):
279 | '''
280 | construct real-space Hamiltonian'''
281 | # firstly, construct the architecture
282 | self.Ham=[]
283 | for origin_orbital_index in range(self.norbital):
284 | hopping_tmp=[]
285 | for destiny_orbital_index in range(self.norbital):
286 | hopping_tmp.append([])
287 | self.Ham.append(hopping_tmp)
288 |
289 | # then import all hoppings
290 | for hopping in self.hopping:
291 | # source # target # overlat # t
292 | self.Ham[hopping[0]][hopping[1]].append([hopping[2],hopping[3]])
293 |
294 | def constructHk(self,kpt=[0.,0.,0.],debug=False):
295 | "Construct Hamiltonian for a certain k-point with reduced coordinates"
296 | if len(kpt)==2:
297 | kpt=list(kpt)
298 | kpt.append(0)
299 | kpt=np.array(kpt)
300 |
301 | Ham_k=[]
302 | for ibloch in range(self.norbital):
303 | Hk_tmp=[]
304 | for jbloch in range(self.norbital):
305 | matrix_element=0.
306 | for hopping in self.Ham[ibloch][jbloch]:
307 | matrix_element+=hopping[1]*np.exp(-2j*np.pi*np.dot(kpt,hopping[0]),dtype=complex)
308 |
309 | Hk_tmp.append(matrix_element)
310 | Ham_k.append(Hk_tmp)
311 | #if debug:
312 | # print(Ham_k)
313 | #print(self.onsite_energy)
314 | Ham_k=np.array(Ham_k)+self.onsite_energy*np.eye(self.norbital,dtype=complex)
315 |
316 | #if debug:
317 | # print(Ham_k)
318 | # exit()
319 | return Ham_k
320 |
321 | def solveHk(self,kpt=[0.,0.,0.],return_orb=False,debug=False):
322 | '''solve the eigen-values for a k-point with reduced coordinates,
323 | and return the eigen-vectors optionally
324 | '''
325 | #if debug:
326 | # print(kpt)
327 | # print(self.Ham)
328 | # exit()
329 | Ham_k=self.constructHk(kpt=kpt,debug=debug)
330 | #print(Ham_k)
331 | eig, vec = np.linalg.eigh(Ham_k,'U')
332 | #if debug: exit()
333 |
334 | if return_orb:
335 | return eig, vec
336 | else:
337 | return eig
338 |
339 | def genKPath(self,highSymK,nikpt):
340 | '''
341 | generate kpath between high-symmetry kpoints
342 | '''
343 | kpath=[]
344 | npath=len(highSymK)-1
345 | for ipath in range(npath):
346 | dk=(highSymK[ipath+1]-highSymK[ipath])/nikpt[ipath]
347 | for ikpt in range(nikpt[ipath]):
348 | kpath.append(ikpt*dk+highSymK[ipath])
349 | kpath.append(highSymK[npath])
350 | return kpath
351 |
352 | def autoGenerateKpath2D(self,nikpt=20):
353 | '''
354 | generate k-path automatically,
355 | only for 2D case, temporally
356 | Parameter(s):
357 | nikpt: represents the number of interval KPs between two high-symmetric KP
358 | '''
359 | b1=self.reci_lattice[0][:2]/2
360 | b2=self.reci_lattice[1][:2]/2
361 | b1b2=b1+b2
362 | # calc. coordinates of edge
363 | # in cartesian coor.
364 | factor=np.array([b1,b2])
365 | res=np.array([np.dot(b1,b1),np.dot(b2,b2)])
366 | K_cart=np.dot(np.linalg.inv(factor),res)
367 | # in reci-fractional coor.
368 | K0=np.dot(np.array([K_cart[0],K_cart[1],0.]),np.linalg.inv(self.reci_lattice))
369 |
370 | # another possible
371 | factor=np.array([b1,b1b2])
372 | res=np.array([np.dot(b1,b1),np.dot(b1b2,b1b2)])
373 | K_cart=np.dot(np.linalg.inv(factor),res)
374 | K1=np.dot(np.array([K_cart[0],K_cart[1],0.]),np.linalg.inv(self.reci_lattice))
375 |
376 | # chose the short one
377 | K=K0[:2] if np.dot(K0,K0)0 then only plot bands above and underneath half-filling for nfermi"
395 | "e.g., nfermi=1 then only the top valence band and lowest conducting band are plotted"
396 | self.constructHam()
397 | plt.figure()
398 | kpath=np.linspace(0,1,len(self.kpath))
399 | eig=[]
400 | for kpt in self.kpath:
401 | eig_list = self.solveHk(kpt=kpt,debug=True)
402 | eig.append(eig_list)
403 | #for eig in eig_list:
404 | # plt.scatter(ikpt,eig,color='black')
405 | eig=np.array(eig)
406 | if(nfermi==-1):
407 | for iband in range(self.norbital):
408 | plt.plot(kpath,eig[:,iband],color='black')
409 | else:
410 | lower=int(self.norbital/2-nfermi)
411 | higher=int(self.norbital/2+nfermi)
412 | for iband in range(lower,higher):
413 | plt.plot(kpath,eig[:,iband],color='black')
414 | plt.xlim(0,1)
415 | #plt.ylim(0,1.1*np.max(eig.flatten()))
416 | plt.xticks([])
417 | plt.savefig(path+'spectra.png',dpi=300)
418 | plt.close()
419 |
420 | def plot2DStructure(self,vec,Lx=1,Ly=1,kpt=np.array([0,0,0]),S=1.5):
421 | #print(self.orbital_coor)
422 | #print(self.lattice)
423 | #plt.figure()
424 | fout=open('./spinWave.txt','w')
425 | fout.write('#X Y Z dX dY dZ\n')
426 | for x in range(Lx):
427 | for y in range(Ly):
428 | R=np.array([x,y,0])
429 | blochPhase=2*np.pi*((kpt.dot(R))%1)
430 | #print('%d %d %.3f'%(x,y,blochPhase))
431 | for iorb, orb in enumerate(self.orbital_coor):
432 | subOrbPos=(orb[0]+R).dot(self.lattice)
433 |
434 | subOrbPhase=np.log(vec[iorb]/abs(vec[iorb])).imag if abs(vec[iorb])>1e-5 else 0
435 | #phi=(subOrbPhase+blochPhase)#*np.pi*2
436 | wycoffPhase=orb[0].dot(kpt)*2*np.pi
437 | phi=subOrbPhase+blochPhase+wycoffPhase
438 | theta=abs(vec[iorb])*0.5/S*np.pi*0.5
439 | nS=(np.sin(theta)*np.cos(phi),np.sin(theta)*np.sin(phi),np.cos(theta))
440 | #print('theta %.3f phi %.3f'%(theta,phi))
441 | #print(vec)
442 | fout.write('%.6f %.6f %.6f %.6f %.6f %.6f\n'%(*subOrbPos,*nS))
443 | #fout.write('%.6f %.6f %.6f %.6f\n'%(*subOrbPos,phi))
444 | #plt.scatter(subOrbPos[0],subOrbPos[1],c='black')
445 | #plt.annotate('%.3f'%(totalPhase/np.pi/2),(subOrbPos[0],subOrbPos[1]))
446 | #exit()
447 | #plt.show()
448 | fout.close()
449 |
--------------------------------------------------------------------------------
/mcsolver/__init__.py:
--------------------------------------------------------------------------------
1 | __version__="3.0.2"
2 | from . import win
3 | import os
4 |
5 | libpath=os.path.join(os.path.dirname(__file__),'lib')
6 | for lib in os.listdir(libpath):
7 | if 'ising' in lib:
8 | isingLibPath=os.path.join(libpath,lib)
9 | if 'xy' in lib:
10 | xyLibPath=os.path.join(libpath,lib)
11 | if 'heisenberg' in lib:
12 | heisenbergLibPath=os.path.join(libpath,lib)
13 |
14 | win.libPool=[isingLibPath,xyLibPath,heisenbergLibPath]
15 |
16 | def loadMC(rpath): # interface to core codes avoiding GUI
17 | win.startSimulation(updateGUI=False,rpath=rpath)
18 |
19 |
--------------------------------------------------------------------------------
/mcsolver/auxiliary.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2019 7 6
3 |
4 | @author: Andrew
5 | '''
6 | import numpy as np
7 | import os
8 | import shutil
9 |
10 | def getMSD(input,overavg=True,bestChoice=True,verbose=False):
11 | '''
12 | '''
13 | #check the shape
14 | shape=input.shape
15 | if(len(shape)==1):
16 | # the case of one line of data
17 | dim=int(shape[0])
18 | avg=1.*np.sum(input)/dim
19 | sd=0.
20 | diffList=[]
21 | for ele in input:
22 | diff=(ele-avg)*(ele-avg)
23 | diffList.append(diff)
24 | sd+=diff
25 | rmsd=np.sqrt(sd)/dim/abs(avg) if overavg else np.sqrt(sd)/dim
26 | if verbose:
27 | print('dimension is: %d'%dim)
28 | print('average is: %.6f'%avg)
29 | print('relative mean-squared-diff is: %.6f'%rmsd)
30 | if bestChoice:
31 | sortList=quicksort(diffList)
32 | if verbose:
33 | print('the best chois is:',input[sortList[0]],' with derviation: ', diffList[sortList[0]])
34 | return rmsd,sortList[0]
35 |
36 | elif(len(shape)==2):
37 | # the case of 2x2 matrix
38 | ncol=int(shape[1])
39 | rmsdList=[]
40 | bestChoiceList=[]
41 | for icol in range(ncol):
42 | rmsd,bestChoiceID=getMSD(input[:,icol],bestChoice=True,verbose=verbose)
43 | rmsdList.append(rmsd)
44 | bestChoiceList.append(bestChoiceID)
45 | if bestChoice:
46 | return rmsdList,bestChoiceList
47 | else:
48 | return rmsdList
49 | else:
50 | print('cannot handle data dimension >2')
51 | exit()
52 |
53 | def getCombination(inputList=[],ncomb=1):
54 | '''
55 | This function can generate combinations from extracted elements in
56 | inputList, e.g., if we want to select two elements from [1,2,3],
57 | they maybe either [1,2], [1,3] or [2,3], thus we can use this facility as
58 | comb=getCombination(inputList=[1,2,3],ncomb=2)
59 | then we can get a list of: [ [1,2], [1,3], [2,3] ]
60 |
61 | params definition:
62 | inputList: the pool of elements
63 | ncomb : num. of elements in combination
64 | '''
65 | #print 'conduct function'
66 | #print 'input:', inputList
67 | ntot=len(inputList)
68 | if(ncomb==1):
69 | result=[]
70 | for ele in inputList:
71 | result.append([ele])
72 | return result
73 | else:
74 | if(ncomb>ntot):
75 | print('Error: num. of combinations larger than input!')
76 | exit()
77 | else:
78 | result=[]
79 | for ihead in range(0,ntot-ncomb+1):
80 | headele=inputList[ihead]
81 | #print 'head element:',headele
82 | resList=list(inputList[ihead+1:ntot])
83 | #print 'reside list:',resList
84 | resCombList=getCombination(resList,ncomb=ncomb-1)
85 | for ele in resCombList:
86 | ele.insert(0,headele)
87 | #print 'ele',ele
88 | result.append(list(ele))
89 | #print 'ele',ele
90 | #result.append(result_head)
91 | return result
92 |
93 | def doesTheTwoListHaveSameNumber(list1,list2):
94 | for n1 in list1:
95 | for n2 in list2:
96 | if n1==n2:
97 | return True
98 | return False
99 |
100 | def findTheFirstSameNumberAmongTwoList(list1,list2): # if no same element presented, return -1
101 | for n1 in list1:
102 | for n2 in list2:
103 | if n1==n2:
104 | return n1
105 | return -1
106 |
107 | def improveTheMatrixRankToThree(mat:np.ndarray):
108 | if np.linalg.matrix_rank(mat)==3: return mat
109 |
110 | if np.linalg.matrix_rank(mat)==2:
111 | # try to fill one of the dimension
112 | for idim in range(3):
113 | mat_trial=np.array(list(mat))
114 | mat_trial[idim,idim]=1
115 | if np.linalg.matrix_rank(mat_trial)==3: return mat_trial
116 | raise('Fail to improve the matrix rank')
117 |
118 | if np.linalg.matrix_rank(mat)==1:
119 | for idim in range(2):
120 | for jdim in range(idim+1,3):
121 | mat_trial=np.array(list(mat))
122 | mat_trial[idim,idim]=1
123 | mat_trial[jdim,jdim]=1
124 | if np.linalg.matrix_rank(mat_trial)==3: return mat_trial
125 | raise('Fail to improve the matrix rank')
126 |
127 | class Node:
128 | def __init__(self,value=0,maxValue=9,leftNode=False):
129 | self.value=value
130 | self.maxValue=maxValue
131 | self.leftNode=leftNode
132 | def addone(self):
133 | self.value+=1
134 | if self.value>self.maxValue:
135 | # carry site
136 | if self.leftNode and self.leftNode.addone():
137 | self.value=self.leftNode.value+1
138 | else:
139 | return False
140 | if self.leftNode:
141 | self.leftNode.maxValue=self.value-1
142 | return True
143 |
144 | def getCombinationLoop(input_list=[],ncomb=1,maxComb=-1):
145 | totInput=len(input_list)
146 | index_list=[i for i in range(totInput)]
147 | # create linked list
148 | rootNode=Node(value=0,maxValue=totInput-1)
149 | for i in range(1,ncomb):
150 | node_i=Node(value=i,maxValue=totInput-1,leftNode=rootNode)
151 | rootNode=node_i
152 | # generate combination numbers in one loop
153 | def getTree(remoteNode):
154 | tree=[remoteNode.value]
155 | while(remoteNode.leftNode):
156 | tree.insert(0,remoteNode.leftNode.value)
157 | remoteNode=remoteNode.leftNode
158 | return tree
159 | comb_list=[[input_list[i] for i in getTree(rootNode)]]
160 | ncount=0
161 | while(rootNode.addone()):
162 | comb_list.append([input_list[i] for i in getTree(rootNode)])
163 | #print(getTree(rootNode))
164 | ncount+=1
165 | if maxComb>0 and ncount>=maxComb:
166 | break
167 | return comb_list
168 |
169 |
170 | def quicksort(input_list=[]):
171 | '''
172 | Sort the input list and return a sort index list
173 | e.g. we want to sort input_list = [1, 3, 2, 5, 0]
174 | then the function will return the sorted INDEX:
175 | output = [4, 0, 2, 1, 3]
176 | its first element is 4, since the lowest num. 0
177 | is at 4th position in original input_list, and so on
178 |
179 | WARNING: the input_list will also be changed forever.
180 | '''
181 | def __firstSort(input_list,sort_list,low,high):
182 | l=low;h=high
183 | split=input_list[low]
184 |
185 | while(lsplit):
187 | h-=1
188 |
189 | if(llow :
213 | __firstSort(input_list,sort_list,low,h-1)
214 |
215 | if h dir %s exist, skip'%path)
235 | #print('WARNING: %s exist'%path)
236 |
237 | def ls(path):
238 | try:
239 | return os.listdir(path)
240 | except OSError as err:
241 | print(err, '--> cannot find %s, stop'%path)
242 | exit()
243 |
244 | def cp(file_src, file_des):
245 | try:
246 | shutil.copy2(file_src,file_des)
247 | except IOError as err:
248 | print(err, '--> copy file %s to %s failed, stop'%(file_src,file_des))
249 | exit()
250 | #except FileNotFoundError as err:
251 | # print(err, '--> cannot find %s, stop'%file_src)
252 | # exit()
253 | #except shutil.SameFileError as err:
254 | # print(err, '--> %s and %s are the same file, skip'%(file_src,file_des))
255 |
256 | def rm(path,quiet=False):
257 | try:
258 | os.remove(path)
259 | except OSError as err:
260 | if not quiet: print(err, '--> remove file %s failed, skip'%path)
261 |
--------------------------------------------------------------------------------
/mcsolver/fileio.py:
--------------------------------------------------------------------------------
1 | from tkinter import filedialog
2 | from re import findall
3 | try:
4 | from . import guiMain as gui
5 | from . import win
6 | except:
7 | import guiMain as gui
8 | import win
9 |
10 | global LMatrix, LPack, pos, S, DList, h, H0, H1, nH, dipoleAlpha, bondList, T0, T1, nT, nthermal, nsweep, ninterval, xAxisType, modelType, algorithm, GcOrb, ncores, spinFrame
11 | global orbGroupList, groupInSC
12 | global localCircuitList # local circuit used to calculate the local topological charge
13 | # initial value
14 | xAxisType='T'
15 | orbGroupList=[]
16 | groupInSC=True
17 | GcOrb=[0,0,[0,0,0]]
18 | h=0
19 | H0,H1,nH=0,0,1
20 | dipoleAlpha=0
21 | spinFrame=0
22 | localCircuitList=[]
23 |
24 | def collectParam():
25 | global LMatrix, LPack, pos, S, DList, h, H0, H1, nH, dipoleAlpha, bondList, T0, T1, nT, nthermal, nsweep, ninterval, xAxisType, modelType, algorithm, GcOrb, ncores, spinFrame, localCircuitList
26 | # get lattice
27 | a1=gui.latticeGui[0].report()
28 | a2=gui.latticeGui[1].report()
29 | a3=gui.latticeGui[2].report()
30 | LMatrix=[a1,a2,a3]
31 | print('Lattice matrix:')
32 | print(a1)
33 | print(a2)
34 | print(a3)
35 |
36 | # get supercell size
37 | LPack=[int(x) for x in gui.supercellGui.report()]
38 | print('supercell:')
39 | print(LPack[0],LPack[1],LPack[2])
40 |
41 | # get oribtal position and spin state and onsite-anisotropy
42 | pos=[ele[3] for ele in gui.OrbListBox.infoData]
43 | S=[ele[2] for ele in gui.OrbListBox.infoData]
44 | DList=[ele[4] for ele in gui.OrbListBox.infoData]
45 | for ipos, iS, iD in zip(pos,S,DList):
46 | print('positions:',ipos,'Spin:',iS,'onsite-Anisotropy:',iD)
47 |
48 | # set field
49 | print('isotropic magnetic field is set to %.3f'%h)
50 |
51 | # get bonds
52 | bondList=[
53 | [bond_data[2][0],bond_data[2][1],\
54 | bond_data[2][2],\
55 | bond_data[1][0],bond_data[1][1],bond_data[1][2],bond_data[1][3],bond_data[1][4],bond_data[1][5],bond_data[1][6],bond_data[1][7],bond_data[1][8]]
56 | for bond_data in gui.BondBox.infoData
57 | ]
58 |
59 | print('bonds:')
60 | for ibond, bond in enumerate(bondList):
61 | print("ID %d: orb%d-orb%d [%d %d %d] J:"%(ibond,bond[0],bond[1],bond[2][0],bond[2][1],bond[2][2]))
62 | print(bond[3:])
63 | #print(bondList)
64 |
65 | # get TList
66 | T0, T1, nT=gui.TListGui.report()
67 | nT=int(nT)
68 | print('Temperature range: %.2f ~ %.2f with %d sampling points'%(T0, T1, nT))
69 |
70 | # get HList
71 | H0, H1, nH=gui.HListGui.report()
72 | nH=int(nH)
73 | print('Magnetic field range: %.2f ~ %.2f with %d sampling points'%(H0, H1, nH))
74 |
75 | # topological info.
76 | print('Local circuits per cell: %d'%len(localCircuitList))
77 | for icircuit, circuit in enumerate(localCircuitList):
78 | print("ID %d, enclosed by orb %d [%d %d %d], orb %d [%d %d %d], and orb %d [%d %d %d]"%(icircuit,circuit[0][0],*circuit[0][1],circuit[1][0],*circuit[1][1],circuit[2][0],*circuit[2][1]))
79 |
80 | # get thermalizations and sweeps
81 | nthermal, nsweep, ninterval= [int(x) for x in gui.MCparamGui.report()]
82 | print('thermalizations, sweeps and tau:')
83 | print(nthermal, nsweep, ninterval)
84 |
85 | # get model and algorithm
86 | xAxisType=gui.xAxisGui.get()
87 | print('X Axis is',xAxisType)
88 | modelType = gui.modelGui.get()
89 | print('Model:',modelType)
90 | algorithm = gui.algorithmGui.get()
91 | print('Algorithm:',algorithm)
92 |
93 | # get orb. info. for Gc calc.
94 | #print(gui.corrGui.report())
95 | s, t, v1, v2, v3 = [int(x) for x in gui.corrGui.report()]
96 | GcOrb=[[s,t],[v1,v2,v3]]
97 | print('Measure correlation between orb%d and orb%d with overLat: (%d, %d, %d)'%(s,t,v1,v2,v3))
98 |
99 | # get num. of output spin frames
100 | spinFrame=int(gui.spinFrameGui.report()[0])
101 | print('For each setting, %d frames of spin distribution in real space would be output'%spinFrame)
102 |
103 | # get ncores
104 | ncores= int(gui.coreGui.report()[0])
105 | print('using %d cores'%ncores)
106 |
107 | def saveParam():
108 | global LMatrix, LPack, pos, S, DList, h, H0, H1, nH, dipoleAlpha, bondList, T0, T1, nT, nthermal, nsweep, ninterval, xAxisType, modelType, algorithm, GcOrb, ncores, spinFrame
109 | collectParam()
110 | # write into files
111 | filePath=filedialog.asksaveasfilename()
112 | f=open(filePath,'w')
113 | f.write("This is mcsolver's save file, version: 3.0\n")
114 | f.write("Lattice:\n")
115 | a1, a2, a3= LMatrix
116 | f.write("%.9f %.9f %.9f\n"%(a1[0],a1[1],a1[2]))
117 | f.write("%.9f %.9f %.9f\n"%(a2[0],a2[1],a2[2]))
118 | f.write("%.9f %.9f %.9f\n"%(a3[0],a3[1],a3[2]))
119 | f.write("Supercell used in MC simulations:\n")
120 | Lx, Ly, Lz=LPack
121 | f.write("%d %d %d\n"%(Lx,Ly,Lz))
122 | f.write("Orbitals in cell:\n")
123 | f.write("%d\n"%len(pos))
124 | f.write("Positions, initial spin states and onsite-anisotropy of every orbital:\n")
125 | for ele in gui.OrbListBox.infoData:
126 | f.write("orb %d: type %d spin %.9f pos [%.9f %.9f %.9f] Dx %.9f Dy %.9f Dz %.9f h %.9f\n"%(ele[0],ele[1],ele[2],\
127 | ele[3][0],ele[3][1],ele[3][2],\
128 | ele[4][0],ele[4][1],ele[4][2],h))
129 | f.write("Bonds:\n")
130 | f.write("%d\n"%len(bondList))
131 | f.write("id, source, target, overLat, exchange matrix elements of each bond:\n")
132 | for bond_data in gui.BondBox.infoData:
133 | f.write("bond %d: Jx %.9f Jy %.9f Jz %.9f Jxy %.9f Jxz %.9f Jyz %.9f Jyx %.9f Jzx %.9f Jzy %.9f orb %d to orb %d over [%d %d %d]\n"%\
134 | (bond_data[0],\
135 | bond_data[1][0],bond_data[1][1],bond_data[1][2],bond_data[1][3],bond_data[1][4],bond_data[1][5],bond_data[1][6],bond_data[1][7],bond_data[1][8],\
136 | bond_data[2][0],bond_data[2][1],bond_data[2][2][0],bond_data[2][2][1],bond_data[2][2][2]\
137 | ))
138 |
139 | f.write("Temperature scanning region:\n")
140 | f.write("Tmin %.9f Tmax %.9f nT %d\n"%(T0, T1, nT))
141 | f.write("Field scanning region (in unit 1.48872 T, only if Kelvin and uB is used for energy and spin):\n")
142 | f.write("Hmin %.9f Hmax %.9f nH %d\n"%(H0, H1, nH))
143 | f.write("Dipole long-range coupling:\n")
144 | f.write("alpha %.6f\n"%dipoleAlpha)
145 | f.write("Measurement:\n")
146 | f.write("measure the correlation function between orb%d and orb%d over [%d %d %d]\n"%(GcOrb[0][0],GcOrb[0][1],GcOrb[1][0],GcOrb[1][1],GcOrb[1][2]))
147 | f.write("Supergroup\n")
148 | f.write("OrbGroup:1\n")
149 | f.write("Supergroup\n")
150 | f.write("group0 orb0-orb0\n")
151 | f.write(">>> Topological section <<<\n")
152 | f.write("LocalCircuit per cell: %d (set to 0 to skip the calc. for topo. Q)\n"%len(localCircuitList))
153 | for icircuit, circuit in enumerate(localCircuitList):
154 | f.write("Circuit %d enclosed by orb %d [%d %d %d], orb %d [%d %d %d], and orb %d [%d %d %d]\n"%(icircuit,circuit[0][0],*circuit[0][1],circuit[1][0],*circuit[1][1],circuit[2][0],*circuit[2][1]))
155 | f.write(">>> End of Topological section <<<\n")
156 | f.write("Distribution output frame: %d\n"%spinFrame)
157 | f.write("Sweeps for thermalization and statistics, and relaxiation step for each sweep:\n")
158 | f.write("%d %d %d\n"%(nthermal, nsweep, ninterval))
159 | f.write("XAxis type:\n")
160 | f.write(xAxisType+'\n')
161 | f.write("Model type:\n")
162 | f.write(modelType+'\n')
163 | f.write("Algorithm:\n")
164 | f.write(algorithm+'\n')
165 | f.write("Ncores:\n")
166 | f.write("%d\n"%ncores)
167 | f.close()
168 |
169 | def loadParam(updateGUI=True,rpath='./mcInput'):
170 | global LMatrix, LPack, pos, S, DList, h, bondList, T0, T1, nT, H0, H1, nH, dipoleAlpha, nthermal, nsweep, ninterval, xAxisType, modelType, algorithm, GcOrb, ncores, spinFrame
171 | global orbGroupList, groupInSC, localCircuitList
172 | filePath=filedialog.askopenfilename() if updateGUI else rpath
173 | f=open(filePath,'r')
174 | data=[line for line in f.read().split('\n') if line]
175 | f.close()
176 | # load version info.
177 | version=findall(r"[0-9\.]+",data[0])[0]
178 | if version!=str(win.settingFileVersion):
179 | print("unknown file or version (only support v%s)"%str(win.settingFileVersion))
180 | return False
181 |
182 | # decide position of each tag
183 | tagLattice=tagSupercell=tagOrbitals=tagBonds=tagTemperature=tagSweeps=tagModel=tagAlgorithm=tagNcores=tagDipole=tagField=tagTopo=0
184 | for iline, line in enumerate(data):
185 | keyword=findall(r"[a-zA-Z]+",line)
186 | if len(keyword)==0:
187 | continue
188 | if keyword[0]=='Lattice':
189 | tagLattice=iline
190 | if keyword[0]=='Supercell':
191 | tagSupercell=iline
192 | if keyword[0]=='Orbitals':
193 | tagOrbitals=iline
194 | if keyword[0]=='Bonds':
195 | tagBonds=iline
196 | if keyword[0]=='Temperature':
197 | tagTemperature=iline
198 | if keyword[0]=='Field':
199 | tagField=iline
200 | if keyword[0]=='Dipole':
201 | tagDipole=iline
202 | if keyword[0]=='Sweeps':
203 | tagSweeps=iline
204 | if keyword[0]=='Model':
205 | tagModel=iline
206 | if keyword[0]=='Algorithm':
207 | tagAlgorithm=iline
208 | if keyword[0]=='Measurement':
209 | tagMesurement=iline
210 | if keyword[0]=='OrbGroup':
211 | tagOrbGroup=iline
212 | if keyword[0]=='Ncores':
213 | tagNcores=iline
214 | if keyword[0]=='Distribution':
215 | tagDistribution=iline
216 | if keyword[0]=='XAxis':
217 | tagXAxis=iline
218 | if keyword[0]=='LocalCircuit':
219 | tagTopo=iline
220 |
221 | if tagLattice*tagSupercell*tagOrbitals*tagBonds*tagTemperature*tagSweeps*tagModel*tagAlgorithm*tagNcores*tagField*tagDipole*tagDistribution*tagXAxis*tagOrbGroup*tagTopo==0:
222 | print("cannot find some tags")
223 | return False
224 |
225 | # load lattice
226 | LMatrix=[[float(x) for x in findall(r"[0-9\.\-]+",data[tagLattice+1+i])] for i in range(3)]
227 | # load supercell
228 | LPack=[int(x) for x in findall(r"[0-9]+",data[tagSupercell+1])]
229 | # load orbitals
230 | norb=int(findall(r"[0-9]+",data[tagOrbitals+1])[0])
231 | orbInfo=[]
232 | pos=[]
233 | S=[]
234 | DList=[]
235 | for i in range(norb):
236 | ele=findall(r"[0-9\.\-]+",data[tagOrbitals+3+i])
237 | orbInfo.append([int(ele[0]),int(ele[1]),float(ele[2]),\
238 | (float(ele[3]),float(ele[4]),float(ele[5])),\
239 | (float(ele[6]),float(ele[7]),float(ele[8]))])
240 | pos.append([float(ele[3]),float(ele[4]),float(ele[5])])
241 | S.append(float(ele[2]))
242 | DList.append([float(ele[6]),float(ele[7]),float(ele[8])])
243 |
244 | # load bonds
245 | nbonds=int(findall(r"[0-9]+",data[tagBonds+1])[0])
246 | bondInfo=[]
247 | bondList=[]
248 | for i in range(nbonds):
249 | ele=findall(r"[0-9\.\-]+",data[tagBonds+3+i])
250 | bondInfo.append([int(ele[0]),
251 | [float(ele[1]),float(ele[2]),float(ele[3]),float(ele[4]),float(ele[5]),float(ele[6]),float(ele[7]),float(ele[8]),float(ele[9])],
252 | [int(ele[10]),int(ele[11]),(int(ele[12]),int(ele[13]),int(ele[14]))]
253 | ])
254 | # source target [overlat. ] Jz Jx Jy Jxy Jxz Jyz Jyx Jzy Jzx
255 | bondList.append([int(ele[10]),int(ele[11]),[int(ele[12]),int(ele[13]),int(ele[14])],float(ele[1]),float(ele[2]),float(ele[3]),float(ele[4]),float(ele[5]),float(ele[6]),float(ele[7]),float(ele[8]),float(ele[9])])
256 |
257 | # load mesurements
258 | GcPack=findall(r'[0-9\-]+',data[tagMesurement+1])
259 | s, t, v1, v2, v3 = [int(x) for x in GcPack]
260 | GcOrb=[[s,t],[v1,v2,v3]]
261 |
262 | nOrbGroup=int(findall(r"[0-9]+",data[tagOrbGroup])[0])
263 | groupInSC=True if data[tagOrbGroup+1]=='Supergroup' else False
264 | orbGroupList=[]
265 | for i in range(nOrbGroup):
266 | _, orbID0, orbID1 = findall(r"[0-9]+",data[tagOrbGroup+i+2])
267 | orbGroupList.append([j for j in range(int(orbID0),int(orbID1)+1)])
268 |
269 | # load topological circuits
270 | # load bonds
271 | nCircuits=int(findall(r"[0-9]+",data[tagTopo])[0])
272 | localCircuitList=[]
273 | for icircuit in range(nCircuits):
274 | ele=[int(x) for x in findall(r"[0-9\-]+",data[tagTopo+1+icircuit])]
275 | # S1 id S1 overLat S2 id S2 overLat S3 id S3 overLat
276 | circuit_data_packed=[(ele[1],(ele[2],ele[3],ele[4],)),(ele[5],(ele[6],ele[7],ele[8],)),(ele[9],(ele[10],ele[11],ele[12],)),]
277 | localCircuitList.append(circuit_data_packed)
278 |
279 | # load other parameters
280 | Tpack=findall(r"[0-9\.]+",data[tagTemperature+1])
281 | T0, T1, nT = float(Tpack[0]), float(Tpack[1]), int(Tpack[2])
282 | Hpack=findall(r'[0-9\.\-]+',data[tagField+1])
283 | H0, H1, nH = float(Hpack[0]), float(Hpack[1]), int(Hpack[2])
284 | dipoleAlpha=float(findall(r'[0-9\.\-]+',data[tagDipole+1])[0])
285 | spinFrame=int(findall(r'[0-9]+',data[tagDistribution])[0])
286 | nTermSweep=findall(r"[0-9\.\-]+",data[tagSweeps+1])
287 | nthermal, nsweep, ninterval=[int(x) for x in nTermSweep]
288 | xAxisType=data[tagXAxis+1]
289 | modelType=data[tagModel+1]
290 | algorithm=data[tagAlgorithm+1]
291 | _ncores=[int(data[tagNcores+1])]
292 | ncores=_ncores[0]
293 |
294 | if not updateGUI:
295 | return True
296 | # update gui window
297 | for i in range(3):
298 | gui.latticeGui[i].setValue([float(x) for x in LMatrix[i]])
299 | gui.updateLatticeData()
300 | gui.supercellGui.setValue(LPack)
301 | gui.OrbListBox.updateInfo(orbInfo)
302 | gui.BondBox.updateInfo(bondInfo)
303 | gui.TListGui.setValue(Tpack)
304 | gui.HListGui.setValue(Hpack)
305 | gui.corrGui.setValue(GcPack)
306 | gui.MCparamGui.setValue(nTermSweep)
307 | gui.xaxisStr.set(xAxisType)
308 | gui.modelStr.set(modelType)
309 | gui.algoStr.set(algorithm)
310 | gui.spinFrameGui.setValue([spinFrame])
311 | gui.coreGui.setValue(_ncores)
312 | gui.updateStructureViewer()
313 | return True
314 |
--------------------------------------------------------------------------------
/mcsolver/guiMain.py:
--------------------------------------------------------------------------------
1 | from tkinter import Label, LabelFrame, Frame, Spinbox, Button, END, VERTICAL, N, S, W, E, StringVar, filedialog, Toplevel
2 | from multiprocessing import cpu_count
3 | from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg#,NavigationToolbar2Tk
4 | from matplotlib.figure import Figure
5 | from mpl_toolkits.mplot3d.axes3d import Axes3D
6 | from re import findall, match
7 | import numpy as np
8 | try:
9 | from . import toolbox as toolbox
10 | from . import WannierKit as wan
11 | from . import fileio as io
12 | except:
13 | import toolbox as toolbox
14 | import WannierKit as wan
15 | import fileio as io
16 |
17 | global gui # root gui
18 | global latticeGui, supercellGui, latticeData # read lattice matrix
19 | global nOrbnBondGui, nOrb, nBonds # read number of orbitals and bonds
20 |
21 | global OrbListBox, IDandTypeNote, PosNote, AnisotropyNote
22 | global BondBox, IDandTypeOfBondNote, BondDetailNote
23 |
24 | global TlistGui, HListGui, MCparamGui, xaxisStr, xAxisGui, modelGui, modelStr, algorithmGui, algoStr, corrGui, spinFrameGui, coreGui
25 | global resultViewerBase, resultViewer, structureFrame, structureViewer, structureAxis
26 | global submitBtn
27 |
28 | #gui=tk.Tk(className='mc solver v0.0.1')
29 |
30 | ###################
31 | # latice settings #
32 | ###################
33 |
34 | def loadLatticePannel():
35 | global gui, latticeGui, supercellGui
36 | LatticeFrame=LabelFrame(gui,text='Lattice')
37 | LatticeFrame.grid(row=0,column=0)
38 |
39 | f=Figure(figsize=(3.2,0.4))
40 | ax=f.add_subplot(1,1,1)
41 | ax.axis('off')
42 | ax.text(-0.15,0.4,r"$H=\sum_{m\neq n,\alpha\beta}J_{mn}^{\alpha\beta} S_m^\alpha S_n^\beta + \sum_{m\alpha} D_m^\alpha(S_m^\alpha S_m^\alpha)$")
43 | Hamiltonian=FigureCanvasTkAgg(f,LatticeFrame)
44 | Hamiltonian.draw()
45 | Hamiltonian.get_tk_widget().grid(row=0,column=0,columnspan=2)
46 |
47 | #HamiltonianLable=Label(LatticeFrame,text=r"$H=\sum_{ij}J_{i,j}S_i\dotS_j + \sum_i D_i(S_i\dot S_i)$")
48 | #HamiltonianLable.grid(row=0,column=0,columnspan=2)
49 |
50 | a0_base=Frame(LatticeFrame)
51 | noteFrame0=toolbox.NoteFrm(a0_base, init_notes=['a1:','',''],init_data=[1,0,0],row=True)
52 | a0_base.grid(row=1,column=0)
53 |
54 | a1_base=Frame(LatticeFrame)
55 | noteFrame1=toolbox.NoteFrm(a1_base, init_notes=['a2:','',''],init_data=[0,1,0],row=True)
56 | a1_base.grid(row=2,column=0)
57 |
58 | a2_base=Frame(LatticeFrame)
59 | noteFrame2=toolbox.NoteFrm(a2_base, init_notes=['a3:','',''],init_data=[0,0,1],row=True)
60 | a2_base.grid(row=3,column=0)
61 |
62 | latticeGui=[noteFrame0,noteFrame1,noteFrame2]
63 |
64 | supercell_base=Frame(LatticeFrame)
65 | supercellGui=toolbox.NoteFrm(supercell_base,init_notes=['SC:','x','x'],init_data=[16,16,1],row=True,entryWidth=3)
66 | supercell_base.grid(row=1,column=1,sticky='SE')
67 |
68 | def updateLatticeData():
69 | global latticeGui, latticeData
70 | latticeData=[]
71 | for reporter in latticeGui:
72 | latticeData.append(reporter.report())
73 | latticeData=np.array(latticeData)
74 |
75 | ####################
76 | # orbital settings #
77 | ####################
78 |
79 | def correspondToOrbList(*arg):
80 | global OrbListBox, IDandTypeNote, PosNote, AnisotropyNote
81 | data=OrbListBox.report()
82 | if len(data)>0:
83 | IDandTypeNote.entry_list[0].config(state='normal')
84 | IDandTypeNote.setValue([data[0],data[1],data[2]]) # id, type, spin
85 | IDandTypeNote.entry_list[0].config(state='disabled')
86 | PosNote.setValue(data[3]) # fractional coordinates
87 | AnisotropyNote.setValue(data[4])
88 | updateStructureViewer(lightOrb=data[0])
89 |
90 | def addOrb():
91 | global OrbListBox, IDandTypeNote, PosNote, AnisotropyNote
92 | newData=list(OrbListBox.infoData)
93 | idAndType=IDandTypeNote.report()
94 | pos=PosNote.report()
95 | ani=AnisotropyNote.report()
96 | newData.append([len(newData),int(idAndType[1]),idAndType[2],tuple(pos),tuple(ani)])
97 | OrbListBox.updateInfo(newData)
98 | updateStructureViewer()
99 |
100 | def deletOrb():
101 | global OrbListBox, IDandTypeNote, PosNote
102 | newData=list(OrbListBox.infoData)
103 | if len(newData)==0:
104 | return
105 | idAndType=IDandTypeNote.report()
106 | idxs=int(idAndType[0])
107 | newData.pop(idxs)
108 | OrbListBox.updateInfo(newData)
109 | updateStructureViewer()
110 |
111 | def resetOrb():
112 | global OrbListBox, IDandTypeNote, PosNote, AnisotropyNote
113 | newData=list(OrbListBox.infoData)
114 | if len(newData)==0:
115 | return
116 | idAndType=IDandTypeNote.report()
117 | pos=PosNote.report()
118 | ani=AnisotropyNote.report()
119 | idxs=int(idAndType[0])
120 | #print(idxs)
121 | newData.pop(idxs)
122 | newData.insert(idxs,[int(idAndType[0]),int(idAndType[1]),idAndType[2],tuple(pos),tuple(ani)])
123 | OrbListBox.updateInfo(newData)
124 | updateStructureViewer()
125 |
126 | def orbitalDataFormat(info):
127 | return 'ID: %d Spin: %.1f FracX: %.3f %.3f %.3f Ani: %.2f %.2f %.2f'%(info[0],info[2],info[3][0],info[3][1],info[3][2],info[4][0],info[4][1],info[4][2])
128 |
129 | def loadOrbitals():
130 | global gui, OrbListBox, IDandTypeNote, PosNote, AnisotropyNote
131 | OrbFrame=LabelFrame(gui,text='Orbital list')
132 | OrbFrame.grid(row=1,column=0,columnspan=1)
133 |
134 | list_base=Frame(OrbFrame)
135 | list_base.grid(row=0,column=0,columnspan=2)
136 | OrbListBox=toolbox.InfoList(list_base, correspondToOrbList, orbitalDataFormat, initialInfo=[[0,0,1,(0.,0.,0.),(0.,0.,0.)]],width=45,height=5)
137 |
138 | addOrbFrameBase=Frame(OrbFrame)
139 | addOrbFrameBase.grid(row=1,column=0)
140 |
141 | id_base=Frame(addOrbFrameBase)
142 | id_base.grid(row=0,column=0)
143 | IDandTypeNote=toolbox.NoteFrm(id_base, init_notes=['ID:','Type:','Init spin:'],init_data=[0,0,1],row=True,entryWidth=5)
144 | IDandTypeNote.entry_list[0].config(state='disabled')
145 | pos_base=Frame(addOrbFrameBase)
146 | pos_base.grid(row=1,column=0,sticky='W')
147 | PosNote=toolbox.NoteFrm(pos_base, init_notes=['pos','',''],init_data=[0.,0.,0.],row=True,entryWidth=6)
148 |
149 | anis_base=Frame(addOrbFrameBase)
150 | anis_base.grid(row=2,column=0,sticky=(W,E))
151 | AnisotropyNote=toolbox.NoteFrm(anis_base, init_notes=['Ani: Dx','Dy','Dz'],init_data=[0,0,0],row=True,entryWidth=6)
152 |
153 | addBtn=Button(addOrbFrameBase,text='add',command=addOrb)
154 | addBtn.grid(row=0,column=1,rowspan=3)
155 | resetBtn=Button(addOrbFrameBase,text='reset',command=resetOrb)
156 | resetBtn.grid(row=0,column=2,rowspan=3)
157 | delBtn=Button(addOrbFrameBase,text='delet',command=deletOrb)
158 | delBtn.grid(row=0,column=3,rowspan=3)
159 |
160 |
161 | ##################
162 | # Bonds settings #
163 | ##################
164 |
165 | def correspondToBondList(*arg):
166 | global BondBox, IDandTypeOfBondNote, BondDetailNote
167 | data=BondBox.report()
168 | if len(data)>0:
169 | IDandTypeOfBondNote.entry_list[0].config(state='normal')
170 | IDandTypeOfBondNote.setValue([data[0],data[1][0],data[1][1],data[1][2],data[1][3],data[1][4],data[1][5],data[1][6],data[1][7],data[1][8]]) # id, [Jz, Jx, Jy, Jxy, Jxz, Jyz, Jyx, Jzx, Jzy]
171 | IDandTypeOfBondNote.entry_list[0].config(state='disabled')
172 | BondDetailNote.setValue([data[2][0],data[2][1],int(data[2][2][0]),int(data[2][2][1]),int(data[2][2][2])]) # fractional coordinates
173 | updateStructureViewer(lightID=data[0])
174 |
175 | def reviewBond():
176 | bondPannel=Toplevel()
177 | bondPannel.title('bond setting')
178 |
179 | def addBond():
180 | global BondBox, IDandTypeOfBondNote, BondDetailNote
181 | newData=list(BondBox.infoData)
182 | idAndType=IDandTypeOfBondNote.report()
183 | bondDetail=BondDetailNote.report()
184 | newData.append([len(newData),
185 | [idAndType[1],idAndType[2],idAndType[3],idAndType[4],idAndType[5],idAndType[6],idAndType[7],idAndType[8],idAndType[9]],
186 | [int(bondDetail[0]),int(bondDetail[1]),[int(bondDetail[2]),int(bondDetail[3]),int(bondDetail[4])]]])
187 | BondBox.updateInfo(newData)
188 | updateStructureViewer()
189 |
190 | def deletBond():
191 | global BondBox, IDandTypeOfBondNote, BondDetailNote
192 | newData=list(BondBox.infoData)
193 | if len(newData)==0:
194 | return
195 | idAndType=IDandTypeOfBondNote.report()
196 | idxs=int(idAndType[0])
197 | newData.pop(idxs)
198 | BondBox.updateInfo(newData)
199 | updateStructureViewer()
200 |
201 | def resetBond():
202 | global BondBox, IDandTypeOfBondNote, BondDetailNote
203 | newData=list(BondBox.infoData)
204 | if len(newData)==0:
205 | return
206 | idAndType=IDandTypeOfBondNote.report()
207 | bondDetail=BondDetailNote.report()
208 | idxs=int(idAndType[0])
209 | newData.pop(idxs)
210 | newData.insert(idxs,[len(newData),
211 | [idAndType[1],idAndType[2],idAndType[3],idAndType[4],idAndType[5],idAndType[6],idAndType[7],idAndType[8],idAndType[9]],
212 | [int(bondDetail[0]),int(bondDetail[1]),[int(bondDetail[2]),int(bondDetail[3]),int(bondDetail[4])]]])
213 | BondBox.updateInfo(newData)
214 | updateStructureViewer()
215 |
216 | def bondDataFormat(info):
217 | return 'ID%d orb%d-orb%d [%d %d %d] J: xx %.2f yy %.2f zz %.2f xy %.2f xz %.2f yz %.2f yx %.2f zx%.2f zy%.2f'%(info[0],info[2][0],info[2][1],info[2][2][0],info[2][2][1],info[2][2][2],info[1][0],info[1][1],info[1][2],info[1][3],info[1][4],info[1][5],info[1][6],info[1][7],info[1][8])
218 |
219 | def loadBonds():
220 | global gui, BondBox, IDandTypeOfBondNote, BondDetailNote
221 | BondFrame=LabelFrame(gui,text='Bond list')
222 | BondFrame.grid(row=2,column=0,columnspan=1)
223 |
224 | list_base=Frame(BondFrame)
225 | list_base.grid(row=0,column=0,columnspan=2)
226 | BondBox=toolbox.InfoList(list_base, correspondToBondList, bondDataFormat,
227 | initialInfo=[[0,[-1,-1,-1,0,0,0,0,0,0],[0,0,(1,0,0)]],[1,[-1,-1,-1,0,0,0,0,0,0],[0,0,(0,1,0)]]],
228 | width=45,height=5)
229 |
230 | addBondFrameBase=Frame(BondFrame)
231 | addBondFrameBase.grid(row=1,column=0)
232 |
233 | #note1=Label(addBondFrameBase, text='xx yy zz xy xz yz yx zx zy')
234 | #note1.grid(row=0,column=0,columnspan=5,sticky=(E))
235 |
236 | id_base=Frame(addBondFrameBase)
237 | id_base.grid(row=1,column=0,columnspan=5,sticky=(W,E))
238 |
239 | IDandTypeOfBondNote=toolbox.NoteFrm(id_base, init_notes=['ID:','J:','','','','','','','',''],init_data=[1,-1,-1,-1,0,0,0,0,0,0],row=True,entryWidth=3)
240 | IDandTypeOfBondNote.entry_list[0].config(state='disabled')
241 |
242 | detail_base=Frame(addBondFrameBase)
243 | detail_base.grid(row=2,column=0,sticky=(W,E))
244 | BondDetailNote=toolbox.NoteFrm(detail_base, init_notes=['s','t','over lat.','',''],init_data=[0,0,1,0,0],row=True,entryWidth=3)
245 |
246 | unitLabel=Label(BondFrame,text='Note all energy units are in Kelvin (1meV=11.604609K)')
247 | unitLabel.grid(row=3,column=0,sticky=(W,E))
248 |
249 | #reviewBtn=Button(addBondFrameBase,text='review',command=reviewBond)
250 | #reviewBtn.grid(row=1,column=1,sticky='E')
251 | addBtn=Button(addBondFrameBase,text='add',command=addBond)
252 | addBtn.grid(row=2,column=2,rowspan=1,sticky='E')
253 | resetBtn=Button(addBondFrameBase,text='reset',command=resetBond)
254 | resetBtn.grid(row=2,column=3,rowspan=1,sticky='E')
255 | delBtn=Button(addBondFrameBase,text='delet',command=deletBond)
256 | delBtn.grid(row=2,column=4,rowspan=1,sticky='E')
257 |
258 | ###############
259 | # MC settings #
260 | ###############
261 |
262 | def loadMCSettings():
263 | global gui, TListGui, HListGui, MCparamGui, xaxisStr, xAxisGui, modelGui, modelStr, algorithmGui, algoStr, corrGui, spinFrameGui, coreGui
264 | SettingFrame=LabelFrame(gui,text='Other settings')
265 | SettingFrame.grid(row=3,column=0,sticky=(W,E))
266 |
267 | temp_base=Frame(SettingFrame)
268 | temp_base.grid(row=0,column=0)
269 | TListGui=toolbox.NoteFrm(temp_base, init_notes=['T start:','T end','total points:'], init_data=[0.9,1.2,8],row=True,entryWidth=6)
270 |
271 | field_base=Frame(SettingFrame)
272 | field_base.grid(row=1,column=0)
273 | HListGui=toolbox.NoteFrm(field_base, init_notes=['H start:','H end','total points:'], init_data=[0,0.1,1],row=True,entryWidth=6)
274 |
275 | MCparam_base=Frame(SettingFrame)
276 | MCparam_base.grid(row=2,column=0,sticky='W')
277 | MCparamGui=toolbox.NoteFrm(MCparam_base, init_notes=['nthermal:','nsweep:','tau:'], init_data=[40000,80000,1],row=True)
278 |
279 | model_base=Frame(SettingFrame)
280 | model_base.grid(row=3,column=0,sticky='W')
281 |
282 | label0=Label(model_base,text='xAxis:')
283 | label0.grid(row=0,column=0)
284 | xaxisStr=StringVar()
285 | xAxisGui=Spinbox(model_base,from_=1, to=2, values=['T','H'],textvariable=xaxisStr,width=2)
286 | xAxisGui.grid(row=0,column=1)
287 |
288 | label1=Label(model_base,text='Model:')
289 | label1.grid(row=0,column=2)
290 | modelStr=StringVar()
291 | modelGui=Spinbox(model_base,from_=1, to=3, values=['Ising','XY','Heisenberg'],textvariable=modelStr,width=6)
292 | modelGui.grid(row=0,column=3)
293 | modelStr.set('XY')
294 |
295 | label2=Label(model_base,text='Algorithm:')
296 | label2.grid(row=0,column=4)
297 | algoStr=StringVar()
298 | algorithmGui=Spinbox(model_base,from_=1, to=3, values=['Wolff','Metropolis','Swedsen-Wang'],textvariable=algoStr,width=6)
299 | algorithmGui.grid(row=0,column=5)
300 |
301 | corr_base=Frame(SettingFrame)
302 | corr_base.grid(row=4,column=0,sticky='W')
303 | corrGui=toolbox.NoteFrm(corr_base, init_notes=['Measure corr. si','sj','overLat:','',''], init_data=[0,0,0,0,0],entryWidth=3,row=True)
304 |
305 | lastline=Frame(SettingFrame)
306 | lastline.grid(row=5,column=0,sticky='W')
307 |
308 | spinFrame_base=Frame(lastline)
309 | spinFrame_base.grid(row=0,column=0,sticky='W')
310 | spinFrameGui=toolbox.NoteFrm(spinFrame_base, init_notes=['nFrame:'], init_data=[0],entryWidth=3)
311 |
312 | core_base=Frame(lastline)
313 | core_base.grid(row=0,column=1,sticky='W')
314 | coreGui=toolbox.NoteFrm(core_base, init_notes=['core:'], init_data=[np.max([1,int(cpu_count()/2)])],entryWidth=3)
315 |
316 | ########################
317 | # Structure visualizer #
318 | ########################
319 |
320 | def loadStructureViewer():
321 | global gui, latticeGui, OrbListBox, BondBox, supercellGui, structureFrame, structureViewer, structureAxis
322 | structureFrame=LabelFrame(gui, text='Structure viewer')
323 | structureFrame.grid(row=0,column=1,rowspan=2)
324 |
325 | tb=wan.TBmodel()
326 | a1=latticeGui[0].report()
327 | a2=latticeGui[1].report()
328 | a3=latticeGui[2].report()
329 | tb.lattice=np.array([a1,a2,a3])
330 | tb.orbital_coor=[[np.array(ele[3]),50,'red',(0,0,ele[2])] for ele in OrbListBox.infoData]
331 | tb.norbital=len(tb.orbital_coor)
332 | tb.hopping=[[bond_data[2][0],bond_data[2][1],np.array(bond_data[2][2]),bond_data[1][0],'green', 2] for bond_data in BondBox.infoData]
333 | tb.nhoppings=len(tb.hopping)
334 | Lx, Ly, Lz=[4 if x>1 else 1 for x in supercellGui.report() ]
335 | tb.make_supercell([Lx,0,0],[0,Ly,0],[0,0,Lz])
336 | f, structureAxis=tb.viewStructure()
337 |
338 | x0, x1 = structureAxis.get_xlim()
339 | y0, y1 = structureAxis.get_ylim()
340 | z0, z1 = structureAxis.get_zlim()
341 |
342 | ox=(x0+x1)/2;oy=(y0+y1)/2;oz=(z0+z1)/2
343 | xlen=abs(x1-x0);ylen=abs(y1-y0);zlen=abs(z1-z0)
344 | lenMax_half=np.max([xlen,ylen,zlen])/2
345 | structureAxis.set_xlim(ox-lenMax_half,ox+lenMax_half)
346 | structureAxis.set_ylim(oy-lenMax_half,oy+lenMax_half)
347 | structureAxis.set_zlim(oz-lenMax_half,oz+lenMax_half)
348 | #structureAxis.view_init(elev=0,azim=0)
349 |
350 | structureViewer=FigureCanvasTkAgg(f,structureFrame)
351 | structureViewer.draw()
352 | structureViewer.get_tk_widget().grid(row=0,column=0)
353 | structureAxis.figure.canvas=structureViewer
354 | structureAxis.mouse_init()
355 |
356 | def updateStructureViewer(lightID=-1,lightOrb=-1):
357 | global gui, latticeGui, OrbListBox, BondBox, supercellGui, structureFrame, structureViewer, structureAxis
358 | elev, azim = structureAxis.elev, structureAxis.azim
359 | x0, x1 = structureAxis.get_xlim()
360 | y0, y1 = structureAxis.get_ylim()
361 | z0, z1 = structureAxis.get_zlim()
362 |
363 | tb=wan.TBmodel()
364 | a1=latticeGui[0].report()
365 | a2=latticeGui[1].report()
366 | a3=latticeGui[2].report()
367 | tb.lattice=np.array([a1,a2,a3])
368 | tb.orbital_coor=[[np.array(ele[3]),100 if ele[0]==lightOrb else 50,'yellow' if ele[0]==lightOrb else 'red',(0,0,ele[2]) ] for ele in OrbListBox.infoData]
369 | tb.norbital=len(tb.orbital_coor)
370 | tb.hopping=[[bond_data[2][0],bond_data[2][1],np.array(bond_data[2][2]),bond_data[1][0],'yellow' if bond_data[0]==lightID else 'green', 6 if bond_data[0]==lightID else 2] for bond_data in BondBox.infoData]
371 | tb.nhoppings=len(tb.hopping)
372 | Lx, Ly, Lz=[4 if x>1 else 1 for x in supercellGui.report() ]
373 | tb.make_supercell([Lx,0,0],[0,Ly,0],[0,0,Lz])
374 | f, structureAxis=tb.viewStructure()
375 | structureAxis.view_init(elev=elev,azim=azim)
376 | structureAxis.set_xlim(x0,x1)
377 | structureAxis.set_ylim(y0,y1)
378 | structureAxis.set_zlim(z0,z1)
379 |
380 | structureViewer.get_tk_widget().destroy()
381 | structureViewer=FigureCanvasTkAgg(f,structureFrame)
382 | structureViewer.draw()
383 | structureViewer.get_tk_widget().pack()
384 | structureAxis.figure.canvas=structureViewer
385 | structureAxis.mouse_init()
386 |
387 | #####################
388 | # Resutl visualizer #
389 | #####################
390 |
391 | def loadResultViewer():
392 | global gui, resultViewerBase, resultViewer
393 | resultViewerBase=LabelFrame(gui, text='Result viewer')
394 | resultViewerBase.grid(row=2,column=1,rowspan=2)
395 |
396 | f=Figure(figsize=(4,3))
397 | f.add_subplot(111).plot([0,2],[0,0],color='black')
398 | resultViewer=FigureCanvasTkAgg(f,resultViewerBase)
399 | resultViewer.draw()
400 | resultViewer.get_tk_widget().pack()
401 |
402 | def updateResultViewer(TList=[],magList=[], susList=[]):
403 | global gui, resultViewerBase, resultViewer
404 | #print('updating:',TList,magList)
405 | f=Figure(figsize=(4,3))
406 | ax=f.add_subplot(111,label=0)
407 | ax.scatter(TList,magList,color='red',label='')
408 |
409 | ax2=ax.twinx()
410 | ax2.scatter(TList,susList,color='blue',label=r'Capa')
411 | ax2.set_ylim(min(susList),max(susList))
412 |
413 | f.legend()
414 |
415 | resultViewer.get_tk_widget().destroy()
416 | resultViewer=FigureCanvasTkAgg(f,resultViewerBase)
417 | resultViewer.draw()
418 | resultViewer.get_tk_widget().pack()
419 |
420 | #############
421 | # Func btn #
422 | #############
423 |
424 | def loadStartBtn(submitFunc):
425 | global gui, saveBtn, loadBtn, submitBtn
426 | submit_base=Frame(gui)
427 | submit_base.grid(row=4,column=0,columnspan=2)
428 |
429 | saveBtn=Button(submit_base,text='Save',command=io.saveParam)
430 | saveBtn.grid(row=0,column=0,rowspan=3)
431 |
432 | loadBtn=Button(submit_base,text='Load',command=io.loadParam)
433 | loadBtn.grid(row=0,column=1,rowspan=3)
434 |
435 | submitBtn=Button(submit_base,text='StartMC',command=submitFunc)
436 | submitBtn.grid(row=0,column=2,rowspan=3)
437 |
438 | note1=Label(submit_base, text='Thanks for your attention and I wish you would find sth. helpful.', width=80)
439 | note1.grid(row=0,column=3)
440 |
441 | note2=Label(submit_base, text='Please cite: Magnetic switches via electric field in BN nanoribbons. Appl. Surf. Sci. 480(2019)', width=80)
442 | note2.grid(row=1,column=3)
443 |
444 | #note3=Label(submit_base, text='Thank you very much!', width=80)
445 | #note3.grid(row=2,column=3)
446 |
447 | def loadEverything(root,submitFunc):
448 | global gui
449 | gui=root
450 | loadLatticePannel()
451 | updateLatticeData()
452 |
453 | loadOrbitals()
454 | loadBonds()
455 | loadMCSettings()
456 | loadStructureViewer()
457 | loadResultViewer()
458 | loadStartBtn(submitFunc)
459 |
--------------------------------------------------------------------------------
/mcsolver/input.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import Lattice as lat
3 | import mcMain as mc
4 | import matplotlib.pyplot as plt
5 | import time
6 |
7 | ## magnetic crystal part
8 | LMatrix=[[1,0,0],
9 | [0,1,0],
10 | [0,0,1]]
11 | # magnetic orbitals in fractional coordinates
12 | pos=[[0,0,0]]
13 | # spin number
14 | Spin=[1]
15 | # single ion anisotropy
16 | D=np.array([[0.0,0.0,-0.0]])
17 | # couplings #source #target #edge #J(meV) negative for FM coupling
18 | bond1=lat.Bond(0,0,np.array([1,0,0]),-1,-1,-1, 0, 0, 0, 0, 0, 0, True)
19 | bond2=lat.Bond(0,0,np.array([0,1,0]),-1,-1,-1, 0, 0, 0, 0, 0, 0, True)
20 |
21 | bondList=[bond1,bond2]
22 |
23 | time0=time.time()
24 | mcslave=mc.MC(0,LMatrix,pos=pos,S=Spin,D=D,bondList=bondList,
25 | Lx=16,Ly=16,Lz=1,
26 | T=0.2,ki_s=0,ki_t=0,ki_overLat=[2,0,0],
27 | orbGroupList=[[0]],groupInSC=True,h=0.0,dipoleAlpha=0.0,On=1,spinFrame=0)
28 | # Check MC part
29 | data=mcslave.mainLoopViaCLib_On(nsweep=80000,nthermal=40000,ninterval=1,algo='Wolff',On=3,flunc=0.0)
30 |
31 |
32 | # Spin-wave part
33 |
34 | print('time elapsed: %.3f s'%(time.time()-time0))
35 |
36 |
--------------------------------------------------------------------------------
/mcsolver/interface2swt.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2019 7 22
3 |
4 | @author: Andrew
5 | '''
6 | #import matplotlib
7 | #matplotlib.use('Agg')
8 | import matplotlib.pyplot as plt
9 | import numpy as np
10 | import auxiliary as aux
11 | import WannierKit
12 | import scipy.optimize as opt
13 | import fileio as io
14 |
15 | global tb # tight-binding model (for spin-wave calc.)
16 | global S # local spin
17 | global Jz_eff, Jxy, A_eff # the coupling constants extracted from DFT calc.
18 | global hBZ # half the Brillouin zone
19 | global dhBZ # double the BZ
20 | global norb # number of mag. ions in cell
21 | global eig0_set # the eigenvalues on the hBZ
22 | global magList_HF # store the MT curv calc. by Hatree-Fock
23 | global magList_MF # MT by mean-field
24 | global eig0_HF, jka, bka, twojka, JB0ab, B0, JBkaa, fourA, twoA # Hatree-Fock needed
25 | global Jekn, onsite, Jkaa, JBkaa_db
26 | global x0
27 | global Tc, Tc_MF
28 |
29 | def mainLoop(rpath):
30 | global tb,eig0_set,Tc,Tc_MF,magList_HF,magList_MF,S
31 | # create mc main directory
32 | print('start renormalized spin-wave theoretical calculations')
33 | io.loadParam(updateGUI=False,rpath=rpath)
34 | # initialize tight-binding model
35 | tb=WannierKit.TBmodel()
36 | __tbInit()
37 | tb.plotbands()
38 | eig0_min=np.min(eig0_set)
39 | print('spin-wave gap at 0K is: %.6f'%eig0_min)
40 | if(eig0_min>0):
41 | Sigma=0
42 | for eig in eig0_set:
43 | Sigma+=1./eig
44 | Tc_=(S+1)*len(eig0_set)/3./Sigma
45 | print('mean field estimation for Tc: %.3f'%Tc_)
46 | #exit()
47 |
48 | print('start scf procedure for each temperature, to get M-T curv')
49 | # calc M-T curv
50 | Tc, magList_HF = __MTCurv(path='./',draw=True,algo='HF_longWave')
51 | print('Hatree-Fock and long wave approximation give Tc:',Tc,'(Kelvin)')
52 | print
53 | #exit()
54 | Tc_MF,magList_MF=__MTCurv(path='./',draw=True,algo='meanfield')
55 | print('Mean-field approximation give Tc:',Tc_MF,'(Kelvin)')
56 | print('Spin-wave theory Tc (Hatree-Fock long wave limit): {:.1f}\n'.format(Tc))
57 | print('Spin-wave theory Tc (Mean-field approximation): {:.1f}\n'.format(Tc_MF))
58 | #__spinWave_T_vs_Occ('./',algo='HF_longWave')
59 | #__spinWave_T_vs_Occ('./',algo='Mean_Field')
60 | return Tc
61 | else:
62 | print('find zero or negative spin-wave gap!')
63 | print('Spin-wave theory find no Tc!\n')
64 | return 0
65 |
66 | def drawSpinWave(rpath,kpt,ibnd,Lx=5,Ly=5):
67 | global tb,eig0_set,Tc,Tc_MF,magList_HF,magList_MF,S
68 | # create mc main directory
69 | print('output spin waves on band%d at kpt %.3f %.3f %.3f'%(ibnd,*kpt))
70 | io.loadParam(updateGUI=False,rpath=rpath)
71 | # initialize tight-binding model
72 | tb=WannierKit.TBmodel()
73 | __tbInit()
74 |
75 | eig,vec=tb.solveHk(kpt=kpt,return_orb=True)
76 | #print(vec[:,ibnd])
77 | tb.plot2DStructure(vec[:,ibnd],kpt=np.array(kpt),Lx=Lx,Ly=Ly,S=io.S[0])
78 |
79 | def __tbInit():
80 | global tb, hBZ, dhBZ, S, norb
81 | # parameters for Hatree-Fock calc.
82 | global eig0_set, fourA, twoA, A
83 |
84 | global eig0_HF, Jekn, onsite, Jkaa, JBkaa_db, x0
85 |
86 |
87 | # set lattice
88 | tb.lattice=np.array(io.LMatrix)
89 | # set kpath for test
90 | tb.genReciLattice()
91 | #print('high')
92 | tb.autoGenerateKpath2D(20)
93 | # get coupling constants
94 | S=io.S[0]
95 | A=io.DList[0][0]-(io.DList[0][1]+io.DList[0][2])/2
96 | # set tb hoppings and diagonal terms according to eq. (S9)
97 | tb.orbital_coor=[[np.array(pos),50,'red'] for pos in io.pos]
98 | tb.norbital=len(io.S)
99 | #print(io.S)
100 | norb=tb.norbital
101 | onsite=np.ones(tb.norbital)*2*A
102 | #print(onsite)
103 | hopping=[]
104 |
105 | Jrab, Brab=[], []
106 | for bond in io.bondList:
107 | sourceID, targetID=bond[0], bond[1]
108 | overLat=bond[2]
109 | Jz, Jx, Jy= bond[3], bond[4], bond[5]
110 | J=(Jx+Jy)/2.
111 | B=Jz-J
112 | # onsite energy
113 | onsite[sourceID]+=Jz
114 | onsite[targetID]+=Jz
115 | # hopping
116 | hopping.append([sourceID,targetID,np.array(overLat),J])
117 | Jrab.append([sourceID,targetID,np.array(overLat),J])
118 | Brab.append([sourceID,targetID,np.array(overLat),B])
119 |
120 | #for j, b in zip(Jrab,Brab):
121 | # print(j)
122 | # print(b)
123 | # set half Brillouin zone
124 | hBZ=[]
125 | dk=1./io.LPack[0]
126 | for ikptx in range(io.LPack[0]):
127 | for ikpty in range(int(io.LPack[0]/2)):
128 | hBZ.append([ikptx*dk,ikpty*dk])
129 | dhBZ=list(hBZ)
130 | dhBZ.extend(hBZ)
131 |
132 | # get Jekn
133 | tb.onsite_energy=np.zeros(tb.norbital)
134 | tb.hopping=hopping
135 | tb.fixHopping()
136 | tb.constructHam()
137 | Jekn=np.array([tb.solveHk(kpt=kpt) for kpt in hBZ])
138 |
139 | # jkaa in hBZ
140 | Jkaa=np.array([np.diag(tb.constructHk(kpt))[0] for kpt in hBZ]).real
141 |
142 | # produce eig0_HF
143 | eig0_HF=S*(Jekn-onsite)
144 |
145 | # j(k1-k,aa) in double hBZ
146 | Jkaa_db=np.array([np.diag(tb.constructHk(kpt))[0] for kpt in dhBZ])
147 |
148 | # B(k1-k,aa) in double hBZ
149 | tb.hopping=Brab
150 | tb.fixHopping()
151 | tb.constructHam()
152 | Bkaa_db=[np.diag(tb.constructHk(kpt))[0] for kpt in dhBZ]
153 |
154 | # J + B
155 | JBkaa_db=(Jkaa_db+Bkaa_db).real
156 |
157 | # x0 initial occ.
158 | x0=np.array([0.]*len(eig0_HF))
159 |
160 | fourA=4*A
161 | twoA=2*A
162 |
163 | # get eig0_set
164 | #print(onsite)
165 | #exit()
166 | tb.onsite_energy=-S*onsite/11.58875
167 | #print(tb.onsite_energy)
168 | #exit()
169 | tb.hopping=hopping
170 | for hop in tb.hopping:
171 | hop[3]*=S/11.58875
172 | tb.fixHopping()
173 | tb.constructHam()
174 |
175 | __getEigen0()
176 |
177 | def __getEigen0():
178 | global tb, hBZ, eig0_set, eig0_HF
179 | #eig0_HF=np.array([tb.solveHk(kpt=kpt) for kpt in hBZ])
180 | eig0_set=np.array(list(eig0_HF)).flatten()
181 | #print(eig0_set)
182 |
183 | def __spinWaveSCF(T=1.,getGap=False):
184 | '''mean field approximation'''
185 | global S, eig0_set
186 | beta=1./T
187 | global eig_ren
188 | def bzSum(eigList,beta):
189 | ntot=0.
190 | for eig in eigList:
191 | ntot+=1./(np.exp(beta*eig)-1.)
192 | return ntot
193 |
194 | N=len(eig0_set)
195 | #n_avg=0
196 |
197 | def scf_meanfield(n_avg):
198 | global eig_ren
199 | eigList=(1-n_avg/2/S)*eig0_set
200 | ntot=bzSum(eigList,beta)
201 | eig_ren=np.min(eigList)
202 | return (ntot/N-n_avg)**2
203 |
204 | out=opt.minimize_scalar(scf_meanfield,bounds=(0,S))
205 | if getGap:
206 | return out['fun'], out['x'], eig_ren
207 | return out['fun'], out['x']
208 |
209 | def __spinWaveSCF_HF(T=1.,getGap=False):
210 | '''Hatree-Fock level discussed in H1 expression'''
211 | global S, eig0_HF, Jkaa, JBkaa_db, Jekn, onsite, norb, A, twoA, fourA
212 | global x0
213 | global eig_ren
214 | beta=1./T
215 | N=len(eig0_HF)
216 |
217 | def scf_Hatree_Fock(nk_avg):
218 | global eig_ren
219 | ntot=np.sum(nk_avg)
220 | # independent contribution
221 | contr_ind=A+ntot/N*(-Jekn+onsite+twoA) #
222 | # dependent contribution
223 | contr_dep=1./N*np.array([np.dot((JBkaa_db[N-ik:2*N-ik]-Jkaa),nk_avg) for ik in range(N)])
224 | # renormalized eig
225 | eig_ren=(eig0_HF+contr_ind).T+contr_dep
226 |
227 | # occ renorm
228 | nk_renorm=[np.sum(nk)/norb for nk in 1./(np.exp(beta*eig_ren.T)-1.)]
229 | diff_nk=np.array(nk_renorm)-nk_avg
230 | return np.dot(diff_nk,diff_nk)
231 |
232 | out=opt.minimize(scf_Hatree_Fock,x0,bounds=[(0,None) for i in range(N)])
233 | # update x0
234 | x0=out['x']
235 | if getGap:
236 | return out['fun'], np.sum(out['x'])*norb/N, np.min(eig_ren)
237 | return out['fun'], np.sum(out['x'])*norb/N
238 |
239 | def __spinWaveSCF_HF_longWave(T=1., getGap=False):
240 | '''Hatree-Fock level using long-wave approximation'''
241 | global S, eig0_HF, Jkaa, JBkaa_db, Jekn, onsite, norb, A, twoA, fourA
242 | beta=1./T
243 | N=len(eig0_HF)
244 | global eig_ren, nk_renorm, contr_ind, contr_dep
245 | def scf_HF_longwave(nk_avg):
246 | global eig_ren, nk_renorm, contr_ind, contr_dep
247 | # independent contribution
248 | contr_ind=A+nk_avg*(-Jekn+onsite+twoA) # modified ignore the A term
249 | # dependent contribution
250 | contr_dep=nk_avg*(JBkaa_db[0:N]-Jkaa[0])
251 | # renormalized eig
252 | eig_ren=(eig0_HF+contr_ind).T+contr_dep
253 |
254 | # occ renorm
255 | nk_renorm=np.sum([np.sum(nk) for nk in 1./(np.exp(beta*eig_ren.T)-1.)])/norb/N
256 | diff_nk=nk_renorm-nk_avg
257 | return diff_nk*diff_nk
258 |
259 | out=opt.minimize_scalar(scf_HF_longwave,bounds=(0,S/norb),method='Bounded')
260 | #print(nk_renorm)
261 | #print(np.min(eig_ren),np.max(eig_ren))
262 | #print(contr_dep)
263 | #print(contr_ind.T+contr_dep)
264 | #print(twoA)
265 | #exit()
266 | if getGap:
267 | return out['fun'], out['x']*norb, np.min(eig_ren)
268 | return out['fun'], out['x']*norb
269 |
270 | def __spinWave_T_vs_Occ(path,algo='HF_longWave'):
271 | '''Draw the T vs Occ. phase'''
272 | global S, Tc, Tc_MF, eig0_HF, eig0_set, Jkaa, JBkaa_db, Jekn, onsite, norb, A, twoA, fourA
273 | N=len(eig0_HF)
274 |
275 | def scf_HF_longwave(nk_avg,beta):
276 | # independent contribution
277 | contr_ind=A+nk_avg*(-Jekn+onsite+twoA) # modified ignore the A term
278 | # dependent contribution
279 | contr_dep=nk_avg*(JBkaa_db[0:N]-Jkaa[0])
280 | # renormalized eig
281 | eig_ren=(eig0_HF+contr_ind).T+contr_dep
282 |
283 | # occ renorm
284 | nk_renorm=np.sum([np.sum(nk) for nk in 1./(np.exp(beta*eig_ren.T)-1.)])/norb/N
285 | diff_nk=nk_renorm-nk_avg
286 | return np.min([-np.log(np.max([diff_nk*diff_nk,1E-10])),10])
287 |
288 | def scf_meanfield(n_avg,beta):
289 | eigList=(1-n_avg/2/S)*eig0_set
290 | ntot=np.sum(1./(np.exp(beta*eigList)-1.))
291 | diff=ntot/len(eigList)-n_avg
292 | return np.min([-np.log(np.max([diff*diff,1E-10])),10])
293 |
294 | T=np.linspace(1,Tc*1.2,101)
295 | T_mf=np.linspace(1,Tc_MF*1.2,101)
296 | Occ=np.linspace(0,S/norb,101)
297 | Occ_tot=np.linspace(0,S,101)
298 | phase=[]
299 | if algo=='HF_longWave':
300 | for t in T:
301 | phase.append([scf_HF_longwave(nk_avg,beta=1./t) for nk_avg in Occ])
302 | xlabel=[int(num) for num in np.linspace(1,Tc*1.2,6)]
303 | else:
304 | for t in T_mf:
305 | phase.append([scf_meanfield(n_avg,beta=1./t) for n_avg in Occ_tot])
306 | xlabel=[int(num) for num in np.linspace(1,Tc_MF*1.2,6)]
307 | plt.figure(figsize=(6,6))
308 | plt.imshow(np.array(phase).T,origin='low',extent=(0,10,0,10))
309 | #plt.colorbar()
310 | ylabel=['%.2f'%num for num in np.linspace(0,S,6)]
311 | plt.xticks(range(0,12,2),xlabel)
312 | plt.yticks(range(0,12,2),ylabel)
313 | #plt.xlabel(r'Temperature (K)')
314 | #plt.ylabel(r'Spin-wave occ.')
315 | plt.tick_params(labelsize=20)
316 | plt.savefig(path+algo+'OT.png',dpi=300)
317 | plt.close()
318 |
319 | def __MTCurv(path='./',draw=False,algo='HF_longWave'):
320 | global S, eig0_set, norb
321 | global eig0_HF
322 | global twoA,fourA,A
323 | global JBkaa_db, Jekn, Jkaa, onsite
324 |
325 | magList=[]
326 | TList=[]
327 | T=1.
328 | mag0=-5
329 | while(True):
330 | if(algo=='HF_longWave'):
331 | fun, n_avg, gap = __spinWaveSCF_HF_longWave(T,getGap=True)
332 | elif(algo=='HF'):
333 | fun, n_avg, gap = __spinWaveSCF_HF(T,getGap=True)
334 | else:
335 | fun, n_avg, gap = __spinWaveSCF(T,getGap=True)
336 | mag=2*(S-n_avg)
337 | print(T, fun, mag, mag-mag0, gap)
338 | mag0=mag
339 | if(fun>1e-8):
340 | break
341 | if(mag<0):
342 | break
343 | magList.append(mag)
344 | TList.append(T)
345 | T+=1
346 | if(draw):
347 | plt.figure()
348 | plt.scatter(TList,magList)
349 | plt.xlim(0,T)
350 | plt.savefig(path+algo+'MT.png',dpi=300)
351 | plt.close()
352 | return T, magList
353 |
354 | #mainLoop('./spg8Co8Gd4H.txt')
355 | #drawSpinWave('./samples/CrI3With2NNCoupling',[1./5,1./5,0.],0,Lx=6,Ly=6)
--------------------------------------------------------------------------------
/mcsolver/isingLib.c:
--------------------------------------------------------------------------------
1 | #define PY_SSIZE_T_CLEAN
2 | #include "Python.h"
3 | #include
4 | #include
5 | #include
6 |
7 | typedef struct Orb
8 | {
9 | int id;
10 | double spin;
11 | double h;
12 | int nlink;
13 | double *linkStrength;
14 | int inBlock;
15 | struct Orb **linkedOrb;
16 |
17 | int chosen;
18 | struct Orb **linkedOrb_rnorm;
19 | int nOrbInCluster;
20 | struct Orb **orb_cluster;
21 | }Orb;
22 |
23 | void establishLattice(Orb *lattice, int totOrbs, double initSpin[totOrbs], double h, int maxNLinking, int nlink[maxNLinking], double linkStrength[totOrbs*maxNLinking],
24 | int totOrb_rnorm, int nOrbInCluster, int rOrb[totOrb_rnorm], int rOrbCluster[totOrb_rnorm*nOrbInCluster]){
25 | for(int i=0;iid);
49 | }
50 | }
51 | }
52 |
53 | void establishLinking(Orb *lattice, int totOrbs, int maxNLinking, int nlink[maxNLinking], int linkedOrb[totOrbs*maxNLinking],
54 | int totOrb_rnorm, int rOrb[totOrb_rnorm], int linkedOrb_rnorm[totOrb_rnorm*maxNLinking]){
55 | for(int iorb=0;iorbid,lattice[iorb].linkStrength[ilink]);
66 | // }
67 | //}
68 | for(int i=0;iid,lattice[iorb].linkStrength[ilink]);
115 | }
116 | }
117 | lattice[totOrbs-1].linkedOrb=(Orb**)malloc((totOrbs-1)*sizeof(Orb*));
118 | for(int i=0;inlink;i++){
124 | corr+=(source->linkStrength[i])*(source->spin)*(source->linkedOrb[i]->spin);
125 | }
126 | return corr;
127 | }
128 |
129 | double getDeltaOnsiteEnergy(Orb *source){ // Only field term contributes,
130 | return 2*source->h*source->spin;
131 | }
132 |
133 | double getMajoritySpin(Orb *_orb){
134 | //printf("start calc majority spin in block, %d orbs in total, centering orb%d\n",_orb->nOrbInCluster,_orb->id);
135 | double avg_spin=0.0;
136 | for(int ispin=0;ispin<_orb->nOrbInCluster;ispin++){
137 | avg_spin+=_orb->orb_cluster[ispin]->spin;
138 | }
139 | if (avg_spin>0){
140 | return fabs(_orb->spin);
141 | }else if (avg_spin<0){
142 | return -fabs(_orb->spin);
143 | }else{
144 | if (rand()/(double) RAND_MAX>0.5){
145 | return fabs(_orb->spin);
146 | }else{
147 | return -fabs(_orb->spin);
148 | }
149 | }
150 | }
151 |
152 | double getCorrEnergy_rnorm(Orb *source){
153 | //printf("now we are calc. the corr. energy to orb%d\n",source->id);
154 | double corr=0;
155 | double avg_spin_source=getMajoritySpin(source);
156 | for(int i=0;inlink;i++){
157 | //printf("link to orb%d\n",source->linkedOrb_rnorm[i]->id);
158 | double avg_spin_target=getMajoritySpin(source->linkedOrb_rnorm[i]);
159 | corr+=(source->linkStrength[i])*avg_spin_source*avg_spin_target;
160 | }
161 | //printf("Ecorr=%.3f\n",corr);
162 | return corr;
163 | }
164 |
165 | int expandBlock(int*beginIndex, int*endIndex, Orb *buffer[], int*blockLen, Orb *block[]){
166 | //printf(" Buffer: now start and end pt is %d, %d.\n",*beginIndex, *endIndex);
167 | if(*beginIndex>*endIndex) return 0;
168 |
169 | // FIFO
170 | Orb *outOrb=buffer[*beginIndex];
171 | *beginIndex+=1; // pop out the first element
172 |
173 | //FILO
174 | //Orb *outOrb=buffer[*endIndex];
175 | //*endIndex-=1; // pop out the last element
176 |
177 | int i;
178 | //printf("there are %d linked orbs\n",outOrb->nlink);
179 | for(i=0;inlink;i++){
180 | Orb *linkedOrb=outOrb->linkedOrb[i];
181 | //printf(" considering the %d orb which is linking to %d orb, it is %d in block \n", linkedOrb->id, outOrb->id, linkedOrb->inBlock);
182 | if(linkedOrb->inBlock==0){
183 | double corr=(outOrb->linkStrength[i])*(outOrb->spin)*(linkedOrb->spin); // bond strength
184 | //printf(" since it is not in block thus we calc. the correlation energy is %f\n",corr);
185 | if(corr<0 && (1-exp(2*corr))>rand()/(double) RAND_MAX){
186 | //printf(" -->>fortunately it is added to block, Padd=%f\n",(1-exp(2*corr)));
187 | // update block
188 | *blockLen+=1;
189 | block[*blockLen-1]=linkedOrb;
190 | linkedOrb->inBlock=1; // register into block
191 | // update buffer
192 | *endIndex+=1;
193 | buffer[*endIndex]=linkedOrb;
194 | }//else{
195 | // printf(" -->>unfortunately it is not added to block, Padd=%f\n",(1-exp(2*corr)));
196 | //}
197 | }
198 | }
199 | return 1;
200 | }
201 |
202 | void blockUpdate(int totOrbs, Orb lattice[], double*p_energy, double*p_totSpin){
203 | //printf("one block update step is initializaing...\n");
204 | for(int i=0;iinBlock=1;
213 | int beginIndex=0, endIndex=0, blockLen=1, i;
214 | int *p_beginIndex=&beginIndex, *p_endIndex=&endIndex, *p_blockLen=&blockLen;
215 |
216 | //printf("the seed Orb is %d\n",block[0]->id);
217 | while (expandBlock(p_beginIndex, p_endIndex, buffer, p_blockLen, block)==1)
218 | {
219 | //printf(" Block size is %d\n",*p_blockLen);
220 | }
221 |
222 | double tot_d_onsiteEnergy=0; // case field on
223 | // single-ion anisotropy
224 | for(i=0;i<*p_blockLen;i++) tot_d_onsiteEnergy+=getDeltaOnsiteEnergy(block[i]);
225 | if(tot_d_onsiteEnergy<=0 || exp(-tot_d_onsiteEnergy)>rand()/(double) RAND_MAX){
226 | for(i=0;i<*p_blockLen;i++){
227 | block[i]->spin*=-1;
228 | if(block[i]->idspin*2);
229 | }
230 | *p_energy=0.;
231 | for(i=0;ih*(lattice+i)->spin;
233 | }
234 | }
235 | free(block);free(buffer);
236 | }
237 |
238 | void localUpdate(int totOrbs, Orb lattice[], double *p_energy, double *p_totSpin){
239 | unsigned long long r1=(unsigned long long)rand();
240 | unsigned long long r2=(unsigned long long)rand();
241 | unsigned long long seedID=(r1*RAND_MAX+r2)%totOrbs; // chose one orb
242 | double corr=2*(getCorrEnergy(lattice+seedID)-lattice[seedID].h*lattice[seedID].spin);
243 | //printf("local update: try to flip orb%d, corr=%.6f\n",lattice[seedID].id,corr);
244 | if(corr>=0){
245 | lattice[seedID].spin*=-1;
246 | *p_totSpin+=(lattice[seedID].spin*2);
247 | *p_energy-=corr;
248 | }else if (exp(corr)>rand()/(double) RAND_MAX){
249 | lattice[seedID].spin*=-1;
250 | *p_totSpin+=(lattice[seedID].spin*2);
251 | *p_energy-=corr;
252 | }
253 | //printf("local update finished\n");
254 | }
255 |
256 | // interface to block update and local update algorithm
257 | void (*p_mcUpdate)(int totOrbs, Orb lattice[], double *p_energy, double *p_totSpin);
258 |
259 | PyObject * MCMainFunction(PyObject* self, PyObject* args){
260 | // read in all parameters
261 | PyObject* py_algorithm;
262 | PyObject* py_initSpin;
263 | PyObject* py_nthermal;
264 | PyObject* py_nsweep;
265 | PyObject* py_maxNLinking;
266 | PyObject* py_ninterval;
267 | PyObject* py_nlink;
268 | PyObject* py_linkStrength;
269 | PyObject* py_linkedOrb;
270 | PyObject* py_corrOrbPair;
271 | PyObject* py_h;
272 | PyObject* py_rOrb;
273 | PyObject* py_rOrbCluster;
274 | PyObject* py_linkedOrb_rnorm;
275 | PyObject* py_spinFrame;
276 | PyObject* callback; // callback function
277 | PyArg_ParseTuple(args,"OOOOOOOOOOOOOOOO",
278 | &py_algorithm,&py_initSpin,&py_nthermal,&py_nsweep,&py_ninterval,
279 | &py_maxNLinking,&py_nlink,&py_linkStrength,&py_linkedOrb,
280 | &py_corrOrbPair,
281 | &py_h,
282 | &py_rOrb,&py_rOrbCluster,&py_linkedOrb_rnorm,
283 | &py_spinFrame,
284 | &callback);
285 |
286 | int algorithm=(int)PyLong_AsLong(py_algorithm);
287 | //printf("%d\n",algorithm);
288 | int nthermal=(int)PyLong_AsLong(py_nthermal);
289 | int nsweep=(int)PyLong_AsLong(py_nsweep);
290 | int maxNLinking=(int)PyLong_AsLong(py_maxNLinking);
291 | int ninterval=(int)PyLong_AsLong(py_ninterval);
292 | int spinFrame=(int)PyLong_AsLong(py_spinFrame);
293 |
294 | int totOrbs=(int)PyTuple_Size(py_initSpin);
295 | double *initSpin=(double*)malloc(totOrbs*sizeof(double));
296 | for(int iorb=0;iorb0){
370 | output_per_sweep=nsweep/spinFrame;
371 | spinFrameData=PyTuple_New(spinFrame);
372 | }else{
373 | spinFrameData=PyFloat_FromDouble(0.0);
374 | }
375 | for(int i=0;i0 & i%output_per_sweep==0){
382 | PyObject *spinDistribution=PyTuple_New(totOrbs);
383 | for(int j=0;j0) *p_energy_rnorm+=getCorrEnergy_rnorm(lattice+j)/2-(lattice+j)->h*(lattice+j)->spin;
391 | }
392 | //printf("calc. energy for renormalized lattice done\n");
393 |
394 | // spin statistics over space in each frame
395 | double spin_i_avg=0;
396 | double spin_j_avg=0;
397 | double corrAvg=0.0;
398 | for(int j=0;j=norb or ki_t>=norb:
34 | print("ERROR: index out of range ki_S=%d, ki_t=%d, norb=%d\n"%(ki_s,ki_t,norb))
35 | raise("Input Error!")
36 | self.correlatedOrbitalPair=lat.establishLinking(self.lattice_array,bondList,ki_s=ki_s,ki_t=ki_t,ki_overLat=ki_overLat,Lmatrix=np.array(LMatrix),bmatrix=np.array(pos),dipoleAlpha=dipoleAlpha)
37 | self.dipoleCorrection = False
38 | if abs(dipoleAlpha)>1e-5:
39 | self.dipoleCorrection=True
40 | lat.generateDipoleBondings(self.lattice,dipoleAlpha/T,On=On)
41 | self.ID=ID
42 | self.T=T
43 | self.Sz=Lx*Ly*Lz*sum(S)
44 | self.Energy=0.
45 | self.blockLen=0
46 | self.ki_s=ki_s
47 | self.ki_t=ki_t
48 | self.h=h
49 | self.spinFrame=spinFrame
50 |
51 | def mainLoopViaCLib(self,nsweep=1000,nthermal=500,ninterval=-1,algo='Wolff'):
52 | self.nsweep=nsweep
53 | self.nthermal=nthermal
54 | ninterval=self.totOrbs if ninterval<=0 else ninterval
55 |
56 | # initial spin
57 | initSpin=[]
58 | nlinking=[]
59 | nlinking_list=[]
60 | for iorb, orb in enumerate(self.lattice):
61 | initSpin.append(orb.spin)
62 | nlinking.append(len(orb.linkedOrb))
63 | nlinking_list.append(len(orb.linkedOrb))
64 |
65 | # link strength
66 | maxNLinking=max(nlinking_list)
67 | #nlinking=len(orb.linkedOrb)
68 | linkStrength,linkData=[],[]
69 | #linkStrength_rnorm=(c_double*(self.totOrbs*maxNLinking))() # linking for renormalization
70 | for iorb, orb in enumerate(self.lattice):
71 | for ilinking in range(maxNLinking):
72 | if ilinking>=nlinking_list[iorb]:
73 | linkData.append(-1)
74 | linkStrength.append(0.)
75 | #linkStrength_rnorm[cnt]=c_double(0.)
76 | else:
77 | linkData.append(orb.linkedOrb[ilinking].id)
78 | linkStrength.append(orb.linkStrength[ilinking])
79 |
80 | #-------------------------------------------------------------------------------#
81 | # linking info. for renormalized lattice
82 | # count total sites in shrinked lat.
83 |
84 | #print("total %d orbs in renormalized lattice"%totOrb_rnorm)
85 | rOrb,rOrbCluster,linkData_rnorm=[],[],[] # store id of renormalized orbs in cluster
86 | for orb in self.lattice:
87 | if orb.chosen:
88 | rOrb.append(orb.id)
89 | #print("orb%d is chosen"%orb.id)
90 | for orbInCluster in orb.orb_cluster:
91 | rOrbCluster.append(orbInCluster.id)
92 |
93 | for iorb in range(maxNLinking):
94 | if iorb0:
134 | self.outputSpinDistributionForIsing(spinDistributionList)
135 | return spin_i, spin_j, spin_ij, autoCorr, E, E2, U4
136 |
137 | def mainLoopViaCLib_On(self,nsweep=1000,nthermal=5000,ninterval=-1,algo='Metroplis',On=3,flunc=0.0,h=0.,binGraph=False):
138 | def callback(k):
139 | print("callbak function of python is reporting, recived parameter is:")
140 | print(k)
141 | return
142 |
143 | self.nsweep=nsweep
144 | self.nthermal=nthermal
145 | ninterval=self.totOrbs if ninterval<=0 else ninterval
146 |
147 | updateAlgorithm=0 # default Metropolis algorithm
148 | if algo=='Wolff': updateAlgorithm=1
149 |
150 | initSpin,initD,nlinking=[],[],[]
151 | for orb in self.lattice:
152 | initSpin.append(orb.spin)
153 | for i in range(3):
154 | initD.append(orb.D[i])
155 | nlinking.append(len(orb.linkedOrb))
156 |
157 | # link strength
158 | ignoreNonDiagonalJ=1
159 | maxNLinking=max(nlinking)
160 | linkStrength,linkData=[],[] # thus the nlinking of every orbs are the same
161 |
162 | for iorb, orb in enumerate(self.lattice):
163 | #print("orb%d"%orb.id)
164 | for ilinking in range(maxNLinking):
165 | if ilinking>=nlinking[iorb]:
166 | linkData.append(-1)
167 | for i in range(9): # set the redundant bond strength to zero
168 | linkStrength.append(0.)
169 | else:
170 | linkData.append(orb.linkedOrb[ilinking].id)
171 | #print("link %d :"%ilinking,orb.linkStrength[ilinking])
172 | for i in range(9): # set the bond strength
173 | linkStrength.append(orb.linkStrength[ilinking][i])
174 | if abs(orb.linkStrength[ilinking][i]) > 1e-6 and i>=3: ignoreNonDiagonalJ=0
175 |
176 | # topological circuits
177 | localCircuits=[]
178 | for circuit in self.localCircuit:
179 | for orb in circuit: localCircuits+=[orb.id]
180 |
181 | # correlated info.
182 | corrOrbitalPair=[]
183 | for pair in self.correlatedOrbitalPair:corrOrbitalPair+=pair
184 |
185 | # orb group
186 | nOrbGroup=len(self.orbGroup)
187 | maxOrbGroupSize=1
188 | if nOrbGroup>0:
189 | maxOrbGroupSize=len(self.orbGroup[0])
190 | if nOrbGroup>1:
191 | maxOrbGroupSize=np.max([len(subGroup) for subGroup in self.orbGroup])
192 | orbGroupList=[]
193 | for subGroup in self.orbGroup:
194 | for iorb in range(maxOrbGroupSize):
195 | if iorb>>>")
209 | for orb in self.lattice:
210 | if orb.chosen:
211 | #print("orb%d is chosen"%orb.id)
212 | rOrb.append(orb.id)
213 | for orbInCluster in orb.orb_cluster:
214 | rOrbCluster.append(orbInCluster.id)
215 | #print(" orb%d"%orbInCluster.id)
216 |
217 | for iorb in range(maxNLinking):
218 | if iorb C C_v
261 | print('T=%.3f h=%.3f =%.3f =%.3f =%.3f =%.3f =%.3f =%.3f =%.3f =%.3f =%.3f =%.6f =%.3f =%.3f =%.3f r=%.3f rr=%.3f =%.3f =%.3f =%.3f'%(
262 | self.T,self.h,spin_i_tot_z,spin_j_tot_z,spin_tot_z,spin_i_h,spin_j_h,spin_tot_h,spin_i_len,spin_j_len,spin_ij,np.dot(spin_i,spin_j),E,E2, U4,spin_ij_r,np.dot(spin_i_r,spin_j_r), E_r, E2_r, topologicalQ))
263 | with open('./out','a') as fout:
264 | fout.write('T= %.6E h= %.6E = %.6E = %.6E = %.6E = %.6E = %.6E = %.6E = %.6E = %.6E = %.6E = %.6E = %.6E = %.6E = %.6E r= %.6E rr= %.6E = %.6E = %.6E = %.6E\n'%(
265 | self.T,self.h,spin_i_tot_z,spin_j_tot_z,spin_tot_z,spin_i_h,spin_j_h,spin_tot_h,spin_i_len,spin_j_len,spin_ij,np.dot(spin_i,spin_j),E,E2, U4,spin_ij_r,np.dot(spin_i_r,spin_j_r), E_r, E2_r, topologicalQ))
266 | # FFT on the MC random data makes no sense
267 | #if self.spinFrame==nsweep:self.outputSpinWaveSpetra(spinDistributionList)
268 |
269 | if self.spinFrame>0:self.outputSpinDistributionForOn(spinDistributionList)
270 |
271 | if len(self.orbGroup)>0:self.outputSpinGroup(spinDotSpinBetweenGroups)
272 | return spin_i, spin_j, spin_ij, autoCorr, E, E2, U4, topologicalQ
273 |
274 | def outputSpinGroup(self,spinDotSpinData):
275 | with open('./spinDotSpin.txt','a') as fout:
276 | # title
277 | fout.write('%.3f %.3f '%(self.T,self.h))
278 | cnt=0
279 | for i in range(len(self.orbGroup)+1):
280 | for j in range(len(self.orbGroup)+1):
281 | #keyword1='group_%d'%i if i!=self.orbGroup else 'Total'
282 | #keyword2='group_%d'%j if j!=self.orbGroup else 'Total'
283 | #title='#'+keyword1+'_'+keyword2+' '
284 | fout.write('%.6f '%spinDotSpinData[cnt])
285 | cnt+=1
286 | for i in range(len(self.orbGroup)+1):
287 | fout.write('%.6f '%spinDotSpinData[cnt])
288 | cnt+=1
289 | fout.write('\n')
290 |
291 | def outputSpinDistributionForIsing(self,distributionList):
292 | for iframe in range(self.spinFrame):
293 | with open('./IsingSpinDistribution.T%.3f.H%.3f.%d.txt'%(self.T,self.h,iframe),'w') as fout:
294 | fout.write("#x #y #z #spin\n")
295 | for orb in self.lattice:
296 | fout.write('%.6f %.6f %.6f %.3f\n'%(orb.x,orb.y,orb.z,
297 | distributionList[iframe][orb.id]))
298 |
299 | def outputSpinWaveSpetra(self,distributionList):
300 | print("start FFT")
301 | time0=time.time()
302 | # get the 1st orb on gamma-K
303 | cnt=0
304 | id_list=[]
305 | for i in range(self.Lx):
306 | id_list.append(self.lattice_array[i][i][0][0].id)
307 | cnt+=1
308 | if cnt>=self.Ly:
309 | break
310 | T_R_x_data=np.array(distributionList)[:,id_list,0]
311 | amplitude=np.log(abs(fft.fft2(T_R_x_data)))[:50,:]
312 | print("end FFT, time elapsed %.3fs"%(time.time()-time0))
313 | plt.imshow(amplitude,origin='lower',extent=(0,1,0,1))
314 | plt.show()
315 | exit()
316 |
317 | def outputSpinDistributionForOn(self,distributionList):
318 | for iframe in range(self.spinFrame):
319 | with open('./OnSpinDistribution.T%.3f.H%.3f.%d.txt'%(self.T,self.h,iframe),'w') as fout:
320 | fout.write("#x #y #z #spinx #spiny #spinz\n")
321 | for orb in self.lattice:
322 | fout.write('%.6f %.6f %.6f %.6f %.6f %.6f\n'%(orb.x,orb.y,orb.z,
323 | distributionList[iframe][orb.id][0],distributionList[iframe][orb.id][1],distributionList[iframe][orb.id][2]))
324 |
325 | def mainLoop(self,nsweep=10000,nthermal=5000):
326 | self.nsweep=nsweep
327 | self.nthermal=nthermal
328 | sAvgData=[]
329 | EnergyData=[]
330 | blockData=[]
331 |
332 | process=0
333 | for ithermal in range(nthermal):
334 | if ithermal>=nthermal*0.01*process:
335 | #print('thermalization %2d percent'%process)
336 | process+=1
337 | #print('thermalization:',ithermal)
338 | for imcStep in range(self.totOrbs):
339 | #self.LocalUpdate()
340 | self.BlockUpdate()
341 |
342 | print('sweep started')
343 | process=0
344 | for isweep in range(nsweep):
345 | if isweep>=nsweep*0.01*process:
346 | print('simulation has done %2d percent'%process)
347 | process+=1
348 | sAvgSweep=energySweep=blockSweep=0
349 | for imcStep in range(self.totOrbs):
350 | #self.LocalUpdate()
351 | self.BlockUpdate()
352 | sAvgSweep+=np.abs(self.Sz)
353 | energySweep+=self.Energy
354 | blockSweep+=self.blockLen
355 |
356 | #print(sAvgSweep/self.totOrbs)
357 | sAvgData.append(sAvgSweep/self.totOrbs)
358 | EnergyData.append(energySweep/self.totOrbs)
359 | blockData.append(blockSweep/self.totOrbs)
360 |
361 | self.sAvgData=sAvgData
362 | self.EnergyData=EnergyData
363 | print(np.mean(sAvgData)/self.totOrbs, np.std(sAvgData)/self.totOrbs, np.mean(blockData)/self.totOrbs/self.T)
364 | return np.mean(sAvgData), np.mean(EnergyData), np.std(sAvgData), np.std(EnergyData)
365 |
366 | def saveData(self):
367 | data=open('./task'+str(self.ID),'w')
368 | data.write('Temperature:%.3f \n'%self.T)
369 | data.write('Energy List, %5d total lines:\n'%self.nsweep)
370 | for energy in self.EnergyData:
371 | data.write('%.6f \n'%(energy/self.totOrbs))
372 | data.write('spin List, %5d total lines: \n'%self.nsweep)
373 | for spin in self.sAvgData:
374 | data.write('%.6f \n'%abs(spin/self.totOrbs))
375 | data.close()
376 |
377 | def LocalUpdate(self):
378 | seedOrb=self.lattice[randint(0,self.totOrbs-1)]
379 | corr=seedOrb.getCorrEnergyDirect()
380 | if corr>=0:
381 | seedOrb.spin*=-1
382 | self.Sz+=(seedOrb.spin*2)
383 | self.Energy-=corr*2
384 | elif np.exp(2*corr)>random():
385 | seedOrb.spin*=-1
386 | self.Sz+=(seedOrb.spin*2)
387 | self.Energy-=corr*2
388 | return
389 |
390 | def BlockUpdate(self):
391 | seedOrb=self.lattice[randint(0,self.totOrbs-1)]
392 | seedOrb.inBlock=True
393 | block=[seedOrb]
394 | buffer=[seedOrb]
395 |
396 | def expandBuffer():
397 | #print(len(buffer))
398 | if len(buffer)==0:
399 | return False
400 | outOrb=buffer.pop(0)
401 | for ilinkedOrb, linkedOrb in enumerate(outOrb.linkedOrb):
402 | if linkedOrb.inBlock:
403 | continue
404 | corr=outOrb.linkStrength[ilinkedOrb]*outOrb.spin*linkedOrb.spin
405 | if corr<0 and (1-np.exp(2*corr))>random.random():
406 | linkedOrb.inBlock=True
407 | block.append(linkedOrb)
408 | buffer.append(linkedOrb)
409 | return True
410 |
411 | while(expandBuffer()):
412 | pass
413 |
414 | for blockOrb in block:
415 | blockOrb.spin*=-1
416 | blockOrb.inBlock=False
417 | self.Sz+=(blockOrb.spin*2)
418 | #print(len(block))
419 | self.blockLen=len(block)
420 | return
421 |
422 |
423 |
424 |
--------------------------------------------------------------------------------
/mcsolver/toolbox.py:
--------------------------------------------------------------------------------
1 | from tkinter import Label, Entry, Listbox,Scrollbar, END, VERTICAL, N, S, StringVar
2 |
3 | class NoteFrm:
4 | frm_base=None
5 |
6 | label_list=[]
7 | entry_list=[]
8 | data_list=[]
9 |
10 | totn=2
11 | row=False
12 |
13 | def __init__(self,frm_base,init_notes=[],init_data=[0,0],totn=2,row=False,entryWidth=8,labelWidth=8):
14 | self.frm_base=frm_base
15 | self.totn=len(init_data)
16 | self.row=row
17 | self.entryWidth=entryWidth
18 | self.labelWidth=labelWidth
19 | self.loadlabel(frm_base,init_notes)
20 | self.loadentries(frm_base,init_data)
21 |
22 |
23 |
24 | def loadlabel(self,frm_base,init_notes):
25 | self.label_list=[]
26 | for i in range(self.totn):
27 | label=Label(frm_base,text=init_notes[i])
28 | self.label_list.append(label)
29 |
30 | if self.row:
31 | for i in range(self.totn):
32 | self.label_list[i].grid(row=0,column=2*i)
33 | #self.label_list[i+1].grid(row=0,column=3*i+2)
34 | else:
35 | for i in range(self.totn):
36 | self.label_list[i].grid(row=i,column=0)
37 | #self.label_list[2*i+1].grid(row=i,column=2)
38 |
39 |
40 | def loadentries(self,frm_base,init_data):
41 | self.entry_list=[]
42 | for i in range(self.totn):
43 | entry=Entry(frm_base,width=self.entryWidth)
44 | entry.insert(0,init_data[i])
45 | self.entry_list.append(entry)
46 |
47 | if self.row:
48 | for i in range(self.totn):
49 | self.entry_list[i].grid(row=0,column=2*i+1)
50 |
51 | else:
52 | for i in range(self.totn):
53 | self.entry_list[i].grid(row=i,column=1)
54 |
55 | def setValue(self,data=[1,600]):
56 | #print data
57 | for i in range(self.totn):
58 | self.entry_list[i].delete(0,END)
59 | self.entry_list[i].insert(0,data[i])
60 |
61 | def report(self,strrep=False):
62 | self.data_list=[]
63 | if strrep:
64 | for ele in self.entry_list:
65 | value=ele.get()
66 | #value=value if value else '0'
67 | self.data_list.append(value)
68 | else:
69 | for ele in self.entry_list:
70 | value=ele.get()
71 | self.data_list.append(float(value))
72 | return self.data_list
73 |
74 | class InfoList:
75 |
76 | def __init__(self,baseFrame, selectEvent, dataFormat, initialInfo=[],width=30,height=5):
77 | self.infoData=initialInfo
78 | self.dataFormat=dataFormat
79 | self.infoList=Listbox(baseFrame,width=width,height=height,listvariable=StringVar(value=[ele[0] for ele in self.infoData]))
80 | self.infoList.bind('<>',selectEvent)
81 | self.infoList.grid(row=0,column=0)
82 |
83 | self.scrollbar=Scrollbar(baseFrame,orient=VERTICAL, command=self.infoList.yview)
84 | self.scrollbar.grid(row=0,column=1,sticky=(N,S))
85 | self.infoList['yscrollcommand']=self.scrollbar.set
86 |
87 | self.updateInfo(self.infoData)
88 |
89 | def updateInfo(self,infoData=[]):
90 | self.infoList.delete(0,len(self.infoData)-1)
91 | self.infoData=infoData
92 | for iinfo, info in enumerate(self.infoData):
93 | info[0]=iinfo
94 | self.infoList.insert(iinfo,self.dataFormat(info))
95 | for i in range(0,len(self.infoData),2):
96 | self.infoList.itemconfigure(i, background='#f0f0ff')
97 |
98 | def report(self):
99 | idxs = self.infoList.curselection()
100 | if len(idxs)==1:
101 | return self.infoData[idxs[0]]
102 | return []
--------------------------------------------------------------------------------
/mcsolver/win.py:
--------------------------------------------------------------------------------
1 | from tkinter import Tk
2 | from multiprocessing import Pool, freeze_support
3 | import numpy as np
4 | import time
5 |
6 | try:
7 | from . import guiMain as gui
8 | from . import Lattice as lat
9 | from . import mcMain as mc
10 | from . import fileio as io
11 | except:
12 | import guiMain as gui
13 | import Lattice as lat
14 | import mcMain as mc
15 | import fileio as io
16 |
17 | global path, settingFileVersion
18 | libPool=[None,None,None]
19 | settingFileVersion=3.0
20 |
21 | def startMC(param): # start MC for Ising model
22 | # unzip all global parameters for every processing
23 | ID, T, bondList,LMatrix,pos,S,DList,h,nsweep,nthermal,ninterval,Lx,Ly,Lz,algorithm,GcOrb,orbGroupList,groupInSC,dipoleAlpha,spinFrame=param
24 | mcslave=mc.MC(ID,LMatrix,pos=pos,S=S,D=DList,bondList=bondList,T=T,Lx=Lx,Ly=Ly,Lz=Lz,ki_s=GcOrb[0][0],ki_t=GcOrb[0][1],ki_overLat=GcOrb[1],orbGroupList=orbGroupList,groupInSC=groupInSC,h=h,dipoleAlpha=dipoleAlpha,spinFrame=spinFrame)
25 | spin_i, spin_j, spin_ij, autoCorr, E, E2, U4=mcslave.mainLoopViaCLib(nsweep=nsweep,nthermal=nthermal,ninterval=ninterval,algo=algorithm)
26 | #mData=abs(mData)/Lx/Ly/Lz
27 | #eData/=(Lx*Ly*Lz)
28 | #print("=",np.mean(corr))
29 | return ID, T, h, spin_i, spin_j, spin_ij, autoCorr, E, E2, U4, mcslave.totOrbs
30 |
31 | def startMCForOn(param): # start MC for O(n) model
32 | # unzip all global parameters for every processing
33 | ID, T, bondList,LMatrix,pos,S,DList,h,nsweep,nthermal,ninterval,Lx,Ly,Lz,algorithm,On,GcOrb,orbGroupList,groupInSC,dipoleAlpha,spinFrame,localCircuit=param
34 | mcslave=mc.MC(ID,LMatrix,pos=pos,S=S,D=DList,bondList=bondList,T=T,Lx=Lx,Ly=Ly,Lz=Lz,ki_s=GcOrb[0][0],ki_t=GcOrb[0][1],ki_overLat=GcOrb[1],orbGroupList=orbGroupList,groupInSC=groupInSC,h=h,dipoleAlpha=dipoleAlpha,On=On,spinFrame=spinFrame,localCircuitList=localCircuit)
35 | spin_i, spin_j, spin_ij, autoCorr, E, E2, U4, topologicalQ = mcslave.mainLoopViaCLib_On(nsweep=nsweep,nthermal=nthermal,ninterval=ninterval,algo=algorithm,On=On)
36 | #mData=abs(mData)/Lx/Ly/Lz
37 | #eData/=(Lx*Ly*Lz)
38 | return ID, T, h, spin_i, spin_j, spin_ij, autoCorr, E, E2, U4, topologicalQ, mcslave.totOrbs
39 |
40 | def startSimulation(updateGUI=True, rpath=''):
41 | time0=time.time()
42 | # clean possible existed files
43 | with open('./out','w') as fout:
44 | fout.write('#T #H\n')
45 | with open('./spinDotSpin.txt','w') as fout:
46 | fout.write('#T #H\n')
47 |
48 | if updateGUI:
49 | gui.submitBtn.config(state='disabled')
50 | io.collectParam()
51 | else:
52 | if not io.loadParam(updateGUI=False, rpath=rpath):
53 | 'Error: win::startSimulation load file failed. stop this function.'
54 | return
55 |
56 | TList=np.linspace(io.T0,io.T1,io.nT)
57 | HList=np.linspace(io.H0,io.H1,io.nH)
58 | bondList=[lat.Bond(bond_data[0],bond_data[1], # source and target
59 | np.array([int(x) for x in bond_data[2]]), # over lat.
60 | bond_data[3],bond_data[4],bond_data[5], # strength Jxx, Jyy, Jzz
61 | bond_data[6],bond_data[7],bond_data[8], # strength Jxy, Jxz, Jyz
62 | bond_data[9],bond_data[10],bond_data[11], # strength Jyx, Jzx, Jzy
63 | True if io.modelType!='Ising' else False) # On
64 | for bond_data in io.bondList] # ergodic
65 | LMatrix=np.array(io.LMatrix)
66 | pos=np.array(io.pos)
67 |
68 | if(io.modelType=='Ising'):
69 | if io.algorithm!='Metropolis' and io.algorithm!='Wolff':
70 | print('For now, only Metropolis and Wolff algorithm is supported for Ising model')
71 | if updateGUI: gui.submitBtn.config(state='normal')
72 | return
73 |
74 | paramPack=[]
75 | for iH, H in enumerate(HList):
76 | for iT, T in enumerate(TList):
77 | paramPack.append([iH*len(TList)+iT,T,bondList,LMatrix,pos,io.S,io.DList,H,io.nsweep,io.nthermal,io.ninterval,io.LPack[0],io.LPack[1],io.LPack[2],io.algorithm,
78 | io.GcOrb,io.orbGroupList,io.groupInSC,io.dipoleAlpha,io.spinFrame])
79 |
80 | TResult=[];HResult=[];SpinIResult=[];SpinJResult=[];susResult=[];energyResult=[];capaResult=[];u4Result=[];QResult=[];autoCorrResult=[]
81 | while(True): # using pump strategy to reduce the costs of RAM
82 | if len(paramPack)==0:
83 | break
84 | # pump tasks
85 | paramPack_tmp=[]
86 | for index in range(io.ncores):
87 | paramPack_tmp.append(paramPack.pop(0))
88 | if len(paramPack)==0:
89 | break
90 | pool=Pool(processes=io.ncores)
91 | for result in pool.imap_unordered(startMC,paramPack_tmp):
92 | ID, T, h, spin_i, spin_j, spin_ij, autoCorr, E, E2, U4, N=result
93 | TResult.append(T)
94 | HResult.append(h)
95 | SpinIResult.append(spin_i)
96 | SpinJResult.append(spin_j)
97 | susResult.append((spin_ij-spin_i*spin_j)/T)
98 | QResult.append(0.)
99 | autoCorrResult.append(autoCorr)
100 | energyResult.append(E)
101 | capaResult.append((E2-E*E)/T**2*N)
102 | u4Result.append(U4)
103 | pool.close()
104 | if updateGUI: gui.updateResultViewer(TList=TResult if io.xAxisType=='T' else HResult, magList=[(si+sj)/2 for si,sj in zip(SpinIResult,SpinJResult)], susList=capaResult)
105 | # continuous model settings
106 | elif(io.modelType=='XY' or io.modelType=='Heisenberg'):
107 | for bond in bondList:
108 | bond.On=True # switch on the vector type bonding
109 | if io.algorithm!='Metropolis' and io.algorithm!='Wolff':
110 | print('For now, only Metropolis and Wolff algorithm is supported for O(n) model')
111 | if updateGUI: gui.submitBtn.config(state='normal')
112 | return
113 |
114 | On=2 if io.modelType=='XY' else 3
115 | paramPack=[]
116 | for iH, H in enumerate(HList):
117 | for iT, T in enumerate(TList):
118 | paramPack.append([iH*len(TList)+iT,T,bondList,LMatrix,pos,io.S,io.DList,H,io.nsweep,io.nthermal,io.ninterval,io.LPack[0],io.LPack[1],io.LPack[2],io.algorithm,On,
119 | io.GcOrb,io.orbGroupList,io.groupInSC,io.dipoleAlpha,io.spinFrame,io.localCircuitList])
120 |
121 | TResult=[];HResult=[];SpinIResult=[];SpinJResult=[];susResult=[];energyResult=[];capaResult=[];u4Result=[];QResult=[];autoCorrResult=[]
122 | while(True): # using pump strategy to reduce the costs of RAM
123 | if len(paramPack)==0:
124 | break
125 | # pump tasks
126 | paramPack_tmp=[]
127 | for index in range(io.ncores):
128 | paramPack_tmp.append(paramPack.pop(0))
129 | if len(paramPack)==0:
130 | break
131 | pool=Pool(processes=io.ncores)
132 | for result in pool.imap_unordered(startMCForOn,paramPack_tmp):
133 | ID, T, h, spin_i, spin_j, spin_ij, autoCorr, E, E2, U4, topologicalQ, N =result
134 | TResult.append(T)
135 | HResult.append(h)
136 | SpinIResult.append(np.sqrt(sum(spin_i*spin_i)))
137 | SpinJResult.append(np.sqrt(sum(spin_j*spin_j)))
138 | susResult.append((spin_ij-np.dot(spin_i,spin_j))/T)
139 | QResult.append(topologicalQ)
140 | autoCorrResult.append(autoCorr)
141 | energyResult.append(E)
142 | capaResult.append((E2-E*E)/T**2*N)
143 | u4Result.append(U4)
144 | pool.close()
145 | if updateGUI: gui.updateResultViewer(TList=TResult if io.xAxisType=='T' else HResult, magList=SpinIResult, susList=capaResult)
146 | else:
147 | print("for now only Ising, XY and Heisenberg model is supported")
148 | if updateGUI: gui.submitBtn.config(state='normal')
149 | return
150 |
151 | # writting result file
152 | f=open('./result.txt','w')
153 | f.write('#Temp #Field # # #Susc #Energy(K) #Capacity(K/K) #Topo.Q #U4 #Auto-corr. \n')
154 | for T, H, si, sj, sus, energy, capa, topo_q, u4, autoCorr in zip(TResult, HResult, SpinIResult, SpinJResult, susResult, energyResult, capaResult, QResult, u4Result, autoCorrResult):
155 | f.write('%15.6E%15.6E%15.6E%15.6E%15.6E%15.6E%15.6E%15.6E%15.6E%15.6E\n'%(T, H, si, sj, sus, energy, capa, topo_q, u4, autoCorr))
156 | f.close()
157 | if updateGUI: gui.submitBtn.config(state='normal')
158 | print("time elapsed %.3f s"%(time.time()-time0))
159 | return
160 |
161 | if __name__ == '__main__': # crucial for multiprocessing in Windows
162 | freeze_support()
163 | app=Tk(className='mc solver v3.0')
164 | gui.loadEverything(app,startSimulation)
165 | app.mainloop()
--------------------------------------------------------------------------------
/samples/CrI3With2NNCoupling:
--------------------------------------------------------------------------------
1 | This is mcsolver's save file, version: 3.0
2 | Lattice:
3 | 1.000000000 0.000000000 0.000000000
4 | -0.500000000 0.866025404 0.000000000
5 | 0.000000000 0.000000000 1.000000000
6 | Supercell used in MC simulations:
7 | 32 32 1
8 | Orbitals in cell:
9 | 2
10 | Positions, initial spin states and onsite-anisotropy of every orbital:
11 | orb 0: type 0 spin 1.500000000 pos [0.333333333 0.666666667 0.000000000] Dz -3.12276251875 Dx 0.000000000 Dy 0.000000000
12 | orb 1: type 0 spin 1.500000000 pos [0.666666667 0.333333333 0.000000000] Dz -3.12276251875 Dx 0.000000000 Dy 0.000000000
13 | Bonds:
14 | 12
15 | id, source, target, overLat, Jz, Jx, Jy of each bond:
16 | bond 0: Jz -19.49182553875 Jx -18.47237479 Jy -18.47237479 0 0 0 0 0 0 orb 0 to orb 1 over [0 0 0]
17 | bond 1: Jz -19.49182553875 Jx -18.47237479 Jy -18.47237479 0 0 0 0 0 0 orb 0 to orb 1 over [-1 0 0]
18 | bond 2: Jz -19.49182553875 Jx -18.47237479 Jy -18.47237479 0 0 0 0 0 0 orb 0 to orb 1 over [0 1 0]
19 | bond 3: Jz -5.7387258225 Jx -6.1364053675 Jy -6.1364053675 0 0 0 0 0 0 orb 0 to orb 0 over [1 0 0]
20 | bond 4: Jz -5.7387258225 Jx -6.1364053675 Jy -6.1364053675 0 0 0 0 0 0 orb 0 to orb 0 over [1 1 0]
21 | bond 5: Jz -5.7387258225 Jx -6.1364053675 Jy -6.1364053675 0 0 0 0 0 0 orb 0 to orb 0 over [0 1 0]
22 | bond 6: Jz -5.7387258225 Jx -6.1364053675 Jy -6.1364053675 0 0 0 0 0 0 orb 1 to orb 1 over [1 0 0]
23 | bond 7: Jz -5.7387258225 Jx -6.1364053675 Jy -6.1364053675 0 0 0 0 0 0 orb 1 to orb 1 over [1 1 0]
24 | bond 8: Jz -5.7387258225 Jx -6.1364053675 Jy -6.1364053675 0 0 0 0 0 0 orb 1 to orb 1 over [0 1 0]
25 | bond 9: Jz 4.57737083 Jx 4.474132450625 Jy 4.474132450625 0 0 0 0 0 0 orb 0 to orb 1 over [-1 1 0]
26 | bond 10: Jz 4.57737083 Jx 4.474132450625 Jy 4.474132450625 0 0 0 0 0 0 orb 0 to orb 1 over [1 1 0]
27 | bond 11: Jz 4.57737083 Jx 4.474132450625 Jy 4.474132450625 0 0 0 0 0 0 orb 0 to orb 1 over [-1 -1 0]
28 | Dipole long range correction:
29 | alpha 0.0
30 | Temperature scanning region:
31 | Tmin 30.000000000 Tmax 50.000000000 nT 21
32 | Field scanning region (in unit 1.48872 T, only if Kelvin and uB is used for energy and spin):
33 | Hmin 0 Hmax 0.1 nH 1
34 | Measurement:
35 | measure the correlation function between orb0 and orb0 over [0 0 0]
36 | OrbGroup: 2
37 | Supergroup
38 | group0 orb0-orb0
39 | group1 orb1-orb1
40 | >>> Topological section <<<
41 | LocalCircuit per cell: 0 (set to 0 to skip the calc. for topo. Q)
42 | >>> End of Topological section <<<
43 | Sweeps for thermalization and statistics, and relaxiation step for each sweep:
44 | 80000 640000 0
45 | Model type:
46 | Heisenberg
47 | Algorithm:
48 | Metropolis
49 | XAxis type:
50 | T
51 | Distribution output frame: 0
52 | Ncores:
53 | 6
54 |
--------------------------------------------------------------------------------
/samples/SkyrmionOnHexLattice:
--------------------------------------------------------------------------------
1 | This is mcsolver's save file, version: 3.0
2 | Lattice:
3 | 1 0 0
4 | -0.5 0.8660254 0
5 | 0 0 1
6 | Supercell used in MC simulations:
7 | 16 16 1
8 | Orbitals in cell:
9 | 2
10 | Positions, initial spin states and onsite-anisotropy of every orbital:
11 | orb 0: type 0 spin 1 pos [0.3333333 0.6666667 0] Dx 0 Dy 0 Dz -0.1 h 0
12 | orb 1: type 0 spin 1 pos [0.6666667 0.3333333 0] Dx 0 Dy 0 Dz -0.1 h 0
13 | Bonds:
14 | 3
15 | id, source, target, overLat, exchange matrix elements of each bond:
16 | bond 0: Jx -1 Jy -1 Jz -1 Jxy 0 Jxz -0.8660254 Jyz 0.5 Jyx 0 Jzx 0.8660254 Jzy -0.5 orb 0 to orb 1 over [ 0 0 0]
17 | bond 1: Jx -1 Jy -1 Jz -1 Jxy 0 Jxz 0 Jyz -1 Jyx 0 Jzx 0 Jzy 1 orb 0 to orb 1 over [ 0 1 0]
18 | bond 2: Jx -1 Jy -1 Jz -1 Jxy 0 Jxz 0.8660254 Jyz 0.5 Jyx 0 Jzx -0.8660254 Jzy -0.5 orb 0 to orb 1 over [-1 0 0]
19 | Temperature scanning region:
20 | Tmin 0.3 Tmax 0.3 nT 1
21 | Field scanning region (in unit 1.48872 T, only if Kelvin and uB is used for energy and spin):
22 | Hmin 0 Hmax 0.7 nH 16
23 | Dipole long-range coupling:
24 | alpha 0
25 | Measurement:
26 | measure the correlation function between orb0 and orb0 over [0 0 0]
27 | Supergroup
28 | OrbGroup:1
29 | Supergroup
30 | group0 orb0-orb0
31 | >>> Topological section <<<
32 | LocalCircuit per cell: 4 (set to 0 to skip the calc. for topo. Q)
33 | Circuit 0 enclosed by orb 1 [0 0 0], orb 1 [1 0 0], and orb 0 [1 0 0]
34 | Circuit 1 enclosed by orb 1 [1 0 0], orb 1 [1 1 0], and orb 0 [1 0 0]
35 | Circuit 2 enclosed by orb 1 [0 0 0], orb 0 [1 0 0], and orb 1 [1 1 0]
36 | Circuit 3 enclosed by orb 1 [0 0 0], orb 1 [1 1 0], and orb 1 [0 1 0]
37 | >>> End of Topological section <<<
38 | Distribution output frame: 1
39 | Sweeps for thermalization and statistics, and relaxiation step for each sweep:
40 | 40000 80000 0
41 | XAxis type:
42 | H
43 | Model type:
44 | Heisenberg
45 | Algorithm:
46 | Metropolis
47 | Ncores:
48 | 16
49 |
--------------------------------------------------------------------------------
/samples/SkyrmionOnSqaureLattice:
--------------------------------------------------------------------------------
1 | This is mcsolver's save file, version: 3.0
2 | Lattice:
3 | 1 0 0
4 | 0 1 0
5 | 0 0 1
6 | Supercell used in MC simulations:
7 | 16 16 1
8 | Orbitals in cell:
9 | 1
10 | Positions, initial spin states and onsite-anisotropy of every orbital:
11 | orb 0: type 0 spin 1 pos [0 0 0] Dx 0 Dy 0 Dz -0.1 h 0
12 | Bonds:
13 | 2
14 | id, source, target, overLat, exchange matrix elements of each bond:
15 | bond 0: Jx -1 Jy -1 Jz -1 Jxy 0 Jxz 1 Jyz 0 Jyx 0 Jzx -1 Jzy 0 orb 0 to orb 0 over [1 0 0]
16 | bond 1: Jx -1 Jy -1 Jz -1 Jxy 0 Jxz 0 Jyz 1 Jyx 0 Jzx 0 Jzy -1 orb 0 to orb 0 over [0 1 0]
17 | Temperature scanning region:
18 | Tmin 0.3 Tmax 0.3 nT 1
19 | Field scanning region (in unit 1.48872 T, only if Kelvin and uB is used for energy and spin):
20 | Hmin 0 Hmax 0.7 nH 8
21 | Dipole long-range coupling:
22 | alpha 0
23 | Measurement:
24 | measure the correlation function between orb0 and orb0 over [0 0 0]
25 | Supergroup
26 | OrbGroup:1
27 | Supergroup
28 | group0 orb0-orb0
29 | >>> Topological section <<<
30 | LocalCircuit per cell: 2 (set to 0 to skip the calc. for topo. Q)
31 | Circuit 0 enclosed by orb 0 [0 0 0], orb 0 [1 0 0], and orb 0 [1 1 0]
32 | Circuit 1 enclosed by orb 0 [0 0 0], orb 0 [1 1 0], and orb 0 [0 1 0]
33 | >>> End of Topological section <<<
34 | Distribution output frame: 0
35 | Sweeps for thermalization and statistics, and relaxiation step for each sweep:
36 | 40000 80000 0
37 | XAxis type:
38 | H
39 | Model type:
40 | Heisenberg
41 | Algorithm:
42 | Metropolis
43 | Ncores:
44 | 4
45 |
--------------------------------------------------------------------------------
/samples/Square_XY_isotropic:
--------------------------------------------------------------------------------
1 | This is mcsolver's save file, version: 3.0
2 | Lattice:
3 | 1.000000000 0.000000000 0.000000000
4 | 0.000000000 1.000000000 0.000000000
5 | 0.000000000 0.000000000 1.000000000
6 | Supercell used in MC simulations:
7 | 16 16 1
8 | Orbitals in cell:
9 | 1
10 | Positions, initial spin states and onsite-anisotropy of every orbital:
11 | orb 0: type 0 spin 1.000000000 pos [0.000000000 0.000000000 0.000000000] Dx 0.000000000 Dy 0.000000000 Dz 0.000000000 h 0.000000000
12 | Bonds:
13 | 2
14 | id, source, target, overLat, exchange matrix elements of each bond:
15 | bond 0: Jx -1.000000000 Jy -1.000000000 Jz -1.000000000 Jxy 0.000000000 Jxz 0.000000000 Jyz 0.000000000 Jyx 0.000000000 Jzx 0.000000000 Jzy 0.000000000 orb 0 to orb 0 over [1 0 0]
16 | bond 1: Jx -1.000000000 Jy -1.000000000 Jz -1.000000000 Jxy 0.000000000 Jxz 0.000000000 Jyz 0.000000000 Jyx 0.000000000 Jzx 0.000000000 Jzy 0.000000000 orb 0 to orb 0 over [0 1 0]
17 | Temperature scanning region:
18 | Tmin 0.900000000 Tmax 1.200000000 nT 8
19 | Field scanning region (in unit 1.48872 T, only if Kelvin and uB is used for energy and spin):
20 | Hmin 0.000000000 Hmax 0.100000000 nH 1
21 | Dipole long-range coupling:
22 | alpha 0.000000
23 | Measurement:
24 | measure the correlation function between orb0 and orb0 over [0 0 0]
25 | Supergroup
26 | OrbGroup:1
27 | Supergroup
28 | group0 orb0-orb0
29 | >>> Topological section <<<
30 | LocalCircuit per cell: 0 (set to 0 to skip the calc. for topo. Q)
31 | >>> End of Topological section <<<
32 | Distribution output frame: 0
33 | Sweeps for thermalization and statistics, and relaxiation step for each sweep:
34 | 40000 80000 1
35 | XAxis type:
36 | T
37 | Model type:
38 | XY
39 | Algorithm:
40 | Wolff
41 | Ncores:
42 | 4
43 |
--------------------------------------------------------------------------------
/samples/sim_XYmodel_under_Linux.py:
--------------------------------------------------------------------------------
1 | import mcsolver
2 |
3 | mcsolver.loadMC("./Square_XY_isotropic")
4 |
--------------------------------------------------------------------------------
/samples/sim_XYmodel_under_Windows.py:
--------------------------------------------------------------------------------
1 | from multiprocessing import freeze_support
2 | import mcsolver
3 |
4 | if __name__ == '__main__': # crucial for multiprocessing in Windows
5 | freeze_support()
6 | mcsolver.loadMC("./Square_XY_isotropic")
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | # -*- coding: UTF-8 -*-
2 | from distutils.core import setup, Extension
3 |
4 | with open("README.md", "r") as fh:
5 | long_description = fh.read()
6 |
7 | isingLib=Extension('isinglib',sources=['./mcsolver/isingLib.c'],language='c',extra_compile_args=['-std=c99','-fPIC','-O3'])
8 | xyLib=Extension('xylib',sources=['./mcsolver/xyLib.c'],language='c',extra_compile_args=['-std=c99','-fPIC','-O3'])
9 | heisenbergLib=Extension('heisenberglib',sources=['./mcsolver/heisenbergLib.c'],language='c',extra_compile_args=['-std=c99','-fPIC','-O3'])
10 |
11 | setup(
12 | name="mcsolver",
13 | version="3.1.1",
14 | author="Liang Liu",
15 | author_email="liangliu@main.sdu.edu.cn",
16 | description="A user friendly program to do Monte Carlo sims for magnetic systems",
17 | long_description=long_description,
18 | #long_description_content_type="text/markdown",
19 | url="https://github.com/golddoushi/mcsolver",
20 | packages=["mcsolver"],
21 | #include_package_data=True,
22 | ext_package="mcsolver.lib",
23 | ext_modules=[isingLib,xyLib,heisenbergLib],
24 | classifiers=[
25 | "Programming Language :: Python :: 3",
26 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
27 | "Development Status :: 4 - Beta",
28 | "Operating System :: OS Independent",
29 | "Topic :: Scientific/Engineering :: Physics",
30 | "Topic :: Scientific/Engineering :: Visualization",
31 | ],
32 | )
--------------------------------------------------------------------------------