From 63085fdbbf16addd82460d84e8d5f9a18b1ca936 Mon Sep 17 00:00:00 2001 From: Blazej Tez Date: Fri, 20 Jun 2025 16:08:35 +0200 Subject: [PATCH 1/6] chore: remove unused pylint file --- .pylintrc | 588 ------------------------------------------------------ 1 file changed, 588 deletions(-) delete mode 100644 .pylintrc diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index 8f4ebd7..0000000 --- a/.pylintrc +++ /dev/null @@ -1,588 +0,0 @@ -[MASTER] - -# A comma-separated list of package or module names from where C extensions may -# be loaded. Extensions are loading into the active Python interpreter and may -# run arbitrary code. -extension-pkg-whitelist= - -# Specify a score threshold to be exceeded before program exits with error. -fail-under=10.0 - -# Add files or directories to the blacklist. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the blacklist. The -# regex matches against base names, not paths. -ignore-patterns= - -# Python code to execute, usually for sys.path manipulation such as -# pygtk.require(). -#init-hook= - -# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the -# number of processors available to use. -jobs=1 - -# Control the amount of potential inferred values when inferring a single -# object. This can help the performance when dealing with large functions or -# complex, nested conditions. -limit-inference-results=100 - -# List of plugins (as comma separated values of python module names) to load, -# usually to register additional checkers. -load-plugins= - -# Pickle collected data for later comparisons. -persistent=yes - -# When enabled, pylint would attempt to guess common misconfiguration and emit -# user-friendly hints instead of false-positive error messages. -suggestion-mode=yes - -# Allow loading of arbitrary C extensions. Extensions are imported into the -# active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. -confidence= - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once). You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use "--disable=all --enable=classes -# --disable=W". -disable=print-statement, - parameter-unpacking, - unpacking-in-except, - old-raise-syntax, - backtick, - long-suffix, - old-ne-operator, - old-octal-literal, - import-star-module-level, - non-ascii-bytes-literal, - raw-checker-failed, - bad-inline-option, - locally-disabled, - file-ignored, - suppressed-message, - useless-suppression, - deprecated-pragma, - use-symbolic-message-instead, - apply-builtin, - basestring-builtin, - buffer-builtin, - cmp-builtin, - coerce-builtin, - execfile-builtin, - file-builtin, - long-builtin, - raw_input-builtin, - reduce-builtin, - standarderror-builtin, - unicode-builtin, - xrange-builtin, - coerce-method, - delslice-method, - getslice-method, - setslice-method, - no-absolute-import, - old-division, - dict-iter-method, - dict-view-method, - next-method-called, - metaclass-assignment, - indexing-exception, - raising-string, - reload-builtin, - oct-method, - hex-method, - nonzero-method, - cmp-method, - input-builtin, - round-builtin, - intern-builtin, - unichr-builtin, - map-builtin-not-iterating, - zip-builtin-not-iterating, - range-builtin-not-iterating, - filter-builtin-not-iterating, - using-cmp-argument, - eq-without-hash, - div-method, - idiv-method, - rdiv-method, - exception-message-attribute, - invalid-str-codec, - sys-max-int, - bad-python3-import, - deprecated-string-function, - deprecated-str-translate-call, - deprecated-itertools-function, - deprecated-types-field, - next-method-defined, - dict-items-not-iterating, - dict-keys-not-iterating, - dict-values-not-iterating, - deprecated-operator-function, - deprecated-urllib-function, - xreadlines-attribute, - deprecated-sys-function, - exception-escape, - comprehension-escape - -# Enable the message, report, category or checker with the given id(s). You can -# either give multiple identifier separated by comma (,) or put this option -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -enable=c-extension-no-member - - -[REPORTS] - -# Python expression which should return a score less than or equal to 10. You -# have access to the variables 'error', 'warning', 'refactor', and 'convention' -# which contain the number of messages in each category, as well as 'statement' -# which is the total number of statements analyzed. This score is used by the -# global evaluation report (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details. -#msg-template= - -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio). You can also give a reporter class, e.g. -# mypackage.mymodule.MyReporterClass. -output-format=text - -# Tells whether to display a full report or only the messages. -reports=no - -# Activate the evaluation score. -score=yes - - -[REFACTORING] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - -# Complete name of functions that never returns. When checking for -# inconsistent-return-statements if a never returning function is called then -# it will be considered as an explicit return statement and no message will be -# printed. -never-returning-functions=sys.exit - - -[BASIC] - -# Naming style matching correct argument names. -argument-naming-style=snake_case - -# Regular expression matching correct argument names. Overrides argument- -# naming-style. -#argument-rgx= - -# Naming style matching correct attribute names. -attr-naming-style=snake_case - -# Regular expression matching correct attribute names. Overrides attr-naming- -# style. -#attr-rgx= - -# Bad variable names which should always be refused, separated by a comma. -bad-names=foo, - bar, - baz, - toto, - tutu, - tata - -# Bad variable names regexes, separated by a comma. If names match any regex, -# they will always be refused -bad-names-rgxs= - -# Naming style matching correct class attribute names. -class-attribute-naming-style=any - -# Regular expression matching correct class attribute names. Overrides class- -# attribute-naming-style. -#class-attribute-rgx= - -# Naming style matching correct class names. -class-naming-style=PascalCase - -# Regular expression matching correct class names. Overrides class-naming- -# style. -#class-rgx= - -# Naming style matching correct constant names. -const-naming-style=UPPER_CASE - -# Regular expression matching correct constant names. Overrides const-naming- -# style. -#const-rgx= - -# Minimum line length for functions/classes that require docstrings, shorter -# ones are exempt. -docstring-min-length=-1 - -# Naming style matching correct function names. -function-naming-style=snake_case - -# Regular expression matching correct function names. Overrides function- -# naming-style. -#function-rgx= - -# Good variable names which should always be accepted, separated by a comma. -good-names=i, - j, - k, - ex, - Run, - _ - -# Good variable names regexes, separated by a comma. If names match any regex, -# they will always be accepted -good-names-rgxs= - -# Include a hint for the correct naming format with invalid-name. -include-naming-hint=no - -# Naming style matching correct inline iteration names. -inlinevar-naming-style=any - -# Regular expression matching correct inline iteration names. Overrides -# inlinevar-naming-style. -#inlinevar-rgx= - -# Naming style matching correct method names. -method-naming-style=snake_case - -# Regular expression matching correct method names. Overrides method-naming- -# style. -#method-rgx= - -# Naming style matching correct module names. -module-naming-style=snake_case - -# Regular expression matching correct module names. Overrides module-naming- -# style. -#module-rgx= - -# Colon-delimited sets of names that determine each other's naming style when -# the name regexes allow several styles. -name-group= - -# Regular expression which should only match function or class names that do -# not require a docstring. -no-docstring-rgx=^_ - -# List of decorators that produce properties, such as abc.abstractproperty. Add -# to this list to register other decorators that produce valid properties. -# These decorators are taken in consideration only for invalid-name. -property-classes=abc.abstractproperty - -# Naming style matching correct variable names. -variable-naming-style=snake_case - -# Regular expression matching correct variable names. Overrides variable- -# naming-style. -#variable-rgx= - - -[FORMAT] - -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -expected-line-ending-format= - -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ - -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' - -# Maximum number of characters on a single line. -max-line-length=100 - -# Maximum number of lines in a module. -max-module-lines=1000 - -# Allow the body of a class to be on the same line as the declaration if body -# contains single statement. -single-line-class-stmt=no - -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no - - -[LOGGING] - -# The type of string formatting that logging methods do. `old` means using % -# formatting, `new` is for `{}` formatting. -logging-format-style=old - -# Logging modules to check that the string format arguments are in logging -# function parameter format. -logging-modules=logging - - -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -notes=FIXME, - XXX, - TODO - -# Regular expression of note tags to take in consideration. -#notes-rgx= - - -[SIMILARITIES] - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - -# Ignore imports when computing similarities. -ignore-imports=no - -# Minimum lines number of a similarity. -min-similarity-lines=4 - - -[SPELLING] - -# Limits count of emitted suggestions for spelling mistakes. -max-spelling-suggestions=4 - -# Spelling dictionary name. Available dictionaries: none. To make it work, -# install the python-enchant package. -spelling-dict= - -# List of comma separated words that should not be checked. -spelling-ignore-words= - -# A path to a file that contains the private dictionary; one word per line. -spelling-private-dict-file= - -# Tells whether to store unknown words to the private dictionary (see the -# --spelling-private-dict-file option) instead of raising a message. -spelling-store-unknown-words=no - - -[STRING] - -# This flag controls whether inconsistent-quotes generates a warning when the -# character used as a quote delimiter is used inconsistently within a module. -check-quote-consistency=no - -# This flag controls whether the implicit-str-concat should generate a warning -# on implicit string concatenation in sequences defined over several lines. -check-str-concat-over-line-jumps=no - - -[TYPECHECK] - -# List of decorators that produce context managers, such as -# contextlib.contextmanager. Add to this list to register other decorators that -# produce valid context managers. -contextmanager-decorators=contextlib.contextmanager - -# List of members which are set dynamically and missed by pylint inference -# system, and so shouldn't trigger E1101 when accessed. Python regular -# expressions are accepted. -generated-members= - -# Tells whether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# Tells whether to warn about missing members when the owner of the attribute -# is inferred to be None. -ignore-none=yes - -# This flag controls whether pylint should warn about no-member and similar -# checks whenever an opaque object is returned when inferring. The inference -# can return multiple potential results while evaluating a Python object, but -# some branches might not be evaluated, which results in partial inference. In -# that case, it might be useful to still emit no-member and other checks for -# the rest of the inferred objects. -ignore-on-opaque-inference=yes - -# List of class names for which member attributes should not be checked (useful -# for classes with dynamically set attributes). This supports the use of -# qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local - -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis). It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules= - -# Show a hint with possible names when a member name was not found. The aspect -# of finding the hint is based on edit distance. -missing-member-hint=yes - -# The minimum edit distance a name should have in order to be considered a -# similar match for a missing member name. -missing-member-hint-distance=1 - -# The total number of similar names that should be taken in consideration when -# showing a hint for a missing member. -missing-member-max-choices=1 - -# List of decorators that change the signature of a decorated function. -signature-mutators= - - -[VARIABLES] - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid defining new builtins when possible. -additional-builtins= - -# Tells whether unused global variables should be treated as a violation. -allow-global-unused-variables=yes - -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_, - _cb - -# A regular expression matching the name of dummy variables (i.e. expected to -# not be used). -dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ - -# Argument names that match this expression will be ignored. Default to name -# with leading underscore. -ignored-argument-names=_.*|^ignored_|^unused_ - -# Tells whether we should check for unused import in __init__ files. -init-import=no - -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io - - -[CLASSES] - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__, - __new__, - setUp, - __post_init__ - -# List of member names, which should be excluded from the protected access -# warning. -exclude-protected=_asdict, - _fields, - _replace, - _source, - _make - -# List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls - -# List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=cls - - -[DESIGN] - -# Maximum number of arguments for function / method. -max-args=5 - -# Maximum number of attributes for a class (see R0902). -max-attributes=7 - -# Maximum number of boolean expressions in an if statement (see R0916). -max-bool-expr=5 - -# Maximum number of branch for function / method body. -max-branches=12 - -# Maximum number of locals for function / method body. -max-locals=15 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - -# Maximum number of return / yield for function / method body. -max-returns=6 - -# Maximum number of statements in function / method body. -max-statements=50 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=2 - - -[IMPORTS] - -# List of modules that can be imported at any level, not just the top level -# one. -allow-any-import-level= - -# Allow wildcard imports from modules that define __all__. -allow-wildcard-with-all=no - -# Analyse import fallback blocks. This can be used to support both Python 2 and -# 3 compatible code, which means that the block might have code that exists -# only in one or another interpreter, leading to false positives when analysed. -analyse-fallback-blocks=no - -# Deprecated modules which should not be used, separated by a comma. -deprecated-modules=optparse,tkinter.tix - -# Create a graph of external dependencies in the given file (report RP0402 must -# not be disabled). -ext-import-graph= - -# Create a graph of every (i.e. internal and external) dependencies in the -# given file (report RP0402 must not be disabled). -import-graph= - -# Create a graph of internal dependencies in the given file (report RP0402 must -# not be disabled). -int-import-graph= - -# Force import order to recognize a module as part of the standard -# compatibility libraries. -known-standard-library= - -# Force import order to recognize a module as part of a third party library. -known-third-party=enchant - -# Couples of modules and preferred modules, separated by a comma. -preferred-modules= - - -[EXCEPTIONS] - -# Exceptions that will emit a warning when being caught. Defaults to -# "BaseException, Exception". -overgeneral-exceptions=BaseException, - Exception From a073ac9b82e788b659d35cee87b8ef27d29594f6 Mon Sep 17 00:00:00 2001 From: Blazej Tez Date: Fri, 20 Jun 2025 16:08:48 +0200 Subject: [PATCH 2/6] chore: remove unused module Praktyki --- .gitmodules | 6 ------ src/Praktyki | 1 - 2 files changed, 7 deletions(-) delete mode 100644 .gitmodules delete mode 160000 src/Praktyki diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 58aba77..0000000 --- a/.gitmodules +++ /dev/null @@ -1,6 +0,0 @@ -[submodule "src/Praktyki"] - path = src/Praktyki - url = https://github.com/KolRobOsk/Praktyki.git -[submodule "src/qcpp"] - path = src/qcpp - url = git@cruncher:qcpp diff --git a/src/Praktyki b/src/Praktyki deleted file mode 160000 index bd392ab..0000000 --- a/src/Praktyki +++ /dev/null @@ -1 +0,0 @@ -Subproject commit bd392ab4dea8dba5773555dc402f97c82572fd29 From df17fecf676b196d9886a4f0fcd6ccb59ed7d393 Mon Sep 17 00:00:00 2001 From: Blazej Tez Date: Fri, 20 Jun 2025 16:09:19 +0200 Subject: [PATCH 3/6] chore: remove unused directory src/validation --- src/validation/__init__.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/validation/__init__.py diff --git a/src/validation/__init__.py b/src/validation/__init__.py deleted file mode 100644 index e69de29..0000000 From 78689c43bd32b34cb440d5a8552a31265936ac07 Mon Sep 17 00:00:00 2001 From: Blazej Tez Date: Fri, 20 Jun 2025 16:09:56 +0200 Subject: [PATCH 4/6] chore: remove unused class for cartesian to spherical coordinated --- src/util/cart2sph.py | 46 -------------------------------------------- 1 file changed, 46 deletions(-) delete mode 100644 src/util/cart2sph.py diff --git a/src/util/cart2sph.py b/src/util/cart2sph.py deleted file mode 100644 index a1b9984..0000000 --- a/src/util/cart2sph.py +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import numexpr as ne -import numpy as np -from data_structure import raster -import portion as P - - -class Cart2Sph: - def __init__(self, x_linspace, y_linspace, z_linspace): - - self.x, self.y, self.z = np.meshgrid(x_linspace, y_linspace, - z_linspace) - - def _cart2sph(self, x, y, z, ceval=ne.evaluate): - """ x, y, z : ndarray coordinates - ceval: backend to use: - - eval : pure Numpy - - numexpr.evaluate: Numexpr """ - azimuth = ceval('arctan2(y,x)') - print(f"{np.min(azimuth)}, {np.max(azimuth)}") - xy2 = ceval('x**2 + y**2') - elevation = ceval('arctan2(sqrt(xy2),z)') - print(f"{np.min(elevation)}, {np.max(elevation)}") - r = ceval('sqrt(xy2 + z**2)') - return r, azimuth, elevation - - def evaluate(self): - - r, azimuth, elevation = self._cart2sph(self.x,self.y,self.z) - print(azimuth.min()) - print(elevation.min()) - print(r.min()) - - return r, azimuth, elevation, self.x, self.y, self.z - - -if __name__ == "__main__": - - r = raster.Raster(1) - x_linspace = r.linspace(P.closed(-1., 1)) - - c = Cart2Sph(x_linspace, x_linspace, x_linspace) - - print(c.evaluate()) From 03e4c2dfabf55d9f530f8e2b36d9b6eb93d82d24 Mon Sep 17 00:00:00 2001 From: Blazej Tez Date: Fri, 20 Jun 2025 16:11:56 +0200 Subject: [PATCH 5/6] chore: move data folder one directory level higher, also it's not a module It does not belong to src directory --- {src/data => data}/visualize.py | 0 src/data/__init__.py | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {src/data => data}/visualize.py (100%) delete mode 100644 src/data/__init__.py diff --git a/src/data/visualize.py b/data/visualize.py similarity index 100% rename from src/data/visualize.py rename to data/visualize.py diff --git a/src/data/__init__.py b/src/data/__init__.py deleted file mode 100644 index e69de29..0000000 From 90aef96511cb1d2ae71059a3d4c43aa837888aee Mon Sep 17 00:00:00 2001 From: Blazej Tez Date: Sat, 21 Jun 2025 23:29:58 +0000 Subject: [PATCH 6/6] cleaning packages, removing unused files --- .gitignore | 24 +- .python-version | 1 + src/main.py => main.py | 3 +- requirements.txt | Bin 1110 -> 156 bytes run.sh | 3 + src/__init__.py | 0 src/solver/lobpcg_torch.py | 85 ------- src/solver/run.sh | 2 - .../util_cub.py => util/cub.py} | 211 +++++++++--------- data/visualize.py => visualize.py | 1 + 10 files changed, 124 insertions(+), 206 deletions(-) create mode 100644 .python-version rename src/main.py => main.py (97%) create mode 100644 run.sh delete mode 100644 src/__init__.py delete mode 100644 src/solver/lobpcg_torch.py delete mode 100755 src/solver/run.sh rename src/{data_structure/util_cub.py => util/cub.py} (91%) rename data/visualize.py => visualize.py (97%) diff --git a/.gitignore b/.gitignore index fe3d446..fdd0b13 100644 --- a/.gitignore +++ b/.gitignore @@ -1,13 +1,11 @@ -**/__pycache__ -**/misc -**/dist -**/build -**/src/Praktyki -**/src/qcpp -**/qc.egg-info -*.png -*.pdf -*.log -*.so -/.idea/ -/Praktyki/ \ No newline at end of file +**/__pycache__ +**/misc +**/dist +**/build +**/qc.egg-info +*.png +*.pdf +*.log +*.so +/.idea/ +/venv/ diff --git a/.python-version b/.python-version new file mode 100644 index 0000000..843a60c --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.9.21 diff --git a/src/main.py b/main.py similarity index 97% rename from src/main.py rename to main.py index 7a68379..25e2c6c 100644 --- a/src/main.py +++ b/main.py @@ -1,5 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- +#TODO: cleanup of main from boxes, linspaces instead +#TODO: remove mayavi, use visualize.py instead import argparse from typing import Tuple @@ -8,7 +10,6 @@ import portion as P from mayavi.mlab import contour3d, show -import Praktyki.cut_box_3D as box import psi.hydrogenpsi as hydrogenpsi import data_structure.raster as raster diff --git a/requirements.txt b/requirements.txt index e2c59771131003cb4f7aafabbe70d92632fb53b7..e146c9996c32d6645f290c884340f795ebfbc0be 100644 GIT binary patch literal 156 zcmXAiOA5m<3`F-nMWK5s{wzX4XDNvrVnh5PmP&p5I_>h!8)m%J{`B%%wD}Ne3lmH# zEnJVnM_h?4%wR^+mv9OUTjW0v;6^i?YJJ>f%>!+Y+@P_6KaQvwnCyVrIKwGIRmK))@PuwDFF@DMGXXU*F{NrXkrFjak7ww~K%92> zU>hdzj;_oxQDZDnR>z(u-g!*%kqQ-jn&lJU z>jN%klbCWM4G8t#IN#!^s-I8}B9Lz$m74HDnzt}Fs4l!-_@rp>!WI>|EvS_|n%XUh zP#Vz{4wnZPmH9vZcUNveOneq4tnzhkuRhsVuaUXF@VDfDO{_p;Y@4=3HKM+{k39@8 z!pqY8X~>oH%2P&osjj6*wJW@mqfs}xnK(Ko^X3d!rcIVxEvFPE&VJ4{oot*rbf#Sn zovM>=fg+kgifH!Yet{u2b?&NkFJf1d`jpY($mvXVYt)xEyn-d1R#rc$#(R!#pQ*O@ znp>ZMs`j^{ckj|J;A(hE;&(RWkyDyW%T5ejan8Rh7-Cv22;~fY>pJGPBV)*``_+Q1 K`6b0O9Qg%}o1?z~ diff --git a/run.sh b/run.sh new file mode 100644 index 0000000..c944ef7 --- /dev/null +++ b/run.sh @@ -0,0 +1,3 @@ +#!/bin/sh +source venv/bin/activate +python src/solver/ex.py 2>&1 | tee -a log diff --git a/src/__init__.py b/src/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/src/solver/lobpcg_torch.py b/src/solver/lobpcg_torch.py deleted file mode 100644 index 297a0c7..0000000 --- a/src/solver/lobpcg_torch.py +++ /dev/null @@ -1,85 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -import time - -import scipy.linalg -import cupy as cp -from data_structure import raster -from hamiltonian.hamiltonian import HamiltonianOperatorCuPy - - -class HydrogenLOBPCG: - def __init__(self, h: HamiltonianOperatorCuPy): - - self.h = h - pass - - def RayleighRitz(self, S): - - STS = np.transpose(S).dot(S) - Ddiag = np.diag(STS)**(-.5) - D = np.diag(Ddiag) - Ddiag = Ddiag[..., np.newaxis] - DSTSD = Ddiag * STS * Ddiag.T - - R = scipy.linalg.cholesky(DSTSD) - - invR = scipy.linalg.lapack.dtrtri(R)[0] # returns np.inv(R.T) - AS = self.h.matvec(S).get() - STAS = np.transpose(S).dot(AS) - AUX = invR.dot(Ddiag * STAS * Ddiag.T).dot(np.transpose(invR)) - w, v = scipy.linalg.eigh(AUX) - C = (Ddiag * np.transpose(invR)).dot(v) - return C, np.diag(w) - - def lobpcgK(self, X: np.ndarray, tau: float): - C, Theta = self.RayleighRitz(X) - diagTheta = np.diag(Theta) - diagTheta = diagTheta[..., np.newaxis] - nx = np.size(X, 1) - m = np.size(X, 0) - X = X.dot(C) - X = cp.array(X, dtype=cp.float32) - cdiagThetaT = cp.array(diagTheta.T, dtype=cp.float32) - R = (self.h.matvec(X) - X.dot(cdiagThetaT)).get() - S = np.empty((m, 2 * nx)) - S[:, :nx] = X.get() - S[:, nx:] = R - for i in range(20): - tic = time.time() - [C, Theta] = self.RayleighRitz(S) - X = S.dot(C[:, :nx]) - diagTheta = np.diag(Theta) - print(f'eigenvalue: {np.min(diagTheta)}') - diagTheta = diagTheta[..., np.newaxis] - tic1 = time.time() - R = self.h.operate_vec(X) - X * diagTheta.T[:, :nx] - toc1 = time.time() - print(f'time elapsed for R: {toc1-tic1} sec.') - P = S[:, nx:].dot(C[nx:, :nx]) - S = np.empty((m, 2 * nx + np.size(P, 1))) - S[:, :nx] = X - S[:, nx:2 * nx] = R - S[:, 2 * nx:] = P - toc = time.time() - print(f'time elapsed for one iteration: {toc-tic} sec.') - -if __name__ == "__main__": - HYDROGEN_RADIUS = 10. - ALPHA = 0.28294212105225837470023780155114 - - interval = P.closed(-HYDROGEN_RADIUS, HYDROGEN_RADIUS) - box_ = box.box3D(interval, interval, interval) - r = raster.Raster(10) - xl, yl, zl = r.box_linspaces(box_) - N = len(xl) * len(yl) * len(zl) - - hamiltonian = HamiltonianOperatorCuPy(xl, yl, zl, extent=HYDROGEN_RADIUS) - - h = HydrogenLOBPCG(hamiltonian) - X, Y, Z = cp.meshgrid(cp.array(xl), cp.array(yl), cp.array(zl)) - gaussian_orbital = cp.exp(-ALPHA * (X ** 2 + Y ** 2 + Z ** 2), dtype=cp.float32) - norm_factor = cp.sum(gaussian_orbital ** 2) * hamiltonian.h ** 3 - gaussian_orbital /= cp.sqrt(norm_factor) - x0 = cp.reshape(gaussian_orbital, (N, 1)).get() - h.lobpcgK(x0, 1e-4) diff --git a/src/solver/run.sh b/src/solver/run.sh deleted file mode 100755 index 3548cc4..0000000 --- a/src/solver/run.sh +++ /dev/null @@ -1,2 +0,0 @@ -source ~/mgr/qc/venv/bin/activate -python ex.py 2>&1 | tee -a log diff --git a/src/data_structure/util_cub.py b/src/util/cub.py similarity index 91% rename from src/data_structure/util_cub.py rename to src/util/cub.py index 8bc3eaf..b0bafee 100644 --- a/src/data_structure/util_cub.py +++ b/src/util/cub.py @@ -1,105 +1,106 @@ -import cupy as cp - - -def save_basic(file_path, array): - """ - Saves a 3D CuPy ndarray as a .cub file. - - Parameters: - file_path (str): Path to the .cub file. - array (cp.ndarray): 3D CuPy array to save. - """ - if array.ndim != 3: - raise ValueError("Array must be 3D.") - - # Get the shape of the array - shape = array.shape - - # Save the shape and data_structure to the file - with open(file_path, 'wb') as f: - # Save shape first (3 integers) - f.write(cp.array(shape, dtype=cp.int32).tobytes()) - - # Save the flattened array data_structure - f.write(array.astype(cp.float32).tobytes()) - -def save_cub(file_path, array, voxel_size=(1.0, 1.0, 1.0)): - """ - Saves a 3D CuPy ndarray as a .cub file with a single hydrogen atom at the center. - - Parameters: - file_path (str): Path to the .cub file. - array (cp.ndarray): 3D CuPy array to save. - voxel_size (tuple): Voxel size along each axis (dx, dy, dz). - """ - if array.ndim != 3: - raise ValueError("Array must be 3D.") - - nx, ny, nz = array.shape - dx, dy, dz = voxel_size - - # Calculate origin to center the grid at (0, 0, 0) - origin_x = - (nx * dx) / 2.0 - origin_y = - (ny * dy) / 2.0 - origin_z = - (nz * dz) / 2.0 - - with open(file_path, 'w') as f: - # First two comment lines - f.write("Generated by save_cub\n") - f.write("OUTER LOOP: X, MIDDLE LOOP: Y, INNER LOOP: Z\n") - - # Third line: number of atoms and origin of volumetric data_structure - f.write(f"{1:5d} {origin_x:12.6f} {origin_y:12.6f} {origin_z:12.6f}\n") - - # Next three lines: number of voxels and voxel vectors - f.write(f"{nx:5d} {dx:12.6f} {0.0:12.6f} {0.0:12.6f}\n") - f.write(f"{ny:5d} {0.0:12.6f} {dy:12.6f} {0.0:12.6f}\n") - f.write(f"{nz:5d} {0.0:12.6f} {0.0:12.6f} {dz:12.6f}\n") - - # Atom information: Single hydrogen atom at the center - # Atomic number for hydrogen is 1 - # Charge is 0.0 (assuming neutral atom) - f.write(f"{1:5d} {0.0:12.6f} {0.0:12.6f} {0.0:12.6f} {0.0:12.6f}\n") - - # Retrieve data_structure from GPU to CPU - data = array.get() - - # Volumetric data_structure: write one floating point number per voxel - # Outer loop: X, Middle loop: Y, Inner loop: Z - count = 0 - for ix in range(nx): - for iy in range(ny): - for iz in range(nz): - value = data[ix, iy, iz] - f.write(f"{value:13.5E}") - count += 1 - if count % 6 == 0: - f.write("\n") - # Ensure a newline after each Z-axis loop if needed - if count % 6 != 0: - f.write("\n") - # Add a final newline at the end of the file - f.write("\n") - - -def load_basic(file_path): - """ - Loads a .cub file into a 3D CuPy ndarray. - - Parameters: - file_path (str): Path to the .cub file. - - Returns: - cp.ndarray: The loaded 3D CuPy array. - """ - with open(file_path, 'rb') as f: - # Read the shape (3 integers) - shape = cp.frombuffer(f.read(12), dtype=cp.int32) - shape = tuple(shape.get()) - # Read the flattened array data_structure - array = cp.frombuffer(f.read(), dtype=cp.float32) - - # Reshape it into the original 3D shape - array = array.reshape(shape) - - return array +import cupy as cp + + +def save_basic(file_path, array): + """ + Saves a 3D CuPy ndarray as a .cub file. + + Parameters: + file_path (str): Path to the .cub file. + array (cp.ndarray): 3D CuPy array to save. + """ + if array.ndim != 3: + raise ValueError("Array must be 3D.") + + # Get the shape of the array + shape = array.shape + + # Save the shape and data_structure to the file + with open(file_path, "wb") as f: + # Save shape first (3 integers) + f.write(cp.array(shape, dtype=cp.int32).tobytes()) + + # Save the flattened array data_structure + f.write(array.astype(cp.float32).tobytes()) + + +def save_cub(file_path, array, voxel_size=(1.0, 1.0, 1.0)): + """ + Saves a 3D CuPy ndarray as a .cub file with a single hydrogen atom at the center. + + Parameters: + file_path (str): Path to the .cub file. + array (cp.ndarray): 3D CuPy array to save. + voxel_size (tuple): Voxel size along each axis (dx, dy, dz). + """ + if array.ndim != 3: + raise ValueError("Array must be 3D.") + + nx, ny, nz = array.shape + dx, dy, dz = voxel_size + + # Calculate origin to center the grid at (0, 0, 0) + origin_x = -(nx * dx) / 2.0 + origin_y = -(ny * dy) / 2.0 + origin_z = -(nz * dz) / 2.0 + + with open(file_path, "w") as f: + # First two comment lines + f.write("Generated by save_cub\n") + f.write("OUTER LOOP: X, MIDDLE LOOP: Y, INNER LOOP: Z\n") + + # Third line: number of atoms and origin of volumetric data_structure + f.write(f"{1:5d} {origin_x:12.6f} {origin_y:12.6f} {origin_z:12.6f}\n") + + # Next three lines: number of voxels and voxel vectors + f.write(f"{nx:5d} {dx:12.6f} {0.0:12.6f} {0.0:12.6f}\n") + f.write(f"{ny:5d} {0.0:12.6f} {dy:12.6f} {0.0:12.6f}\n") + f.write(f"{nz:5d} {0.0:12.6f} {0.0:12.6f} {dz:12.6f}\n") + + # Atom information: Single hydrogen atom at the center + # Atomic number for hydrogen is 1 + # Charge is 0.0 (assuming neutral atom) + f.write(f"{1:5d} {0.0:12.6f} {0.0:12.6f} {0.0:12.6f} {0.0:12.6f}\n") + + # Retrieve data_structure from GPU to CPU + data = array.get() + + # Volumetric data_structure: write one floating point number per voxel + # Outer loop: X, Middle loop: Y, Inner loop: Z + count = 0 + for ix in range(nx): + for iy in range(ny): + for iz in range(nz): + value = data[ix, iy, iz] + f.write(f"{value:13.5E}") + count += 1 + if count % 6 == 0: + f.write("\n") + # Ensure a newline after each Z-axis loop if needed + if count % 6 != 0: + f.write("\n") + # Add a final newline at the end of the file + f.write("\n") + + +def load_basic(file_path): + """ + Loads a .cub file into a 3D CuPy ndarray. + + Parameters: + file_path (str): Path to the .cub file. + + Returns: + cp.ndarray: The loaded 3D CuPy array. + """ + with open(file_path, "rb") as f: + # Read the shape (3 integers) + shape = cp.frombuffer(f.read(12), dtype=cp.int32) + shape = tuple(shape.get()) + # Read the flattened array data_structure + array = cp.frombuffer(f.read(), dtype=cp.float32) + + # Reshape it into the original 3D shape + array = array.reshape(shape) + + return array diff --git a/data/visualize.py b/visualize.py similarity index 97% rename from data/visualize.py rename to visualize.py index 3a6a5d0..04baab7 100644 --- a/data/visualize.py +++ b/visualize.py @@ -1,3 +1,4 @@ +#TODO it has to be either more interactive or more intelligent than that import numpy as np from data_structure.util_cub import load_basic from mayavi.modules.api import ScalarCutPlane