keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/math/gaussian/sum.h
.h
6,375
234
#ifndef SCITBX_MATH_GAUSSIAN_SUM_H #define SCITBX_MATH_GAUSSIAN_SUM_H #ifndef SCITBX_MATH_GAUSSIAN_SUM_MAX_N_TERMS #define SCITBX_MATH_GAUSSIAN_SUM_MAX_N_TERMS 10 #endif #include <scitbx/math/gaussian/term.h> #include <scitbx/array_family/small.h> #include <scitbx/array_family/shared.h> #include <scitbx/error.h> namespace scitbx { namespace math { namespace gaussian { //! Sum of Gaussian terms plus a constant. template <typename FloatType=double> class sum { public: //! Maximum number of terms. BOOST_STATIC_CONSTANT(std::size_t, max_n_terms=SCITBX_MATH_GAUSSIAN_SUM_MAX_N_TERMS); //! Default constructor. Some data members are not initialized! sum() {} //! Initialization of the constant. explicit sum(FloatType const& c, bool use_c=true) : c_(c), use_c_(use_c) { SCITBX_ASSERT(use_c || c == 0); } //! Initialization of the terms and optionally the constant. /*! If c is different from zero use_c will automatically be set to true. <p> Not available in Python. */ sum( af::small<term<FloatType>, max_n_terms> const& terms, FloatType const& c=0, bool use_c=false) : terms_(terms), c_(c), use_c_(use_c || c != 0) {} //! Initialization of the terms and optionally the constant. /*! If c is different from zero use_c will automatically be set to true. */ sum( af::small<FloatType, max_n_terms> const& a, af::small<FloatType, max_n_terms> const& b, FloatType const& c=0, bool use_c=false) : c_(c), use_c_(use_c || c != 0) { SCITBX_ASSERT(a.size() == b.size()); for(std::size_t i=0;i<a.size();i++) { terms_.push_back(term<FloatType>(a[i], b[i])); } } //! Initialization of the terms and optionally the constant. /*! If c is different from zero use_c will automatically be set to true. If ab contains an odd number of elements the last element is used to initialize c and use_c will bet set to true. */ sum( af::const_ref<FloatType> const& ab, FloatType const& c=0, bool use_c=false) : c_(c), use_c_(use_c || c != 0) { SCITBX_ASSERT(!use_c || ab.size() % 2 == 0); SCITBX_ASSERT(ab.size() / 2 <= max_n_terms); std::size_t n = ab.size(); if (n % 2 != 0) { n--; c_ = ab.back(); use_c_ = true; } for(std::size_t i=0;i<n;i+=2) { terms_.push_back(term<FloatType>(ab[i], ab[i+1])); } } //! Number of terms. std::size_t n_terms() const { return terms_.size(); } //! Terms. /*! Not available in Python. */ af::small<term<FloatType>, max_n_terms> const& terms() const { return terms_; } //! Array of coefficients a. af::small<FloatType, max_n_terms> array_of_a() const { af::small<FloatType, max_n_terms> result; for(std::size_t i=0;i<terms_.size();i++) { result.push_back(terms_[i].a); } return result; } //! Array of coefficients b. af::small<FloatType, max_n_terms> array_of_b() const { af::small<FloatType, max_n_terms> result; for(std::size_t i=0;i<terms_.size();i++) { result.push_back(terms_[i].b); } return result; } //! Coefficient c. FloatType const& c() const { return c_; } //! Flag. bool use_c() const { return use_c_; } //! Total number of parameters. std::size_t n_parameters() const { std::size_t result = n_terms() * 2; if (use_c()) result++; return result; } //! Array of parameters a0,b0,...,ai,bi[,c]. af::shared<FloatType> parameters() const { af::shared<FloatType> result; result.reserve(n_parameters()); for(std::size_t i=0;i<terms_.size();i++) { term<FloatType> const& ti = terms_[i]; result.push_back(ti.a); result.push_back(ti.b); } if (use_c()) result.push_back(c_); return result; } //! Sum of Gaussian terms at the point x, given x^2. FloatType at_x_sq(FloatType const& x_sq) const { FloatType result = c_; for(std::size_t i=0;i<terms_.size();i++) { result += terms_[i].at_x_sq(x_sq); } return result; } //! Sum of Gaussian terms at the points x, given x^2. af::shared<FloatType> at_x_sq(af::const_ref<FloatType> const& x_sq) const { af::shared<double> result(x_sq.size(),af::init_functor_null<double>()); for(std::size_t i=0;i<x_sq.size();i++) { result[i] = at_x_sq(x_sq[i]); } return result; } //! Sum of Gaussian terms at the point x. FloatType at_x(FloatType const& x) const { return at_x_sq(x * x); } //! Sum of Gaussian terms at the points x. af::shared<FloatType> at_x(af::const_ref<FloatType> const& x) const { af::shared<double> result(x.size(),af::init_functor_null<double>()); for(std::size_t i=0;i<x.size();i++) { result[i] = at_x(x[i]); } return result; } //! Gradient w.r.t. x at the point x. FloatType gradient_dx_at_x(FloatType const& x) const { FloatType result = 0; for(std::size_t i=0;i<terms_.size();i++) { result += terms_[i].gradient_dx_at_x(x); } return result; } //! Integral dx from 0 to the point x. FloatType integral_dx_at_x( FloatType const& x, FloatType const& b_min_for_erf_based_algorithm=1e-3) { FloatType result = c_ * x; for(std::size_t i=0;i<terms_.size();i++) { result += terms_[i].integral_dx_at_x( x, b_min_for_erf_based_algorithm); } return result; } protected: af::small<term<FloatType>, max_n_terms> terms_; FloatType c_; bool use_c_; }; }}} // scitbx::math::gaussian #endif // SCITBX_MATH_GAUSSIAN_SUM_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/math/erf/constants.h
.h
2,494
80
#ifndef SCITBX_MATH_ERF_CONSTANTS_H #define SCITBX_MATH_ERF_CONSTANTS_H #include <cstddef> namespace scitbx { namespace math { //! Port of http://www.netlib.org/specfun/erf (as of 2003 Dec 03). namespace erf_constants { //! Port of http://www.netlib.org/specfun/erf (as of 2003 Dec 03). /*! From the FORTRAN documentation: <pre> Explanation of machine-dependent constants XMIN = the smallest positive floating-point number. XINF = the largest positive finite floating-point number. XNEG = the largest negative argument acceptable to ERFCX; the negative of the solution to the equation 2*exp(x*x) = XINF. XSMALL = argument below which erf(x) may be represented by 2*x/sqrt(pi) and above which x*x will not underflow. A conservative value is the largest machine number X such that 1.0 + X = 1.0 to machine precision. XBIG = largest argument acceptable to ERFC; solution to the equation: W(x) * (1-0.5/x**2) = XMIN, where W(x) = exp(-x*x)/[x*sqrt(pi)]. XHUGE = argument above which 1.0 - 1/(2*x*x) = 1.0 to machine precision. A conservative value is 1/[2*sqrt(XSMALL)] XMAX = largest acceptable argument to ERFCX; the minimum of XINF and 1/[sqrt(pi)*XMIN]. </pre> */ template <typename FloatType> struct machine_dependent_base { machine_dependent_base( FloatType const& xinf_, FloatType const& xneg_, FloatType const& xsmall_, FloatType const& xbig_, FloatType const& xhuge_, FloatType const& xmax_) : xinf(xinf_), xneg(xneg_), xsmall(xsmall_), xbig(xbig_), xhuge(xhuge_), xmax(xmax_) {} FloatType xinf, xneg, xsmall, xbig, xhuge, xmax; }; template <typename FloatType, std::size_t SizeOfFloatType=sizeof(FloatType)> struct machine_dependent; template <typename FloatType> struct machine_dependent<FloatType, 4> : machine_dependent_base<FloatType> { machine_dependent() : machine_dependent_base<FloatType>( 3.40e38, -9.382, 5.96e-8, 9.194, 2.90e3, 4.79e37) {} }; template <typename FloatType> struct machine_dependent<FloatType, 8> : machine_dependent_base<FloatType> { machine_dependent() : machine_dependent_base<FloatType>( 1.79e308, -26.628e0, 1.11e-16, 26.543e0, 6.71e7, 2.53e307) {} }; }}} // namespace scitbx::math::erf_constants #endif // SCITBX_MATH_ERF_CONSTANTS_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/math/erf/engine.h
.h
6,740
188
#ifndef SCITBX_MATH_ERF_ENGINE_H #define SCITBX_MATH_ERF_ENGINE_H #include <scitbx/math/erf/constants.h> #include <cmath> namespace scitbx { namespace math { //! Port of http://www.netlib.org/specfun/erf (as of 2003 Dec 03). /*! From the FORTRAN documentation: <pre> This packet evaluates erf(x), erfc(x), and exp(x*x)*erfc(x) for a real argument x. It contains three FUNCTION type subprograms: ERF, ERFC, and ERFCX (or DERF, DERFC, and DERFCX), and one SUBROUTINE type subprogram, CALERF. The calling statements for the primary entries are: Y=ERF(X) (or Y=DERF(X)), Y=ERFC(X) (or Y=DERFC(X)), and Y=ERFCX(X) (or Y=DERFCX(X)). The routine CALERF is intended for internal packet use only, all computations within the packet being concentrated in this routine. The function subprograms invoke CALERF with the statement CALL CALERF(ARG,RESULT,JINT) where the parameter usage is as follows Function Parameters for CALERF call ARG Result JINT ERF(ARG) ANY REAL ARGUMENT ERF(ARG) 0 ERFC(ARG) ABS(ARG) .LT. XBIG ERFC(ARG) 1 ERFCX(ARG) XNEG .LT. ARG .LT. XMAX ERFCX(ARG) 2 The main computation evaluates near-minimax approximations from "Rational Chebyshev approximations for the error function" by W. J. Cody, Math. Comp., 1969, PP. 631-638. This transportable program uses rational functions that theoretically approximate erf(x) and erfc(x) to at least 18 significant decimal digits. The accuracy achieved depends on the arithmetic system, the compiler, the intrinsic functions, and proper selection of the machine-dependent constants. </pre> */ template <typename FloatType, typename AintIntType=long> struct erf_engine : erf_constants::machine_dependent<FloatType> { FloatType compute(FloatType const& arg, int jint) { FloatType sixten = 16.; FloatType four = 4.; FloatType one = 1.; FloatType half = .5; FloatType two = 2.; FloatType zero = 0.; FloatType sqrpi = 5.6418958354775628695e-1; FloatType thresh = 0.46875; FloatType a[] = {3.16112374387056560e00, 1.13864154151050156e02, 3.77485237685302021e02, 3.20937758913846947e03, 1.85777706184603153e-1 }; FloatType b[] = {2.36012909523441209e01, 2.44024637934444173e02, 1.28261652607737228e03, 2.84423683343917062e03 }; FloatType c[] = {5.64188496988670089e-1, 8.88314979438837594e0, 6.61191906371416295e01, 2.98635138197400131e02, 8.81952221241769090e02, 1.71204761263407058e03, 2.05107837782607147e03, 1.23033935479799725e03, 2.15311535474403846e-8 }; FloatType d[] = {1.57449261107098347e01, 1.17693950891312499e02, 5.37181101862009858e02, 1.62138957456669019e03, 3.29079923573345963e03, 4.36261909014324716e03, 3.43936767414372164e03, 1.23033935480374942e03 }; FloatType p[] = {3.05326634961232344e-1, 3.60344899949804439e-1, 1.25781726111229246e-1, 1.60837851487422766e-2, 6.58749161529837803e-4, 1.63153871373020978e-2 }; FloatType q[] = {2.56852019228982242e00, 1.87295284992346047e00, 5.27905102951428412e-1, 6.05183413124413191e-2, 2.33520497626869185e-3 }; FloatType result; FloatType x = arg; FloatType y = x; if (y < 0) y = -y; if (y <= thresh) { FloatType ysq = zero; if (y > this->xsmall) ysq = y * y; FloatType xnum = a[5-1]*ysq; FloatType xden = ysq; for(std::size_t i=1;i<=3;i++) { xnum = (xnum + a[i-1]) * ysq; xden = (xden + b[i-1]) * ysq; } result = x * (xnum + a[4-1]) / (xden + b[4-1]); if (jint != 0) result = one - result; if (jint == 2) result = exp_(ysq) * result; return result; } else if (y <= four) { FloatType xnum = c[9-1]*y; FloatType xden = y; for(std::size_t i=1;i<=7;i++) { xnum = (xnum + c[i-1]) * y; xden = (xden + d[i-1]) * y; } result = (xnum + c[8-1]) / (xden + d[8-1]); if (jint != 2) { FloatType ysq = aint_(y*sixten)/sixten; FloatType del_ = (y-ysq)*(y+ysq); result = exp_(-ysq*ysq) * exp_(-del_) * result; } } else { result = zero; if (y >= this->xbig) { if ((jint != 2) || (y >= this->xmax)) goto label_300; if (y >= this->xhuge) { result = sqrpi / y; goto label_300; } } FloatType ysq = one / (y * y); FloatType xnum = p[6-1]*ysq; FloatType xden = ysq; for(std::size_t i=1;i<=4;i++) { xnum = (xnum + p[i-1]) * ysq; xden = (xden + q[i-1]) * ysq; } result = ysq *(xnum + p[5-1]) / (xden + q[5-1]); result = (sqrpi - result) / y; if (jint != 2) { FloatType ysq = aint_(y*sixten)/sixten; FloatType del_ = (y-ysq)*(y+ysq); result = exp_(-ysq*ysq) * exp_(-del_) * result; } } label_300: if (jint == 0) { result = (half - result) + half; if (x < zero) result = -result; } else if (jint == 1) { if (x < zero) result = two - result; } else { if (x < zero) { if (x < this->xneg) { result = this->xinf; } else { FloatType ysq = aint_(x*sixten)/sixten; FloatType del_ = (x-ysq)*(x+ysq); y = exp_(ysq*ysq) * exp_(del_); result = (y+y) - result; } } } return result; } static FloatType exp_(FloatType const& x) { return static_cast<FloatType>(std::exp(x)); } static FloatType aint_(FloatType const& x) { return static_cast<FloatType>(static_cast<AintIntType>(x)); } }; }} // namespace scitbx::math #endif // SCITBX_MATH_ERF_ENGINE_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/fftpack/factorization.h
.h
2,249
79
#ifndef SCITBX_FFTPACK_FACTORIZATION_H #define SCITBX_FFTPACK_FACTORIZATION_H #include <scitbx/array_family/tiny_types.h> #include <scitbx/array_family/ref.h> #include <scitbx/array_family/shared.h> namespace scitbx { namespace fftpack { /*! \brief Determination of prime factors for both complex-to-complex and real-to-complex transforms. */ class factorization { public: //! Default constructor. factorization() : n_(0) {} //! Determination of the %factorization of N. /*! Computation of the prime factors of N with the specialization that one length-4 transform is computed instead of two length-2 transforms. */ factorization(std::size_t n, bool real_to_complex); //! Access the n that was passed to the constructor. std::size_t n() const { return n_; } //! Access the factors of n. af::shared<int> factors() const { return factors_; } protected: std::size_t n_; af::shared<int> factors_; }; namespace detail { template <typename IntegerType> IntegerType count_reduce(IntegerType& red_n, const IntegerType& factor) { IntegerType result = 0; while (red_n % factor == 0) { red_n /= factor; result++; } return result; } } // namespace detail inline // Potential NOINLINE factorization::factorization(std::size_t n, bool real_to_complex) : n_(n) { // Based on the first parts of FFTPACK41 cffti1.f and rffti1.f. const af::int3 opt_factors(3, 4, 2); af::int3 perm(2, 0, 1); if (real_to_complex) { // XXX does this make a difference? perm[1] = 1; perm[2] = 0; } af::int3 count; count.fill(0); int red_n = n_; int i; for (i = 0; red_n > 1 && i < opt_factors.size(); i++) { count[i] = detail::count_reduce(red_n, opt_factors[i]); } for (i = 0; i < opt_factors.size(); i++) { factors_.insert(factors_.end(), count[perm[i]], opt_factors[perm[i]]); } for (int factor = 5; red_n > 1; factor += 2) { factors_.insert( factors_.end(), detail::count_reduce(red_n, factor), factor); } } }} // namespace scitbx::fftpack #endif // SCITBX_FFTPACK_FACTORIZATION_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/fftpack/complex_to_complex_3d.h
.h
6,345
194
#ifndef SCITBX_FFTPACK_COMPLEX_TO_COMPLEX_3D_H #define SCITBX_FFTPACK_COMPLEX_TO_COMPLEX_3D_H #include <scitbx/fftpack/complex_to_complex.h> #include <scitbx/error.h> #include <omptbx/omp_or_stubs.h> //#define SCITBX_FFTPACK_COMPLEX_TO_COMPLEX_3D_NO_PRAGMA_OMP namespace scitbx { namespace fftpack { //! 3-dimensional complex-to-complex Fast Fourier Transformation. template <typename RealType, typename ComplexType = std::complex<RealType> > class complex_to_complex_3d { public: #ifndef DOXYGEN_SHOULD_SKIP_THIS typedef RealType real_type; typedef ComplexType complex_type; #endif // DOXYGEN_SHOULD_SKIP_THIS //! Default constructor. complex_to_complex_3d() {} //! Initialization for transforms of lengths n. /*! See also: Constructor of complex_to_complex. */ complex_to_complex_3d(const af::int3& n); //! Initialization for transforms of lengths n0, n1, n2. /*! See also: Constructor of complex_to_complex. */ complex_to_complex_3d(std::size_t n0, std::size_t n1, std::size_t n2); //! Access the n (or n0, n1, n2) that was passed to the constructor. af::int3 n() const { return af::int3(fft1d_[0].n(), fft1d_[1].n(), fft1d_[2].n()); } //! In-place "forward" Fourier transformation. /*! See also: complex_to_complex */ template <typename MapType> void forward( MapType map, real_type* scratch=0) { transform(select_sign<forward_tag>(), map, scratch); } //! In-place "backward" Fourier transformation. /*! See also: complex_to_complex */ template <typename MapType> void backward( MapType map, real_type* scratch=0) { transform(select_sign<backward_tag>(), map, scratch); } protected: // This accepts complex or real maps. template <typename Tag, typename MapType> void transform( select_sign<Tag> tag, MapType map, real_type* scratch) { typedef typename MapType::value_type real_or_complex_type; real_or_complex_type const* select_overload = 0; transform(tag, map, scratch, select_overload); } // Cast map of real to map of complex. template <typename Tag, typename MapType> void transform( select_sign<Tag> tag, MapType map, real_type* scratch, real_type const* select_overload) { SCITBX_ASSERT(select_overload == 0); typedef typename MapType::accessor_type accessor_type; accessor_type dim_real(map.accessor()); if (dim_real[2] % 2 != 0) { throw error("Number of elements in third dimension must be even."); } af::ref<complex_type, accessor_type> cmap( reinterpret_cast<complex_type*>(map.begin()), accessor_type(dim_real[0], dim_real[1], dim_real[2] / 2)); complex_type const* select_complex_overload = 0; transform(tag, cmap, scratch, select_complex_overload); } // Core routine always works on complex maps. template <typename Tag, typename MapType> void transform( select_sign<Tag> tag, MapType map, real_type* scratch, complex_type const* select_overload) { // FUTURE: move out of class body { if (select_overload != 0) { // Unreachable. // Trick to avoid g++ 4.4.0 warnings when compiling with -fopenmp. throw std::runtime_error(__FILE__); } int nx = fft1d_[0].n(); int ny = fft1d_[1].n(); int nz = fft1d_[2].n(); int seq_size = 2 * std::max(std::max(nx, ny), nz); scitbx::auto_array<real_type> seq_and_scratch; if (omp_in_parallel() == 0) omp_set_dynamic(0); #if !defined(SCITBX_FFTPACK_COMPLEX_TO_COMPLEX_3D_NO_PRAGMA_OMP) #pragma omp parallel #endif { int num_threads = omp_get_num_threads(); int i_thread = omp_get_thread_num(); #if !defined(SCITBX_FFTPACK_COMPLEX_TO_COMPLEX_3D_NO_PRAGMA_OMP) #pragma omp single #endif { seq_and_scratch = scitbx::auto_array<real_type>( new real_type[2 * seq_size * num_threads]); } real_type* scratch = seq_and_scratch.get() + 2 * seq_size * i_thread; complex_type* seq = reinterpret_cast<complex_type*>(scratch + seq_size); #if !defined(SCITBX_FFTPACK_COMPLEX_TO_COMPLEX_3D_NO_PRAGMA_OMP) #pragma omp for #endif for (int iz = 0; iz < nz; iz++) { for (int iy = 0; iy < ny; iy++) { for (int ix = 0; ix < nx; ix++) { seq[ix] = map(ix, iy, iz); } // Transform along x (slow direction) fft1d_[0].transform(tag, seq, scratch); for (int ix = 0; ix < nx; ix++) { map(ix, iy, iz) = seq[ix]; } } for (int ix = 0; ix < nx; ix++) { for (int iy = 0; iy < ny; iy++) { seq[iy] = map(ix, iy, iz); } // Transform along y (medium direction) fft1d_[1].transform(tag, seq, scratch); for (int iy = 0; iy < ny; iy++) { map(ix, iy, iz) = seq[iy]; } } } #if !defined(SCITBX_FFTPACK_COMPLEX_TO_COMPLEX_3D_NO_PRAGMA_OMP) #pragma omp for #endif for (int ix = 0; ix < nx; ix++) { for (int iy = 0; iy < ny; iy++) { // Transform along z (fast direction) fft1d_[2].transform(tag, &map(ix, iy, 0), scratch); } } } } } private: af::tiny<complex_to_complex<real_type, complex_type>, 3> fft1d_; }; template <typename RealType, typename ComplexType> complex_to_complex_3d<RealType, ComplexType >::complex_to_complex_3d(const af::int3& n) { for(std::size_t i=0;i<3;i++) { fft1d_[i] = complex_to_complex<real_type, complex_type>(n[i]); } } template <typename RealType, typename ComplexType> complex_to_complex_3d<RealType, ComplexType >::complex_to_complex_3d(std::size_t n0, std::size_t n1, std::size_t n2) { fft1d_[0] = complex_to_complex<real_type, complex_type>(n0); fft1d_[1] = complex_to_complex<real_type, complex_type>(n1); fft1d_[2] = complex_to_complex<real_type, complex_type>(n2); } }} // namespace scitbx::fftpack #endif // SCITBX_FFTPACK_COMPLEX_TO_COMPLEX_3D_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/fftpack/complex_to_complex.h
.h
25,010
753
#ifndef SCITBX_FFTPACK_COMPLEX_TO_COMPLEX_H #define SCITBX_FFTPACK_COMPLEX_TO_COMPLEX_H #include <scitbx/fftpack/factorization.h> #include <scitbx/fftpack/detail/ref.h> #include <scitbx/array_family/shared.h> #include <scitbx/auto_array.h> #include <algorithm> #include <complex> #include <cmath> namespace scitbx { //! Fast Fourier Transformations based on FFTPACK. /*! The Fast Fourier Transform toolbox provides 1-dimensional and 3-dimensional in-place complex-to-complex and real-to-complex transforms. There are no restrictions on the lengths of the sequences to be transformed. However, the transforms are most efficient when the sequence length is a product of 2, 3 and 5. <p> scitbx/fftpack is a pure C++ adaption of the complex-to-complex and real-to-complex transforms of FFTPACK Version 4.1 (Nov 1988) by Paul Swarztrauber (see http://www.scd.ucar.edu/softlib/FFTPACK.html and the references below). <p> The core of scitbx/fftpack is implemented exclusively in C++ header files. Therefore it is not necessary to link with a support library. Only the optional Python bindings that are provided for convenience need to be compiled. <p> scitbx/fftpack is reasonably fast on the machines where it was tested (Tru64 Unix, Linux, Windows with Visual C++ 6), but is not as fast as FFTW (http://www.fftw.org/). Depending on the machine, compiler settings, transform lengths and the dimensionality (1D or 3D), scitbx/fftpack is about 30%-300% slower than FFTW for transform lengths that are a multiple of 2, 3 and 5. This is no surprise, since FFTW is a very sophisticated library that adjusts itself to a particular hardware, and was developed specifically for modern, cache-based architectures. In particular, the performance on Athlon Linux machines is very impressive. Unfortunately, the FFTW license does not permit the inclusion in an Open Source project (the GNU General Public License is too restrictive). Therefore the public domain FFTPACK was chosen as the basis for scitbx/fftpack. <p> It is hoped that scitbx/fftpack facilitates the development of an elegant, generic C++ interface for Fast Fourier Transforms. Once such an interface is worked out, it should be easy to provide implementations with different core transform algorithms, such as FFTW. <p> <i>References</i>: <ul> <li>"Vectorizing the Fast Fourier Transforms", by Paul Swarztrauber, Parallel Computations, G. Rodrigue, ed., Academic Press, New York 1982. <li>"Fast Fourier Transforms Algorithms for Vector Computers", by Paul Swarztrauber, Parallel Computing, (1984) pp.45-63. </ul> */ namespace fftpack { #ifndef DOXYGEN_SHOULD_SKIP_THIS struct forward_tag {}; struct backward_tag {}; template <class Tag> struct select_sign {}; // FUTURE: use partial specialiation template <> struct select_sign<forward_tag> { template <class FloatType> static FloatType plusminus(const FloatType&a, const FloatType& b) { return a + b; } template <class FloatType> static FloatType minusplus(const FloatType&a, const FloatType& b) { return a - b; } template <class FloatType> static FloatType unaryplusminus(const FloatType&a) { return a; } template <class FloatType> static FloatType unaryminusplus(const FloatType&a) { return -a; } }; // FUTURE: use partial specialiation template <> struct select_sign<backward_tag> { template <class FloatType> static FloatType plusminus(const FloatType&a, const FloatType& b) { return a - b; } template <class FloatType> static FloatType minusplus(const FloatType&a, const FloatType& b) { return a + b; } template <class FloatType> static FloatType unaryplusminus(const FloatType&a) { return -a; } template <class FloatType> static FloatType unaryminusplus(const FloatType&a) { return a; } }; #endif // DOXYGEN_SHOULD_SKIP_THIS //! Complex-to-complex Fast Fourier Transformation. template <typename RealType, typename ComplexType = std::complex<RealType> > class complex_to_complex : public factorization { public: #ifndef DOXYGEN_SHOULD_SKIP_THIS typedef RealType real_type; typedef ComplexType complex_type; typedef detail::ref_2d_tp<real_type> dim2; typedef detail::ref_3d_tp<real_type> dim3; #endif // DOXYGEN_SHOULD_SKIP_THIS //! Default constructor. complex_to_complex() : factorization() {} //! Initialization for transforms of length n. /*! This constructor determines the factorization of n, pre-computes some constants, determines the "twiddle factors" needed in the transformation (n complex values), and allocates scratch space (n complex values). */ complex_to_complex(std::size_t n); //! Access to the pre-computed "twiddle factors." af::shared<real_type> wa() const { return wa_; } /*! \brief In-place "forward" Fourier transformation of a sequence of length n(). */ /*! Equivalent to, but much faster than the following Python code:<pre> for i in range(n): Sum = 0 for k in range(n): Sum += Seq_in[k] * exp(-2*pi*1j*i*k/n) Seq_out.append(Sum) </pre> Note that 1j is the imaginary number (sqrt(-1)) in Python. */ template <typename ComplexOrRealIterOrPtrType> void forward( ComplexOrRealIterOrPtrType seq_begin, real_type* scratch=0) { transform(select_sign<forward_tag>(), &(*seq_begin), scratch); } /*! \brief In-place "backward" Fourier transformation of a sequence of length n(). */ /*! Equivalent to, but much faster than the following Python code:<pre> for i in range(n): Sum = 0 for k in range(n): Sum += Seq_in[k] * exp(+2*pi*1j*i*k/n) Seq_out.append(Sum) </pre> Note that 1j is the imaginary number (sqrt(-1)) in Python. */ template <typename ComplexOrRealIterOrPtrType> void backward( ComplexOrRealIterOrPtrType seq_begin, real_type* scratch=0) { transform(select_sign<backward_tag>(), &(*seq_begin), scratch); } //! Generic in-place Fourier transformation of a contiguous sequence. template <typename Tag> void transform( select_sign<Tag> tag, complex_type* seq_begin, real_type* scratch=0) { transform(tag, reinterpret_cast<real_type*>(seq_begin), scratch); } //! Generic in-place Fourier transformation of a contiguous sequence. template <typename Tag> void transform( select_sign<Tag> tag, real_type* c, /* seq_begin */ real_type* ch=0 /* scratch */) // FUTURE: move out of class body { if (n_ < 2) return; scitbx::auto_array<real_type> scratch; if (ch == 0) { scratch = auto_array<real_type>(new real_type[n_ * 2]); ch = scratch.get(); } const real_type* wa = &(*(wa_.begin())); bool na = false; std::size_t l1 = 1; std::size_t iw = 0; for (std::size_t k1 = 0; k1 < factors_.size(); k1++) { std::size_t ip = factors_[k1]; std::size_t l2 = ip*l1; std::size_t ido = n_/l2; std::size_t idot = ido+ido; std::size_t idl1 = idot*l1; if (ip == 4) { std::size_t ix2 = iw+idot; std::size_t ix3 = ix2+idot; if (!na) { pass4(tag, idot,l1,c,ch,wa+iw,wa+ix2,wa+ix3); } else { pass4(tag, idot,l1,ch,c,wa+iw,wa+ix2,wa+ix3); } na = !na; } else if (ip == 2) { if (!na) { pass2(tag, idot,l1,c,ch,wa+iw); } else { pass2(tag, idot,l1,ch,c,wa+iw); } na = !na; } else if (ip == 3) { std::size_t ix2 = iw+idot; if (!na) { pass3(tag, idot,l1,c,ch,wa+iw,wa+ix2); } else { pass3(tag, idot,l1,ch,c,wa+iw,wa+ix2); } na = !na; } else if (ip == 5) { std::size_t ix2 = iw+idot; std::size_t ix3 = ix2+idot; std::size_t ix4 = ix3+idot; if (!na) { pass5(tag, idot,l1,c,ch,wa+iw,wa+ix2,wa+ix3,wa+ix4); } else { pass5(tag, idot,l1,ch,c,wa+iw,wa+ix2,wa+ix3,wa+ix4); } na = !na; } else { bool nac; if (!na) { passg(tag, nac, idot,ip,l1,idl1,iw,c,ch,wa); } else { passg(tag, nac, idot,ip,l1,idl1,iw,ch,c,wa); } if (nac) na = !na; } l1 = l2; iw = iw+(ip-1)*idot; } if (na) { std::copy(ch, ch + 2 * n_, c); } } private: // Constants. real_type two_pi_; real_type one_half_; real_type cos30_; real_type sin18_; real_type cos18_; real_type sin36_; real_type cos36_; static real_type deg_as_rad(const real_type& phi) { return phi * std::atan(real_type(1)) / real_type(45); } // Scratch space. af::shared<real_type> wa_; // Codelets for prime factors 2,3,4,5 and a general transform. template <class Tag> void pass2(select_sign<Tag>, std::size_t ido, std::size_t l1, real_type* cc_begin, real_type* ch_begin, const real_type* wa1) // FUTURE: move out of class body { dim3 cc(cc_begin, ido, 2, l1); dim3 ch(ch_begin, ido, l1, 2); if (ido == 2) { for (std::size_t k = 0; k < l1; k++) { ch(0,k,0) = cc(0,0,k) + cc(0,1,k); ch(1,k,0) = cc(1,0,k) + cc(1,1,k); ch(0,k,1) = cc(0,0,k) - cc(0,1,k); ch(1,k,1) = cc(1,0,k) - cc(1,1,k); } } else { for (std::size_t k = 0; k < l1; k++) { for (std::size_t i0 = 0; i0 < ido; i0 += 2) { std::size_t i1 = i0 + 1; ch(i0,k,0) = cc(i0,0,k) + cc(i0,1,k); ch(i1,k,0) = cc(i1,0,k) + cc(i1,1,k); real_type tr2 = cc(i0,0,k) - cc(i0,1,k); real_type ti2 = cc(i1,0,k) - cc(i1,1,k); ch(i0,k,1) = select_sign<Tag>::plusminus(wa1[i0]*tr2,wa1[i1]*ti2); ch(i1,k,1) = select_sign<Tag>::minusplus(wa1[i0]*ti2,wa1[i1]*tr2); } } } } template <class Tag> void pass3(select_sign<Tag>, std::size_t ido, std::size_t l1, real_type* cc_begin, real_type* ch_begin, const real_type* wa1, const real_type* wa2) // FUTURE: move out of class body { dim3 cc(cc_begin, ido, 3, l1); dim3 ch(ch_begin, ido, l1, 3); real_type taui = select_sign<Tag>::unaryminusplus(cos30_); if (ido == 2) { for (std::size_t k = 0; k < l1; k++) { real_type tr2 = cc(0,1,k) + cc(0,2,k); real_type ti2 = cc(1,1,k) + cc(1,2,k); real_type cr2 = cc(0,0,k) - one_half_ * tr2; real_type ci2 = cc(1,0,k) - one_half_ * ti2; real_type cr3 = taui * (cc(0,1,k) - cc(0,2,k)); real_type ci3 = taui * (cc(1,1,k) - cc(1,2,k)); ch(0,k,0) = cc(0,0,k) + tr2; ch(1,k,0) = cc(1,0,k) + ti2; ch(0,k,1) = cr2 - ci3; ch(1,k,1) = ci2 + cr3; ch(0,k,2) = cr2 + ci3; ch(1,k,2) = ci2 - cr3; } } else { for (std::size_t k = 0; k < l1; k++) { for (std::size_t i0 = 0; i0 < ido; i0 += 2) { std::size_t i1 = i0 + 1; real_type tr2 = cc(i0,1,k) + cc(i0,2,k); real_type ti2 = cc(i1,1,k) + cc(i1,2,k); real_type cr2 = cc(i0,0,k) - one_half_ * tr2; real_type ci2 = cc(i1,0,k) - one_half_ * ti2; real_type cr3 = taui * (cc(i0,1,k) - cc(i0,2,k)); real_type ci3 = taui * (cc(i1,1,k) - cc(i1,2,k)); real_type dr2 = cr2 - ci3; real_type di2 = ci2 + cr3; real_type dr3 = cr2 + ci3; real_type di3 = ci2 - cr3; ch(i0,k,0) = cc(i0,0,k) + tr2; ch(i1,k,0) = cc(i1,0,k) + ti2; ch(i0,k,1) = select_sign<Tag>::plusminus(wa1[i0]*dr2,wa1[i1]*di2); ch(i1,k,1) = select_sign<Tag>::minusplus(wa1[i0]*di2,wa1[i1]*dr2); ch(i0,k,2) = select_sign<Tag>::plusminus(wa2[i0]*dr3,wa2[i1]*di3); ch(i1,k,2) = select_sign<Tag>::minusplus(wa2[i0]*di3,wa2[i1]*dr3); } } } } template <class Tag> void pass4(select_sign<Tag>, std::size_t ido, std::size_t l1, real_type* cc_begin, real_type* ch_begin, const real_type* wa1, const real_type* wa2, const real_type* wa3) // FUTURE: move out of class body { dim3 cc(cc_begin, ido, 4, l1); dim3 ch(ch_begin, ido, l1, 4); if (ido == 2) { for (std::size_t k = 0; k < l1; k++) { real_type tr1 = cc(0,0,k)-cc(0,2,k); real_type ti1 = cc(1,0,k)-cc(1,2,k); real_type tr2 = cc(0,0,k)+cc(0,2,k); real_type ti2 = cc(1,0,k)+cc(1,2,k); real_type tr3 = cc(0,1,k)+cc(0,3,k); real_type ti3 = cc(1,1,k)+cc(1,3,k); real_type tr4 = select_sign<Tag>::unaryplusminus(cc(1,1,k)-cc(1,3,k)); real_type ti4 = select_sign<Tag>::unaryplusminus(cc(0,3,k)-cc(0,1,k)); ch(0,k,0) = tr2+tr3; ch(1,k,0) = ti2+ti3; ch(0,k,1) = tr1+tr4; ch(1,k,1) = ti1+ti4; ch(0,k,2) = tr2-tr3; ch(1,k,2) = ti2-ti3; ch(0,k,3) = tr1-tr4; ch(1,k,3) = ti1-ti4; } } else { for (std::size_t k = 0; k < l1; k++) { for (std::size_t i0 = 0; i0 < ido; i0 += 2) { std::size_t i1 = i0 + 1; real_type tr1 = cc(i0,0,k)-cc(i0,2,k); real_type ti1 = cc(i1,0,k)-cc(i1,2,k); real_type tr2 = cc(i0,0,k)+cc(i0,2,k); real_type ti2 = cc(i1,0,k)+cc(i1,2,k); real_type tr3 = cc(i0,1,k)+cc(i0,3,k); real_type ti3 = cc(i1,1,k)+cc(i1,3,k); real_type tr4 = select_sign<Tag>::unaryplusminus(cc(i1,1,k)-cc(i1,3,k)); real_type ti4 = select_sign<Tag>::unaryplusminus(cc(i0,3,k)-cc(i0,1,k)); real_type cr3 = tr2-tr3; real_type ci3 = ti2-ti3; real_type cr2 = tr1+tr4; real_type cr4 = tr1-tr4; real_type ci2 = ti1+ti4; real_type ci4 = ti1-ti4; ch(i0,k,0) = tr2+tr3; ch(i1,k,0) = ti2+ti3; ch(i0,k,1) = select_sign<Tag>::plusminus(wa1[i0]*cr2,wa1[i1]*ci2); ch(i1,k,1) = select_sign<Tag>::minusplus(wa1[i0]*ci2,wa1[i1]*cr2); ch(i0,k,2) = select_sign<Tag>::plusminus(wa2[i0]*cr3,wa2[i1]*ci3); ch(i1,k,2) = select_sign<Tag>::minusplus(wa2[i0]*ci3,wa2[i1]*cr3); ch(i0,k,3) = select_sign<Tag>::plusminus(wa3[i0]*cr4,wa3[i1]*ci4); ch(i1,k,3) = select_sign<Tag>::minusplus(wa3[i0]*ci4,wa3[i1]*cr4); } } } } template <class Tag> void pass5(select_sign<Tag>, std::size_t ido, std::size_t l1, real_type* cc_begin, real_type* ch_begin, const real_type* wa1, const real_type* wa2, const real_type* wa3, const real_type* wa4) // FUTURE: move out of class body { dim3 cc(cc_begin, ido, 5, l1); dim3 ch(ch_begin, ido, l1, 5); real_type ti11 = select_sign<Tag>::unaryminusplus(cos18_); real_type ti12 = select_sign<Tag>::unaryminusplus(sin36_); if (ido == 2) { for (std::size_t k = 0; k < l1; k++) { real_type tr2 = cc(0,1,k)+cc(0,4,k); real_type ti2 = cc(1,1,k)+cc(1,4,k); real_type tr3 = cc(0,2,k)+cc(0,3,k); real_type ti3 = cc(1,2,k)+cc(1,3,k); real_type tr4 = cc(0,2,k)-cc(0,3,k); real_type ti4 = cc(1,2,k)-cc(1,3,k); real_type tr5 = cc(0,1,k)-cc(0,4,k); real_type ti5 = cc(1,1,k)-cc(1,4,k); real_type cr2 = cc(0,0,k)+sin18_*tr2-cos36_*tr3; real_type ci2 = cc(1,0,k)+sin18_*ti2-cos36_*ti3; real_type cr3 = cc(0,0,k)-cos36_*tr2+sin18_*tr3; real_type ci3 = cc(1,0,k)-cos36_*ti2+sin18_*ti3; real_type cr5 = ti11*tr5+ti12*tr4; real_type ci5 = ti11*ti5+ti12*ti4; real_type cr4 = ti12*tr5-ti11*tr4; real_type ci4 = ti12*ti5-ti11*ti4; ch(0,k,0) = cc(0,0,k)+tr2+tr3; ch(1,k,0) = cc(1,0,k)+ti2+ti3; ch(0,k,1) = cr2-ci5; ch(1,k,1) = ci2+cr5; ch(0,k,2) = cr3-ci4; ch(1,k,2) = ci3+cr4; ch(0,k,3) = cr3+ci4; ch(1,k,3) = ci3-cr4; ch(0,k,4) = cr2+ci5; ch(1,k,4) = ci2-cr5; } } else { for (std::size_t k = 0; k < l1; k++) { for (std::size_t i0 = 0; i0 < ido; i0 += 2) { std::size_t i1 = i0 + 1; real_type tr2 = cc(i0,1,k)+cc(i0,4,k); real_type ti2 = cc(i1,1,k)+cc(i1,4,k); real_type tr3 = cc(i0,2,k)+cc(i0,3,k); real_type ti3 = cc(i1,2,k)+cc(i1,3,k); real_type tr4 = cc(i0,2,k)-cc(i0,3,k); real_type ti4 = cc(i1,2,k)-cc(i1,3,k); real_type tr5 = cc(i0,1,k)-cc(i0,4,k); real_type ti5 = cc(i1,1,k)-cc(i1,4,k); real_type cr2 = cc(i0,0,k)+sin18_*tr2-cos36_*tr3; real_type ci2 = cc(i1,0,k)+sin18_*ti2-cos36_*ti3; real_type cr3 = cc(i0,0,k)-cos36_*tr2+sin18_*tr3; real_type ci3 = cc(i1,0,k)-cos36_*ti2+sin18_*ti3; real_type cr4 = ti12*tr5-ti11*tr4; real_type ci4 = ti12*ti5-ti11*ti4; real_type cr5 = ti11*tr5+ti12*tr4; real_type ci5 = ti11*ti5+ti12*ti4; real_type dr3 = cr3-ci4; real_type dr4 = cr3+ci4; real_type di3 = ci3+cr4; real_type di4 = ci3-cr4; real_type dr5 = cr2+ci5; real_type dr2 = cr2-ci5; real_type di5 = ci2-cr5; real_type di2 = ci2+cr5; ch(i0,k,0) = cc(i0,0,k)+tr2+tr3; ch(i1,k,0) = cc(i1,0,k)+ti2+ti3; ch(i0,k,1) = select_sign<Tag>::plusminus(wa1[i0]*dr2,wa1[i1]*di2); ch(i1,k,1) = select_sign<Tag>::minusplus(wa1[i0]*di2,wa1[i1]*dr2); ch(i0,k,2) = select_sign<Tag>::plusminus(wa2[i0]*dr3,wa2[i1]*di3); ch(i1,k,2) = select_sign<Tag>::minusplus(wa2[i0]*di3,wa2[i1]*dr3); ch(i0,k,3) = select_sign<Tag>::plusminus(wa3[i0]*dr4,wa3[i1]*di4); ch(i1,k,3) = select_sign<Tag>::minusplus(wa3[i0]*di4,wa3[i1]*dr4); ch(i0,k,4) = select_sign<Tag>::plusminus(wa4[i0]*dr5,wa4[i1]*di5); ch(i1,k,4) = select_sign<Tag>::minusplus(wa4[i0]*di5,wa4[i1]*dr5); } } } } template <class Tag> void passg(select_sign<Tag>, bool& nac, std::size_t ido, std::size_t ip, std::size_t l1, std::size_t idl1, std::size_t iw, real_type* cc_begin, real_type* ch_begin, const real_type* wa) // FUTURE: move out of class body { dim3 cc(cc_begin, ido, ip, l1); dim3 c1(cc_begin, ido, l1, ip); dim2 c2(cc_begin, idl1, ip); dim3 ch(ch_begin, ido, l1, ip); dim2 ch2(ch_begin, idl1, ip); std::size_t idot = ido/2; std::size_t ipph = (ip+1)/2; std::size_t idp = ip*ido; if (ido >= l1) { for (std::size_t j = 1; j < ipph; j++) { std::size_t jc = ip-j; for (std::size_t k = 0; k < l1; k++) { for (std::size_t i = 0; i < ido; i++) { ch(i,k,j) = cc(i,j,k)+cc(i,jc,k); ch(i,k,jc) = cc(i,j,k)-cc(i,jc,k); } } } for (std::size_t k = 0; k < l1; k++) { for (std::size_t i = 0; i < ido; i++) { ch(i,k,0) = cc(i,0,k); } } } else { for (std::size_t j = 1; j < ipph; j++) { std::size_t jc = ip-j; for (std::size_t i = 0; i < ido; i++) { for (std::size_t k = 0; k < l1; k++) { ch(i,k,j) = cc(i,j,k)+cc(i,jc,k); ch(i,k,jc) = cc(i,j,k)-cc(i,jc,k); } } } for (std::size_t i = 0; i < ido; i++) { for (std::size_t k = 0; k < l1; k++) { ch(i,k,0) = cc(i,0,k); } } } std::size_t idl = 0; for (std::size_t l = 1; l < ipph; l++) { std::size_t lc = ip-l; for (std::size_t ik = 0; ik < idl1; ik++) { c2(ik,l) = ch2(ik,0)+wa[iw+idl]*ch2(ik,1); c2(ik,lc) = select_sign<Tag>::unaryminusplus( wa[iw+idl+1]*ch2(ik,ip-1)); } std::size_t idlj = idl; idl += ido; for (std::size_t j = 2; j < ipph; j++) { std::size_t jc = ip-j; idlj += idl; if (idlj >= idp) idlj = idlj-idp; real_type war = wa[iw+idlj]; real_type wai = wa[iw+idlj+1]; for (std::size_t ik = 0; ik < idl1; ik++) { c2(ik,l) = c2(ik,l)+war*ch2(ik,j); c2(ik,lc) = select_sign<Tag>::minusplus(c2(ik,lc),wai*ch2(ik,jc)); } } } std::size_t j; for (j = 1; j < ipph; j++) { for (std::size_t ik = 0; ik < idl1; ik++) { ch2(ik,0) += ch2(ik,j); } } for (j = 1; j < ipph; j++) { std::size_t jc = ip-j; for (std::size_t ik0 = 0; ik0 < idl1; ik0 += 2) { std::size_t ik1 = ik0 + 1; ch2(ik0,j) = c2(ik0,j)-c2(ik1,jc); ch2(ik0,jc) = c2(ik0,j)+c2(ik1,jc); ch2(ik1,j) = c2(ik1,j)+c2(ik0,jc); ch2(ik1,jc) = c2(ik1,j)-c2(ik0,jc); } } if (ido == 2) { nac = true; return; } std::copy(ch_begin, ch_begin + idl1, cc_begin); for (j = 1; j < ip; j++) { for (std::size_t k = 0; k < l1; k++) { c1(0,k,j) = ch(0,k,j); c1(1,k,j) = ch(1,k,j); } } if (idot <= l1) { std::size_t idij = 2; for (std::size_t j = 1; j < ip; j++) { for (std::size_t i0 = 2; i0 < ido; i0 += 2) { std::size_t i1 = i0 + 1; for (std::size_t k = 0; k < l1; k++) { c1(i0,k,j) = select_sign<Tag>::plusminus( wa[iw+idij]*ch(i0,k,j),wa[iw+idij+1]*ch(i1,k,j)); c1(i1,k,j) = select_sign<Tag>::minusplus( wa[iw+idij]*ch(i1,k,j),wa[iw+idij+1]*ch(i0,k,j)); } idij += 2; } idij += 2; } } else { std::size_t idj = 2; for (std::size_t j = 1; j < ip; j++) { for (std::size_t k = 0; k < l1; k++) { std::size_t idij = idj; for (std::size_t i0 = 2; i0 < ido; i0 += 2) { std::size_t i1 = i0 + 1; c1(i0,k,j) = select_sign<Tag>::plusminus( wa[iw+idij]*ch(i0,k,j),wa[iw+idij+1]*ch(i1,k,j)); c1(i1,k,j) = select_sign<Tag>::minusplus( wa[iw+idij]*ch(i1,k,j),wa[iw+idij+1]*ch(i0,k,j)); idij += 2; } } idj += ido; } } nac = false; return; } }; template <typename RealType, typename ComplexType> complex_to_complex<RealType, ComplexType>::complex_to_complex(std::size_t n) : factorization(n, false), wa_(2 * n) { if (n_ < 2) return; // Precompute constants for real_type. two_pi_ = real_type(8) * std::atan(real_type(1)); one_half_ = real_type(1) / real_type(2); cos30_ = std::cos(deg_as_rad(30)); sin18_ = std::sin(deg_as_rad(18)); cos18_ = std::cos(deg_as_rad(18)); sin36_ = std::sin(deg_as_rad(36)); cos36_ = std::cos(deg_as_rad(36)); // Computation of the sin and cos terms. // Based on the second part of fftpack41/cffti1.f. real_type* wa = &(*(wa_.begin())); real_type argh = two_pi_ / real_type(n_); std::size_t i = 0; std::size_t l1 = 1; for (std::size_t k1 = 0; k1 < factors_.size(); k1++) { std::size_t ip = factors_[k1]; std::size_t ld = 0; std::size_t l2 = l1 * ip; std::size_t idot = 2 * (n_ / l2) + 2; for (std::size_t j = 0; j < ip - 1; j++) { std::size_t i1 = i; wa[i ] = real_type(1); wa[i+1] = real_type(0); ld += l1; std::size_t fi = 0; real_type argld = real_type(ld) * argh; for (std::size_t ii = 4; ii <= idot; ii += 2) { i += 2; fi++; real_type arg = real_type(fi) * argld; wa[i ] = std::cos(arg); wa[i+1] = std::sin(arg); } if (ip > 5) { wa[i1 ] = wa[i ]; wa[i1+1] = wa[i+1]; } } l1 = l2; } } }} // namespace scitbx::fftpack #endif // SCITBX_FFTPACK_COMPLEX_TO_COMPLEX_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/fftpack/detail/ref.h
.h
1,113
50
#ifndef SCITBX_FFTPACK_DETAIL_REF_H #define SCITBX_FFTPACK_DETAIL_REF_H namespace scitbx { namespace fftpack { namespace detail { template <class ElementType> class ref_2d_tp { public: ref_2d_tp(ElementType* Start, std::size_t nx, std::size_t) : start_(Start), nx_(nx) {} ElementType& operator()(std::size_t ix, std::size_t iy) { return start_[iy * nx_ + ix]; } private: ElementType* start_; std::size_t nx_; }; template <class ElementType> class ref_3d_tp { public: ref_3d_tp(ElementType* Start, std::size_t nx, std::size_t ny, std::size_t) : start_(Start), nx_(nx), ny_(ny) {} ElementType& operator()(std::size_t ix, std::size_t iy, std::size_t iz) { return start_[(iz * ny_ + iy) * nx_ + ix]; } private: ElementType* start_; std::size_t nx_; std::size_t ny_; }; }}} // namespace scitbx::fftpack::detail #endif // SCITBX_FFTPACK_DETAIL_REF_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/ref.h
.h
15,046
516
#ifndef SCITBX_ARRAY_FAMILY_REF_H #define SCITBX_ARRAY_FAMILY_REF_H #include <scitbx/error.h> #include <scitbx/math/traits.h> #include <scitbx/array_family/error.h> #include <scitbx/array_family/accessors/trivial.h> #include <scitbx/array_family/detail/ref_helpers.h> #include <algorithm> #include <boost/scoped_array.hpp> namespace scitbx { namespace af { template <typename ElementType, typename AccessorType = trivial_accessor> class const_ref { public: SCITBX_ARRAY_FAMILY_TYPEDEFS typedef AccessorType accessor_type; typedef typename accessor_type::index_type index_type; typedef typename accessor_type::index_value_type index_value_type; const_ref() {} const_ref(const ElementType* begin, accessor_type const& accessor) : begin_(begin), accessor_(accessor) { init(); } // convenience constructors const_ref(const ElementType* begin, index_value_type const& n0) : begin_(begin), accessor_(n0) { init(); } const_ref(const ElementType* begin, index_value_type const& n0, index_value_type const& n1) : begin_(begin), accessor_(n0, n1) { init(); } const_ref(const ElementType* begin, index_value_type const& n0, index_value_type const& n1, index_value_type const& n2) : begin_(begin), accessor_(n0, n1, n2) { init(); } accessor_type const& accessor() const { return accessor_; } size_type size() const { return size_; } /// Matrix ref interface (only make sense for relevant accessors) //@{ bool is_square() const { return accessor_.is_square(); } std::size_t n_rows() const { return accessor_.n_rows(); } std::size_t n_columns() const { return accessor_.n_columns(); } bool is_diagonal(bool require_square=true) const; //@} const ElementType* begin() const { return begin_; } const ElementType* end() const { return end_; } const_reverse_iterator rbegin() const { return const_reverse_iterator(end_); } const_reverse_iterator rend() const { return const_reverse_iterator(begin_); } ElementType const& front() const { return begin_[0]; } ElementType const& back() const { return end_[-1]; } ElementType const& operator[](size_type i) const { return begin_[i]; } ElementType const& at(size_type i) const { if (i >= size_) throw_range_error(); return begin_[i]; } const_ref<ElementType> as_1d() const { return const_ref<ElementType>(begin_, size_); } value_type const& operator()(index_type const& i) const { return begin_[accessor_(i)]; } // Convenience operator() value_type const& operator()(index_value_type const& i0) const { return begin_[accessor_(i0)]; } value_type const& operator()(index_value_type const& i0, index_value_type const& i1) const { return begin_[accessor_(i0, i1)]; } value_type const& operator()(index_value_type const& i0, index_value_type const& i1, index_value_type const& i2) const { return begin_[accessor_(i0, i1, i2)]; } bool all_eq(const_ref const& other) const; bool all_eq(ElementType const& other) const; bool all_ne(const_ref const& other) const; bool all_ne(ElementType const& other) const; bool all_lt(const_ref const& other) const; bool all_lt(ElementType const& other) const; bool all_gt(const_ref const& other) const; bool all_gt(ElementType const& other) const; bool all_le(const_ref const& other) const; bool all_le(ElementType const& other) const; bool all_ge(const_ref const& other) const; bool all_ge(ElementType const& other) const; bool all_approx_equal( const_ref const& other, typename scitbx::math::abs_traits< ElementType>::result_type const& tolerance) const; bool all_approx_equal( ElementType const& other, typename scitbx::math::abs_traits< ElementType>::result_type const& tolerance) const; bool all_approx_equal_relatively( const_ref const& other, typename scitbx::math::abs_traits< ElementType>::result_type const& relative_error) const; bool all_approx_equal_relatively( ElementType const& other, typename scitbx::math::abs_traits< ElementType>::result_type const& relative_error) const; protected: void init() { size_ = accessor_.size_1d(); end_ = begin_ + size_; } const ElementType* begin_; accessor_type accessor_; size_type size_; const ElementType* end_; }; template<typename ElementType, class AccessorType> bool const_ref<ElementType, AccessorType>::is_diagonal(bool require_square) const { if (require_square && !is_square()) return false; for (index_value_type ir=0;ir<n_rows();ir++) for (index_value_type ic=0;ic<n_columns();ic++) if (ir != ic && (*this)(ir,ic)) return false; return true; } template <class E> class expression; template <typename ElementType, typename AccessorType = trivial_accessor> class ref : public const_ref<ElementType, AccessorType> { public: SCITBX_ARRAY_FAMILY_TYPEDEFS typedef const_ref<ElementType, AccessorType> base_class; typedef AccessorType accessor_type; typedef typename accessor_type::index_type index_type; typedef typename accessor_type::index_value_type index_value_type; ref() {} ref(ElementType* begin, accessor_type accessor) : base_class(begin, accessor) {} // convenience constructors ref(ElementType* begin, index_value_type const& n0) : base_class(begin, n0) {} ref(ElementType* begin, index_value_type const& n0, index_value_type const& n1) : base_class(begin, n0, n1) {} ref(ElementType* begin, index_value_type const& n0, index_value_type const& n1, index_value_type const& n2) : base_class(begin, n0, n1, n2) {} template <class E> ref &operator=(expression<E> const &e); template <class E> ref &operator+=(expression<E> const &e); template <class E> ref &operator-=(expression<E> const &e); template <class E> ref &operator*=(expression<E> const &e); ElementType* begin() const { return const_cast<ElementType*>(this->begin_); } ElementType* end() const { return const_cast<ElementType*>(this->end_); } reverse_iterator rbegin() const { return reverse_iterator(this->end()); } reverse_iterator rend() const { return reverse_iterator(this->begin()); } ElementType& front() const { return begin()[0]; } ElementType& back() const { return end()[-1]; } ElementType& operator[](size_type i) const { return begin()[i]; } ElementType& at(size_type i) const { if (i >= this->size_) throw_range_error(); return begin()[i]; } ref const& fill(ElementType const& x) const { std::fill(begin(), end(), x); return *this; } ref<ElementType> as_1d() const { return ref<ElementType>(this->begin(), this->size_); } value_type& operator()(index_type const& i) const { return begin()[this->accessor_(i)]; } // Convenience operator() value_type& operator()(index_value_type const& i0) const { return begin()[this->accessor_(i0)]; } value_type& operator()(index_value_type const& i0, index_value_type const& i1) const { return begin()[this->accessor_(i0, i1)]; } value_type& operator()(index_value_type const& i0, index_value_type const& i1, index_value_type const& i2) const { return begin()[this->accessor_(i0, i1, i2)]; } /// Matrix ref interface (only make sense for relevant accessors) //@{ //! Swaps two rows in place. void swap_rows(index_value_type const& i1, index_value_type const& i2) const { std::swap_ranges(&(*this)(i1,0), &(*this)(i1+1,0), &(*this)(i2,0)); } //! Swaps two columns in place. void swap_columns(index_value_type const& i1, index_value_type const& i2) const { for(index_value_type ir=0;ir<this->n_rows();ir++) { std::swap((*this)(ir,i1), (*this)(ir,i2)); } } //! Sets diagonal matrix. /*! Off-diagonal elements are set to zero. */ void set_diagonal(ElementType const& d, bool require_square=true) const { SCITBX_ASSERT(!require_square || this->is_square()); this->fill(0); index_value_type m = this->n_rows(), n = this->n_columns(); for(index_value_type i=0; i < std::min(m,n); i++) (*this)(i,i) = d; } //! Sets diagonal matrix. /*! Off-diagonal elements are set to zero. */ void set_diagonal(af::const_ref<ElementType> const& d, bool require_square=true) const { SCITBX_ASSERT(!require_square || this->is_square()); SCITBX_ASSERT(this->n_rows() >= d.size()); SCITBX_ASSERT(this->n_columns() >= d.size()); this->fill(0); index_value_type m = this->n_rows(), n = this->n_columns(); for(index_value_type i=0; i < d.size(); i++) (*this)(i,i) = d[i]; } //! Sets identity matrix. /*! Off-diagonal elements are set to zero. */ void set_identity(bool require_square=true) const { set_diagonal(1, require_square); } /// Efficiently transpose a square matrix in-place void transpose_square_in_place() const { SCITBX_ASSERT(this->is_square()); for (index_value_type ir=0;ir<this->n_rows();ir++) for (index_value_type ic=ir+1;ic<this->n_columns();ic++) std::swap((*this)(ir, ic), (*this)(ic, ir)); } /// Transpose a matrix in-place. /** It involves a copy if it is not squared. */ void transpose_in_place(); //@} }; template <typename ElementType, class AccessorType> void ref<ElementType, AccessorType>::transpose_in_place() { if (this->is_square()) { this->transpose_square_in_place(); } else { boost::scoped_array<ElementType> mt_buffer(new ElementType[this->size()]); ref mt(mt_buffer.get(), this->n_columns(), this->n_rows()); for (index_value_type ir=0;ir<this->n_rows();ir++) for (index_value_type ic=0;ic<this->n_columns();ic++) mt(ic, ir) = (*this)(ir, ic); std::copy(mt.begin(), mt.end(), this->begin()); this->accessor_ = mt.accessor(); this->init(); } } template <typename ArrayType> const_ref<typename ArrayType::value_type> make_const_ref(ArrayType const& a) { typedef typename ArrayType::value_type value_type; typedef const_ref<value_type> return_type; typedef typename return_type::accessor_type accessor_type; return return_type( (a.size() == 0 ? 0 : &(*(a.begin()))), accessor_type(a.size())); } template <typename ArrayType> ref<typename ArrayType::value_type> make_ref(ArrayType& a) { typedef typename ArrayType::value_type value_type; typedef ref<value_type> return_type; typedef typename return_type::accessor_type accessor_type; return return_type( (a.size() == 0 ? 0 : &(*(a.begin()))), accessor_type(a.size())); } /// Wrapper for expression template /** This class is just a wrapper, which shall be inherited using the CRTP: class foo : public af::expression<foo>; Each member function of expression<E> forward to E's member function with the same name. Thus E shall implement those member functions which makes sense to its concept. See scitbx::sparse::matrix_times_dense_vector for a real-life example and scitbx/sparse/tests/tst_sparse for the natural syntax made possible by this mechanism */ template <class E> class expression { public: E const &heir() const { return static_cast<E const &>(*this); } /// Total number of elements std::size_t size() const { return heir().size(); } /// Accessor template <class AccessorType> AccessorType accessor(AccessorType const &proto) const { return heir().expression_accessor(proto); } /// Assign the elements of the expression to the memory referred to by x template <class ElementType, class AccessorType> void assign_to(af::ref<ElementType, AccessorType> const &x) const { heir().assign_to(x); } /// Add the elements of the expression to the memory referred to by x template <class ElementType, class AccessorType> void add_to(af::ref<ElementType, AccessorType> const &x) const { heir().add_to(x); } /// Substract the elements of the expression from the memory referred to by x template <class ElementType, class AccessorType> void substract_from(af::ref<ElementType, AccessorType> const &x) const { heir().substract_from(x); } /// Multiply the elements of the expression to the memory referred to by x template <class ElementType, class AccessorType> void multiply_with(af::ref<ElementType, AccessorType> const &x) const { heir().multiply_with(x); } }; template <class ElementType, class AccessorType> template <class E> inline ref<ElementType, AccessorType> &ref<ElementType, AccessorType>::operator=(expression<E> const &e) { e.assign_to(*this); return *this; } template <class ElementType, class AccessorType> template <class E> inline ref<ElementType, AccessorType> &ref<ElementType, AccessorType>::operator+=(expression<E> const &e) { e.add_to(*this); return *this; } template <class ElementType, class AccessorType> template <class E> inline ref<ElementType, AccessorType> &ref<ElementType, AccessorType>::operator-=(expression<E> const &e) { e.substract_from(*this); return *this; } template <class ElementType, class AccessorType> template <class E> inline ref<ElementType, AccessorType> &ref<ElementType, AccessorType>::operator*=(expression<E> const &e) { e.multiply_with(*this); return *this; } }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_REF_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/tiny_algebra.h
.h
55,109
1,839
/* ***************************************************** THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT EDIT. ***************************************************** Generated by: scitbx.source_generators.array_family.generate_algebras */ #ifndef SCITBX_ARRAY_FAMILY_TINY_ALGEBRA_H #define SCITBX_ARRAY_FAMILY_TINY_ALGEBRA_H #ifndef DOXYGEN_SHOULD_SKIP_THIS #include <scitbx/array_family/tiny.h> #include <scitbx/array_family/operator_traits_builtin.h> #include <scitbx/array_family/detail/operator_functors.h> #include <scitbx/array_family/detail/generic_array_operators.h> #include <scitbx/array_family/detail/std_imports.h> #include <scitbx/array_family/misc_functions.h> namespace scitbx { namespace af { template<typename ElementType, std::size_t N> inline tiny<ElementType, N> operator-(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_negate< return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator!(tiny<ElementType, N> const& a) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_logical_not< return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, N> operator+( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_plus< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> operator+( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_plus< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> operator+( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_plus< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<ElementType1, N>& operator+=( tiny<ElementType1, N>& a1, tiny<ElementType2, N> const& a2) { array_operation_in_place_a_a(fn::functor_ip_plus< ElementType1, ElementType2>(), a1.begin(), a2.begin(), N); return a1; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N>& operator+=( tiny<ElementType, N>& a1, ElementType const& a2) { array_operation_in_place_a_s(fn::functor_ip_plus< ElementType, ElementType>(), a1.begin(), a2, N); return a1; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, N> operator-( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_minus< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> operator-( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_minus< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> operator-( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_minus< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<ElementType1, N>& operator-=( tiny<ElementType1, N>& a1, tiny<ElementType2, N> const& a2) { array_operation_in_place_a_a(fn::functor_ip_minus< ElementType1, ElementType2>(), a1.begin(), a2.begin(), N); return a1; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N>& operator-=( tiny<ElementType, N>& a1, ElementType const& a2) { array_operation_in_place_a_s(fn::functor_ip_minus< ElementType, ElementType>(), a1.begin(), a2, N); return a1; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, N> operator*( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_multiplies< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> operator*( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_multiplies< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> operator*( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_multiplies< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<ElementType1, N>& operator*=( tiny<ElementType1, N>& a1, tiny<ElementType2, N> const& a2) { array_operation_in_place_a_a(fn::functor_ip_multiplies< ElementType1, ElementType2>(), a1.begin(), a2.begin(), N); return a1; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N>& operator*=( tiny<ElementType, N>& a1, ElementType const& a2) { array_operation_in_place_a_s(fn::functor_ip_multiplies< ElementType, ElementType>(), a1.begin(), a2, N); return a1; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, N> operator/( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_divides< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> operator/( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_divides< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> operator/( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_divides< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<ElementType1, N>& operator/=( tiny<ElementType1, N>& a1, tiny<ElementType2, N> const& a2) { array_operation_in_place_a_a(fn::functor_ip_divides< ElementType1, ElementType2>(), a1.begin(), a2.begin(), N); return a1; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N>& operator/=( tiny<ElementType, N>& a1, ElementType const& a2) { array_operation_in_place_a_s(fn::functor_ip_divides< ElementType, ElementType>(), a1.begin(), a2, N); return a1; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, N> operator%( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_modulus< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> operator%( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_modulus< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> operator%( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_modulus< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<ElementType1, N>& operator%=( tiny<ElementType1, N>& a1, tiny<ElementType2, N> const& a2) { array_operation_in_place_a_a(fn::functor_ip_modulus< ElementType1, ElementType2>(), a1.begin(), a2.begin(), N); return a1; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N>& operator%=( tiny<ElementType, N>& a1, ElementType const& a2) { array_operation_in_place_a_s(fn::functor_ip_modulus< ElementType, ElementType>(), a1.begin(), a2, N); return a1; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<bool, N> operator&&( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_logical_and< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator&&( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_logical_and< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator&&( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_logical_and< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<bool, N> operator||( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_logical_or< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator||( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_logical_or< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator||( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_logical_or< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<bool, N> operator==( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_equal_to< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator==( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_equal_to< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator==( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_equal_to< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<bool, N> operator!=( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_not_equal_to< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator!=( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_not_equal_to< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator!=( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_not_equal_to< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<bool, N> operator>( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_greater< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator>( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_greater< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator>( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_greater< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<bool, N> operator<( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_less< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator<( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_less< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator<( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_less< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<bool, N> operator>=( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_greater_equal< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator>=( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_greater_equal< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator>=( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_greater_equal< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<bool, N> operator<=( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_less_equal< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator<=( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_less_equal< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> operator<=( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_less_equal< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> absolute(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_absolute<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> pow2(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_pow2<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> acos(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_acos<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> cos(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_cos<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> tan(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_tan<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> asin(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_asin<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> cosh(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_cosh<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> tanh(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_tanh<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> atan(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_atan<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> exp(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_exp<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> sin(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_sin<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> fabs(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_fabs<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> log(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_log<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> sinh(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_sinh<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> ceil(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_ceil<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> floor(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_floor<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> log10(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_log10<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> sqrt(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_sqrt<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> abs(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_abs<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> conj(tiny<ElementType, N> const& a) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a(fn::functor_conj<return_element_type, ElementType>(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<ElementType1, N> fmod_positive( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny<ElementType1, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_fmod_positive< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> fmod_positive( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_fmod_positive< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> fmod_positive( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_fmod_positive< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<ElementType1, N> fmod( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny<ElementType1, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_fmod< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> fmod( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_fmod< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> fmod( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_fmod< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<ElementType1, N> pow( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny<ElementType1, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_pow< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> pow( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_pow< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> pow( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_pow< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<ElementType1, N> atan2( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny<ElementType1, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_atan2< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> atan2( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_atan2< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> atan2( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_atan2< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<ElementType1, N> each_min( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny<ElementType1, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_each_min< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> each_min( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_each_min< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> each_min( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_each_min< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType1, std::size_t N, typename ElementType2> inline tiny<ElementType1, N> each_max( tiny<ElementType1, N> const& a1, tiny<ElementType2, N> const& a2) { typedef tiny<ElementType1, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a(fn::functor_each_max< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> each_max( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s(fn::functor_each_max< return_element_type, ElementType, ElementType>(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> each_max( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a(fn::functor_each_max< return_element_type, ElementType, ElementType>(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> real(tiny<std::complex<ElementType>, N> const& a) { typedef tiny<ElementType, N> return_array_type; return_array_type result; array_operation_a(fn::functor_real< ElementType, std::complex<ElementType> >(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> imag(tiny<std::complex<ElementType>, N> const& a) { typedef tiny<ElementType, N> return_array_type; return_array_type result; array_operation_a(fn::functor_imag< ElementType, std::complex<ElementType> >(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> abs(tiny<std::complex<ElementType>, N> const& a) { typedef tiny<ElementType, N> return_array_type; return_array_type result; array_operation_a(fn::functor_abs< ElementType, std::complex<ElementType> >(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> arg(tiny<std::complex<ElementType>, N> const& a) { typedef tiny<ElementType, N> return_array_type; return_array_type result; array_operation_a(fn::functor_arg< ElementType, std::complex<ElementType> >(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<ElementType, N> norm(tiny<std::complex<ElementType>, N> const& a) { typedef tiny<ElementType, N> return_array_type; return_array_type result; array_operation_a(fn::functor_norm< ElementType, std::complex<ElementType> >(), a.begin(), result.begin(), a.size(), true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<std::complex<ElementType>, N> pow( tiny<std::complex<ElementType>, N> const& a1, tiny<int, N> const& a2) { typedef tiny<std::complex<ElementType>, N> return_array_type; return_array_type result; array_operation_a_a(fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, int >(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<std::complex<ElementType>, N> pow( tiny<std::complex<ElementType>, N> const& a1, int const& a2) { typedef tiny<std::complex<ElementType>, N> return_array_type; return_array_type result; array_operation_a_s(fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, int >(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<std::complex<ElementType>, N> pow( std::complex<ElementType> const& a1, tiny<int, N> const& a2) { typedef tiny<std::complex<ElementType>, N> return_array_type; return_array_type result; array_operation_s_a(fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, int >(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<std::complex<ElementType>, N> pow( tiny<std::complex<ElementType>, N> const& a1, tiny<ElementType, N> const& a2) { typedef tiny<std::complex<ElementType>, N> return_array_type; return_array_type result; array_operation_a_a(fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, ElementType >(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<std::complex<ElementType>, N> pow( tiny<std::complex<ElementType>, N> const& a1, ElementType const& a2) { typedef tiny<std::complex<ElementType>, N> return_array_type; return_array_type result; array_operation_a_s(fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, ElementType >(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<std::complex<ElementType>, N> pow( std::complex<ElementType> const& a1, tiny<ElementType, N> const& a2) { typedef tiny<std::complex<ElementType>, N> return_array_type; return_array_type result; array_operation_s_a(fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, ElementType >(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<std::complex<ElementType>, N> pow( tiny<std::complex<ElementType>, N> const& a1, tiny<std::complex<ElementType>, N> const& a2) { typedef tiny<std::complex<ElementType>, N> return_array_type; return_array_type result; array_operation_a_a(fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, std::complex<ElementType> >(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<std::complex<ElementType>, N> pow( tiny<std::complex<ElementType>, N> const& a1, std::complex<ElementType> const& a2) { typedef tiny<std::complex<ElementType>, N> return_array_type; return_array_type result; array_operation_a_s(fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, std::complex<ElementType> >(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<std::complex<ElementType>, N> pow( std::complex<ElementType> const& a1, tiny<std::complex<ElementType>, N> const& a2) { typedef tiny<std::complex<ElementType>, N> return_array_type; return_array_type result; array_operation_s_a(fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, std::complex<ElementType> >(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<std::complex<ElementType>, N> pow( tiny<ElementType, N> const& a1, tiny<std::complex<ElementType>, N> const& a2) { typedef tiny<std::complex<ElementType>, N> return_array_type; return_array_type result; array_operation_a_a(fn::functor_pow< std::complex<ElementType>, ElementType, std::complex<ElementType> >(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<std::complex<ElementType>, N> pow( tiny<ElementType, N> const& a1, std::complex<ElementType> const& a2) { typedef tiny<std::complex<ElementType>, N> return_array_type; return_array_type result; array_operation_a_s(fn::functor_pow< std::complex<ElementType>, ElementType, std::complex<ElementType> >(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<std::complex<ElementType>, N> pow( ElementType const& a1, tiny<std::complex<ElementType>, N> const& a2) { typedef tiny<std::complex<ElementType>, N> return_array_type; return_array_type result; array_operation_s_a(fn::functor_pow< std::complex<ElementType>, ElementType, std::complex<ElementType> >(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<std::complex<ElementType>, N> polar( tiny<ElementType, N> const& a1, tiny<ElementType, N> const& a2) { typedef tiny<std::complex<ElementType>, N> return_array_type; return_array_type result; array_operation_a_a(fn::functor_polar< std::complex<ElementType>, ElementType, ElementType >(), a1.begin(), a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<std::complex<ElementType>, N> polar( tiny<ElementType, N> const& a1, ElementType const& a2) { typedef tiny<std::complex<ElementType>, N> return_array_type; return_array_type result; array_operation_a_s(fn::functor_polar< std::complex<ElementType>, ElementType, ElementType >(), a1.begin(), a2, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<std::complex<ElementType>, N> polar( ElementType const& a1, tiny<ElementType, N> const& a2) { typedef tiny<std::complex<ElementType>, N> return_array_type; return_array_type result; array_operation_s_a(fn::functor_polar< std::complex<ElementType>, ElementType, ElementType >(), a1, a2.begin(), result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> approx_equal( tiny<ElementType, N> const& a1, tiny<ElementType, N> const& a2, ElementType const& tolerance) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_a_s(fn::functor_approx_equal< return_element_type, ElementType, ElementType, ElementType>(), a1.begin(), a2.begin(), tolerance, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> approx_equal( tiny<ElementType, N> const& a1, ElementType const& a2, ElementType const& tolerance) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_a_s_s(fn::functor_approx_equal< return_element_type, ElementType, ElementType, ElementType>(), a1.begin(), a2, tolerance, result.begin(), N, true_type()); return result; } template<typename ElementType, std::size_t N> inline tiny<bool, N> approx_equal( ElementType const& a1, tiny<ElementType, N> const& a2, ElementType const& tolerance) { typedef tiny<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return_array_type result; array_operation_s_a_s(fn::functor_approx_equal< return_element_type, ElementType, ElementType, ElementType>(), a1, a2.begin(), tolerance, result.begin(), N, true_type()); return result; } }} // namespace scitbx::af #endif // DOXYGEN_SHOULD_SKIP_THIS #endif // SCITBX_ARRAY_FAMILY_TINY_ALGEBRA_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/tiny.h
.h
1,013
39
#ifndef SCITBX_ARRAY_FAMILY_TINY_H #define SCITBX_ARRAY_FAMILY_TINY_H #include <scitbx/array_family/tiny_plain.h> #include <scitbx/array_family/ref_reductions.h> namespace scitbx { namespace af { // Automatic allocation, fixed size, standard operators. template <typename ElementType, std::size_t N> class tiny : public tiny_plain<ElementType, N> { public: SCITBX_ARRAY_FAMILY_TYPEDEFS typedef tiny_plain<ElementType, N> base_class; tiny() {} template <typename OtherArrayType> tiny(array_adaptor<OtherArrayType> const& a_a) : base_class(a_a) {} template <typename OtherArrayType> tiny(array_adaptor_with_static_cast<OtherArrayType> const& a_a) : base_class(a_a) {} SCITBX_ARRAY_FAMILY_TINY_CONVENIENCE_CONSTRUCTORS(tiny) SCITBX_ARRAY_FAMILY_TINY_COPY_AND_ASSIGNMENT(tiny) # include <scitbx/array_family/detail/reducing_boolean_mem_fun.h> }; }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_TINY_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/versa_plain.h
.h
7,354
248
#ifndef SCITBX_ARRAY_FAMILY_VERSA_PLAIN_H #define SCITBX_ARRAY_FAMILY_VERSA_PLAIN_H #include <scitbx/error.h> #include <scitbx/array_family/shared_plain.h> namespace scitbx { namespace af { template <typename ElementType, typename AccessorType = trivial_accessor> class versa_plain : public shared_plain<ElementType> { public: SCITBX_ARRAY_FAMILY_TYPEDEFS typedef shared_plain<ElementType> base_class; typedef base_class base_array_type; typedef AccessorType accessor_type; typedef typename accessor_type::index_type index_type; typedef typename accessor_type::index_value_type index_value_type; typedef versa_plain<ElementType> one_dim_type; typedef typename one_dim_type::accessor_type one_dim_accessor_type; versa_plain() {} explicit versa_plain(AccessorType const& ac) : base_class(ac.size_1d()), m_accessor(ac) {} explicit versa_plain(index_value_type const& n0) : base_class(AccessorType(n0).size_1d()), m_accessor(n0) {} versa_plain(AccessorType const& ac, ElementType const& x) : base_class(ac.size_1d(), x), m_accessor(ac) {} versa_plain(index_value_type const& n0, ElementType const& x) : base_class(AccessorType(n0).size_1d(), x), m_accessor(n0) {} // non-std template <typename FunctorType> versa_plain(AccessorType const& ac, init_functor<FunctorType> const& ftor) : base_class(ac.size_1d(), ftor), m_accessor(ac) {} // non-std template <typename FunctorType> versa_plain(index_value_type const& n0, init_functor<FunctorType> const& ftor) : base_class(AccessorType(n0).size_1d(), ftor), m_accessor(n0) {} versa_plain(versa_plain<ElementType, AccessorType> const& other, weak_ref_flag) : base_class(other, weak_ref_flag()), m_accessor(other.m_accessor) {} versa_plain(base_class const& other, AccessorType const& ac) : base_class(other), m_accessor(ac) { if (other.size() < size()) throw_range_error(); } versa_plain(base_class const& other, index_value_type const& n0) : base_class(other), m_accessor(n0) { if (other.size() < size()) throw_range_error(); } versa_plain(base_class const& other, AccessorType const& ac, ElementType const& x) : base_class(other), m_accessor(ac) { base_class::resize(m_accessor.size_1d(), x); } versa_plain(base_class const& other, index_value_type const& n0, ElementType const& x) : base_class(other), m_accessor(n0) { base_class::resize(m_accessor.size_1d(), x); } versa_plain(sharing_handle* other_handle, AccessorType const& ac) : base_class(other_handle), m_accessor(ac) { if (other_handle->size / this->element_size() < size()) { throw_range_error(); } } versa_plain(sharing_handle* other_handle, index_value_type const& n0) : base_class(other_handle), m_accessor(n0) { if (other_handle->size / this->element_size() < size()) { throw_range_error(); } } versa_plain(sharing_handle* other_handle, AccessorType const& ac, ElementType const& x) : base_class(other_handle), m_accessor(ac) { base_class::resize(m_accessor.size_1d(), x); } versa_plain(sharing_handle* other_handle, index_value_type const& n0, ElementType const& x) : base_class(other_handle), m_accessor(n0) { base_class::resize(m_accessor.size_1d(), x); } template <typename OtherArrayType> versa_plain(array_adaptor<OtherArrayType> const& a_a) : base_class(a_a), m_accessor((a_a.pointee)->size()) {} AccessorType const& accessor() const { return m_accessor; } bool check_shared_size() const { return base_class::size() >= m_accessor.size_1d(); } size_type size() const { size_type sz = m_accessor.size_1d(); SCITBX_ASSERT(base_class::size() >= sz); return sz; } // since size() is not a virtual function end() needs to be redefined. SCITBX_ARRAY_FAMILY_BEGIN_END_ETC(versa_plain, base_class::begin(), size()) SCITBX_ARRAY_FAMILY_TAKE_VERSA_REF(begin(), m_accessor) void resize(AccessorType const& ac) { m_accessor = ac; base_class::resize(m_accessor.size_1d(), ElementType()); } void resize(AccessorType const& ac, ElementType const& x) { m_accessor = ac; base_class::resize(m_accessor.size_1d(), x); } one_dim_type as_1d() { return one_dim_type(*this, one_dim_accessor_type(size())); } versa_plain<ElementType, AccessorType> deep_copy() const { base_array_type c(begin(), end()); return versa_plain<ElementType, AccessorType>(c, m_accessor); } base_array_type as_base_array() const { return base_array_type(*this); } versa_plain<ElementType, AccessorType> weak_ref() const { return versa_plain<ElementType, AccessorType>(*this, weak_ref_flag()); } value_type& operator()(index_type const& i) { return begin()[m_accessor(i)]; } value_type const& operator()(index_type const& i) const { return begin()[m_accessor(i)]; } // Convenience operator() value_type const& operator()(index_value_type const& i0) const { return begin()[m_accessor(i0)]; } value_type& operator()(index_value_type const& i0) { return begin()[m_accessor(i0)]; } value_type const& operator()(index_value_type const& i0, index_value_type const& i1) const { return begin()[m_accessor(i0, i1)]; } value_type& operator()(index_value_type const& i0, index_value_type const& i1) { return begin()[m_accessor(i0, i1)]; } value_type const& operator()(index_value_type const& i0, index_value_type const& i1, index_value_type const& i2) const { return begin()[m_accessor(i0, i1, i2)]; } value_type& operator()(index_value_type const& i0, index_value_type const& i1, index_value_type const& i2) { return begin()[m_accessor(i0, i1, i2)]; } protected: AccessorType m_accessor; private: // disable modifiers (push_back_etc.h), except for resize() void assign(); void push_back(); void append(); void extend(); void pop_back(); void insert(); void erase(); void clear(); }; }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_VERSA_PLAIN_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/array_adaptor.h
.h
761
39
#ifndef SCITBX_ARRAY_FAMILY_ARRAY_ADAPTOR_H #define SCITBX_ARRAY_FAMILY_ARRAY_ADAPTOR_H namespace scitbx { namespace af { template <typename T> struct array_adaptor { const T* pointee; array_adaptor(T const& a) : pointee(&a) {} }; template <typename T> inline array_adaptor<T> adapt(T const& a) { return array_adaptor<T>(a); } template <typename T> struct array_adaptor_with_static_cast { const T* pointee; array_adaptor_with_static_cast(T const& a) : pointee(&a) {} }; template <typename T> inline array_adaptor_with_static_cast<T> adapt_with_static_cast(T const& a) { return array_adaptor_with_static_cast<T>(a); } }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_ARRAY_ADAPTOR_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/ref_reductions.h
.h
14,796
522
#ifndef SCITBX_ARRAY_FAMILY_REDUCTIONS_H #define SCITBX_ARRAY_FAMILY_REDUCTIONS_H #include <scitbx/error.h> #include <scitbx/math/approx_equal.h> #include <scitbx/array_family/ref.h> #include <scitbx/array_family/misc_functions.h> #include <boost/optional.hpp> #include <complex> namespace scitbx { namespace af { template <typename ElementType1, typename AccessorType1, typename ElementType2, typename AccessorType2> int order( const_ref<ElementType1, AccessorType1> const& a1, const_ref<ElementType2, AccessorType2> const& a2) { std::size_t sz_min = (a1.size() < a2.size() ? a1.size() : a2.size()); for(std::size_t i=0;i<sz_min;i++) { if (a1[i] < a2[i]) return -1; if (a2[i] < a1[i]) return 1; } if (a1.size() < a2.size()) return -1; if (a2.size() < a1.size()) return 1; return 0; } template <typename ElementType, typename AccessorType> std::size_t max_index(const_ref<ElementType, AccessorType> const& a) { if (a.size() == 0) { throw std::runtime_error("max_index() argument is an empty array"); } std::size_t result = 0; for(std::size_t i=1;i<a.size();i++) { if (a[result] < a[i]) result = i; } return result; } template <typename ElementType, typename AccessorType> std::size_t min_index(const_ref<ElementType, AccessorType> const& a) { if (a.size() == 0) { throw std::runtime_error("min_index() argument is an empty array"); } std::size_t result = 0; for(std::size_t i=1;i<a.size();i++) { if (a[result] > a[i]) result = i; } return result; } template<typename ElementType, typename AccessorType, class PredicateType> boost::optional<std::size_t> first_index(const_ref<ElementType, AccessorType> const& a, PredicateType p) { typedef typename const_ref<ElementType, AccessorType>::const_iterator iter; boost::optional<std::size_t> result; iter i = std::find_if(a.begin(), a.end(), p); if (i != a.end()) result = i - a.begin(); return result; } template<typename ElementType, typename AccessorType, class PredicateType> boost::optional<std::size_t> last_index(const_ref<ElementType, AccessorType> const& a, PredicateType p) { typedef typename const_ref<ElementType, AccessorType>::const_reverse_iterator iter; boost::optional<std::size_t> result; iter i = std::find_if(a.rbegin(), a.rend(), p); if (i != a.rend()) result = a.rend() - i - 1; return result; } template <typename ElementType, typename AccessorType> ElementType max(const_ref<ElementType, AccessorType> const& a) { if (a.size() == 0) { throw std::runtime_error("max() argument is an empty array"); } ElementType result = a[0]; for(std::size_t i=1;i<a.size();i++) { if (result < a[i]) result = a[i]; } return result; } template <typename ElementType, typename AccessorType> ElementType min(const_ref<ElementType, AccessorType> const& a) { if (a.size() == 0) { throw std::runtime_error("min() argument is an empty array"); } ElementType result = a[0]; for(std::size_t i=1;i<a.size();i++) { if (result > a[i]) result = a[i]; } return result; } template <typename ElementType, typename AccessorType> ElementType max_absolute(const_ref<ElementType, AccessorType> const& a) { if (a.size() == 0) { throw std::runtime_error("max_absolute() argument is an empty array"); } ElementType result = fn::absolute(a[0]); for(std::size_t i=1;i<a.size();i++) { ElementType const& ai = a[i]; if (ai > 0) { if (result < ai) result = ai; } else { if (result < -ai) result = -ai; } } return result; } template <typename ElementType, typename AccessorType> ElementType sum(const_ref<ElementType, AccessorType> const& a) { ElementType result = 0; for(std::size_t i=0;i<a.size();i++) result += a[i]; return result; } template <typename ElementType, typename AccessorType> ElementType sum_sq(const_ref<ElementType, AccessorType> const& a) { ElementType result = 0; for(std::size_t i=0;i<a.size();i++) result += a[i] * a[i]; return result; } template <typename ElementType, typename AccessorType> ElementType sum_sq(const_ref<std::complex<ElementType>, AccessorType> const& a) { ElementType result = 0; for(std::size_t i=0;i<a.size();i++) result += std::norm(a[i]); return result; } template <typename ElementType, typename AccessorType> ElementType norm(const_ref<ElementType, AccessorType> const& a) { return std::sqrt(sum_sq(a)); } template <typename ElementType, typename AccessorType> ElementType product(const_ref<ElementType, AccessorType> const& a) { std::size_t sz = a.size(); if (sz == 0) return 0; ElementType result = 1; for(std::size_t i=0;i<sz;i++) result *= a[i]; return result; } template <typename ElementType, typename AccessorType> ElementType mean(const_ref<ElementType, AccessorType> const& a) { if (a.size() == 0) { throw std::runtime_error("mean() argument is an empty array"); } ElementType result = a[0]; for(std::size_t i=1;i<a.size();i++) result += a[i]; return result * (1. / a.size()); } template <typename ElementType, typename AccessorType> ElementType mean_sq(const_ref<ElementType, AccessorType> const& a) { if (a.size() == 0) { throw std::runtime_error("mean_sq() argument is an empty array"); } ElementType result = a[0] * a[0]; for(std::size_t i=1;i<a.size();i++) result += a[i] * a[i]; return result * (1. / a.size()); } template <typename ElementType, typename AccessorType> ElementType mean_sq(const_ref<std::complex<ElementType>, AccessorType> const& a) { if (a.size() == 0) { throw std::runtime_error("mean_sq() argument is an empty array"); } ElementType result = std::norm(a[0]); for(std::size_t i=1;i<a.size();i++) result += std::norm(a[i]); return result / a.size(); } template <typename ElementTypeValues, typename AccessorTypeValues, typename ElementTypeWeights, typename AccessorTypeWeights> ElementTypeValues mean_weighted( const_ref<ElementTypeValues, AccessorTypeValues> const& values, const_ref<ElementTypeWeights, AccessorTypeWeights> const& weights) { if (values.size() != weights.size()) throw_range_error(); if (values.size() == 0) { throw std::runtime_error("mean_weighted() argument is an empty array"); } ElementTypeValues sum_vw = values[0] * weights[0]; ElementTypeWeights sum_w = weights[0]; for(std::size_t i=1;i<values.size();i++) { sum_vw += values[i] * weights[i]; sum_w += weights[i]; } return sum_vw / sum_w; } template <typename ElementTypeValues, typename AccessorTypeValues, typename ElementTypeWeights, typename AccessorTypeWeights> ElementTypeValues mean_sq_weighted( const_ref<ElementTypeValues, AccessorTypeValues> const& values, const_ref<ElementTypeWeights, AccessorTypeWeights> const& weights) { if (values.size() != weights.size()) throw_range_error(); if (values.size() == 0) { throw std::runtime_error( "mean_sq_weighted() argument is an empty array"); } ElementTypeValues sum_vvw = values[0] * values[0] * weights[0]; ElementTypeWeights sum_w = weights[0]; for(std::size_t i=1;i<values.size();i++) { sum_vvw += values[i] * values[i] * weights[i]; sum_w += weights[i]; } return sum_vvw / sum_w; } template <typename ElementType> struct min_max_mean { min_max_mean() {} template <typename AccessorType> min_max_mean(const_ref<ElementType, AccessorType> const& values) : n(values.size()) { if (n == 0) return; ElementType min_v = values[0]; ElementType max_v = min_v; ElementType sum_v = min_v; for(std::size_t i=1;i<values.size();i++) { ElementType const& vi = values[i]; if (vi < min_v) min_v = vi; if (max_v < vi) max_v = vi; sum_v += vi; } min = min_v; max = max_v; sum = sum_v; mean = sum_v / values.size(); } std::size_t n; boost::optional<ElementType> min; boost::optional<ElementType> max; boost::optional<ElementType> sum; boost::optional<ElementType> mean; }; template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_eq(const_ref const& other) const { const ElementType* o = other.begin(); const ElementType* t = begin(); const ElementType* e = end(); if (e-t != other.end()-o) return false; while (t != e) { if (!(*t++ == *o++)) return false; } return true; } template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_eq(ElementType const& other) const { const ElementType* t = begin(); const ElementType* e = end(); while (t != e) { if (!(*t++ == other)) return false; } return true; } template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_ne(const_ref const& other) const { const ElementType* o = other.begin(); const ElementType* t = begin(); const ElementType* e = end(); if (e-t != other.end()-o) return false; while (t != e) { if (!(*t++ != *o++)) return false; } return true; } template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_ne(ElementType const& other) const { const ElementType* t = begin(); const ElementType* e = end(); while (t != e) { if (!(*t++ != other)) return false; } return true; } template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_lt(const_ref const& other) const { const ElementType* o = other.begin(); const ElementType* t = begin(); const ElementType* e = end(); if (e-t != other.end()-o) throw_range_error(); while (t != e) { if (!(*t++ < *o++)) return false; } return true; } template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_lt(ElementType const& other) const { const ElementType* t = begin(); const ElementType* e = end(); while (t != e) { if (!(*t++ < other)) return false; } return true; } template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_gt(const_ref const& other) const { const ElementType* o = other.begin(); const ElementType* t = begin(); const ElementType* e = end(); if (e-t != other.end()-o) throw_range_error(); while (t != e) { if (!(*t++ > *o++)) return false; } return true; } template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_gt(ElementType const& other) const { const ElementType* t = begin(); const ElementType* e = end(); while (t != e) { if (!(*t++ > other)) return false; } return true; } template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_le(const_ref const& other) const { const ElementType* o = other.begin(); const ElementType* t = begin(); const ElementType* e = end(); if (e-t != other.end()-o) throw_range_error(); while (t != e) { if (!(*t++ <= *o++)) return false; } return true; } template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_le(ElementType const& other) const { const ElementType* t = begin(); const ElementType* e = end(); while (t != e) { if (!(*t++ <= other)) return false; } return true; } template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_ge(const_ref const& other) const { const ElementType* o = other.begin(); const ElementType* t = begin(); const ElementType* e = end(); if (e-t != other.end()-o) throw_range_error(); while (t != e) { if (!(*t++ >= *o++)) return false; } return true; } template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_ge(ElementType const& other) const { const ElementType* t = begin(); const ElementType* e = end(); while (t != e) { if (!(*t++ >= other)) return false; } return true; } template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_approx_equal( const_ref const& other, typename scitbx::math::abs_traits< ElementType>::result_type const& tolerance) const { if (size() != other.size()) return false; scitbx::math::approx_equal_absolutely<ElementType> predicate(tolerance); for (std::size_t i=0; i<size(); ++i) { if (!predicate((*this)[i], other[i])) return false; } return true; } template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_approx_equal( ElementType const& other, typename scitbx::math::abs_traits< ElementType>::result_type const& tolerance) const { scitbx::math::approx_equal_absolutely<ElementType> predicate(tolerance); for (std::size_t i=0; i<size(); ++i) { if (!predicate((*this)[i], other)) return false; } return true; } template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_approx_equal_relatively( const_ref const& other, typename scitbx::math::abs_traits< ElementType>::result_type const& relative_error) const { if (size() != other.size()) return false; scitbx::math::approx_equal_relatively<ElementType> predicate(relative_error); for (std::size_t i=0; i<size(); ++i) { if (!predicate((*this)[i], other[i])) return false; } return true; } template <typename ElementType, typename AccessorType> bool const_ref<ElementType, AccessorType> ::all_approx_equal_relatively( ElementType const& other, typename scitbx::math::abs_traits< ElementType>::result_type const& relative_error) const { scitbx::math::approx_equal_relatively<ElementType> predicate(relative_error); for (std::size_t i=0; i<size(); ++i) { if (!predicate((*this)[i], other)) return false; } return true; } }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_REDUCTIONS_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/tiny_mat_ref.h
.h
640
25
#include <scitbx/array_family/ref.h> #include <scitbx/array_family/accessors/mat_grid.h> namespace scitbx { namespace af { template <typename ElementType, int Rows, int Cols> class tiny_mat_ref : public ref<ElementType, mat_grid> { public: tiny_mat_ref(ElementType *storage) : ref<ElementType, mat_grid>(storage, mat_grid(Rows, Cols)) {} }; template <typename ElementType, int Rows, int Cols> class tiny_mat_const_ref : public const_ref<ElementType, mat_grid> { public: tiny_mat_const_ref(ElementType const *storage) : const_ref<ElementType, mat_grid>(storage, mat_grid(Rows, Cols)) {} }; }}
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/small_reductions.h
.h
3,714
156
/* ***************************************************** THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT EDIT. ***************************************************** Generated by: scitbx.source_generators.array_family.generate_reductions */ #ifndef SCITBX_ARRAY_FAMILY_SMALL_REDUCTIONS_H #define SCITBX_ARRAY_FAMILY_SMALL_REDUCTIONS_H #ifndef DOXYGEN_SHOULD_SKIP_THIS #include <scitbx/array_family/ref_reductions.h> #include <scitbx/array_family/small_plain.h> namespace scitbx { namespace af { template <typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> int inline order( small_plain<ElementType1, N1> const& a1, small_plain<ElementType2, N2> const& a2) { return order(a1.const_ref(), a2.const_ref()); } template <typename ElementType, std::size_t N> inline std::size_t max_index(small_plain<ElementType, N> const& a) { return max_index(a.const_ref()); } template <typename ElementType, std::size_t N> inline std::size_t min_index(small_plain<ElementType, N> const& a) { return min_index(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType max(small_plain<ElementType, N> const& a) { return max(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType min(small_plain<ElementType, N> const& a) { return min(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType max_absolute(small_plain<ElementType, N> const& a) { return max_absolute(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType sum(small_plain<ElementType, N> const& a) { return sum(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType sum_sq(small_plain<ElementType, N> const& a) { return sum_sq(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType product(small_plain<ElementType, N> const& a) { return product(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType mean(small_plain<ElementType, N> const& a) { return mean(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType mean_sq(small_plain<ElementType, N> const& a) { return mean_sq(a.const_ref()); } template <typename ElementTypeValues, std::size_t N1, typename ElementTypeWeights, std::size_t N2> inline ElementTypeValues mean_weighted( small_plain<ElementTypeValues, N1> const& values, small_plain<ElementTypeWeights, N2> const& weights) { return mean_weighted(values.const_ref(), weights.const_ref()); } template <typename ElementTypeValues, std::size_t N1, typename ElementTypeWeights, std::size_t N2> inline ElementTypeValues mean_sq_weighted( small_plain<ElementTypeValues, N1> const& values, small_plain<ElementTypeWeights, N2> const& weights) { return mean_sq_weighted(values.const_ref(), weights.const_ref()); } template <typename ElementType, std::size_t N, class PredicateType> inline boost::optional<std::size_t> first_index(small_plain<ElementType, N> const& a, PredicateType p) { return first_index(a.const_ref(), p); } template <typename ElementType, std::size_t N, class PredicateType> inline boost::optional<std::size_t> last_index(small_plain<ElementType, N> const& a, PredicateType p) { return last_index(a.const_ref(), p); } }} // namespace scitbx::af #endif // DOXYGEN_SHOULD_SKIP_THIS #endif // SCITBX_ARRAY_FAMILY_SMALL_REDUCTIONS_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/versa.h
.h
4,381
171
#ifndef SCITBX_ARRAY_FAMILY_VERSA_H #define SCITBX_ARRAY_FAMILY_VERSA_H #include <scitbx/array_family/versa_plain.h> #include <scitbx/array_family/ref_reductions.h> namespace scitbx { namespace af { template <typename ElementType, typename AccessorType = trivial_accessor> class versa : public versa_plain<ElementType, AccessorType> { public: typedef versa<ElementType, AccessorType> this_type; SCITBX_ARRAY_FAMILY_TYPEDEFS typedef versa_plain<ElementType, AccessorType> base_class; typedef typename base_class::base_array_type base_array_type; typedef AccessorType accessor_type; typedef typename accessor_type::index_value_type index_value_type; typedef versa<ElementType> one_dim_type; typedef typename one_dim_type::accessor_type one_dim_accessor_type; versa() {} explicit versa(AccessorType const& ac) : base_class(ac) {} explicit versa(index_value_type const& n0) : base_class(n0) {} versa(AccessorType const& ac, ElementType const& x) : base_class(ac, x) {} versa(index_value_type const& n0, ElementType const& x) : base_class(n0, x) {} #if !(defined(BOOST_MSVC) && BOOST_MSVC <= 1200) // VC++ 6.0 // non-std template <typename FunctorType> versa(AccessorType const& ac, init_functor<FunctorType> const& ftor) : base_class(ac, ftor) {} // non-std template <typename FunctorType> versa(index_value_type const& n0, init_functor<FunctorType> const& ftor) : base_class(n0, ftor) {} #endif // non-std template <class E> versa(expression<E> const &e) : base_class(e.accessor(base_class::accessor()), init_functor_null<ElementType>()) { e.assign_to(this->ref()); } versa(base_class const& other) : base_class(other) {} versa(base_class const& other, weak_ref_flag) : base_class(other, weak_ref_flag()) {} versa(base_array_type const& other, AccessorType const& ac) : base_class(other, ac) {} versa(base_array_type const& other, index_value_type const& n0) : base_class(other, n0) {} versa(base_array_type const& other, AccessorType const& ac, ElementType const& x) : base_class(other, ac, x) {} versa(base_array_type const& other, index_value_type const& n0, ElementType const& x) : base_class(other, n0, x) {} versa(sharing_handle* other_handle, AccessorType const& ac) : base_class(other_handle, ac) {} versa(sharing_handle* other_handle, index_value_type const& n0) : base_class(other_handle, n0) {} versa(sharing_handle* other_handle, AccessorType const& ac, ElementType const& x) : base_class(other_handle, ac) {} versa(sharing_handle* other_handle, index_value_type const& n0, ElementType const& x) : base_class(other_handle, n0) {} template <typename OtherArrayType> versa(array_adaptor<OtherArrayType> const& a_a) : base_class(a_a) {} one_dim_type as_1d() { return one_dim_type(*this, one_dim_accessor_type(this->size())); } this_type deep_copy() const { base_array_type c(this->begin(), this->end()); return this_type(c, this->m_accessor); } this_type weak_ref() const { return this_type(*this, weak_ref_flag()); } /// Expression templates //@{ template <class E> versa& operator=(expression<E> const &e) { this->ref() = e; return *this; } template <class E> versa& operator+=(expression<E> const &e) { this->ref() += e; return *this; } template <class E> versa& operator-=(expression<E> const &e) { this->ref() -= e; return *this; } template <class E> versa& operator*=(expression<E> const &e) { this->ref() *= e; return *this; } //@} # include <scitbx/array_family/detail/reducing_boolean_mem_fun.h> }; }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_VERSA_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/small_plain.h
.h
4,156
154
#ifndef SCITBX_ARRAY_FAMILY_SMALL_PLAIN_H #define SCITBX_ARRAY_FAMILY_SMALL_PLAIN_H #include <scitbx/array_family/tiny.h> #include <scitbx/array_family/detail/auto_allocator.h> namespace scitbx { namespace af { // Automatic allocation, variable size. template <typename ElementType, std::size_t N> class small_plain { public: static const std::size_t capacity_value = N; SCITBX_ARRAY_FAMILY_TYPEDEFS small_plain() : m_size(0) {} explicit small_plain(size_type const& sz) : m_size(0) { if (N < sz) throw_range_error(); std::uninitialized_fill_n(begin(), sz, ElementType()); m_size = sz; } // non-std small_plain(af::reserve const& sz) : m_size(0) { if (N < sz()) throw_range_error(); } small_plain(size_type const& sz, ElementType const& x) : m_size(0) { if (N < sz) throw_range_error(); std::uninitialized_fill_n(begin(), sz, x); m_size = sz; } // non-std template <typename FunctorType> small_plain(size_type const& sz, init_functor<FunctorType> const& ftor) : m_size(0) { if (N < sz) throw_range_error(); (*ftor.held)(begin(), sz); m_size = sz; } small_plain(const ElementType* first, const ElementType* last) : m_size(0) { if (N < last - first) throw_range_error(); std::uninitialized_copy(first, last, begin()); m_size = last - first; } #if !(defined(BOOST_MSVC) && BOOST_MSVC <= 1200) // VC++ 6.0 template <typename OtherElementType> small_plain(const OtherElementType* first, const OtherElementType* last) : m_size(0) { if (N < last - first) throw_range_error(); uninitialized_copy_typeconv(first, last, begin()); m_size = last - first; } #endif small_plain(small_plain<ElementType, N> const& other) : m_size(0) { std::uninitialized_copy(other.begin(), other.end(), begin()); m_size = other.m_size; } template <typename OtherArrayType> small_plain(array_adaptor<OtherArrayType> const& a_a) : m_size(0) { OtherArrayType const& a = *(a_a.pointee); if (a.size() > N) throw_range_error(); for(std::size_t i=0;i<a.size();i++) push_back(a[i]); } ~small_plain() { clear(); } small_plain<ElementType, N>& operator=(small_plain<ElementType, N> const& other) { clear(); std::uninitialized_copy(other.begin(), other.end(), begin()); m_size = other.m_size; return *this; } size_type size() const { return m_size; } bool empty() const { if (size() == 0) return true; return false; } static size_type max_size() { return N; } static size_type capacity() { return N; } SCITBX_ARRAY_FAMILY_BEGIN_END_ETC(small_plain, ((ElementType*)(m_elems.buffer)), m_size) // fix this SCITBX_ARRAY_FAMILY_TAKE_REF(begin(), m_size) void swap(small_plain<ElementType, N>& other) { std::swap(*this, other); } void reserve(size_type const& sz) { if (N < sz) throw_range_error(); } # include <scitbx/array_family/detail/push_back_etc.h> protected: void m_insert_overflow(ElementType* /*pos*/, size_type const& /*n*/, ElementType const& /*x*/, bool /*at_end*/) { throw_range_error(); } void m_insert_overflow(ElementType* /*pos*/, const ElementType* /*first*/, const ElementType* /*last*/) { throw_range_error(); } void m_set_size(size_type const& sz) { m_size = sz; } void m_incr_size(size_type const& n) { m_size += n; } void m_decr_size(size_type const& n) { m_size -= n; } detail::auto_allocator<ElementType, N> m_elems; size_type m_size; }; }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_SMALL_PLAIN_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/type_traits.h
.h
1,431
71
#ifndef SCITBX_ARRAY_FAMILY_TYPE_TRAITS_H #define SCITBX_ARRAY_FAMILY_TYPE_TRAITS_H namespace scitbx { namespace af { struct false_type {}; struct true_type {}; }} #include <boost/config.hpp> #if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) #define SCITBX_ARRAY_FAMILY_STATIC_ASSERT_HAS_TRIVIAL_DESTRUCTOR namespace scitbx { namespace af { template <typename T> struct has_trivial_destructor { typedef false_type value; }; }} #else #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> #define SCITBX_ARRAY_FAMILY_STATIC_ASSERT_HAS_TRIVIAL_DESTRUCTOR \ { \ BOOST_STATIC_ASSERT(::boost::has_trivial_destructor<ElementType>::value); \ } #include <complex> namespace boost { template <typename T> struct has_trivial_destructor<std::complex<T> > { // we really hope that this is true ... static const bool value = ::boost::has_trivial_destructor<T>::value; }; } namespace scitbx { namespace af { template <bool T> struct bool_as_type; template <> struct bool_as_type<false> { typedef false_type value; }; template <> struct bool_as_type<true> { typedef true_type value; }; template <typename T> struct has_trivial_destructor { typedef typename bool_as_type< ::boost::has_trivial_destructor<T>::value>::value value; }; }} #endif // defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) #endif // SCITBX_ARRAY_FAMILY_TYPE_TRAITS_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/small.h
.h
1,599
65
#ifndef SCITBX_ARRAY_FAMILY_SMALL_H #define SCITBX_ARRAY_FAMILY_SMALL_H #include <scitbx/array_family/small_plain.h> #include <scitbx/array_family/ref_reductions.h> namespace scitbx { namespace af { // Automatic allocation, fixed size, standard operators. template <typename ElementType, std::size_t N> class small : public small_plain<ElementType, N> { public: SCITBX_ARRAY_FAMILY_TYPEDEFS typedef small_plain<ElementType, N> base_class; small() {} explicit small(size_type const& sz) : base_class(sz) {} // non-std small(af::reserve const& sz) : base_class(sz) {} small(size_type const& sz, ElementType const& x) : base_class(sz, x) {} #if !(defined(BOOST_MSVC) && BOOST_MSVC <= 1200) // VC++ 6.0 // non-std template <typename FunctorType> small(size_type const& sz, init_functor<FunctorType> const& ftor) : base_class(sz, ftor) {} #endif small(const ElementType* first, const ElementType* last) : base_class(first, last) {} #if !(defined(BOOST_MSVC) && BOOST_MSVC <= 1200) // VC++ 6.0 template <typename OtherElementType> small(const OtherElementType* first, const OtherElementType* last) : base_class(first, last) {} #endif template <typename OtherArrayType> small(array_adaptor<OtherArrayType> const& a_a) : base_class(a_a) {} # include <scitbx/array_family/detail/reducing_boolean_mem_fun.h> }; }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_SMALL_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/misc_functions.h
.h
3,587
150
#ifndef SCITBX_ARRAY_FAMILY_MISC_FUNCTIONS_H #define SCITBX_ARRAY_FAMILY_MISC_FUNCTIONS_H #include <boost/type_traits/is_unsigned.hpp> #include <cmath> #include <cstdlib> namespace scitbx { namespace fn { namespace details { template <typename NumType> class absolute { public: NumType operator()(NumType x) { return (*this)(x, typename boost::is_unsigned<NumType>::type()); } private: /* boost::is_unsigned<my_type> is false by default, which makes this version the default, and the other one the version used only for those types explicitly marked as unsigned. */ NumType operator()(NumType x, boost::false_type is_unsigned) { return std::abs(x); } NumType operator()(NumType x, boost::true_type is_unsigned) { return x; } }; } //! Absolute value. template <typename NumType> inline NumType absolute(NumType const& x) { return details::absolute<NumType>()(x); } //! Floating-point modulus with strictly positive result. template <typename FloatType1, typename FloatType2> inline FloatType1 fmod_positive(FloatType1 const& x, FloatType2 const& y) { FloatType1 result = std::fmod(x, y); while (result < FloatType1(0)) result += y; return result; } //! Square of x. template <typename NumType> inline NumType pow2(NumType const& x) { return x * x; } //! Cube of x. // Not available as array function. template <typename NumType> inline NumType pow3(NumType const& x) { return x * x * x; } //! Fourth power of x. // Not available as array function. template <typename NumType> inline NumType pow4(NumType const& x) { return pow2(pow2(x)); } //! Tests if abs(a-b) <= tolerance. template <class FloatType> bool approx_equal(FloatType const& a, FloatType const& b, FloatType const& tolerance) { FloatType diff = a - b; if (diff < 0.) diff = -diff; if (diff <= tolerance) return true; return false; } //! Helper function object for array operations. template <typename ResultType, typename ArgumentType> struct functor_absolute { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(absolute(x)); } }; //! Helper function object for array operations. template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_fmod_positive { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(fmod_positive(x, y)); } }; //! Helper function object for array operations. template <typename ResultType, typename ArgumentType> struct functor_pow2 { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(pow2(x)); } }; //! Helper function object for array operations. template <typename ResultType, typename ArgumentType1, typename ArgumentType2, typename ArgumentType3> struct functor_approx_equal { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y, ArgumentType3 const& z) const { return ResultType(approx_equal(x, y, z)); } }; }} // namespace scitbx::fn #endif // SCITBX_ARRAY_FAMILY_MISC_FUNCTIONS_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/memory.h
.h
2,774
106
#ifndef SCITBX_ARRAY_FAMILY_MEMORY_H #define SCITBX_ARRAY_FAMILY_MEMORY_H /* + On some platforms std::malloc is 16-byte aligned: - glibc 2.8 onwards on 64 bit system: http://www.gnu.org/s/libc/manual/html_node/Aligned-Memory-Blocks.html the version requirement is lifted from the Eigen library (c.f. comments in src/Core/util/Memory.h) - MacOS X - 64-bit Windows + POSIX provides posix_memalign if the Advanced Real Time option group is present, which is detected by looking at _POSIX_ADVISORY_INFO e.g. as per http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap02.html POSIX itself is detected with _XOPEN_SOURCE as per the same document. */ #if ( \ defined(__GLIBC__) \ && ((__GLIBC__>= 2 && __GLIBC_MINOR__ >= 8) || __GLIBC__>2) \ && defined(__LP64__) \ ) \ || \ defined(__APPLE__) \ || \ defined(_WIN64) #define SCITBX_AF_HAS_ALIGNED_MALLOC 1 #define SCITBX_AF_USE_STD_FOR_ALIGNED_MALLOC 1 #elif defined(_MSC_VER) #define SCITBX_AF_HAS_ALIGNED_MALLOC 1 #define SCITBX_AF_USE_WIN32_FOR_ALIGNED_MALLOC 1 #elif defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE - 0) >= 600 && defined(_POSIX_ADVISORY_INFO) #define SCITBX_AF_HAS_ALIGNED_MALLOC 1 #define SCITBX_AF_USE_POSIX_FOR_ALIGNED_MALLOC 1 #endif #ifdef SCITBX_AF_USE_STD_FOR_ALIGNED_MALLOC #include <cstdlib> #endif #ifdef SCITBX_AF_USE_POSIX_FOR_ALIGNED_MALLOC #include <stdlib.h> #include <new> #endif namespace scitbx { namespace af { /// Like std::malloc but the returned pointer is aligned on 16-byte boundaries /** This is essential for efficient SSE 2 code on Intel processors */ void *aligned_malloc(std::size_t n); /// Free memory allocated by aligned_malloc void aligned_free(void *p); #ifdef SCITBX_AF_USE_STD_FOR_ALIGNED_MALLOC inline void *aligned_malloc(std::size_t n) { return std::malloc(n); } inline void aligned_free(void *p) { std::free(p); } #endif #ifdef SCITBX_AF_USE_POSIX_FOR_ALIGNED_MALLOC inline void *aligned_malloc(std::size_t n) { void *result; if(posix_memalign(&result, 16, n)) throw std::bad_alloc(); return result; } inline void aligned_free(void *p) { std::free(p); } #endif #ifdef SCITBX_AF_USE_WIN32_FOR_ALIGNED_MALLOC inline void *aligned_malloc(std::size_t n) { return _aligned_malloc(n, 16); } inline void aligned_free(void *p) { _aligned_free(p); } #endif }} #endif
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/tiny_reductions.h
.h
3,654
156
/* ***************************************************** THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT EDIT. ***************************************************** Generated by: scitbx.source_generators.array_family.generate_reductions */ #ifndef SCITBX_ARRAY_FAMILY_TINY_REDUCTIONS_H #define SCITBX_ARRAY_FAMILY_TINY_REDUCTIONS_H #ifndef DOXYGEN_SHOULD_SKIP_THIS #include <scitbx/array_family/ref_reductions.h> #include <scitbx/array_family/tiny_plain.h> namespace scitbx { namespace af { template <typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> int inline order( tiny_plain<ElementType1, N1> const& a1, tiny_plain<ElementType2, N2> const& a2) { return order(a1.const_ref(), a2.const_ref()); } template <typename ElementType, std::size_t N> inline std::size_t max_index(tiny_plain<ElementType, N> const& a) { return max_index(a.const_ref()); } template <typename ElementType, std::size_t N> inline std::size_t min_index(tiny_plain<ElementType, N> const& a) { return min_index(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType max(tiny_plain<ElementType, N> const& a) { return max(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType min(tiny_plain<ElementType, N> const& a) { return min(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType max_absolute(tiny_plain<ElementType, N> const& a) { return max_absolute(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType sum(tiny_plain<ElementType, N> const& a) { return sum(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType sum_sq(tiny_plain<ElementType, N> const& a) { return sum_sq(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType product(tiny_plain<ElementType, N> const& a) { return product(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType mean(tiny_plain<ElementType, N> const& a) { return mean(a.const_ref()); } template <typename ElementType, std::size_t N> inline ElementType mean_sq(tiny_plain<ElementType, N> const& a) { return mean_sq(a.const_ref()); } template <typename ElementTypeValues, std::size_t N, typename ElementTypeWeights> inline ElementTypeValues mean_weighted( tiny_plain<ElementTypeValues, N> const& values, tiny_plain<ElementTypeWeights, N> const& weights) { return mean_weighted(values.const_ref(), weights.const_ref()); } template <typename ElementTypeValues, std::size_t N, typename ElementTypeWeights> inline ElementTypeValues mean_sq_weighted( tiny_plain<ElementTypeValues, N> const& values, tiny_plain<ElementTypeWeights, N> const& weights) { return mean_sq_weighted(values.const_ref(), weights.const_ref()); } template <typename ElementType, std::size_t N, class PredicateType> inline boost::optional<std::size_t> first_index(tiny_plain<ElementType, N> const& a, PredicateType p) { return first_index(a.const_ref(), p); } template <typename ElementType, std::size_t N, class PredicateType> inline boost::optional<std::size_t> last_index(tiny_plain<ElementType, N> const& a, PredicateType p) { return last_index(a.const_ref(), p); } }} // namespace scitbx::af #endif // DOXYGEN_SHOULD_SKIP_THIS #endif // SCITBX_ARRAY_FAMILY_TINY_REDUCTIONS_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/small_algebra.h
.h
58,690
1,819
/* ***************************************************** THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT EDIT. ***************************************************** Generated by: scitbx.source_generators.array_family.generate_algebras */ #ifndef SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_H #define SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_H #ifndef DOXYGEN_SHOULD_SKIP_THIS #include <scitbx/array_family/small.h> #if (defined(BOOST_MSVC) && BOOST_MSVC <= 1300) // VC++ 7.0 #define SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2 N1 #else #define SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2 (N1<N2?N1:N2) #endif #include <scitbx/array_family/operator_traits_builtin.h> #include <scitbx/array_family/detail/operator_functors.h> #include <scitbx/array_family/detail/generic_array_functors.h> #include <scitbx/array_family/detail/std_imports.h> #include <scitbx/array_family/misc_functions.h> namespace scitbx { namespace af { template<typename ElementType, std::size_t N> inline small<ElementType, N> operator-(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_negate< return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator!(small<ElementType, N> const& a) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_logical_not< return_element_type, ElementType>(), a.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> operator+( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_plus< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> operator+( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_plus< return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> operator+( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_plus< return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<ElementType1, N1>& operator+=( small<ElementType1, N1>& a1, small<ElementType2, N2> const& a2) { if (a1.size() != a2.size()) throw_range_error(); array_operation_in_place_a_a(fn::functor_ip_plus< ElementType1, ElementType2>(), a1.begin(), a2.begin(), a1.size()); return a1; } template<typename ElementType, std::size_t N> inline small<ElementType, N>& operator+=( small<ElementType, N>& a1, ElementType const& a2) { array_operation_in_place_a_s(fn::functor_ip_plus< ElementType, ElementType>(), a1.begin(), a2, a1.size()); return a1; } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> operator-( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_minus< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> operator-( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_minus< return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> operator-( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_minus< return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<ElementType1, N1>& operator-=( small<ElementType1, N1>& a1, small<ElementType2, N2> const& a2) { if (a1.size() != a2.size()) throw_range_error(); array_operation_in_place_a_a(fn::functor_ip_minus< ElementType1, ElementType2>(), a1.begin(), a2.begin(), a1.size()); return a1; } template<typename ElementType, std::size_t N> inline small<ElementType, N>& operator-=( small<ElementType, N>& a1, ElementType const& a2) { array_operation_in_place_a_s(fn::functor_ip_minus< ElementType, ElementType>(), a1.begin(), a2, a1.size()); return a1; } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> operator*( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_multiplies< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> operator*( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_multiplies< return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> operator*( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_multiplies< return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<ElementType1, N1>& operator*=( small<ElementType1, N1>& a1, small<ElementType2, N2> const& a2) { if (a1.size() != a2.size()) throw_range_error(); array_operation_in_place_a_a(fn::functor_ip_multiplies< ElementType1, ElementType2>(), a1.begin(), a2.begin(), a1.size()); return a1; } template<typename ElementType, std::size_t N> inline small<ElementType, N>& operator*=( small<ElementType, N>& a1, ElementType const& a2) { array_operation_in_place_a_s(fn::functor_ip_multiplies< ElementType, ElementType>(), a1.begin(), a2, a1.size()); return a1; } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> operator/( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_divides< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> operator/( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_divides< return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> operator/( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_divides< return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<ElementType1, N1>& operator/=( small<ElementType1, N1>& a1, small<ElementType2, N2> const& a2) { if (a1.size() != a2.size()) throw_range_error(); array_operation_in_place_a_a(fn::functor_ip_divides< ElementType1, ElementType2>(), a1.begin(), a2.begin(), a1.size()); return a1; } template<typename ElementType, std::size_t N> inline small<ElementType, N>& operator/=( small<ElementType, N>& a1, ElementType const& a2) { array_operation_in_place_a_s(fn::functor_ip_divides< ElementType, ElementType>(), a1.begin(), a2, a1.size()); return a1; } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> operator%( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small< typename binary_operator_traits< ElementType1, ElementType2>::arithmetic, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_modulus< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> operator%( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_modulus< return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> operator%( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_modulus< return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<ElementType1, N1>& operator%=( small<ElementType1, N1>& a1, small<ElementType2, N2> const& a2) { if (a1.size() != a2.size()) throw_range_error(); array_operation_in_place_a_a(fn::functor_ip_modulus< ElementType1, ElementType2>(), a1.begin(), a2.begin(), a1.size()); return a1; } template<typename ElementType, std::size_t N> inline small<ElementType, N>& operator%=( small<ElementType, N>& a1, ElementType const& a2) { array_operation_in_place_a_s(fn::functor_ip_modulus< ElementType, ElementType>(), a1.begin(), a2, a1.size()); return a1; } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> operator&&( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_logical_and< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator&&( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_logical_and< return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator&&( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_logical_and< return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> operator||( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_logical_or< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator||( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_logical_or< return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator||( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_logical_or< return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> operator==( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_equal_to< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator==( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_equal_to< return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator==( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_equal_to< return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> operator!=( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_not_equal_to< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator!=( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_not_equal_to< return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator!=( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_not_equal_to< return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> operator>( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_greater< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator>( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_greater< return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator>( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_greater< return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> operator<( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_less< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator<( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_less< return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator<( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_less< return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> operator>=( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_greater_equal< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator>=( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_greater_equal< return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator>=( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_greater_equal< return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> operator<=( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_less_equal< return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator<=( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_less_equal< return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<bool, N> operator<=( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_less_equal< return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> absolute(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_absolute<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> pow2(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_pow2<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> acos(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_acos<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> cos(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_cos<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> tan(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_tan<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> asin(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_asin<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> cosh(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_cosh<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> tanh(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_tanh<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> atan(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_atan<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> exp(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_exp<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> sin(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_sin<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> fabs(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_fabs<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> log(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_log<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> sinh(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_sinh<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> ceil(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_ceil<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> floor(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_floor<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> log10(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_log10<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> sqrt(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_sqrt<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> abs(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_abs<return_element_type, ElementType>(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> conj(small<ElementType, N> const& a) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_conj<return_element_type, ElementType>(), a.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<ElementType1, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> fmod_positive( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small<ElementType1, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_fmod_positive<return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> fmod_positive( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_fmod_positive<return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> fmod_positive( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_fmod_positive<return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<ElementType1, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> fmod( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small<ElementType1, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_fmod<return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> fmod( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_fmod<return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> fmod( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_fmod<return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<ElementType1, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> pow( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small<ElementType1, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_pow<return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> pow( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_pow<return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> pow( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_pow<return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<ElementType1, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> atan2( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small<ElementType1, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_atan2<return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> atan2( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_atan2<return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> atan2( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_atan2<return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<ElementType1, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> each_min( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small<ElementType1, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_each_min<return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> each_min( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_each_min<return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> each_min( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_each_min<return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template< typename ElementType1, std::size_t N1, typename ElementType2, std::size_t N2> inline small<ElementType1, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> each_max( small<ElementType1, N1> const& a1, small<ElementType2, N2> const& a2) { typedef small<ElementType1, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_each_max<return_element_type, ElementType1, ElementType2>(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> each_max( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_each_max<return_element_type, ElementType, ElementType>(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> each_max( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<ElementType, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_each_max<return_element_type, ElementType, ElementType>(), a1, a2.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> real(small<std::complex<ElementType>, N> const& a) { typedef small<ElementType, N> return_array_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_real< ElementType, std::complex<ElementType> >(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> imag(small<std::complex<ElementType>, N> const& a) { typedef small<ElementType, N> return_array_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_imag< ElementType, std::complex<ElementType> >(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> abs(small<std::complex<ElementType>, N> const& a) { typedef small<ElementType, N> return_array_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_abs< ElementType, std::complex<ElementType> >(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> arg(small<std::complex<ElementType>, N> const& a) { typedef small<ElementType, N> return_array_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_arg< ElementType, std::complex<ElementType> >(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<ElementType, N> norm(small<std::complex<ElementType>, N> const& a) { typedef small<ElementType, N> return_array_type; return return_array_type(a.size(), make_init_functor(make_array_functor_a( fn::functor_norm< ElementType, std::complex<ElementType> >(), a.begin()))); } template<typename ElementType, std::size_t N> inline small<std::complex<ElementType>, N> pow( small<std::complex<ElementType>, N> const& a1, small<int, N> const& a2) { typedef small<std::complex<ElementType>, N> return_array_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, int >(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<std::complex<ElementType>, N> pow( small<std::complex<ElementType>, N> const& a1, int const& a2) { typedef small<std::complex<ElementType>, N> return_array_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, int >(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<std::complex<ElementType>, N> pow( std::complex<ElementType> const& a1, small<int, N> const& a2) { typedef small<std::complex<ElementType>, N> return_array_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, int >(), a1, a2.begin()))); } template<typename ElementType, std::size_t N> inline small<std::complex<ElementType>, N> pow( small<std::complex<ElementType>, N> const& a1, small<ElementType, N> const& a2) { typedef small<std::complex<ElementType>, N> return_array_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, ElementType >(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<std::complex<ElementType>, N> pow( small<std::complex<ElementType>, N> const& a1, ElementType const& a2) { typedef small<std::complex<ElementType>, N> return_array_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, ElementType >(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<std::complex<ElementType>, N> pow( std::complex<ElementType> const& a1, small<ElementType, N> const& a2) { typedef small<std::complex<ElementType>, N> return_array_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, ElementType >(), a1, a2.begin()))); } template<typename ElementType, std::size_t N> inline small<std::complex<ElementType>, N> pow( small<std::complex<ElementType>, N> const& a1, small<std::complex<ElementType>, N> const& a2) { typedef small<std::complex<ElementType>, N> return_array_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, std::complex<ElementType> >(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<std::complex<ElementType>, N> pow( small<std::complex<ElementType>, N> const& a1, std::complex<ElementType> const& a2) { typedef small<std::complex<ElementType>, N> return_array_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, std::complex<ElementType> >(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<std::complex<ElementType>, N> pow( std::complex<ElementType> const& a1, small<std::complex<ElementType>, N> const& a2) { typedef small<std::complex<ElementType>, N> return_array_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_pow< std::complex<ElementType>, std::complex<ElementType>, std::complex<ElementType> >(), a1, a2.begin()))); } template<typename ElementType, std::size_t N> inline small<std::complex<ElementType>, N> pow( small<ElementType, N> const& a1, small<std::complex<ElementType>, N> const& a2) { typedef small<std::complex<ElementType>, N> return_array_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_pow< std::complex<ElementType>, ElementType, std::complex<ElementType> >(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<std::complex<ElementType>, N> pow( small<ElementType, N> const& a1, std::complex<ElementType> const& a2) { typedef small<std::complex<ElementType>, N> return_array_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_pow< std::complex<ElementType>, ElementType, std::complex<ElementType> >(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<std::complex<ElementType>, N> pow( ElementType const& a1, small<std::complex<ElementType>, N> const& a2) { typedef small<std::complex<ElementType>, N> return_array_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_pow< std::complex<ElementType>, ElementType, std::complex<ElementType> >(), a1, a2.begin()))); } template<typename ElementType, std::size_t N> inline small<std::complex<ElementType>, N> polar( small<ElementType, N> const& a1, small<ElementType, N> const& a2) { typedef small<std::complex<ElementType>, N> return_array_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a( fn::functor_polar< std::complex<ElementType>, ElementType, ElementType >(), a1.begin(), a2.begin()))); } template<typename ElementType, std::size_t N> inline small<std::complex<ElementType>, N> polar( small<ElementType, N> const& a1, ElementType const& a2) { typedef small<std::complex<ElementType>, N> return_array_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s( fn::functor_polar< std::complex<ElementType>, ElementType, ElementType >(), a1.begin(), a2))); } template<typename ElementType, std::size_t N> inline small<std::complex<ElementType>, N> polar( ElementType const& a1, small<ElementType, N> const& a2) { typedef small<std::complex<ElementType>, N> return_array_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a( fn::functor_polar< std::complex<ElementType>, ElementType, ElementType >(), a1, a2.begin()))); } template<typename ElementType, std::size_t N1, std::size_t N2> inline small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> approx_equal( small<ElementType, N1> const& a1, small<ElementType, N2> const& a2, ElementType const& tolerance) { typedef small<bool, SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_MIN_N1_N2> return_array_type; typedef typename return_array_type::value_type return_element_type; if (a1.size() != a2.size()) throw_range_error(); return return_array_type(a1.size(), make_init_functor(make_array_functor_a_a_s( fn::functor_approx_equal<return_element_type, ElementType, ElementType, ElementType>(), a1.begin(), a2.begin(), tolerance))); } template<typename ElementType, std::size_t N> inline small<bool, N> approx_equal( small<ElementType, N> const& a1, ElementType const& a2, ElementType const& tolerance) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a1.size(), make_init_functor(make_array_functor_a_s_s( fn::functor_approx_equal<return_element_type, ElementType, ElementType, ElementType>(), a1.begin(), a2, tolerance))); } template<typename ElementType, std::size_t N> inline small<bool, N> approx_equal( ElementType const& a1, small<ElementType, N> const& a2, ElementType const& tolerance) { typedef small<bool, N> return_array_type; typedef typename return_array_type::value_type return_element_type; return return_array_type(a2.size(), make_init_functor(make_array_functor_s_a_s( fn::functor_approx_equal<return_element_type, ElementType, ElementType, ElementType>(), a1, a2.begin(), tolerance))); } }} // namespace scitbx::af #endif // DOXYGEN_SHOULD_SKIP_THIS #endif // SCITBX_ARRAY_FAMILY_SMALL_ALGEBRA_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/shared_plain.h
.h
10,975
382
/* This code is derived in part from: * STLport-4.5.3/stlport/stl/_vector.h * STLport-4.5.3/stlport/stl/_vector.c * * Copyright (c) 1994 * Hewlett-Packard Company * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Copyright (c) 1997 * Moscow Center for SPARC Technology * * Copyright (c) 1999 * Boris Fomitchev * * This material is provided "as is", with absolutely no warranty expressed * or implied. Any use is at your own risk. * * Permission to use or copy this software for any purpose is hereby granted * without fee, provided the above notices are retained on all copies. * Permission to modify the code and to distribute modified code is granted, * provided the above notices are retained, and a notice that the code was * modified is included with the above copyright notice. * */ #ifndef SCITBX_ARRAY_FAMILY_SHARED_PLAIN_H #define SCITBX_ARRAY_FAMILY_SHARED_PLAIN_H #include <scitbx/array_family/tiny.h> #include <scitbx/array_family/type_traits.h> #include <scitbx/array_family/memory.h> namespace scitbx { namespace af { struct weak_ref_flag {}; namespace detail { const std::size_t global_max_size(static_cast<std::size_t>(-1)); } class sharing_handle { public: static bool const ensures_aligned_memory = #ifdef SCITBX_AF_HAS_ALIGNED_MALLOC true; #else false; #endif sharing_handle() : use_count(1), weak_count(0), size(0), capacity(0), data(0) {} sharing_handle(weak_ref_flag) : use_count(0), weak_count(1), size(0), capacity(0), data(0) {} explicit sharing_handle(std::size_t const& sz) : use_count(1), weak_count(0), size(0), capacity(sz), #ifdef SCITBX_AF_HAS_ALIGNED_MALLOC data(reinterpret_cast<char *>(aligned_malloc(sz))) #else data(new char[sz]) #endif {} ~sharing_handle() { #ifdef SCITBX_AF_HAS_ALIGNED_MALLOC aligned_free(data); #else delete[] data; #endif } void deallocate() { #ifdef SCITBX_AF_HAS_ALIGNED_MALLOC aligned_free(data); #else delete[] data; #endif capacity = 0; data = 0; } void swap(sharing_handle& other) { std::swap(size, other.size); std::swap(capacity, other.capacity); std::swap(data, other.data); } std::size_t use_count; std::size_t weak_count; std::size_t size; std::size_t capacity; char* data; private: sharing_handle(sharing_handle const&); sharing_handle& operator=(sharing_handle const&); }; template <typename ElementType> class shared_plain { public: SCITBX_ARRAY_FAMILY_TYPEDEFS static size_type element_size() { return sizeof(ElementType); } public: shared_plain() : m_is_weak_ref(false), m_handle(new sharing_handle) {} explicit shared_plain(size_type const& sz) : m_is_weak_ref(false), m_handle(new sharing_handle(sz * element_size())) { std::uninitialized_fill_n(begin(), sz, ElementType()); m_handle->size = m_handle->capacity; } // non-std shared_plain(af::reserve const& sz) : m_is_weak_ref(false), m_handle(new sharing_handle(sz() * element_size())) {} shared_plain(size_type const& sz, ElementType const& x) : m_is_weak_ref(false), m_handle(new sharing_handle(sz * element_size())) { std::uninitialized_fill_n(begin(), sz, x); m_handle->size = m_handle->capacity; } // non-std template <typename FunctorType> shared_plain(size_type const& sz, init_functor<FunctorType> const& ftor) : m_is_weak_ref(false), m_handle(new sharing_handle(sz * element_size())) { (*ftor.held)(begin(), sz); m_handle->size = m_handle->capacity; } shared_plain(const ElementType* first, const ElementType* last) : m_is_weak_ref(false), m_handle(new sharing_handle((last - first) * element_size())) { std::uninitialized_copy(first, last, begin()); m_handle->size = m_handle->capacity; } #if !(defined(BOOST_MSVC) && BOOST_MSVC <= 1200) // VC++ 6.0 template <typename OtherElementType> shared_plain(const OtherElementType* first, const OtherElementType* last) : m_is_weak_ref(false), m_handle(new sharing_handle((last - first) * element_size())) { uninitialized_copy_typeconv(first, last, begin()); m_handle->size = m_handle->capacity; } #endif // non-std: shallow copy semantics shared_plain(shared_plain<ElementType> const& other) : m_is_weak_ref(other.m_is_weak_ref), m_handle(other.m_handle) { if (m_is_weak_ref) m_handle->weak_count++; else m_handle->use_count++; } // non-std: shallow copy semantics, weak reference shared_plain(shared_plain<ElementType> const& other, weak_ref_flag) : m_is_weak_ref(true), m_handle(other.m_handle) { m_handle->weak_count++; } // non-std explicit shared_plain(sharing_handle* other_handle) : m_is_weak_ref(false), m_handle(other_handle) { SCITBX_ARRAY_FAMILY_STATIC_ASSERT_HAS_TRIVIAL_DESTRUCTOR m_handle->use_count++; } // non-std shared_plain(sharing_handle* other_handle, weak_ref_flag) : m_is_weak_ref(true), m_handle(other_handle) { SCITBX_ARRAY_FAMILY_STATIC_ASSERT_HAS_TRIVIAL_DESTRUCTOR m_handle->weak_count++; } // non-std template <typename OtherArrayType> shared_plain(array_adaptor<OtherArrayType> const& a_a) : m_is_weak_ref(false), m_handle(new sharing_handle) { OtherArrayType const& a = *(a_a.pointee); reserve(a.size()); for(std::size_t i=0;i<a.size();i++) push_back(a[i]); } ~shared_plain() { m_dispose(); } // non-std: shallow copy semantics shared_plain<ElementType>& operator=(shared_plain<ElementType> const& other) { if (m_handle != other.m_handle) { m_dispose(); m_is_weak_ref = other.m_is_weak_ref; m_handle = other.m_handle; if (m_is_weak_ref) m_handle->weak_count++; else m_handle->use_count++; } return *this; } // non-std std::size_t id() const { return reinterpret_cast<std::size_t>(m_handle); } // non-std sharing_handle* handle() { SCITBX_ARRAY_FAMILY_STATIC_ASSERT_HAS_TRIVIAL_DESTRUCTOR return m_handle; } size_type size() const { return m_handle->size / element_size(); } bool empty() const { if (size() == 0) return true; return false; } size_type capacity() const { return m_handle->capacity / element_size(); } static size_type max_size() { return detail::global_max_size / element_size(); } // non-std size_type use_count() const { return m_handle->use_count; } // non-std size_type weak_count() const { return m_handle->weak_count; } // non-std bool is_weak_ref() const { return m_is_weak_ref; } SCITBX_ARRAY_FAMILY_BEGIN_END_ETC(shared_plain, reinterpret_cast<ElementType*>(m_handle->data), size()) SCITBX_ARRAY_FAMILY_TAKE_REF(begin(), size()) void swap(shared_plain<ElementType>& other) { m_handle->swap(*(other.m_handle)); } void reserve(size_type const& sz) { if (capacity() < sz) { shared_plain<ElementType> new_this(((af::reserve(sz)))); std::uninitialized_copy(begin(), end(), new_this.begin()); new_this.m_set_size(size()); new_this.swap(*this); } } // non-std shared_plain<ElementType> deep_copy() const { return shared_plain<ElementType>(begin(), end()); } // non-std shared_plain<ElementType> weak_ref() const { return shared_plain<ElementType>(*this, weak_ref_flag()); } # include <scitbx/array_family/detail/push_back_etc.h> protected: size_type m_compute_new_capacity(size_type const& old_size, size_type const& n) { return old_size + std::max(old_size, n); } void m_insert_overflow(ElementType* pos, size_type const& n, ElementType const& x, bool at_end) { shared_plain<ElementType> new_this((af::reserve(m_compute_new_capacity(size(), n)))); std::uninitialized_copy(begin(), pos, new_this.begin()); new_this.m_set_size(pos - begin()); if (n == 1) { new (new_this.end()) ElementType(x); new_this.m_incr_size(1); } else { // The next call is known to lead to a segmentation fault under // RedHat 8.0 if there is not enough memory (observed with // ElementType = std::vector<vector_element> and // struct vector_element { unsigned i; unsigned j; };). std::uninitialized_fill_n(new_this.end(), n, x); new_this.m_incr_size(n); } if (!at_end) { std::uninitialized_copy(pos, end(), new_this.end()); new_this.m_set_size(size() + n); } new_this.swap(*this); } void m_insert_overflow(ElementType* pos, const ElementType* first, const ElementType* last) { size_type n = last - first; shared_plain<ElementType> new_this((af::reserve(m_compute_new_capacity(size(), n)))); std::uninitialized_copy(begin(), pos, new_this.begin()); new_this.m_set_size(pos - begin()); std::uninitialized_copy(first, last, new_this.end()); new_this.m_incr_size(n); std::uninitialized_copy(pos, end(), new_this.end()); new_this.m_set_size(size() + n); new_this.swap(*this); } void m_set_size(size_type const& sz) { m_handle->size = sz * element_size(); } void m_incr_size(size_type const& n) { m_handle->size = (size() + n) * element_size(); } void m_decr_size(size_type const& n) { m_handle->size = (size() - n) * element_size(); } void m_dispose() { if (m_is_weak_ref) m_handle->weak_count--; else m_handle->use_count--; if (m_handle->use_count == 0) { clear(); if (m_handle->weak_count == 0) delete m_handle; else m_handle->deallocate(); } } bool m_is_weak_ref; sharing_handle* m_handle; }; }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_SHARED_PLAIN_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/shared.h
.h
3,152
134
#ifndef SCITBX_ARRAY_FAMILY_SHARED_H #define SCITBX_ARRAY_FAMILY_SHARED_H #include <scitbx/array_family/shared_plain.h> #include <scitbx/array_family/ref_reductions.h> namespace scitbx { namespace af { // Dynamic allocation, shared (data and size), standard operators. template <typename ElementType> class shared : public shared_plain<ElementType> { public: SCITBX_ARRAY_FAMILY_TYPEDEFS typedef shared_plain<ElementType> base_class; shared() {} explicit shared(size_type const& sz) : base_class(sz) {} // non-std shared(af::reserve const& sz) : base_class(sz) {} shared(size_type const& sz, ElementType const& x) : base_class(sz, x) {} #if !(defined(BOOST_MSVC) && BOOST_MSVC <= 1200) // VC++ 6.0 // non-std template <typename FunctorType> shared(size_type const& sz, init_functor<FunctorType> const& ftor) : base_class(sz, ftor) {} #endif shared(const ElementType* first, const ElementType* last) : base_class(first, last) {} #if !(defined(BOOST_MSVC) && BOOST_MSVC <= 1200) // VC++ 6.0 template <typename OtherElementType> shared(const OtherElementType* first, const OtherElementType* last) : base_class(first, last) {} #endif // non-std shared(base_class const& other) : base_class(other) {} // non-std shared(base_class const& other, weak_ref_flag) : base_class(other, weak_ref_flag()) {} // non-std explicit shared(sharing_handle* other_handle) : base_class(other_handle) {} // non-std shared(sharing_handle* other_handle, weak_ref_flag) : base_class(other_handle, weak_ref_flag()) {} // non-std template <typename OtherArrayType> shared(array_adaptor<OtherArrayType> const& a_a) : base_class(a_a) {} // non-std template <class E> shared(expression<E> const &e) : base_class(e.size(), init_functor_null<ElementType>()) { e.assign_to(this->ref()); } // non-std shared<ElementType> deep_copy() const { return shared<ElementType>(this->begin(), this->end()); } // non-std shared<ElementType> weak_ref() const { return shared<ElementType>(*this, weak_ref_flag()); } /// Expression templates //@{ template <class E> shared& operator=(expression<E> const &e) { this->ref() = e; return *this; } template <class E> shared& operator+=(expression<E> const &e) { this->ref() += e; return *this; } template <class E> shared& operator-=(expression<E> const &e) { this->ref() -= e; return *this; } template <class E> shared& operator*=(expression<E> const &e) { this->ref() *= e; return *this; } //@} # include <scitbx/array_family/detail/reducing_boolean_mem_fun.h> }; }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_SHARED_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/operator_traits_builtin.h
.h
7,239
317
/* ***************************************************** THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT EDIT. ***************************************************** Generated by: scitbx.source_generators.array_family.generate_operator_traits_builtin */ #ifndef SCITBX_ARRAY_FAMILY_OPERATOR_TRAITS_BUILTIN_H #define SCITBX_ARRAY_FAMILY_OPERATOR_TRAITS_BUILTIN_H #ifndef DOXYGEN_SHOULD_SKIP_THIS #include <complex> namespace scitbx { namespace af { // The default traits: the result type is the type of the lhs argument. template<typename TypeLHS, typename TypeRHS> struct binary_operator_traits { typedef TypeLHS arithmetic; }; // The remainder of this file defines the traits where the // result type is the type of the rhs argument. template<> struct binary_operator_traits<signed char, short > { typedef short arithmetic; }; template<> struct binary_operator_traits<signed char, int > { typedef int arithmetic; }; template<> struct binary_operator_traits<signed char, long > { typedef long arithmetic; }; template<> struct binary_operator_traits<signed char, long long > { typedef long long arithmetic; }; template<> struct binary_operator_traits<signed char, float > { typedef float arithmetic; }; template<> struct binary_operator_traits<signed char, double > { typedef double arithmetic; }; template<> struct binary_operator_traits<signed char, std::complex<float> > { typedef std::complex<float> arithmetic; }; template<> struct binary_operator_traits<signed char, std::complex<double> > { typedef std::complex<double> arithmetic; }; template<> struct binary_operator_traits<short, int > { typedef int arithmetic; }; template<> struct binary_operator_traits<short, long > { typedef long arithmetic; }; template<> struct binary_operator_traits<short, long long > { typedef long long arithmetic; }; template<> struct binary_operator_traits<short, float > { typedef float arithmetic; }; template<> struct binary_operator_traits<short, double > { typedef double arithmetic; }; template<> struct binary_operator_traits<short, std::complex<float> > { typedef std::complex<float> arithmetic; }; template<> struct binary_operator_traits<short, std::complex<double> > { typedef std::complex<double> arithmetic; }; template<> struct binary_operator_traits<int, long > { typedef long arithmetic; }; template<> struct binary_operator_traits<int, long long > { typedef long long arithmetic; }; template<> struct binary_operator_traits<int, float > { typedef float arithmetic; }; template<> struct binary_operator_traits<int, double > { typedef double arithmetic; }; template<> struct binary_operator_traits<int, std::complex<float> > { typedef std::complex<float> arithmetic; }; template<> struct binary_operator_traits<int, std::complex<double> > { typedef std::complex<double> arithmetic; }; template<> struct binary_operator_traits<long, long long > { typedef long long arithmetic; }; template<> struct binary_operator_traits<long, float > { typedef float arithmetic; }; template<> struct binary_operator_traits<long, double > { typedef double arithmetic; }; template<> struct binary_operator_traits<long, std::complex<float> > { typedef std::complex<float> arithmetic; }; template<> struct binary_operator_traits<long, std::complex<double> > { typedef std::complex<double> arithmetic; }; template<> struct binary_operator_traits<long long, float > { typedef float arithmetic; }; template<> struct binary_operator_traits<long long, double > { typedef double arithmetic; }; template<> struct binary_operator_traits<long long, std::complex<float> > { typedef std::complex<float> arithmetic; }; template<> struct binary_operator_traits<long long, std::complex<double> > { typedef std::complex<double> arithmetic; }; template<> struct binary_operator_traits<float, double > { typedef double arithmetic; }; template<> struct binary_operator_traits<float, std::complex<float> > { typedef std::complex<float> arithmetic; }; template<> struct binary_operator_traits<float, std::complex<double> > { typedef std::complex<double> arithmetic; }; template<> struct binary_operator_traits<double, std::complex<float> > { typedef std::complex<double> arithmetic; }; template<> struct binary_operator_traits<double, std::complex<double> > { typedef std::complex<double> arithmetic; }; template<> struct binary_operator_traits<std::complex<float>, double > { typedef std::complex<double> arithmetic; }; template<> struct binary_operator_traits<std::complex<float>, std::complex<double> > { typedef std::complex<double> arithmetic; }; template<> struct binary_operator_traits<unsigned char, float > { typedef float arithmetic; }; template<> struct binary_operator_traits<float, unsigned char > { typedef float arithmetic; }; template<> struct binary_operator_traits<unsigned char, double > { typedef double arithmetic; }; template<> struct binary_operator_traits<double, unsigned char > { typedef double arithmetic; }; template<> struct binary_operator_traits<unsigned short, float > { typedef float arithmetic; }; template<> struct binary_operator_traits<float, unsigned short > { typedef float arithmetic; }; template<> struct binary_operator_traits<unsigned short, double > { typedef double arithmetic; }; template<> struct binary_operator_traits<double, unsigned short > { typedef double arithmetic; }; template<> struct binary_operator_traits<unsigned int, float > { typedef float arithmetic; }; template<> struct binary_operator_traits<float, unsigned int > { typedef float arithmetic; }; template<> struct binary_operator_traits<unsigned int, double > { typedef double arithmetic; }; template<> struct binary_operator_traits<double, unsigned int > { typedef double arithmetic; }; template<> struct binary_operator_traits<unsigned long, float > { typedef float arithmetic; }; template<> struct binary_operator_traits<float, unsigned long > { typedef float arithmetic; }; template<> struct binary_operator_traits<unsigned long, double > { typedef double arithmetic; }; template<> struct binary_operator_traits<double, unsigned long > { typedef double arithmetic; }; template<> struct binary_operator_traits<unsigned long long, float > { typedef float arithmetic; }; template<> struct binary_operator_traits<float, unsigned long long > { typedef float arithmetic; }; template<> struct binary_operator_traits<unsigned long long, double > { typedef double arithmetic; }; template<> struct binary_operator_traits<double, unsigned long long > { typedef double arithmetic; }; }} // namespace scitbx::af #endif // DOXYGEN_SHOULD_SKIP_THIS #endif // SCITBX_ARRAY_FAMILY_OPERATOR_TRAITS_BUILTIN_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/tiny_plain.h
.h
1,732
60
#ifndef SCITBX_ARRAY_FAMILY_TINY_PLAIN_H #define SCITBX_ARRAY_FAMILY_TINY_PLAIN_H #include <scitbx/array_family/ref.h> #include <scitbx/array_family/detail/misc.h> #include <scitbx/array_family/detail/tiny_helpers.h> #include <scitbx/array_family/array_adaptor.h> namespace scitbx { namespace af { // Automatic allocation, fixed size. template <typename ElementType, std::size_t N> class tiny_plain { public: SCITBX_ARRAY_FAMILY_TYPEDEFS BOOST_STATIC_CONSTANT(std::size_t, fixed_size=N); ElementType elems[N]; tiny_plain() {} template <typename OtherArrayType> tiny_plain(array_adaptor<OtherArrayType> const& a_a) { OtherArrayType const& a = *(a_a.pointee); if (a.size() != N) throw_range_error(); for(std::size_t i=0;i<N;i++) elems[i] = a[i]; } template <typename OtherArrayType> tiny_plain(array_adaptor_with_static_cast<OtherArrayType> const& a_a) { OtherArrayType const& a = *(a_a.pointee); if (a.size() != N) throw_range_error(); for(std::size_t i=0;i<N;i++) elems[i] = static_cast<ElementType>(a[i]); } SCITBX_ARRAY_FAMILY_TINY_CONVENIENCE_CONSTRUCTORS(tiny_plain) SCITBX_ARRAY_FAMILY_TINY_COPY_AND_ASSIGNMENT(tiny_plain) static size_type size() { return N; } static bool empty() { return false; } static size_type max_size() { return N; } static size_type capacity() { return N; } SCITBX_ARRAY_FAMILY_BEGIN_END_ETC(tiny_plain, elems, N) SCITBX_ARRAY_FAMILY_TAKE_REF(elems, N) void swap(ElementType* other) { std::swap(*this, other); } }; }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_TINY_PLAIN_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/tiny_types.h
.h
2,623
116
#ifndef SCITBX_ARRAY_FAMILY_TINY_TYPES_H #define SCITBX_ARRAY_FAMILY_TINY_TYPES_H #include <scitbx/array_family/tiny.h> namespace scitbx { namespace af { typedef tiny<int, 2> int2; typedef tiny<int, 3> int3; typedef tiny<int, 4> int4; typedef tiny<int, 6> int6; typedef tiny<int, 9> int9; typedef tiny<long, 3> long3; typedef tiny<double, 2> double2; typedef tiny<double, 3> double3; typedef tiny<double, 4> double4; typedef tiny<double, 6> double6; typedef tiny<double, 9> double9; typedef tiny<float, 2> float2; typedef tiny<float, 3> float3; typedef tiny<float, 4> float4; typedef tiny<float, 6> float6; typedef tiny<float, 9> float9; }} // namespace scitbx::af #if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) namespace boost { template<> struct has_trivial_destructor<scitbx::af::int2> { static const bool value = true; }; template<> struct has_trivial_destructor<scitbx::af::int3> { static const bool value = true; }; template<> struct has_trivial_destructor<scitbx::af::int4> { static const bool value = true; }; template<> struct has_trivial_destructor<scitbx::af::int6> { static const bool value = true; }; template<> struct has_trivial_destructor<scitbx::af::int9> { static const bool value = true; }; template<> struct has_trivial_destructor<scitbx::af::long3> { static const bool value = true; }; template<> struct has_trivial_destructor<scitbx::af::double2> { static const bool value = true; }; template<> struct has_trivial_destructor<scitbx::af::double3> { static const bool value = true; }; template<> struct has_trivial_destructor<scitbx::af::double4> { static const bool value = true; }; template<> struct has_trivial_destructor<scitbx::af::double6> { static const bool value = true; }; template<> struct has_trivial_destructor<scitbx::af::double9> { static const bool value = true; }; template<> struct has_trivial_destructor<scitbx::af::float2> { static const bool value = true; }; template<> struct has_trivial_destructor<scitbx::af::float3> { static const bool value = true; }; template<> struct has_trivial_destructor<scitbx::af::float4> { static const bool value = true; }; template<> struct has_trivial_destructor<scitbx::af::float6> { static const bool value = true; }; template<> struct has_trivial_destructor<scitbx::af::float9> { static const bool value = true; }; } #endif // !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) #endif // SCITBX_ARRAY_FAMILY_TINY_TYPES_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/error.h
.h
363
20
#ifndef SCITBX_ARRAY_FAMILY_ERROR_H #define SCITBX_ARRAY_FAMILY_ERROR_H #include <stdexcept> // FIXES for broken compilers #include <boost/config.hpp> namespace scitbx { namespace af { inline void throw_range_error() { throw std::range_error("scitbx array_family range error"); } }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_ERROR_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/accessors/mat_grid.h
.h
290
14
#ifndef SCITBX_ARRAY_FAMILY_ACCESSORS_MAT_GRID_H #define SCITBX_ARRAY_FAMILY_ACCESSORS_MAT_GRID_H #include <scitbx/array_family/accessors/c_grid.h> namespace scitbx { namespace af { /// The grid used for matrices throughout typedef c_grid<2> mat_grid; }} // scitbx::af #endif // GUARD
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/accessors/c_index_1d_calculator.h
.h
788
33
#ifndef SCITBX_ARRAY_FAMILY_ACCESSORS_C_INDEX_1D_CALCULATOR_H #define SCITBX_ARRAY_FAMILY_ACCESSORS_C_INDEX_1D_CALCULATOR_H #include <cstddef> namespace scitbx { namespace af { template <std::size_t N> struct c_index_1d_calculator { template <typename ExtendArrayType, typename IndexType> static std::size_t get(ExtendArrayType const& e, IndexType const& i) { return c_index_1d_calculator<N-1>::get(e, i) * e[N-1] + i[N-1]; } }; template<> struct c_index_1d_calculator<1> { template <typename ExtendArrayType, typename IndexType> static std::size_t get(ExtendArrayType const& /*e*/, IndexType const& i) { return i[0]; } }; }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_ACCESSORS_C_INDEX_1D_CALCULATOR_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/accessors/trivial.h
.h
608
29
#ifndef SCITBX_ARRAY_FAMILY_ACCESSORS_TRIVIAL_H #define SCITBX_ARRAY_FAMILY_ACCESSORS_TRIVIAL_H #include <cstddef> namespace scitbx { namespace af { class trivial_accessor { public: typedef std::size_t index_type; struct index_value_type {}; trivial_accessor() : size_(0) {} trivial_accessor(std::size_t const& n) : size_(n) {} std::size_t size_1d() const { return size_; } std::size_t operator()(std::size_t i) const { return i; } protected: std::size_t size_; }; }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_ACCESSORS_TRIVIAL_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/accessors/c_grid.h
.h
6,459
248
// The implementations in this file are highly redundant in order // to help the optimizer. #ifndef SCITBX_ARRAY_FAMILY_ACCESSORS_C_GRID_H #define SCITBX_ARRAY_FAMILY_ACCESSORS_C_GRID_H #include <scitbx/array_family/accessors/c_index_1d_calculator.h> #include <scitbx/array_family/accessors/flex_grid.h> #include <scitbx/math/compile_time.h> namespace scitbx { namespace af { template <std::size_t Nd, typename IndexValueType=std::size_t> class c_grid : public tiny<IndexValueType, Nd> { public: typedef IndexValueType index_value_type; typedef index_value_type value_type; typedef tiny<IndexValueType, Nd> index_type; c_grid() { for(std::size_t i=0;i<Nd;i++) this->elems[i] = 0; } c_grid(index_type const& n) : index_type(n) {} template <typename FlexIndexType> c_grid(flex_grid<FlexIndexType> const& flex_g) : index_type(af::adapt(flex_g.all())) { SCITBX_ASSERT(flex_g.is_0_based()); SCITBX_ASSERT(!flex_g.is_padded()); } af::flex_grid<> as_flex_grid() const { return af::flex_grid<>(af::adapt(*this)); } std::size_t size_1d() const { return math::compile_time::product<Nd>::get(*this); } index_type index_nd(index_value_type const& i_1d) const { index_type i_nd; i_nd[0] = i_1d; for(std::size_t j=this->size()-1;j;j--) { i_nd[j] = i_nd[0] % this->elems[j]; i_nd[0] /= this->elems[j]; } return i_nd; } bool is_valid_index(index_type const& i) const { for(std::size_t j=0;j<this->size();j++) { if (i[j] >= this->elems[j]) return false; } return true; } std::size_t operator()(index_type const& i) const { return c_index_1d_calculator<Nd>::get(*this, i); } }; template <typename IndexValueType> class c_grid<2, IndexValueType> : public tiny<IndexValueType, 2> { public: typedef IndexValueType index_value_type; typedef index_value_type value_type; typedef tiny<IndexValueType, 2> index_type; c_grid() : index_type(0,0) {} c_grid(index_type const& n) : index_type(n) {} c_grid(index_value_type const& n0, index_value_type const& n1) : index_type(n0, n1) {} template <typename FlexIndexType> c_grid(flex_grid<FlexIndexType> const& flex_g) : index_type(af::adapt(flex_g.all())) { SCITBX_ASSERT(flex_g.is_0_based()); SCITBX_ASSERT(!flex_g.is_padded()); } af::flex_grid<> as_flex_grid() const { return af::flex_grid<>(af::adapt(*this)); } std::size_t size_1d() const { return static_cast<std::size_t>(this->elems[0]) * static_cast<std::size_t>(this->elems[1]); } bool is_square() const { return this->elems[0] == this->elems[1]; } std::size_t n_rows() const { return this->elems[0]; } std::size_t n_columns() const { return this->elems[1]; } index_type index_nd(index_value_type const& i_1d) { return index_type(i_1d / this->elems[1], i_1d % this->elems[1]); } bool is_valid_index(index_type const& i) const { if (i[0] >= this->elems[0]) return false; if (i[1] >= this->elems[1]) return false; return true; } bool is_valid_index( index_value_type const& i0, index_value_type const& i1) const { if (i0 >= this->elems[0]) return false; if (i1 >= this->elems[1]) return false; return true; } std::size_t operator()(index_type const& i) const { return i[0] * this->elems[1] + i[1]; } std::size_t operator()(index_value_type const& i0, index_value_type const& i1) const { return i0 * this->elems[1] + i1; } }; template <typename IndexValueType> class c_grid<3, IndexValueType> : public tiny<IndexValueType, 3> { public: typedef IndexValueType index_value_type; typedef index_value_type value_type; typedef tiny<IndexValueType, 3> index_type; c_grid() : index_type(0,0,0) {} c_grid(index_type const& n) : index_type(n) {} c_grid(index_value_type const& n0, index_value_type const& n1, index_value_type const& n2) : index_type(n0, n1, n2) {} template <typename FlexIndexType> c_grid(flex_grid<FlexIndexType> const& flex_g) : index_type(af::adapt(flex_g.all())) { SCITBX_ASSERT(flex_g.is_0_based()); SCITBX_ASSERT(!flex_g.is_padded()); } af::flex_grid<> as_flex_grid() const { return af::flex_grid<>(af::adapt(*this)); } std::size_t size_1d() const { return static_cast<std::size_t>(this->elems[0]) * static_cast<std::size_t>(this->elems[1]) * static_cast<std::size_t>(this->elems[2]); } index_type index_nd(index_value_type const& i_1d) { index_type i_nd; i_nd[2] = i_1d % this->elems[2]; i_nd[0] = i_1d / this->elems[2]; i_nd[1] = i_nd[0] % this->elems[1]; i_nd[0] /= this->elems[1]; return i_nd; } bool is_valid_index(index_type const& i) const { if (i[0] >= this->elems[0]) return false; if (i[1] >= this->elems[1]) return false; if (i[2] >= this->elems[2]) return false; return true; } bool is_valid_index( index_value_type const& i0, index_value_type const& i1, index_value_type const& i2) const { if (i0 >= this->elems[0]) return false; if (i1 >= this->elems[1]) return false; if (i2 >= this->elems[2]) return false; return true; } std::size_t operator()(index_type const& i) const { return (i[0] * this->elems[1] + i[1]) * this->elems[2] + i[2]; } std::size_t operator()(index_value_type const& i0, index_value_type const& i1, index_value_type const& i2) const { return (i0 * this->elems[1] + i1) * this->elems[2] + i2; } }; }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_ACCESSORS_C_GRID_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/accessors/flex_grid.h
.h
10,471
402
#ifndef SCITBX_ARRAY_FAMILY_ACCESSORS_FLEX_GRID_H #define SCITBX_ARRAY_FAMILY_ACCESSORS_FLEX_GRID_H #include <scitbx/error.h> #include <scitbx/array_family/small.h> #include <scitbx/array_family/small_reductions.h> #include <scitbx/array_family/small_algebra.h> namespace scitbx { namespace af { typedef small<long, 10> flex_grid_default_index_type; template <typename IndexType = flex_grid_default_index_type> class flex_grid { public: typedef IndexType index_type; typedef typename index_type::value_type index_value_type; flex_grid() {} flex_grid(index_type const& all) : all_(all) {} template <typename OtherArrayType> flex_grid(array_adaptor<OtherArrayType> const& a_a) : all_(a_a) {} flex_grid(index_value_type const& all_0) : all_(1, all_0) {} flex_grid(index_value_type const& all_0, index_value_type const& all_1) : all_(1, all_0) { all_.push_back(all_1); } flex_grid(index_value_type const& all_0, index_value_type const& all_1, index_value_type const& all_2) : all_(1, all_0) { all_.push_back(all_1); all_.push_back(all_2); } flex_grid(index_value_type const& all_0, index_value_type const& all_1, index_value_type const& all_2, index_value_type const& all_3) : all_(1, all_0) { all_.push_back(all_1); all_.push_back(all_2); all_.push_back(all_3); } flex_grid(index_value_type const& all_0, index_value_type const& all_1, index_value_type const& all_2, index_value_type const& all_3, index_value_type const& all_4) : all_(1, all_0) { all_.push_back(all_1); all_.push_back(all_2); all_.push_back(all_3); all_.push_back(all_4); } flex_grid(index_value_type const& all_0, index_value_type const& all_1, index_value_type const& all_2, index_value_type const& all_3, index_value_type const& all_4, index_value_type const& all_5) : all_(1, all_0) { all_.push_back(all_1); all_.push_back(all_2); all_.push_back(all_3); all_.push_back(all_4); all_.push_back(all_5); } flex_grid(index_type const& origin, index_type const& last, bool open_range=true) : all_(last), origin_(origin) { all_ -= origin_; if (!open_range) all_ += index_value_type(1); if (origin_.all_eq(0)) origin_.clear(); } flex_grid set_focus(index_type const& focus, bool open_range=true) { SCITBX_ASSERT(focus.size() == all_.size()); focus_ = focus; if (!open_range && focus_.size() > 0) focus_ += index_value_type(1); set_focus_finalize(); return *this; } flex_grid set_focus(index_value_type const& focus_0) { SCITBX_ASSERT(all_.size() == 1); focus_.clear(); focus_.push_back(focus_0); set_focus_finalize(); return *this; } flex_grid set_focus(index_value_type const& focus_0, index_value_type const& focus_1) { SCITBX_ASSERT(all_.size() == 2); focus_.clear(); focus_.push_back(focus_0); focus_.push_back(focus_1); set_focus_finalize(); return *this; } flex_grid set_focus(index_value_type const& focus_0, index_value_type const& focus_1, index_value_type const& focus_2) { SCITBX_ASSERT(all_.size() == 3); focus_.clear(); focus_.push_back(focus_0); focus_.push_back(focus_1); focus_.push_back(focus_2); set_focus_finalize(); return *this; } flex_grid set_focus(index_value_type const& focus_0, index_value_type const& focus_1, index_value_type const& focus_2, index_value_type const& focus_3) { SCITBX_ASSERT(all_.size() == 4); focus_.clear(); focus_.push_back(focus_0); focus_.push_back(focus_1); focus_.push_back(focus_2); focus_.push_back(focus_3); set_focus_finalize(); return *this; } flex_grid set_focus(index_value_type const& focus_0, index_value_type const& focus_1, index_value_type const& focus_2, index_value_type const& focus_3, index_value_type const& focus_4) { SCITBX_ASSERT(all_.size() == 5); focus_.clear(); focus_.push_back(focus_0); focus_.push_back(focus_1); focus_.push_back(focus_2); focus_.push_back(focus_3); focus_.push_back(focus_4); set_focus_finalize(); return *this; } flex_grid set_focus(index_value_type const& focus_0, index_value_type const& focus_1, index_value_type const& focus_2, index_value_type const& focus_3, index_value_type const& focus_4, index_value_type const& focus_5) { SCITBX_ASSERT(all_.size() == 6); focus_.clear(); focus_.push_back(focus_0); focus_.push_back(focus_1); focus_.push_back(focus_2); focus_.push_back(focus_3); focus_.push_back(focus_4); focus_.push_back(focus_5); set_focus_finalize(); return *this; } std::size_t nd() const { return all_.size(); } std::size_t size_1d() const { SCITBX_ASSERT(all_.all_ge(0)); return af::product(all_); } index_type const& all() const { return all_; } bool is_0_based() const { return origin_.size() == 0; } index_type origin() const { if (!is_0_based()) return origin_; return index_type(all_.size(), index_value_type(0)); } index_type last(bool open_range=true) const { index_type result = origin(); result += all_; if (!open_range) result -= index_value_type(1); return result; } bool is_padded() const { return focus_.size() != 0; } index_type focus(bool open_range=true) const { if (is_padded()) { index_type result = focus_; if (!open_range) result -= index_value_type(1); return result; } return last(open_range); } std::size_t focus_size_1d() const { if (focus_.size() == 0) return size_1d(); index_type n = focus(); n -= origin(); SCITBX_ASSERT(n.all_ge(0)); return af::product(n); } bool is_trivial_1d() const { if (nd() != 1) return false; if (!is_0_based()) return false; if (is_padded()) return false; return true; } bool is_square_matrix() const { if (nd() != 2) return false; if (all_[0] != all_[1]) return false; if (!is_0_based()) return false; if (is_padded()) return false; return true; } flex_grid shift_origin() const { if (is_0_based()) return *this; if (!is_padded()) return flex_grid(all_); index_type result_focus = focus_; // step-wise to avoid result_focus -= origin(); // gcc 2.96 internal error return flex_grid(all_).set_focus(result_focus); } bool is_valid_index(index_type const& i) const { std::size_t n = nd(); if (i.size() != n) return false; if (!is_0_based()) { for(std::size_t j=0;j<n;j++) { if (i[j] < origin_[j] || i[j] >= (origin_[j] + all_[j])) { return false; } } } else { for(std::size_t j=0;j<n;j++) { if (i[j] < 0 || i[j] >= all_[j]) { return false; } } } return true; } std::size_t operator()(index_type const& i) const { std::size_t n = nd(); std::size_t result = 0; if (n) { if (!is_0_based()) { for(std::size_t j=0;;) { result += i[j] - origin_[j]; j++; if (j == n) break; result *= all_[j]; } } else { for(std::size_t j=0;;) { result += i[j]; j++; if (j == n) break; result *= all_[j]; } } } return result; } // No assertions to enable maximum performance. std::size_t operator()( index_value_type const& i, index_value_type const& j) const { if (origin_.size() == 0) { return i * all_[1] + j; } return (i-origin_[0]) * all_[1] + (j-origin_[1]); } // No assertions to enable maximum performance. std::size_t operator()( index_value_type const& i, index_value_type const& j, index_value_type const& k) const { if (origin_.size() == 0) { return (i * all_[1] + j) * all_[2] + k; } return ((i-origin_[0]) * all_[1] + (j-origin_[1])) * all_[2] + (k-origin_[2]); } bool operator==(flex_grid<index_type> const& other) const { if (!all_.all_eq(other.all_)) return false; if (!origin_.all_eq(other.origin_)) return false; return focus_.all_eq(other.focus_); } bool operator!=(flex_grid<index_type> const& other) const { return !(*this == other); } protected: index_type all_; index_type origin_; index_type focus_; void set_focus_finalize() { index_type last_ = last(); if (focus_.all_eq(last_)) { focus_.clear(); } else { SCITBX_ASSERT(last_.all_ge(focus_)); } } }; }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_ACCESSORS_FLEX_GRID_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/detail/tiny_helpers.h
.h
3,840
163
// Included from tiny_plain.h // DO NOT INCLUDE THIS FILE DIRECTLY. #define SCITBX_ARRAY_FAMILY_TINY_CONVENIENCE_CONSTRUCTORS(class_name) \ explicit \ class_name( \ value_type const& v0 \ ) { \ this->elems[0] = v0; \ } \ class_name( \ value_type const& v0, \ value_type const& v1 \ ) { \ this->elems[0] = v0; \ this->elems[1] = v1; \ } \ class_name( \ value_type const& v0, \ value_type const& v1, \ value_type const& v2 \ ) { \ this->elems[0] = v0; \ this->elems[1] = v1; \ this->elems[2] = v2; \ } \ class_name( \ value_type const& v0, \ value_type const& v1, \ value_type const& v2, \ value_type const& v3 \ ) { \ this->elems[0] = v0; \ this->elems[1] = v1; \ this->elems[2] = v2; \ this->elems[3] = v3; \ } \ class_name( \ value_type const& v0, \ value_type const& v1, \ value_type const& v2, \ value_type const& v3, \ value_type const& v4 \ ) { \ this->elems[0] = v0; \ this->elems[1] = v1; \ this->elems[2] = v2; \ this->elems[3] = v3; \ this->elems[4] = v4; \ } \ class_name( \ value_type const& v0, \ value_type const& v1, \ value_type const& v2, \ value_type const& v3, \ value_type const& v4, \ value_type const& v5 \ ) { \ this->elems[0] = v0; \ this->elems[1] = v1; \ this->elems[2] = v2; \ this->elems[3] = v3; \ this->elems[4] = v4; \ this->elems[5] = v5; \ } \ class_name( \ value_type const& v0, \ value_type const& v1, \ value_type const& v2, \ value_type const& v3, \ value_type const& v4, \ value_type const& v5, \ value_type const& v6 \ ) { \ this->elems[0] = v0; \ this->elems[1] = v1; \ this->elems[2] = v2; \ this->elems[3] = v3; \ this->elems[4] = v4; \ this->elems[5] = v5; \ this->elems[6] = v6; \ } \ class_name( \ value_type const& v0, \ value_type const& v1, \ value_type const& v2, \ value_type const& v3, \ value_type const& v4, \ value_type const& v5, \ value_type const& v6, \ value_type const& v7 \ ) { \ this->elems[0] = v0; \ this->elems[1] = v1; \ this->elems[2] = v2; \ this->elems[3] = v3; \ this->elems[4] = v4; \ this->elems[5] = v5; \ this->elems[6] = v6; \ this->elems[7] = v7; \ } \ class_name( \ value_type const& v0, \ value_type const& v1, \ value_type const& v2, \ value_type const& v3, \ value_type const& v4, \ value_type const& v5, \ value_type const& v6, \ value_type const& v7, \ value_type const& v8 \ ) { \ this->elems[0] = v0; \ this->elems[1] = v1; \ this->elems[2] = v2; \ this->elems[3] = v3; \ this->elems[4] = v4; \ this->elems[5] = v5; \ this->elems[6] = v6; \ this->elems[7] = v7; \ this->elems[8] = v8; \ } \ class_name( \ value_type const& v0, \ value_type const& v1, \ value_type const& v2, \ value_type const& v3, \ value_type const& v4, \ value_type const& v5, \ value_type const& v6, \ value_type const& v7, \ value_type const& v8, \ value_type const& v9 \ ) { \ this->elems[0] = v0; \ this->elems[1] = v1; \ this->elems[2] = v2; \ this->elems[3] = v3; \ this->elems[4] = v4; \ this->elems[5] = v5; \ this->elems[6] = v6; \ this->elems[7] = v7; \ this->elems[8] = v8; \ this->elems[9] = v9; \ } \ template <typename OtherElementType> \ class_name(const OtherElementType* first, const OtherElementType* last) { \ if (last - first != this->size()) throw_range_error(); \ copy_typeconv(first, last, this->begin()); \ } #define SCITBX_ARRAY_FAMILY_TINY_COPY_AND_ASSIGNMENT(class_name) \ template <typename OtherElementType> \ class_name(tiny_plain<OtherElementType,N> const& rhs) { \ copy_typeconv(rhs.begin(), rhs.end(), this->begin()); \ } \ template <typename OtherElementType> \ class_name<ElementType,N>& \ operator=(tiny_plain<OtherElementType,N> const& rhs) { \ copy_typeconv(rhs.begin(), rhs.end(), this->begin()); \ return *this; \ }
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/detail/generic_array_functors.h
.h
9,246
331
#ifndef SCITBX_ARRAY_FAMILY_GENERIC_ARRAY_FUNCTORS_H #define SCITBX_ARRAY_FAMILY_GENERIC_ARRAY_FUNCTORS_H #include <scitbx/array_family/detail/generic_array_operators.h> namespace scitbx { namespace af { template <typename FunctorType, typename ElementType, typename ElementTypeResult> class array_functor_a { public: array_functor_a(FunctorType const& ftor, const ElementType* a) : m_ftor(ftor), m_a(a) {} void operator()( ElementTypeResult* result, std::size_t const& sz) const { typedef typename has_trivial_destructor<ElementTypeResult>::value htd; array_operation_a(m_ftor, m_a, result, sz, htd()); } protected: FunctorType const& m_ftor; const ElementType* m_a; }; template <typename FunctorType, typename ElementType> inline array_functor_a< FunctorType, ElementType, typename FunctorType::result_type> make_array_functor_a( FunctorType const& ftor, const ElementType* a) { return array_functor_a< FunctorType, ElementType, typename FunctorType::result_type>(ftor, a); } template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementTypeResult> class array_functor_a_a { public: array_functor_a_a( FunctorType const& ftor, const ElementType1* a1, const ElementType2* a2) : m_ftor(ftor), m_a1(a1), m_a2(a2) {} void operator()( ElementTypeResult* result, std::size_t const& sz) const { typedef typename has_trivial_destructor<ElementTypeResult>::value htd; array_operation_a_a(m_ftor, m_a1, m_a2, result, sz, htd()); } protected: FunctorType const& m_ftor; const ElementType1* m_a1; const ElementType2* m_a2; }; template <typename FunctorType, typename ElementType1, typename ElementType2> inline array_functor_a_a< FunctorType, ElementType1, ElementType2, typename FunctorType::result_type> make_array_functor_a_a( FunctorType const& ftor, const ElementType1* a1, const ElementType2* a2) { return array_functor_a_a< FunctorType, ElementType1, ElementType2, typename FunctorType::result_type>(ftor, a1, a2); } template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementTypeResult> class array_functor_a_s { public: array_functor_a_s( FunctorType const& ftor, const ElementType1* a1, ElementType2 const& a2) : m_ftor(ftor), m_a1(a1), m_a2(a2) {} void operator()( ElementTypeResult* result, std::size_t const& sz) const { typedef typename has_trivial_destructor<ElementTypeResult>::value htd; array_operation_a_s(m_ftor, m_a1, m_a2, result, sz, htd()); } protected: FunctorType const& m_ftor; const ElementType1* m_a1; ElementType2 m_a2; }; template <typename FunctorType, typename ElementType1, typename ElementType2> inline array_functor_a_s< FunctorType, ElementType1, ElementType2, typename FunctorType::result_type> make_array_functor_a_s( FunctorType const& ftor, const ElementType1* a1, ElementType2 const& a2) { return array_functor_a_s< FunctorType, ElementType1, ElementType2, typename FunctorType::result_type>(ftor, a1, a2); } template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementTypeResult> class array_functor_s_a { public: array_functor_s_a( FunctorType const& ftor, ElementType1 const& a1, const ElementType2* a2) : m_ftor(ftor), m_a1(a1), m_a2(a2) {} void operator()( ElementTypeResult* result, std::size_t const& sz) const { typedef typename has_trivial_destructor<ElementTypeResult>::value htd; array_operation_s_a(m_ftor, m_a1, m_a2, result, sz, htd()); } protected: FunctorType const& m_ftor; ElementType1 m_a1; const ElementType2* m_a2; }; template <typename FunctorType, typename ElementType1, typename ElementType2> inline array_functor_s_a< FunctorType, ElementType1, ElementType2, typename FunctorType::result_type> make_array_functor_s_a( FunctorType const& ftor, ElementType1 const& a1, const ElementType2* a2) { return array_functor_s_a< FunctorType, ElementType1, ElementType2, typename FunctorType::result_type>(ftor, a1, a2); } template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementType3, typename ElementTypeResult> class array_functor_a_a_s { public: array_functor_a_a_s( FunctorType const& ftor, const ElementType1* a1, const ElementType2* a2, ElementType3 const& a3) : m_ftor(ftor), m_a1(a1), m_a2(a2), m_a3(a3) {} void operator()( ElementTypeResult* result, std::size_t const& sz) const { typedef typename has_trivial_destructor<ElementTypeResult>::value htd; array_operation_a_a_s(m_ftor, m_a1, m_a2, m_a3, result, sz, htd()); } protected: FunctorType const& m_ftor; const ElementType1* m_a1; const ElementType2* m_a2; ElementType3 m_a3; }; template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementType3> inline array_functor_a_a_s< FunctorType, ElementType1, ElementType2, ElementType3, typename FunctorType::result_type> make_array_functor_a_a_s( FunctorType const& ftor, const ElementType1* a1, const ElementType2* a2, ElementType3 const& a3) { return array_functor_a_a_s< FunctorType, ElementType1, ElementType2, ElementType3, typename FunctorType::result_type>(ftor, a1, a2, a3); } template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementType3, typename ElementTypeResult> class array_functor_a_s_s { public: array_functor_a_s_s( FunctorType const& ftor, const ElementType1* a1, ElementType2 const& a2, ElementType3 const& a3) : m_ftor(ftor), m_a1(a1), m_a2(a2), m_a3(a3) {} void operator()( ElementTypeResult* result, std::size_t const& sz) const { typedef typename has_trivial_destructor<ElementTypeResult>::value htd; array_operation_a_s_s(m_ftor, m_a1, m_a2, m_a3, result, sz, htd()); } protected: FunctorType const& m_ftor; const ElementType1* m_a1; ElementType2 m_a2; ElementType3 m_a3; }; template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementType3> inline array_functor_a_s_s< FunctorType, ElementType1, ElementType2, ElementType3, typename FunctorType::result_type> make_array_functor_a_s_s( FunctorType const& ftor, const ElementType1* a1, ElementType2 const& a2, ElementType3 const& a3) { return array_functor_a_s_s< FunctorType, ElementType1, ElementType2, ElementType3, typename FunctorType::result_type>(ftor, a1, a2, a3); } template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementType3, typename ElementTypeResult> class array_functor_s_a_s { public: array_functor_s_a_s( FunctorType const& ftor, ElementType1 const& a1, const ElementType2* a2, ElementType3 const& a3) : m_ftor(ftor), m_a1(a1), m_a2(a2), m_a3(a3) {} void operator()( ElementTypeResult* result, std::size_t const& sz) const { typedef typename has_trivial_destructor<ElementTypeResult>::value htd; array_operation_s_a_s(m_ftor, m_a1, m_a2, m_a3, result, sz, htd()); } protected: FunctorType const& m_ftor; ElementType1 m_a1; const ElementType2* m_a2; ElementType3 m_a3; }; template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementType3> inline array_functor_s_a_s< FunctorType, ElementType1, ElementType2, ElementType3, typename FunctorType::result_type> make_array_functor_s_a_s( FunctorType const& ftor, ElementType1 const& a1, const ElementType2* a2, ElementType3 const& a3) { return array_functor_s_a_s< FunctorType, ElementType1, ElementType2, ElementType3, typename FunctorType::result_type>(ftor, a1, a2, a3); } }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_GENERIC_ARRAY_FUNCTORS_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/detail/reducing_boolean_mem_fun.h
.h
1,932
77
// Included from tiny.h, small.h, shared.h, versa.h // DO NOT INCLUDE THIS FILE DIRECTLY. bool all_eq(base_class const& other) const { return this->const_ref().all_eq(other.const_ref()); } bool all_eq(ElementType const& other) const { return this->const_ref().all_eq(other); } bool all_ne(base_class const& other) const { return this->const_ref().all_ne(other.const_ref()); } bool all_ne(ElementType const& other) const { return this->const_ref().all_ne(other); } bool all_lt(base_class const& other) const { return this->const_ref().all_lt(other.const_ref()); } bool all_lt(ElementType const& other) const { return this->const_ref().all_lt(other); } bool all_gt(base_class const& other) const { return this->const_ref().all_gt(other.const_ref()); } bool all_gt(ElementType const& other) const { return this->const_ref().all_gt(other); } bool all_le(base_class const& other) const { return this->const_ref().all_le(other.const_ref()); } bool all_le(ElementType const& other) const { return this->const_ref().all_le(other); } bool all_ge(base_class const& other) const { return this->const_ref().all_ge(other.const_ref()); } bool all_ge(ElementType const& other) const { return this->const_ref().all_ge(other); } bool all_approx_equal( base_class const& other, ElementType const& tolerance) const { return this->const_ref().all_approx_equal(other.const_ref(),tolerance); } bool all_approx_equal( ElementType const& other, ElementType const& tolerance) const { return this->const_ref().all_approx_equal(other, tolerance); }
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/detail/operator_functors.h
.h
6,386
228
/* ***************************************************** THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT EDIT. ***************************************************** Generated by: scitbx.source_generators.array_family.generate_operator_functors */ #ifndef SCITBX_ARRAY_FAMILY_OPERATOR_FUNCTORS_H #define SCITBX_ARRAY_FAMILY_OPERATOR_FUNCTORS_H namespace scitbx { namespace fn { template <typename ResultType, typename ArgumentType> struct functor_logical_not { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(!x); } }; template <typename ResultType, typename ArgumentType> struct functor_negate { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(-x); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_greater_equal { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(x >= y); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_equal_to { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(x == y); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_logical_or { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(x || y); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_less_equal { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(x <= y); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_logical_and { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(x && y); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_not_equal_to { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(x != y); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_modulus { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(x % y); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_plus { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(x + y); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_multiplies { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(x * y); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_minus { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(x - y); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_divides { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(x / y); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_less { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(x < y); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_greater { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(x > y); } }; template <typename ArgumentType1, typename ArgumentType2> struct functor_ip_minus { ArgumentType1& operator()(ArgumentType1& x, ArgumentType2 const& y) const { x -= y; return x; } }; template <typename ArgumentType1, typename ArgumentType2> struct functor_ip_multiplies { ArgumentType1& operator()(ArgumentType1& x, ArgumentType2 const& y) const { x *= y; return x; } }; template <typename ArgumentType1, typename ArgumentType2> struct functor_ip_divides { ArgumentType1& operator()(ArgumentType1& x, ArgumentType2 const& y) const { x /= y; return x; } }; template <typename ArgumentType1, typename ArgumentType2> struct functor_ip_modulus { ArgumentType1& operator()(ArgumentType1& x, ArgumentType2 const& y) const { x %= y; return x; } }; template <typename ArgumentType1, typename ArgumentType2> struct functor_ip_plus { ArgumentType1& operator()(ArgumentType1& x, ArgumentType2 const& y) const { x += y; return x; } }; }} // namespace scitbx::fn #endif // SCITBX_ARRAY_FAMILY_OPERATOR_FUNCTORS_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/detail/push_back_etc.h
.h
6,033
206
// Included from small_plain.h and shared_plain.h // DO NOT INCLUDE THIS FILE DIRECTLY. void assign(size_type const& sz, ElementType const& x) { if (sz > capacity()) { clear(); reserve(sz); std::uninitialized_fill_n(begin(), sz, x); m_set_size(sz); } else if (sz > size()) { std::fill(begin(), end(), x); std::uninitialized_fill(end(), begin() + sz, x); m_set_size(sz); } else { std::fill_n(begin(), sz, x); erase(begin() + sz, end()); } } void assign(const ElementType* first, const ElementType* last) { size_type sz = last - first; if (sz > capacity()) { clear(); reserve(sz); std::uninitialized_copy(first, last, begin()); m_set_size(sz); } else if (sz > size()) { const ElementType* mid = first + size() ; std::copy(first, mid, begin()); std::uninitialized_copy(mid, last, end()); m_set_size(sz); } else { std::copy(first, last, begin()); erase(begin() + sz, end()); } } void push_back(ElementType const& x) { if (size() < capacity()) { new (end()) ElementType(x); m_incr_size(1); } else { m_insert_overflow(end(), size_type(1), x, true); } } void pop_back() { m_decr_size(1); typedef typename has_trivial_destructor<ElementType>::value htd; detail::destroy_array_element(end(), htd()); } ElementType* insert(ElementType* pos, ElementType const& x) { size_type n = pos - begin(); if (size() == capacity()) { m_insert_overflow(pos, size_type(1), x, false); } else { if (pos == end()) { new (end()) ElementType(x); m_incr_size(1); } else { new (end()) ElementType(*(end() - 1)); m_incr_size(1); ElementType x_copy = x; std::copy_backward(pos, end() - 2, end() - 1); *pos = x_copy; } } return begin() + n; } // restricted to ElementType void insert(ElementType* pos, const ElementType* first, const ElementType* last) { size_type n = last - first; if (n == 0) return; if (size() + n > capacity()) { m_insert_overflow(pos, first, last); } else { size_type n_move_up = end() - pos; ElementType* old_end = end(); if (n_move_up > n) { std::uninitialized_copy(end() - n, end(), end()); m_incr_size(n); std::copy_backward(pos, old_end - n, old_end); std::copy(first, last, pos); } else { const ElementType* mid = first + n_move_up; std::uninitialized_copy(mid, last, end()); m_incr_size(n - n_move_up); std::uninitialized_copy(pos, old_end, end()); m_incr_size(n_move_up); std::copy(first, mid, pos); } } } // non-std void extend(const ElementType* first, const ElementType* last) { // pos == end(); size_type n = last - first; if (n == 0) return; if (size() + n > capacity()) { m_insert_overflow(end(), first, last); } else { std::uninitialized_copy(first, last, end()); m_incr_size(n); } } void insert(ElementType* pos, size_type const& n, ElementType const& x) { if (n == 0) return; if (size() + n > capacity()) { m_insert_overflow(pos, n, x, false); } else { ElementType x_copy = x; size_type n_move_up = end() - pos; ElementType* old_end = end(); if (n_move_up > n) { std::uninitialized_copy(end() - n, end(), end()); m_incr_size(n); std::copy_backward(pos, old_end - n, old_end); std::fill_n(pos, n, x_copy); } else { std::uninitialized_fill_n(end(), n - n_move_up, x_copy); m_incr_size(n - n_move_up); std::uninitialized_copy(pos, old_end, end()); m_incr_size(n_move_up); std::fill(pos, old_end, x_copy); } } } ElementType* erase(ElementType* pos) { if (pos + 1 != end()) { std::copy(pos + 1, end(), pos); } pop_back(); return pos; } ElementType* erase(ElementType* first, ElementType* last) { ElementType* i = std::copy(last, end(), first); typedef typename has_trivial_destructor<ElementType>::value htd; detail::destroy_array_elements(i, end(), htd()); m_decr_size(last - first); return first; } void resize(size_type const& new_size, ElementType const& x) { if (new_size < size()) { erase(begin() + new_size, end()); } else { insert(end(), new_size - size(), x); } } void resize(size_type const& new_size) { resize(new_size, ElementType()); } void clear() { erase(begin(), end()); } #if !(defined(BOOST_MSVC) && BOOST_MSVC <= 1200) // VC++ 6.0 // non-std template <typename OtherElementType> void assign(const OtherElementType* first, const OtherElementType* last) { clear(); size_type sz = last - first; reserve(sz); uninitialized_copy_typeconv(first, last, begin()); m_set_size(sz); } #endif // non-std template <typename OtherArrayType> void assign(OtherArrayType const& other) { if (other.size() == 0) { clear(); } else { assign(&*(other.begin()), (&*(other.begin()))+other.size()); } }
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/detail/misc.h
.h
3,120
133
#ifndef SCITBX_ARRAY_FAMILY_MISC_H #define SCITBX_ARRAY_FAMILY_MISC_H #include <scitbx/array_family/type_traits.h> #include <memory> namespace scitbx { namespace af { class reserve { public: reserve(std::size_t size) : size_(size) {} std::size_t operator()() const { return size_; } private: std::size_t size_; }; template <typename FunctorType> struct init_functor { init_functor() : held(0) {} explicit init_functor(FunctorType const& ftor) : held(&ftor) {} const FunctorType* held; }; template <typename FunctorType> inline init_functor<FunctorType> make_init_functor(FunctorType const& ftor) { return init_functor<FunctorType>(ftor); } template <typename ElementType> struct init_functor_null : init_functor<init_functor_null<ElementType> > { init_functor_null() { this->held = this; } void operator()(ElementType*, std::size_t const&) const { SCITBX_ARRAY_FAMILY_STATIC_ASSERT_HAS_TRIVIAL_DESTRUCTOR } }; namespace detail { template <class ElementType> inline void destroy_array_element(ElementType* elem, false_type) { elem->~ElementType(); } template <class ElementType> inline void destroy_array_element(ElementType* /*elem*/, true_type) { } template <class ElementType> inline void destroy_array_elements(ElementType* first, ElementType* last, false_type) { while (first != last) { first->~ElementType(); ++first; } } template <class ElementType> inline void destroy_array_elements(ElementType*, ElementType*, true_type) { } } // namespace detail #if !defined(__GNUC__) \ || ((__GNUC__ > 3) || ((__GNUC__ == 3) && (__GNUC_MINOR__ > 0))) #define SCITBX_ARRAY_FAMILY_STD_COPY_PERMITS_TYPECONV #endif template <typename InputElementType, typename OutputElementType> inline OutputElementType* copy_typeconv( const InputElementType* first, const InputElementType* last, OutputElementType* result) { #ifdef SCITBX_ARRAY_FAMILY_STD_COPY_PERMITS_TYPECONV return std::copy(first, last, result); #else OutputElementType* p = result; while (first != last) *p++ = OutputElementType(*first++); return result; #endif } template <typename InputElementType, typename OutputElementType> #ifdef SCITBX_ARRAY_FAMILY_STD_COPY_PERMITS_TYPECONV inline #endif OutputElementType* uninitialized_copy_typeconv( const InputElementType* first, const InputElementType* last, OutputElementType* result) { #ifdef SCITBX_ARRAY_FAMILY_STD_COPY_PERMITS_TYPECONV return std::uninitialized_copy(first, last, result); #else OutputElementType* p = result; try { for (; first != last; p++, first++) { new (p) OutputElementType(*first); } } catch (...) { detail::destroy_array_elements(result, p, false_type()); throw; } return result; #endif } }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_MISC_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/detail/auto_allocator.h
.h
515
21
#ifndef SCITBX_ARRAY_FAMILY_AUTO_ALLOCATOR_H #define SCITBX_ARRAY_FAMILY_AUTO_ALLOCATOR_H #include <boost/type_traits/alignment_traits.hpp> namespace scitbx { namespace af { namespace detail { template <typename T, std::size_t N> union auto_allocator { typedef typename boost::type_with_alignment< (boost::alignment_of<T>::value)>::type align_t; align_t dummy_; char buffer[N * sizeof(T)]; }; }}} // namespace scitbx::af::detail #endif // SCITBX_ARRAY_FAMILY_AUTO_ALLOCATOR_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/detail/std_imports.h
.h
8,115
318
/* ***************************************************** THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT EDIT. ***************************************************** Generated by: scitbx.source_generators.array_family.generate_std_imports */ #ifndef SCITBX_ARRAY_FAMILY_STD_IMPORTS_H #define SCITBX_ARRAY_FAMILY_STD_IMPORTS_H #ifndef DOXYGEN_SHOULD_SKIP_THIS #include <cmath> #include <cstdlib> #include <complex> namespace scitbx { namespace fn { using std::acos; using std::cos; using std::tan; using std::asin; using std::cosh; using std::tanh; using std::atan; using std::exp; using std::sin; using std::fabs; using std::log; using std::sinh; using std::ceil; using std::floor; using std::log10; using std::sqrt; using std::fmod; using std::pow; using std::atan2; using std::abs; using std::min; using std::max; using std::conj; using std::real; using std::imag; using std::arg; using std::norm; using std::polar; template <typename ResultType, typename ArgumentType> struct functor_acos { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(acos(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_cos { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(cos(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_tan { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(tan(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_asin { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(asin(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_cosh { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(cosh(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_tanh { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(tanh(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_atan { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(atan(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_exp { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(exp(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_sin { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(sin(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_fabs { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(fabs(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_log { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(log(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_sinh { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(sinh(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_ceil { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(ceil(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_floor { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(floor(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_log10 { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(log10(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_sqrt { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(sqrt(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_abs { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(abs(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_conj { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(conj(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_real { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(real(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_imag { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(imag(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_arg { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(arg(x)); } }; template <typename ResultType, typename ArgumentType> struct functor_norm { typedef ResultType result_type; ResultType operator()(ArgumentType const& x) const { return ResultType(norm(x)); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_fmod { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(fmod(x, y)); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_pow { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(pow(x, y)); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_atan2 { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(atan2(x, y)); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_each_min { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(min(x, y)); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_each_max { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(max(x, y)); } }; template <typename ResultType, typename ArgumentType1, typename ArgumentType2> struct functor_polar { typedef ResultType result_type; ResultType operator()(ArgumentType1 const& x, ArgumentType2 const& y) const { return ResultType(polar(x, y)); } }; }} // namespace scitbx::af #endif // DOXYGEN_SHOULD_SKIP_THIS #endif // SCITBX_ARRAY_FAMILY_STD_IMPORTS_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/detail/generic_array_operators.h
.h
10,267
380
#ifndef SCITBX_ARRAY_FAMILY_GENERIC_ARRAY_OPERATORS_H #define SCITBX_ARRAY_FAMILY_GENERIC_ARRAY_OPERATORS_H #include <scitbx/array_family/detail/misc.h> namespace scitbx { namespace af { // functor(array), non-POD result type template <typename FunctorType, typename ElementType, typename ElementTypeResult> void // not inline array_operation_a( FunctorType const& ftor, const ElementType* a, ElementTypeResult* result, std::size_t const& sz, false_type) { ElementTypeResult* result_start = result; try { ElementTypeResult* result_end = result + sz; for(;result != result_end; a++, result++) { new (result) ElementTypeResult(ftor(*a)); } } catch (...) { scitbx::af::detail::destroy_array_elements(result_start, result, false_type()); throw; } } // functor(array), POD result type template <typename FunctorType, typename ElementType, typename ElementTypeResult> inline void array_operation_a( FunctorType const& ftor, const ElementType* a, ElementTypeResult* result, std::size_t const& sz, true_type) { ElementTypeResult* result_end = result + sz; for(;result != result_end; a++, result++) { *result = ftor(*a); } } // functor(array, array), non-POD result type template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementTypeResult> void // not inline array_operation_a_a( FunctorType const& ftor, const ElementType1* a1, const ElementType2* a2, ElementTypeResult* result, std::size_t const& sz, false_type) { ElementTypeResult* result_start = result; try { ElementTypeResult* result_end = result + sz; for(;result != result_end; a1++, a2++, result++) { new (result) ElementTypeResult(ftor(*a1, *a2)); } } catch (...) { scitbx::af::detail::destroy_array_elements(result_start, result, false_type()); throw; } } // functor(array, array), POD result type template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementTypeResult> inline void array_operation_a_a( FunctorType const& ftor, const ElementType1* a1, const ElementType2* a2, ElementTypeResult* result, std::size_t const& sz, true_type) { ElementTypeResult* result_end = result + sz; for(;result != result_end; a1++, a2++, result++) { *result = ftor(*a1, *a2); } } // functor(array, scalar), non-POD result type template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementTypeResult> void // not inline array_operation_a_s( FunctorType const& ftor, const ElementType1* a1, ElementType2 const& a2, ElementTypeResult* result, std::size_t const& sz, false_type) { ElementTypeResult* result_start = result; try { ElementTypeResult* result_end = result + sz; for(;result != result_end; a1++, result++) { new (result) ElementTypeResult(ftor(*a1, a2)); } } catch (...) { scitbx::af::detail::destroy_array_elements(result_start, result, false_type()); throw; } } // functor(array, scalar), POD result type template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementTypeResult> inline void array_operation_a_s( FunctorType const& ftor, const ElementType1* a1, ElementType2 const& a2, ElementTypeResult* result, std::size_t const& sz, true_type) { ElementTypeResult* result_end = result + sz; for(;result != result_end; a1++, result++) { *result = ftor(*a1, a2); } } // functor(scalar, array), non-POD result type template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementTypeResult> void // not inline array_operation_s_a( FunctorType const& ftor, ElementType1 const& a1, const ElementType2* a2, ElementTypeResult* result, std::size_t const& sz, false_type) { ElementTypeResult* result_start = result; try { ElementTypeResult* result_end = result + sz; for(;result != result_end; a2++, result++) { new (result) ElementTypeResult(ftor(a1, *a2)); } } catch (...) { scitbx::af::detail::destroy_array_elements(result_start, result, false_type()); throw; } } // functor(scalar, array), POD result type template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementTypeResult> inline void array_operation_s_a( FunctorType const& ftor, ElementType1 const& a1, const ElementType2* a2, ElementTypeResult* result, std::size_t const& sz, true_type) { ElementTypeResult* result_end = result + sz; for(;result != result_end; a2++, result++) { *result = ftor(a1, *a2); } } // functor(array, array, scalar), non-POD result type template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementType3, typename ElementTypeResult> void // not inline array_operation_a_a_s( FunctorType const& ftor, const ElementType1* a1, const ElementType2* a2, ElementType3 const& a3, ElementTypeResult* result, std::size_t const& sz, false_type) { ElementTypeResult* result_start = result; try { ElementTypeResult* result_end = result + sz; for(;result != result_end; a1++, a2++, result++) { new (result) ElementTypeResult(ftor(*a1, *a2, a3)); } } catch (...) { scitbx::af::detail::destroy_array_elements(result_start, result, false_type()); throw; } } // functor(array, array, scalar), POD result type template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementType3, typename ElementTypeResult> inline void array_operation_a_a_s( FunctorType const& ftor, const ElementType1* a1, const ElementType2* a2, ElementType3 const& a3, ElementTypeResult* result, std::size_t const& sz, true_type) { ElementTypeResult* result_end = result + sz; for(;result != result_end; a1++, a2++, result++) { *result = ftor(*a1, *a2, a3); } } // functor(array, scalar, scalar), non-POD result type template <typename FunctorType, typename ElementType, typename ElementTypeResult> void // not inline array_operation_a_s_s( FunctorType const& ftor, const ElementType* a1, ElementType const& a2, ElementType const& a3, ElementTypeResult* result, std::size_t const& sz, false_type) { ElementTypeResult* result_start = result; try { ElementTypeResult* result_end = result + sz; for(;result != result_end; a1++, result++) { new (result) ElementTypeResult(ftor(*a1, a2, a3)); } } catch (...) { scitbx::af::detail::destroy_array_elements(result_start, result, false_type()); throw; } } // functor(array, scalar, scalar), POD result type template <typename FunctorType, typename ElementType, typename ElementTypeResult> inline void array_operation_a_s_s( FunctorType const& ftor, const ElementType* a1, ElementType const& a2, ElementType const& a3, ElementTypeResult* result, std::size_t const& sz, true_type) { ElementTypeResult* result_end = result + sz; for(;result != result_end; a1++, result++) { *result = ftor(*a1, a2, a3); } } // functor(scalar, array, scalar), non-POD result type template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementType3, typename ElementTypeResult> void // not inline array_operation_s_a_s( FunctorType const& ftor, ElementType1 const& a1, const ElementType2* a2, ElementType3 const& a3, ElementTypeResult* result, std::size_t const& sz, false_type) // non-POD result type { ElementTypeResult* result_start = result; try { ElementTypeResult* result_end = result + sz; for(;result != result_end; a2++, result++) { new (result) ElementTypeResult(ftor(a1, *a2, a3)); } } catch (...) { scitbx::af::detail::destroy_array_elements(result_start, result, false_type()); throw; } } // functor(scalar, array, scalar), POD result type template <typename FunctorType, typename ElementType1, typename ElementType2, typename ElementType3, typename ElementTypeResult> inline void array_operation_s_a_s( FunctorType const& ftor, ElementType1 const& a1, const ElementType2* a2, ElementType3 const& a3, ElementTypeResult* result, std::size_t const& sz, true_type) { ElementTypeResult* result_end = result + sz; for(;result != result_end; a2++, result++) { *result = ftor(a1, *a2, a3); } } // functor in_place(array, array) template <typename InPlaceFunctorType, typename ElementType1, typename ElementType2> inline void array_operation_in_place_a_a( InPlaceFunctorType const& ftor, ElementType1* a1, const ElementType2* a2, std::size_t const& sz) { ElementType1* a1_end = a1 + sz; for(;a1 != a1_end; a1++, a2++) ftor(*a1, *a2); } // functor in_place(array, scalar) template <typename InPlaceFunctorType, typename ElementType> inline void array_operation_in_place_a_s( InPlaceFunctorType const& ftor, ElementType* a1, ElementType const& a2, std::size_t const& sz) { ElementType* a1_end = a1 + sz; for(;a1 != a1_end; a1++) ftor(*a1, a2); } }} // namespace scitbx::af #endif // SCITBX_ARRAY_FAMILY_GENERIC_ARRAY_OPERATORS_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/array_family/detail/ref_helpers.h
.h
3,470
91
// Included from ref.h // DO NOT INCLUDE THIS FILE DIRECTLY. #include <boost/operators.hpp> namespace scitbx { namespace af { namespace detail { template<class T> class ref_reverse_iterator : public boost::random_access_iterator_helper<ref_reverse_iterator<T>, T> { T* p; typedef ref_reverse_iterator self; typedef std::ptrdiff_t Distance; public: ref_reverse_iterator() : p(0) {} explicit ref_reverse_iterator(T* beg) : p(beg-1) {} ref_reverse_iterator(self const& i) : p(i.p) {} self& operator=(self const& x) { p = x.p; return *this; } T& operator*() const { return *p; } bool operator==(self const& i) const { return p == i.p; } bool operator<(self const& i) const { return p > i.p; } self& operator++() { p--; return *this; } self& operator--() { p++; return *this; } self& operator+=(Distance n) { p -= n; return *this; } self& operator-=(Distance n) { p += n; return *this; } friend Distance operator-(self const& i, self const& j) { return j.p - i.p; } }; }}} #define SCITBX_ARRAY_FAMILY_TYPEDEFS \ typedef ElementType value_type; \ typedef ElementType* iterator; \ typedef const ElementType* const_iterator; \ typedef detail::ref_reverse_iterator<ElementType> reverse_iterator; \ typedef detail::ref_reverse_iterator<const ElementType> const_reverse_iterator; \ typedef ElementType& reference; \ typedef ElementType const& const_reference; \ typedef std::size_t size_type; \ typedef std::ptrdiff_t difference_type; #define SCITBX_ARRAY_FAMILY_BEGIN_END_ETC(this_type, beg, sz) \ ElementType* begin() { return beg; } \ const ElementType* begin() const { return beg; } \ ElementType* end() { return beg+sz; } \ const ElementType* end() const { return beg+sz; } \ reverse_iterator rbegin() { return reverse_iterator(beg+sz); } \ const_reverse_iterator rbegin() const { return const_reverse_iterator(beg+sz); } \ reverse_iterator rend() { return reverse_iterator(beg); } \ const_reverse_iterator rend() const { return const_reverse_iterator(beg); } \ ElementType& front() { return beg[0]; } \ ElementType const& front() const { return beg[0]; } \ ElementType& back() { return beg[sz-1]; } \ ElementType const& back() const { return beg[sz-1]; } \ \ ElementType& operator[](size_type i) { return beg[i]; } \ ElementType const& operator[](size_type i) const { return beg[i]; } \ \ ElementType& at(size_type i) { \ if (i >= sz) throw_range_error(); return beg[i]; \ } \ ElementType const& at(size_type i) const { \ if (i >= sz) throw_range_error(); return beg[i]; \ } \ this_type& fill(ElementType const& x) { \ std::fill(this->begin(), this->end(), x); \ return *this; \ } #define SCITBX_ARRAY_FAMILY_TAKE_REF(beg, sz) \ af::ref<ElementType> \ ref() { \ return af::ref<ElementType>(beg, sz); \ } \ af::const_ref<ElementType> \ const_ref() const { \ return af::const_ref<ElementType>(beg, sz); \ } #define SCITBX_ARRAY_FAMILY_TAKE_VERSA_REF(beg, ac) \ af::ref<ElementType, AccessorType> \ ref() { \ return af::ref<ElementType, AccessorType>(beg, ac); \ } \ af::const_ref<ElementType, AccessorType> \ const_ref() const { \ return af::const_ref<ElementType, AccessorType>(beg, ac); \ }
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/matrix/multiply.h
.h
5,386
228
#ifndef SCITBX_MATRIX_MULTIPLY_H #define SCITBX_MATRIX_MULTIPLY_H namespace scitbx { namespace matrix { //! Generic matrix multiplication function: a * b /*! ab[ar, bc] = a[ar, ac] * b[ac, bc] */ template <typename NumTypeA, typename NumTypeB, typename NumTypeAB> void multiply( const NumTypeA *a, const NumTypeB *b, unsigned ar, unsigned ac, unsigned bc, NumTypeAB *ab) { unsigned i0 = 0; for (unsigned i=0; i<ar; i++, i0+=ac) { for (unsigned k=0;k<bc;k++) { NumTypeAB s = 0; unsigned ij = i0; unsigned jk = k; for (unsigned j=0;j<ac;j++,jk+=bc) { s += a[ij++] * b[jk]; } *ab++ = s; } } } //! Generic matrix multiplication function: a.transpose() * b /*! ab[ac, bc] = a[ar, ac].transpose() * b[ar, bc] */ template <typename NumTypeA, typename NumTypeB, typename NumTypeAtB> void transpose_multiply( const NumTypeA *a, const NumTypeB *b, unsigned ar, unsigned ac, unsigned bc, NumTypeAtB *atb) { unsigned arac = ar * ac; for (unsigned i=0;i<ac;i++) { for (unsigned k=0;k<bc;k++) { NumTypeAtB s = 0; unsigned jk = k; for (unsigned ji=i;ji<arac;ji+=ac,jk+=bc) { s += a[ji] * b[jk]; } *atb++ = s; } } } //! Generic matrix multiplication function: a * b.transpose() /*! ab[ar, br] = a[ar, ac] * b[br, ac].transpose() */ template <typename NumTypeA, typename NumTypeB, typename NumTypeAB> void multiply_transpose( const NumTypeA *a, const NumTypeB *b, unsigned ar, unsigned ac, unsigned br, NumTypeAB *ab) { unsigned i0 = 0; for (unsigned i=0; i<ar; i++, i0+=ac) { unsigned kj = 0; for (unsigned k=0;k<br;k++) { NumTypeAB s = 0; unsigned ij = i0; for (unsigned j=0;j<ac;j++) { s += a[ij++] * b[kj++]; } *ab++ = s; } } } //! Generic matrix multiplication function: a * b, with b in packed_u format. /*! ab[ar, ac] = a[ar, ac] * b[ac, ac] */ template <typename NumTypeA, typename NumTypeB, typename NumTypeAB> void multiply_packed_u( const NumTypeA* a, const NumTypeB* b, unsigned ar, unsigned ac, NumTypeAB *ab) { unsigned i0 = 0; for(unsigned i=0;i<ar;i++,i0+=ac) { for(unsigned k=0;k<ac;k++) { NumTypeAB s = 0; unsigned ij = i0; unsigned jk = k; for(unsigned j=0;j<k;jk+=ac-(++j)) { s += a[ij++] * b[jk]; } for(unsigned j=k;j<ac;j++) { s += a[ij++] * b[jk++]; } *ab++ = s; } } } /*! \brief Generic matrix multiplication function: a * b * a.transpose(), with b in packed_u format. */ /*! size of b is ac*(ac+1)/2; size of ab is ar*ac; size of abat is ar*(ar+1)/2 */ template <typename NumTypeA, typename NumTypeB, typename NumTypeAB, typename NumTypeABAt> void multiply_packed_u_multiply_lhs_transpose( const NumTypeA* a, const NumTypeB* b, unsigned ar, unsigned ac, NumTypeAB *ab, NumTypeABAt *abat) { multiply_packed_u(a, b, ar, ac, ab); unsigned i0 = 0; for(unsigned i=0;i<ar;i++,i0+=ac) { unsigned k0 = i0; for(unsigned k=i;k<ar;k++,k0+=ac) { NumTypeABAt s = 0; unsigned ij = i0; unsigned kj = k0; for(unsigned j=0;j<ac;j++) { s += ab[ij++] * a[kj++]; } *abat++ = s; } } } //! Generic matrix multiplication function: a.transpose() * a /*! ata[ac, ac] = a[ar, ac].transpose() * a[ar, ac] */ template <typename NumTypeA, typename NumTypeAB> void transpose_multiply_as_packed_u( const NumTypeA *a, unsigned ar, unsigned ac, NumTypeAB *ata) { if (ar == 0) { std::fill(ata, ata+(ac*(ac+1)/2), static_cast<NumTypeAB>(0)); return; } std::size_t ik = 0; for(unsigned i=0;i<ac;i++) { for(unsigned k=i;k<ac;k++) { ata[ik++] = a[i] * a[k]; } } unsigned jac = ac; for(unsigned j=1;j<ar;j++,jac+=ac) { ik = 0; for(unsigned i=0;i<ac;i++) { for(unsigned k=i;k<ac;k++) { ata[ik++] += a[jac + i] * a[jac + k]; } } } } //! Generic matrix multiplication function: a.transpose() * d * a /*! a = n x n square matrix d = n diagonal elements of diagonal matrix */ template <typename NumTypeA, typename NumTypeD, typename NumTypeAD> void transpose_multiply_diagonal_multiply_as_packed_u( const NumTypeA *a, const NumTypeD *diagonal_elements, unsigned n, NumTypeAD *atda) { std::size_t ik = 0; for(unsigned i=0;i<n;i++) { NumTypeAD ad = a[i] * diagonal_elements[0]; for(unsigned k=i;k<n;k++) { atda[ik++] = ad * a[k]; } } unsigned jac = n; for(unsigned j=1;j<n;j++,jac+=n) { ik = 0; for(unsigned i=0;i<n;i++) { NumTypeAD ad = a[jac + i] * diagonal_elements[j]; for(unsigned k=i;k<n;k++) { atda[ik++] += ad * a[jac + k]; } } } } }} // namespace scitbx::matrix #endif // SCITBX_MATRIX_MULTIPLY_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/matrix/as_xyz.h
.h
2,132
82
#ifndef SCITBX_MATRIX_AS_XYZ_H #define SCITBX_MATRIX_AS_XYZ_H #include <scitbx/rational.h> #include <scitbx/error.h> #include <cstring> namespace scitbx { namespace matrix { template <typename IntType> std::string rational_as_xyz( int n_rows, int n_columns, const IntType* r_num, IntType r_den, const IntType* t_num, IntType t_den, bool decimal, bool t_first, const char* letters_xyz, const char* separator) { SCITBX_ASSERT(letters_xyz != 0 && std::strlen(letters_xyz) == static_cast<unsigned>(n_columns)); SCITBX_ASSERT(separator != 0); std::string result; for (int i = 0; i < n_rows; i++) { std::string R_term; if (r_num != 0) { for (int j = 0; j < n_columns; j++) { boost::rational<IntType> R_frac(r_num[i*n_columns+j], r_den); if (R_frac != 0) { if (R_frac > 0) { if (!R_term.empty()) { R_term += "+"; } } else { R_term += "-"; R_frac *= -1; } if (R_frac != 1) { R_term += scitbx::format(R_frac, decimal) + "*"; } R_term += letters_xyz[j]; } } } if (i != 0) result += separator; if (t_num == 0) { if (R_term.empty()) result += "0"; else result += R_term; } else { boost::rational<IntType> T_frac(t_num[i], t_den); if (T_frac == 0) { if (R_term.empty()) result += "0"; else result += R_term; } else if (R_term.empty()) { result += scitbx::format(T_frac, decimal); } else if (t_first) { result += scitbx::format(T_frac, decimal); if (R_term[0] != '-') result += "+"; result += R_term; } else { result += R_term; if (T_frac > 0) result += "+"; result += scitbx::format(T_frac, decimal); } } } return result; } }} // namespace scitbx::matrix #endif // SCITBX_MATRIX_AS_XYZ_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/scitbx/matrix/row_echelon.h
.h
5,449
200
#ifndef SCITBX_MATRIX_ROW_ECHELON_H #define SCITBX_MATRIX_ROW_ECHELON_H #include <scitbx/array_family/accessors/mat_grid.h> #include <scitbx/array_family/small.h> #include <scitbx/array_family/misc_functions.h> #include <scitbx/matrix/multiply.h> #include <scitbx/math/gcd.h> namespace scitbx { namespace matrix { namespace row_echelon { namespace detail { template <typename AnyType> inline void swap(AnyType* a, AnyType* b, std::size_t n) { for(std::size_t i=0;i<n;i++) std::swap(a[i], b[i]); } } // namespace detail template <typename IntType> std::size_t form_t(af::ref<IntType, af::mat_grid>& m, af::ref<IntType, af::mat_grid> const& t) { // C++ version of RowEchelonFormT from the CrystGAP package // (GAP Version 3.4.4). // B. Eick, F. Ga"hler and W. Nickel // Computing Maximal Subgroups and Wyckoff Positions of Space Groups // Acta Cryst. (1997). A53, 467 - 474 using std::size_t; size_t mr = m.n_rows(); size_t mc = m.n_columns(); size_t tc = t.n_columns(); if (tc) { SCITBX_ASSERT(t.begin() != 0 && t.n_rows() >= mr); } size_t i, j; for (i = j = 0; i < mr && j < mc;) { size_t k = i; while (k < mr && m(k,j) == 0) k++; if (k == mr) j++; else { if (i != k) { detail::swap(&m(i,0), &m(k,0), mc); if (tc) detail::swap(&t(i,0), &t(k,0), tc); } for (k++; k < mr; k++) { IntType a = scitbx::fn::absolute(m(k, j)); if (a != 0 && a < scitbx::fn::absolute(m(i,j))) { detail::swap(&m(i,0), &m(k,0), mc); if (tc) detail::swap(&t(i,0), &t(k,0), tc); } } if (m(i,j) < 0) { for(size_t ic=0;ic<mc;ic++) m(i,ic) *= -1; if (tc) for(size_t ic=0;ic<tc;ic++) t(i,ic) *= -1; } bool cleared = true; for (k = i+1; k < mr; k++) { IntType a = m(k,j) / m(i,j); if (a != 0) { for(size_t ic=0;ic<mc;ic++) m(k,ic) -= a * m(i,ic); if (tc) for(size_t ic=0;ic<tc;ic++) t(k,ic) -= a * t(i,ic); } if (m(k,j) != 0) cleared = false; } if (cleared) { i++; j++; } } } m = af::ref<IntType, af::mat_grid>(m.begin(), i, mc); return i; } template <typename IntType> std::size_t form(af::ref<IntType, af::mat_grid>& m) { af::ref<IntType, af::mat_grid> t(0,0,0); return form_t(m, t); } template <typename IntType> IntType back_substitution_int( af::const_ref<IntType, af::mat_grid> const& re_mx, const IntType* v = 0, IntType* sol = 0, bool* flag_indep = 0) { using std::size_t; size_t nr = re_mx.n_rows(); size_t nc = re_mx.n_columns(); if (flag_indep) { for(size_t ic=0;ic<nc;ic++) flag_indep[ic] = true; } IntType d = 1; for (size_t ir = nr; ir > 0;) { ir--; size_t ic; for(ic=0;ic<nc;ic++) { if (re_mx(ir,ic)) goto set_sol_ic; } if (v && v[ir] != 0) return 0; continue; set_sol_ic: if (flag_indep) flag_indep[ic] = false; if (sol) { size_t icp = ic + 1; size_t nv = nc - icp; if (nv) { scitbx::matrix::multiply(&re_mx(ir,icp), &sol[icp], 1, nv, 1, &sol[ic]); sol[ic] *= -1; } else { sol[ic] = 0; } if (v) sol[ic] += d * v[ir]; IntType mrc = re_mx(ir,ic); IntType f = math::gcd_int(sol[ic], mrc); if (mrc < 0) f *= -1; sol[ic] /= f; f = mrc / f; if (f != 1) { for(size_t jc=0;jc<nc;jc++) if (jc != ic) sol[jc] *= f; d *= f; } } } return d; } template <typename IntType, typename FloatType> bool back_substitution_float( af::const_ref<IntType, af::mat_grid> const& re_mx, const FloatType* v, FloatType* sol) { SCITBX_ASSERT(sol != 0); using std::size_t; size_t nr = re_mx.n_rows(); size_t nc = re_mx.n_columns(); for (size_t ir = nr; ir > 0;) { ir--; size_t ic; for(ic=0;ic<nc;ic++) { if (re_mx(ir,ic)) goto set_sol_ic; } if (v && v[ir] != 0) return false; continue; set_sol_ic: size_t icp = ic + 1; size_t nv = nc - icp; if (nv) { scitbx::matrix::multiply(&re_mx(ir,icp), &sol[icp], 1, nv, 1, &sol[ic]); sol[ic] = -sol[ic]; } else { sol[ic] = 0; } if (v) sol[ic] += v[ir]; sol[ic] /= static_cast<FloatType>(re_mx(ir,ic)); } return true; } template <typename IntType, std::size_t MaxIndependentIndices = 6> struct independent { independent() {} independent(af::const_ref<IntType, af::mat_grid> const& re_mx) { using std::size_t; size_t nc = re_mx.n_columns(); SCITBX_ASSERT(nc <= MaxIndependentIndices); bool flag_indep[MaxIndependentIndices]; IntType* n_a = 0; SCITBX_ASSERT(back_substitution_int(re_mx, n_a, n_a, flag_indep) >= 1); for(size_t ic=0;ic<nc;ic++) { if (flag_indep[ic]) indices.push_back(ic); } } af::small<std::size_t, MaxIndependentIndices> indices; }; }}} // namespace scitbx::matrix::row_echelon #endif // include guard
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/miller.h
.h
3,831
135
/*! \file Handling of Miller indices. */ #ifndef CCTBX_MILLER_H #define CCTBX_MILLER_H #include <scitbx/vec3.h> #include <scitbx/array_family/misc_functions.h> #include <cctbx/import_scitbx_af.h> #include <cctbx/error.h> #include <cstdio> namespace cctbx { //! Miller index namespace. namespace miller { //! Miller index class. template <typename NumType=int> class index : public scitbx::vec3<NumType> { public: typedef scitbx::vec3<NumType> base_type; //! Default constructor: (h,k,l) = (0,0,0) index() : base_type(0,0,0) {} //! Construction with an instance of the base type. index(base_type const& h) : base_type(h) {} //! Construction from the highest array type in the inheritance tree. template <typename OtherNumType> index(af::tiny_plain<OtherNumType, 3> const& v) { for(std::size_t i=0;i<3;i++) this->elems[i] = v[i]; } //! Construction with raw pointer to index elements. template <typename OtherNumType> explicit index(const OtherNumType* hkl) { for(std::size_t i=0;i<3;i++) this->elems[i] = hkl[i]; } //! Construction from individual h,k,l. index(NumType const& h, NumType const& k, NumType const& l) : base_type(h, k, l) {} //! Definition of sort order for human-readable listings. /*! This comparison is computationally more expensive than fast_less_than below. */ bool operator<(index const& other) const { const int P[3] = {2, 0, 1}; for(std::size_t i=0;i<3;i++) { if (this->elems[P[i]] >= 0 && other[P[i]] < 0) return true; if (this->elems[P[i]] < 0 && other[P[i]] >= 0) return false; } for(std::size_t i=0;i<3;i++) { if ( scitbx::fn::absolute(this->elems[P[i]]) < scitbx::fn::absolute(other[P[i]])) return true; if ( scitbx::fn::absolute(this->elems[P[i]]) > scitbx::fn::absolute(other[P[i]])) return false; } return false; } //! Test this > other, based on sort order defined by operator<(). bool operator>(index const& other) const { if (*this < other) return false; for(std::size_t i=0;i<3;i++) { if (this->elems[i] != other[i]) return true; } return false; } #if defined(BOOST_MSVC) && BOOST_MSVC <= 1300 // VC++ 7.0 // work around compiler bug index operator-() const { return index(-static_cast<base_type>(*this)); } #endif #if defined(__GNUC__) \ && __GNUC__ == 3 \ && __GNUC_MINOR__ == 2 \ && __GNUC_PATCHLEVEL__ != 0 // 3 known to fail, 0 OK, others unknown // work around compiler bug bool operator!=(index const& other) const { return static_cast<base_type>(*this) != static_cast<base_type>(other); } #endif std::string as_string() const { char buf[128]; buf[127] = '\0'; std::sprintf(buf, "(%ld,%ld,%ld)", static_cast<long>(this->elems[0]), static_cast<long>(this->elems[1]), static_cast<long>(this->elems[2])); CCTBX_ASSERT(buf[127] == '\0'); return std::string(buf); } }; /*! \brief Definition of fast comparison for use in, e.g., std::map<miller::index<> >. */ template <typename NumType=int> class fast_less_than { public: //! This fast comparison function is implemented as operator(). bool operator()(index<NumType> const& h1, index<NumType> const& h2) const { for(std::size_t i=0;i<3;i++) { if (h1[i] < h2[i]) return true; if (h1[i] > h2[i]) return false; } return false; } }; }} // namespace cctbx::miller #endif // CCTBX_MILLER_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/coordinates.h
.h
5,808
190
#ifndef CCTBX_COORDINATES_H #define CCTBX_COORDINATES_H #include <scitbx/vec3.h> #include <cctbx/import_scitbx_af.h> namespace cctbx { template <typename FloatType> class fractional; template <typename IntType> class grid_point; //! Class for cartesian (orthogonal, real) coordinates. /*! The template parameter FloatType should be a floating point type (e.g. float or double). <p> See also: class fractional */ template <typename FloatType = double> class cartesian : public scitbx::vec3<FloatType> { public: typedef scitbx::vec3<FloatType> base_type; //! Default constructor: elements are not initialized! cartesian() {} //! The elements of the coordinate vector are copied from v. template <typename OtherFloatType> cartesian(af::tiny_plain<OtherFloatType, 3> const& v) { for(std::size_t i=0;i<3;i++) this->elems[i] = v[i]; } //! The elements of the coordinate vector are copied from xyz. explicit cartesian(const FloatType* xyz) { for(std::size_t i=0;i<3;i++) this->elems[i] = xyz[i]; } //! The elements of the coordinate vector are initialized with x,y,z. cartesian(FloatType const& x, FloatType const& y, FloatType const& z) { this->elems[0] = x; this->elems[1] = y; this->elems[2] = z; } private: // disables construction from fractional template <typename OtherFloatType> cartesian(fractional<OtherFloatType> const&); // disables construction from grid_point template <typename OtherFloatType> cartesian(grid_point<OtherFloatType> const&); }; //! Class for fractional coordinates. /*! The template parameter FloatType should be a floating point type (e.g. float or double). <p> See also: class cartesian */ template <typename FloatType = double> class fractional : public scitbx::vec3<FloatType> { public: typedef scitbx::vec3<FloatType> base_type; //! Default constructor: elements are not initialized! fractional() {} //! The elements of the coordinate vector are copied from v. template <typename OtherFloatType> fractional(af::tiny_plain<OtherFloatType, 3> const& v) { for(std::size_t i=0;i<3;i++) this->elems[i] = v[i]; } //! The elements of the coordinate vector are copied from xyz. template <typename OtherFloatType> explicit fractional(const OtherFloatType* xyz) { for(std::size_t i=0;i<3;i++) this->elems[i] = xyz[i]; } //! The elements of the coordinate vector are initialized with x,y,z. fractional(FloatType const& x, FloatType const& y, FloatType const& z) { this->elems[0] = x; this->elems[1] = y; this->elems[2] = z; } /*! \brief Apply modulus operation such that 0.0 <= x < 1.0 for all elements of the coordinate vector. */ fractional mod_positive() const { fractional result; for(std::size_t i=0;i<3;i++) { result[i] = std::fmod(this->elems[i], 1.); while (result[i] < 0.) result[i] += 1.; while (result[i] >= 1.) result[i] -= 1.; } return result; } /*! \brief Apply modulus operation such that -0.5 < x <= 0.5 for all elements of the coordinate vector. */ fractional mod_short() const { fractional result; for(std::size_t i=0;i<3;i++) { result[i] = std::fmod(this->elems[i], 1.); if (result[i] <= -.5) result[i] += 1.; else if (result[i] > .5) result[i] -= 1.; } return result; } scitbx::vec3<int> unit_shifts() const { scitbx::vec3<int> result; for(std::size_t i=0;i<3;i++) { if (this->elems[i] >= 0.) result[i] = int(this->elems[i] + 0.5); else result[i] = int(this->elems[i] - 0.5); } return result; } private: // disables construction from cartesian template <typename OtherFloatType> fractional(cartesian<OtherFloatType> const&); // disables construction from grid_point template <typename OtherFloatType> fractional(grid_point<OtherFloatType> const&); }; //! Class for grid_point coordinates. /*! The template parameter IntType should be an integral type (e.g. signed int or signed long). <p> See also: class fractional, class cartesian */ template <typename IntType = signed long> class grid_point : public scitbx::vec3<IntType> { public: typedef scitbx::vec3<IntType> base_type; //! Default constructor: elements are not initialized! grid_point() {} //! The elements of the coordinate vector are copied from v. template <typename OtherIntType> grid_point(af::tiny_plain<OtherIntType, 3> const& v) { for(std::size_t i=0;i<3;i++) this->elems[i] = v[i]; } //! The elements of the coordinate vector are copied from xyz. explicit grid_point(const IntType* xyz) { for(std::size_t i=0;i<3;i++) this->elems[i] = xyz[i]; } //! The elements of the coordinate vector are initialized with x,y,z. grid_point(IntType const& x, IntType const& y, IntType const& z) { this->elems[0] = x; this->elems[1] = y; this->elems[2] = z; } private: // disables construction from fractional template <typename OtherIntType> grid_point(fractional<OtherIntType> const&); // disables construction from cartesian template <typename OtherIntType> grid_point(cartesian<OtherIntType> const&); }; } // namespace cctbx #endif // CCTBX_COORDINATES_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/crystal_orientation.h
.h
6,031
185
#ifndef CCTBX_CRYSTL_ORIENT_H #define CCTBX_CRYSTL_ORIENT_H #include <cctbx/uctbx.h> #include <cctbx/sgtbx/change_of_basis_op.h> namespace cctbx { //! Shorthand for default vec3 type in orientation toolbox. typedef scitbx::vec3<double> oc_vec3; //! Shorthand for default mat3 type in orientation toolbox. typedef scitbx::mat3<double> oc_mat3; //! Shorthand for default vector list in orientation toolbox. typedef scitbx::af::shared<oc_vec3> oc_vec3_list; enum basis_type { direct=0, reciprocal=1 }; //! Rotation of a vector /*! Right-hand rotation of a vector (first arg) about a laboratory unit vector (second arg) through an angle expressed in radians (third arg). */ template <typename FloatType> oc_vec3 vector_rotate_thru(oc_vec3 const& vec, oc_vec3 const& unit, FloatType const& angle){ // //Still need to add assertion that unit is indeed a unit vector // return unit*(unit*vec) +(vec-(unit*(unit*vec)))*std::cos(angle) -(vec.cross(unit))*std::sin(angle); } //! Class for the handling of crystal orientation matrix /*! All dimensions are in Angstroms (direct space) and inverse Angstroms (reciprocal space). <p> The reciprocal space matrix is a generalization of the fractionalization matrix: <pre> / A*x B*x C*x \ Matrix A* = | A*y B*y C*y | \ A*z B*z C*z / </pre> The direct space matrix is a generalization of the orthogonalization matrix: <pre> / Ax Ay Az \ Matrix A = | Bx By Bz | \ Cx Cy Cz / </pre> */ class crystal_orientation { public: //! Default constructor. Some data members are not initialized! /*! Not available in Python. */ crystal_orientation(){} //! Constructor using a direct or reciprocal space matrix. /*! basis type flag: false=direct space; true=reciprocal space */ explicit crystal_orientation(oc_mat3 const&, bool const&); //! Access to direct space unit cell. cctbx::uctbx::unit_cell unit_cell() const; //! Access to reciprocal space unit cell. cctbx::uctbx::unit_cell unit_cell_inverse() const; //! Access to direct space orientation matrix. oc_mat3 direct_matrix() const; //! Access to reciprocal space orientation matrix. oc_mat3 reciprocal_matrix() const; //! Change of basis. Return value gives mutated orientation. /*! Input is the change of basis operator for transforming direct space vectors from the current setting to a reference setting. */ crystal_orientation change_basis(cctbx::sgtbx::change_of_basis_op const&) const; //! Change of basis. Return value gives mutated orientation. /*! Input is a rotation matrix, assumed to be the matrix for transforming direct space vectors from the current setting to a reference setting. */ crystal_orientation change_basis(oc_mat3 const&) const; //! Rotation mutator /*! Right-hand rotation of the crystal about a laboratory vector through an angle expressed in radians. */ template <typename FloatType> crystal_orientation rotate_thru( oc_vec3 const& unit_axis, FloatType const& angle) const { // //still need to add an assertion that unit is a unit vector // oc_vec3_list abc; //astar,bstar,cstar for (int i=0; i<3; ++i){ abc.push_back( Astar_.get_column(i) ); } oc_vec3_list newabc; for (int i=0; i<3; ++i){ newabc.push_back( vector_rotate_thru(abc[i],unit_axis,angle) ); } oc_mat3 new_recip_matrix; for (int i=0; i<3; ++i){ new_recip_matrix.set_column( i, newabc[i] ); } return crystal_orientation(new_recip_matrix, cctbx::reciprocal); } //! Simple measure for the similarity of two orientatons. /*! The result is the mean of the squared differences between basis vectors. The basis vectors are taken in direct space. DEPRECATED 7/19/2009. */ inline double direct_mean_square_difference(crystal_orientation const& other) const { return cctbx::uctbx::mean_square_difference( direct_matrix(),other.direct_matrix())/3; } //! Simple measure for the similarity of two orientatons. /*! The result is a sum of mock Z-scores for the three basis vectors of the other orientation. It assumes that the direct space vectors of this crystal orientation are distributed normally with a standard deviation of 1% of the basis vector length. Introduced 8/13/2009. */ inline double difference_Z_score(crystal_orientation const& other) const { oc_mat3 diff = (direct_matrix() - other.direct_matrix()); double Z = 0.0; for (int idx = 0; idx<3; ++idx){ oc_vec3 this_basis_vector(direct_matrix().get_row(idx)); oc_vec3 diff_vector(diff.get_row(idx)); Z += diff_vector.length()/(0.01*this_basis_vector.length()); } return Z; } //! Best change of basis for superimposing onto another orientation. /*! Used for aligning two orientations determined independently from the same crystal sample. The rotation part of an inverse cb_op is returned. */ oc_mat3 best_similarity_transformation(crystal_orientation const& other, double const& fractional_length_tolerance, int unimodular_generator_range=1) const; protected: //! Internal representation of the reciprocal matrix oc_mat3 Astar_; }; //class crystal_orientation } //namespace cctbx #endif // CCTBX_CRYSTL_ORIENT_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/import_scitbx_af.h
.h
190
12
#ifndef CCTBX_IMPORT_SCITBX_AF_H #define CCTBX_IMPORT_SCITBX_AF_H namespace scitbx { namespace af { }} namespace cctbx { namespace af = scitbx::af; } #endif // CCTBX_IMPORT_SCITBX_AF_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/uctbx.h
.h
41,386
1,241
#ifndef CCTBX_UCTBX_H #define CCTBX_UCTBX_H #include <cmath> #include <boost/numeric/conversion/cast.hpp> #include <boost/optional.hpp> #include <scitbx/constants.h> #include <scitbx/sym_mat3.h> #include <scitbx/array_family/tiny_types.h> #include <scitbx/array_family/small.h> #include <scitbx/array_family/shared.h> #include <scitbx/array_family/tiny_mat_ref.h> #include <scitbx/array_family/accessors/c_grid.h> #include <scitbx/math/utils.h> #include <scitbx/vec3.h> #include <cctbx/coordinates.h> #include <cctbx/miller.h> namespace cctbx { // forward declaration namespace sgtbx { class rot_mx; class change_of_basis_op; } //! Shorthand for default vec3 type in unit cell toolbox. typedef scitbx::vec3<double> uc_vec3; //! Shorthand for default mat3 type in unit cell toolbox. typedef scitbx::mat3<double> uc_mat3; //! Shorthand for default sym_mat3 type in unit cell toolbox. typedef scitbx::sym_mat3<double> uc_sym_mat3; //! Unit Cell Toolbox namespace. namespace uctbx { //! Conversion of d-spacing measures. inline double d_star_sq_as_stol_sq(double d_star_sq) { return d_star_sq * .25; } //! Conversion of d-spacing measures. inline af::shared<double> d_star_sq_as_stol_sq(af::const_ref<double> const &d_star_sq) { af::shared<double> result( d_star_sq.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<d_star_sq.size();i++) { result[i] = d_star_sq_as_stol_sq(d_star_sq[i]); } return result; } //! Conversion of d-spacing measures. inline double d_star_sq_as_two_stol(double d_star_sq) { return std::sqrt(d_star_sq); } //! Conversion of d-spacing measures. inline af::shared<double> d_star_sq_as_two_stol(af::const_ref<double> const &d_star_sq) { af::shared<double> result( d_star_sq.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<d_star_sq.size();i++) { result[i] = d_star_sq_as_two_stol(d_star_sq[i]); } return result; } //! Conversion of d-spacing measures. inline double d_star_sq_as_stol(double d_star_sq) { return std::sqrt(d_star_sq) * .5; } //! Conversion of d-spacing measures. inline af::shared<double> d_star_sq_as_stol(af::const_ref<double> const &d_star_sq) { af::shared<double> result( d_star_sq.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<d_star_sq.size();i++) { result[i] = d_star_sq_as_stol(d_star_sq[i]); } return result; } //! Conversion of d-spacing measures. inline double d_star_sq_as_d(double d_star_sq) { if (d_star_sq == 0.) return -1.; return 1. / std::sqrt(d_star_sq); } //! Conversion of d-spacing measures. inline af::shared<double> d_star_sq_as_d(af::const_ref<double> const &d_star_sq) { af::shared<double> result( d_star_sq.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<d_star_sq.size();i++) { result[i] = d_star_sq_as_d(d_star_sq[i]); } return result; } //! Conversion of d-spacing measures. inline double d_star_sq_as_two_theta( double d_star_sq, double wavelength, bool deg=false) { double sin_theta = d_star_sq_as_stol(d_star_sq) * wavelength; CCTBX_ASSERT(sin_theta <= 1.0); double result = 2. * std::asin(sin_theta); if (deg) return scitbx::rad_as_deg(result); return result; } //! Conversion of d-spacing measures. inline af::shared<double> d_star_sq_as_two_theta( af::const_ref<double> const &d_star_sq, double wavelength, bool deg=false) { af::shared<double> result( d_star_sq.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<d_star_sq.size();i++) { result[i] = d_star_sq_as_two_theta(d_star_sq[i], wavelength, deg); } return result; } //! Conversion of d-spacing measures. inline double stol_sq_as_d_star_sq(double stol_sq) { return stol_sq * 4; } //! Conversion of d-spacing measures. inline af::shared<double> stol_sq_as_d_star_sq(af::const_ref<double> const &stol_sq) { af::shared<double> result( stol_sq.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<stol_sq.size();i++) { result[i] = stol_sq_as_d_star_sq(stol_sq[i]); } return result; } //! Conversion of d-spacing measures. inline double two_stol_as_d_star_sq(double two_stol) { return std::pow(two_stol, 2); } //! Conversion of d-spacing measures. inline af::shared<double> two_stol_as_d_star_sq(af::const_ref<double> const &two_stol) { af::shared<double> result( two_stol.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<two_stol.size();i++) { result[i] = two_stol_as_d_star_sq(two_stol[i]); } return result; } //! Conversion of d-spacing measures. inline double stol_as_d_star_sq(double stol) { return std::pow(stol * 2, 2); } //! Conversion of d-spacing measures. inline af::shared<double> stol_as_d_star_sq(af::const_ref<double> const &stol) { af::shared<double> result( stol.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<stol.size();i++) { result[i] = stol_as_d_star_sq(stol[i]); } return result; } //! Conversion of d-spacing measures. inline double d_as_d_star_sq(double d) { if (d == 0.) return -1.; return 1. / std::pow(d, 2); } //! Conversion of d-spacing measures. inline af::shared<double> d_as_d_star_sq(af::const_ref<double> const &d) { af::shared<double> result( d.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<d.size();i++) { result[i] = d_as_d_star_sq(d[i]); } return result; } //! Conversion of d-spacing measures. inline double two_theta_as_d_star_sq( double two_theta, double wavelength, bool deg=false) { double theta = .5 * two_theta; if (deg) theta = scitbx::deg_as_rad(theta); double sin_theta = std::sin(theta); return stol_as_d_star_sq(sin_theta/wavelength); } //! Conversion of d-spacing measures. inline af::shared<double> two_theta_as_d_star_sq( af::const_ref<double> const &two_theta, double wavelength, bool deg=false) { af::shared<double> result( two_theta.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<two_theta.size();i++) { result[i] = two_theta_as_d_star_sq(two_theta[i], wavelength, deg); } return result; } //! Conversion of d-spacing measures. inline double two_theta_as_d( double two_theta, double wavelength, bool deg=false) { return d_star_sq_as_d( two_theta_as_d_star_sq(two_theta, wavelength, deg)); } //! Conversion of d-spacing measures. inline af::shared<double> two_theta_as_d( af::const_ref<double> const &two_theta, double wavelength, bool deg=false) { af::shared<double> result( two_theta.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<two_theta.size();i++) { result[i] = two_theta_as_d(two_theta[i], wavelength, deg); } return result; } template <typename FloatType> FloatType mean_square_difference( scitbx::mat3<FloatType> const& a, scitbx::mat3<FloatType> const& b) { FloatType result = 0; for(std::size_t i=0;i<9;i++) { result += scitbx::fn::pow2(a[i] - b[i]); } return result; } //! Foadi, J., Evans, G. (2011). Acta Cryst. A67, 93-95. bool unit_cell_angles_are_feasible( scitbx::vec3<double> const& values_deg, double tolerance=1e-6); //! Class for the handling of unit cell information. /*! All angles are in degrees. <p> The PDB convention for orthogonalization and fractionalization of coordinates is used: <pre> Crystallographic Basis: D = {a,b,c} Cartesian Basis: C = {i,j,k} i || a j is in (a,b) plane k = i x j </pre> */ class unit_cell { public: //! Default constructor. Some data members are not initialized! /*! volume() of default constructed instances == 0. This may be used to test if a unit_cell instance is valid. <p> Not available in Python. */ unit_cell() : volume_(0) {} //! Constructor using parameters (a, b, c, alpha, beta, gamma). /*! Missing lengths are set to 1, missing angles to 90. <p> See also: paramters() */ explicit unit_cell(af::small<double, 6> const& parameters); //! Constructor using parameters (a, b, c, alpha, beta, gamma). /*! See also: paramters() */ explicit unit_cell(af::double6 const& parameters); //! Constructor using parameters derived from a metrical matrix. /*! The metrical matrix is defined as: <pre> ( a*a, a*b*cos(gamma), a*c*cos(beta) ) ( a*b*cos(gamma), b*b, b*c*cos(alpha) ) ( a*c*cos(beta), b*c*cos(alpha), c*c ) </pre> See also: metrical_matrix() */ explicit unit_cell(uc_sym_mat3 const& metrical_matrix); //! Constructor using an orthogonalization matrix. /*! See also: orthogonalization_matrix() */ explicit unit_cell(uc_mat3 const& orthogonalization_matrix); //! Access to parameters. af::double6 const& parameters() const { return params_; } //! Access to reciprocal cell parameters. af::double6 const& reciprocal_parameters() const { return r_params_; } //! Access to metrical matrix. uc_sym_mat3 const& metrical_matrix() const { return metr_mx_; } //! Access to reciprocal cell metrical matrix. uc_sym_mat3 const& reciprocal_metrical_matrix() const { return r_metr_mx_; } //! Volume of the unit cell. double volume() const { return volume_; } af::double6 const& d_volume_d_params() const { return d_volume_d_params_; } //! Corresponding reciprocal cell. unit_cell reciprocal() const; //! Length^2 of the longest lattice vector in the unit cell. double longest_vector_sq() const; //! Length^2 of the shortest lattice translation vector. /*! The fast_minimum_reduction is used to determine the shortest vector. */ double shortest_vector_sq() const; //! Simple test for degenerated unit cell parameters. bool is_degenerate(double min_min_length_over_max_length=1.e-10, double min_volume_over_min_length=1.e-5); //! Comparison of unit cell parameters. bool is_similar_to(unit_cell const& other, double relative_length_tolerance=0.01, double absolute_angle_tolerance=1., double absolute_length_tolerance=-9999.) const; //! Array of c_inv_r matrices compatible with change_basis. af::shared<scitbx::mat3<int> > similarity_transformations( unit_cell const& other, double relative_length_tolerance=0.02, double absolute_angle_tolerance=2., int unimodular_generator_range=1) const; //! Matrix for the conversion of cartesian to fractional coordinates. /*! x(fractional) = matrix * x(cartesian). */ uc_mat3 const& fractionalization_matrix() const { return frac_; } //! Matrix for the conversion of fractional to cartesian coordinates. /*! x(cartesian) = matrix * x(fractional). */ uc_mat3 const& orthogonalization_matrix() const { return orth_; } //! Matrix for the conversion of grid indices to cartesian coordinates. /*! x(cartesian) = matrix * grid_index. */ template <class IntType> uc_mat3 grid_index_as_site_cart_matrix( scitbx::vec3<IntType> const& gridding) const { uc_mat3 result = orth_; for(unsigned i=0;i<3;i++) { CCTBX_ASSERT(gridding[i] > 0); double f = 1. / boost::numeric_cast<double>(gridding[i]); for(unsigned j=0;j<9;j+=3) result[i+j] *= f; } return result; } //! Conversion of cartesian coordinates to fractional coordinates. template <class FloatType> scitbx::vec3<FloatType> fractionalize(scitbx::vec3<FloatType> const& site_cart) const { // take advantage of the fact that frac_ is upper-triangular. return fractional<FloatType>( frac_[0] * site_cart[0] + frac_[1] * site_cart[1] + frac_[2] * site_cart[2], frac_[4] * site_cart[1] + frac_[5] * site_cart[2], frac_[8] * site_cart[2]); } //! Conversion of fractional coordinates to cartesian coordinates. template <class FloatType> scitbx::vec3<FloatType> orthogonalize(scitbx::vec3<FloatType> const& site_frac) const { // take advantage of the fact that orth_ is upper-triangular. return cartesian<FloatType>( orth_[0] * site_frac[0] + orth_[1] * site_frac[1] + orth_[2] * site_frac[2], orth_[4] * site_frac[1] + orth_[5] * site_frac[2], orth_[8] * site_frac[2]); } //! Conversion of cartesian coordinates to fractional coordinates. template <typename FloatType> af::shared<scitbx::vec3<FloatType> > fractionalize( af::const_ref<scitbx::vec3<FloatType> > const& sites_cart) const { af::shared<scitbx::vec3<FloatType> > result( sites_cart.size(), af::init_functor_null<scitbx::vec3<FloatType> >()); const scitbx::vec3<FloatType>* si = sites_cart.begin(); scitbx::vec3<FloatType>* ri = result.begin(); for(std::size_t i=0;i<sites_cart.size();i++,ri++,si++) { // take advantage of the fact that frac_ is upper-triangular. (*ri)[0] = frac_[0] * (*si)[0] + frac_[1] * (*si)[1] + frac_[2] * (*si)[2]; (*ri)[1] = frac_[4] * (*si)[1] + frac_[5] * (*si)[2]; (*ri)[2] = frac_[8] * (*si)[2]; } return result; } //! Conversion of fractional coordinates to cartesian coordinates. template <typename FloatType> af::shared<scitbx::vec3<FloatType> > orthogonalize( af::const_ref<scitbx::vec3<FloatType> > const& sites_frac) const { af::shared<scitbx::vec3<FloatType> > result( sites_frac.size(), af::init_functor_null<scitbx::vec3<FloatType> >()); const scitbx::vec3<FloatType>* si = sites_frac.begin(); scitbx::vec3<FloatType>* ri = result.begin(); for(std::size_t i=0;i<sites_frac.size();i++,ri++,si++) { // take advantage of the fact that orth_ is upper-triangular. (*ri)[0] = orth_[0] * (*si)[0] + orth_[1] * (*si)[1] + orth_[2] * (*si)[2]; (*ri)[1] = orth_[4] * (*si)[1] + orth_[5] * (*si)[2]; (*ri)[2] = orth_[8] * (*si)[2]; } return result; } //! Optimized fractionalization_matrix().transpose() * v /*! Not available in Python. */ template <class FloatType> scitbx::vec3<FloatType> v_times_fractionalization_matrix_transpose( scitbx::vec3<FloatType> const& v) const { // take advantage of the fact that frac_ is upper-triangular. return fractional<FloatType>( frac_[0] * v[0], frac_[1] * v[0] + frac_[4] * v[1], frac_[2] * v[0] + frac_[5] * v[1] + frac_[8] * v[2]); } // ! gradient wrt Cartesian coordinates from gradient wrt fractional ones /*! The formula is \f$\nabla_{x_c} = F^T \nabla_{x_f}\f$ where \f$F\f$ is the fractionalisation matrix This is syntactic sugar for the long winded and cryptic v_times_fractionalization_matrix_transpose. */ template <class FloatType> scitbx::vec3<FloatType> orthogonalize_gradient (scitbx::vec3<FloatType> const& v) const { return v_times_fractionalization_matrix_transpose(v); } // ! gradient wrt fractional coordinates from gradient wrt Cartesian ones /*! The formula is \f$\nabla_{x_f} = O^T \nabla_{x_c}\f$ where \f$O\f$ is the orthogonalisation matrix */ template <class FloatType> scitbx::vec3<FloatType> fractionalize_gradient (const scitbx::vec3<FloatType>& g) const { const uc_mat3& O = orth_; return fractional<FloatType>(O[0]*g[0], O[1]*g[0] + O[4]*g[1], O[2]*g[0] + O[5]*g[1] + O[8]*g[2]); } /// The linear form transforming ADP u* into u_iso /** If U = { {u_0, u_3, u_4}, {u_3, u_1, u_5}, {u_4, u_5, u_2} } is the layout of u* as per scitbx::sym_mat3 and O ={ {o_0, o_1, o_2}, {0, o_4, o_5}, {0, 0, o_8} } is the layout of the orthogonalisation matrix as per scitbx::mat3, u_iso = 1/3 Tr( O U O^T ) = o_0^2 u_0 + (o_1^2 + o_4^2) u_1 + (o_2^2 + o_5^2 + o_8^2) u_2 + 2 o_0 o_1 u_3 + 2 o_0 o_2 u_4 + 2 (o_1 o_2 + o_4 o_5) u_5 */ af::double6 const &u_star_to_u_iso_linear_form() const { return u_star_to_u_iso_linear_form_; } /// The linear map transforming ADP u* into u_cart /** If U = { {u_0, u_3, u_4}, {u_3, u_1, u_5}, {u_4, u_5, u_2} } is the layout of u* as per scitbx::sym_mat3 and O ={ {o_0, o_1, o_2}, {0, o_4, o_5}, {0, 0, o_8} } is the layout of the orthogonalisation matrix as per scitbx::mat3, u_cart = ( O u* O^T ) can be alternatively be written as u_cart = L u*, where L ={ {o_0^2, o_1^2, o_2^2, 2 o_0 o_1, 2 o_0 o_2, 2 o_1 o_2}, {0, o_4^2, o_5^2, 0, 0, 2 o_4 o_5, {0, 0, o_8^2, 0, 0, 0}, {0, o_1 o_4, o_2 o_5, o_0 o_4, o_0 o_5, o_2 o_4+o_1 o_5}, {0, 0, o_2 o_8, 0, o_0 o_8, o_1 o_8}, {0, 0, o_5 o_8, 0, 0, o_4 o_8} } */ af::const_ref<double, af::mat_grid> u_star_to_u_cart_linear_map() const { return af::tiny_mat_const_ref<double, 6, 6>(u_star_to_u_cart_linear_map_); } /// The linear map transforming ADP u* into u_cif af::double6 const &u_star_to_u_cif_linear_map() const { return u_star_to_u_cif_linear_map_; } //! The gradient of the elements of the metrical matrix wrt the unit cell params af::const_ref<double, af::mat_grid> d_metrical_matrix_d_params() const { return af::tiny_mat_const_ref<double, 6, 6>(d_metrical_matrix_d_params_); } //! Length^2 of a vector of fractional coordinates. /*! Not available in Python. */ template <class FloatType> FloatType length_sq(fractional<FloatType> const& site_frac) const { return orthogonalize(site_frac).length_sq(); } //! Length of a vector of fractional coordinates. template <class FloatType> FloatType length(fractional<FloatType> const& site_frac) const { return std::sqrt(length_sq(site_frac)); } //! Distance^2 between two vectors of fractional coordinates. /*! Not available in Python. */ template <class FloatType> FloatType distance_sq(fractional<FloatType> const& site_frac_1, fractional<FloatType> const& site_frac_2) const { return length_sq(fractional<FloatType>(site_frac_1 - site_frac_2)); } //! Distance between two vectors of fractional coordinates. template <class FloatType> FloatType distance(fractional<FloatType> const& site_frac_1, fractional<FloatType> const& site_frac_2) const { return length(fractional<FloatType>(site_frac_1 - site_frac_2)); } //! Angle in degrees formed by sites 1, 2 and 3 for fractional coordinates. template <class FloatType> boost::optional<FloatType> angle(fractional<FloatType> const& site_frac_1, fractional<FloatType> const& site_frac_2, fractional<FloatType> const& site_frac_3) const { cartesian<FloatType> vec_12 = orthogonalize(site_frac_1 - site_frac_2); cartesian<FloatType> vec_32 = orthogonalize(site_frac_3 - site_frac_2); FloatType length_12 = vec_12.length(); FloatType length_32 = vec_32.length(); if (length_12 == 0 || length_32 == 0) { return boost::optional<FloatType>(); } const FloatType cos_angle = std::max(-1.,std::min(1., (vec_12 * vec_32)/(length_12 * length_32))); return boost::optional<FloatType>( std::acos(cos_angle) / scitbx::constants::pi_180); } //! Dihedral angle in degrees formed by sites 1, 2, 3 and 4 for fractional coordinates. /*! angle = acos[(u x v).(v x w)/(|u x v||v x w|)] The sign of the angle is the sign of (u x v).w */ template <class FloatType> boost::optional<FloatType> dihedral(fractional<FloatType> const& site_frac_1, fractional<FloatType> const& site_frac_2, fractional<FloatType> const& site_frac_3, fractional<FloatType> const& site_frac_4) const { cartesian<FloatType> u = orthogonalize(site_frac_1 - site_frac_2); cartesian<FloatType> v = orthogonalize(site_frac_3 - site_frac_2); cartesian<FloatType> w = orthogonalize(site_frac_3 - site_frac_4); cartesian<FloatType> u_cross_v = u.cross(v); cartesian<FloatType> v_cross_w = v.cross(w); FloatType norm_u_cross_v = u_cross_v.length_sq(); if (norm_u_cross_v == 0) return boost::optional<FloatType>(); FloatType norm_v_cross_w = v_cross_w.length_sq(); if (norm_v_cross_w == 0) return boost::optional<FloatType>(); FloatType cos_angle = std::max(-1.,std::min(1., u_cross_v * v_cross_w / std::sqrt(norm_u_cross_v * norm_v_cross_w))); FloatType angle = std::acos(cos_angle) / scitbx::constants::pi_180; if (u_cross_v * w < 0) { angle *= -1; } return boost::optional<FloatType>(angle); } /*! \brief Shortest length^2 of a vector of fractional coordinates under application of periodicity. */ /*! Not available in Python. */ template <class FloatType> FloatType mod_short_length_sq(fractional<FloatType> const& site_frac) const { return length_sq(site_frac.mod_short()); } /*! \brief Shortest length of a vector of fractional coordinates under application of periodicity. */ template <class FloatType> FloatType mod_short_length(fractional<FloatType> const& site_frac) const { return std::sqrt(mod_short_length_sq(site_frac)); } /*! \brief Shortest distance^2 between two vectors of fractional coordinates under application of periodicity. */ /*! Not available in Python. */ template <class FloatType> FloatType mod_short_distance_sq(fractional<FloatType> const& site_frac_1, fractional<FloatType> const& site_frac_2) const { return mod_short_length_sq( fractional<FloatType>(site_frac_1 - site_frac_2)); } /*! \brief Shortest distance between two vectors of fractional coordinates under application of periodicity. */ template <class FloatType> FloatType mod_short_distance(fractional<FloatType> const& site_frac_1, fractional<FloatType> const& site_frac_2) const { return std::sqrt(mod_short_distance_sq(site_frac_1, site_frac_2)); } /*! \brief Shortest distance^2 between all sites in site_frac_1 and site_frac_2 under application of periodicity. */ /*! Not available in Python. */ template <class FloatType> FloatType min_mod_short_distance_sq( af::const_ref<scitbx::vec3<FloatType> > const& sites_frac_1, fractional<FloatType> const& site_frac_2) const { FloatType result = mod_short_distance_sq( fractional<FloatType>(sites_frac_1[0]), site_frac_2); for(std::size_t i=1;i<sites_frac_1.size();i++) { scitbx::math::update_min( result, mod_short_distance_sq( fractional<FloatType>(sites_frac_1[i]), site_frac_2)); } return result; } /*! \brief Shortest distance between all sites in sites_frac_1 and site_frac_2 under application of periodicity. */ template <class FloatType> FloatType min_mod_short_distance( af::const_ref<scitbx::vec3<FloatType> > const& sites_frac_1, fractional<FloatType> const& site_frac_2) const { return std::sqrt(min_mod_short_distance_sq(sites_frac_1, site_frac_2)); } //! Conversion of fractional-space rotation matrix to Cartesian space. /*! orthogonalization_matrix() * rot_mx * fractionalization_matrix() */ uc_mat3 matrix_cart( sgtbx::rot_mx const& rot_mx) const; //! Transformation (change-of-basis) of unit cell parameters. /*! c_inv_r is the inverse of the 3x3 change-of-basis matrix that transforms coordinates in the old basis system to coodinates in the new basis system. */ unit_cell change_basis(uc_mat3 const& c_inv_r, double r_den=1.) const; //! Transformation (change-of-basis) of unit cell parameters. /*! r is the inverse of the 3x3 change-of-basis matrix that transforms coordinates in the old basis system to coodinates in the new basis system. <p> Not available in Python. */ unit_cell change_basis(sgtbx::rot_mx const& c_inv_r) const; //! Transformation (change-of-basis) of unit cell parameters. unit_cell change_basis(sgtbx::change_of_basis_op const& cb_op) const; /*! \brief Computation of the maximum Miller indices for a given minimum d-spacing. */ /*! d_min is the minimum d-spacing. tolerance compensates for rounding errors. */ miller::index<> max_miller_indices(double d_min, double tolerance=1.e-4) const; //! d-spacing measure d_star_sq = 1/d^2 = (2*sin(theta)/lambda)^2. template <typename NumType> double d_star_sq(miller::index<NumType> const& miller_index) const { return (miller_index[0] * miller_index[0]) * r_metr_mx_[0] + (miller_index[1] * miller_index[1]) * r_metr_mx_[1] + (miller_index[2] * miller_index[2]) * r_metr_mx_[2] + (2 * miller_index[0] * miller_index[1]) * r_metr_mx_[3] + (2 * miller_index[0] * miller_index[2]) * r_metr_mx_[4] + (2 * miller_index[1] * miller_index[2]) * r_metr_mx_[5]; } //! d-spacing measure d_star_sq = 1/d^2 = (2*sin(theta)/lambda)^2. template <typename NumType> af::shared<double> d_star_sq( af::const_ref<miller::index<NumType> > const& miller_indices) const { af::shared<double> result( miller_indices.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<miller_indices.size();i++) { result[i] = d_star_sq(miller_indices[i]); } return result; } //! Maximum d_star_sq for given list of Miller indices. template <typename NumType> double max_d_star_sq( af::const_ref<miller::index<NumType> > const& miller_indices) const { double result = 0; for(std::size_t i=0;i<miller_indices.size();i++) { scitbx::math::update_max(result, d_star_sq(miller_indices[i])); } return result; } //! Minimum and maximum d_star_sq for given list of Miller indices. template <typename NumType> af::double2 min_max_d_star_sq( af::const_ref<miller::index<NumType> > const& miller_indices) const { af::double2 result(0, 0); if (miller_indices.size()) { result.fill(d_star_sq(miller_indices[0])); for(std::size_t i=1;i<miller_indices.size();i++) { double q = d_star_sq(miller_indices[i]); scitbx::math::update_min(result[0], q); scitbx::math::update_max(result[1], q); } } return result; } //! d-spacing measure (sin(theta)/lambda)^2 = d_star_sq/4. template <typename NumType> double stol_sq(miller::index<NumType> const& miller_index) const { return d_star_sq_as_stol_sq(d_star_sq(miller_index)); } //! d-spacing measure (sin(theta)/lambda)^2 = d_star_sq/4. template <typename NumType> af::shared<double> stol_sq( af::const_ref<miller::index<NumType> > const& miller_indices) const { af::shared<double> result( miller_indices.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<miller_indices.size();i++) { result[i] = stol_sq(miller_indices[i]); } return result; } //! d-spacing measure 2*sin(theta)/lambda = 1/d = sqrt(d_star_sq). template <typename NumType> double two_stol(miller::index<NumType> const& miller_index) const { return d_star_sq_as_two_stol(d_star_sq(miller_index)); } //! d-spacing measure 2*sin(theta)/lambda = 1/d = sqrt(d_star_sq). template <typename NumType> af::shared<double> two_stol( af::const_ref<miller::index<NumType> > const& miller_indices) const { af::shared<double> result( miller_indices.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<miller_indices.size();i++) { result[i] = two_stol(miller_indices[i]); } return result; } //! d-spacing measure sin(theta)/lambda = 1/(2*d) = sqrt(d_star_sq)/2. template <typename NumType> double stol(miller::index<NumType> const& miller_index) const { return d_star_sq_as_stol(d_star_sq(miller_index)); } //! d-spacing measure sin(theta)/lambda = 1/(2*d) = sqrt(d_star_sq)/2. template <typename NumType> af::shared<double> stol(af::const_ref<miller::index<NumType> > const& miller_indices) const { af::shared<double> result( miller_indices.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<miller_indices.size();i++) { result[i] = stol(miller_indices[i]); } return result; } //! d-spacing measure d = 1/(2*sin(theta)/lambda). template <typename NumType> double d(miller::index<NumType> const& miller_index) const { return d_star_sq_as_d(d_star_sq(miller_index)); } //! d-spacing measure d = 1/(2*sin(theta)/lambda). template <typename NumType> double d_frac(scitbx::vec3<NumType> const& miller_index) const { return d_star_sq_as_d(d_star_sq(miller::index<NumType>(miller_index))); } //! d-spacing measure d = 1/(2*sin(theta)/lambda). template <typename NumType> af::shared<double> d(af::const_ref<miller::index<NumType> > const& miller_indices) const { af::shared<double> result( miller_indices.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<miller_indices.size();i++) { result[i] = d(miller_indices[i]); } return result; } //! Diffraction angle 2-theta, given wavelength. template <typename NumType> double two_theta( miller::index<NumType> const& miller_index, double wavelength, bool deg=false) const { return d_star_sq_as_two_theta( d_star_sq(miller_index), wavelength, deg); } //! Diffraction angle 2-theta, given wavelength. template <typename NumType> af::shared<double> two_theta( af::const_ref<miller::index<NumType> > const& miller_indices, double wavelength, bool deg=false) const { af::shared<double> result( miller_indices.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<miller_indices.size();i++) { result[i] = two_theta(miller_indices[i], wavelength, deg); } return result; } //! Squared sine of the diffraction angle 2-theta, given wavelength. /*! The result is always positive, using trigonometric identities: sin(2a) = 2*sin(a)*cos(a) and cos^2(a) = 1-sin^2(a) */ template <typename NumType> double sin_sq_two_theta( miller::index<NumType> const& miller_index, double wavelength) const { const double x = d_star_sq_as_stol_sq(d_star_sq(miller_index)) * std::pow(wavelength, 2.0); return std::max(0.0, 4*x*(1-x)); } //! Squared sine of the diffraction angle 2-theta, given wavelength. template <typename NumType> af::shared<double> sin_sq_two_theta( af::const_ref<miller::index<NumType> > const& miller_indices, double wavelength) const { af::shared<double> result( miller_indices.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<miller_indices.size();i++) { result[i] = sin_sq_two_theta(miller_indices[i], wavelength); } return result; } //! Sine of the diffraction angle 2-theta, given wavelength. template <typename NumType> double sin_two_theta( miller::index<NumType> const& miller_index, double wavelength) const { const double x = d_star_sq_as_stol_sq(d_star_sq(miller_index)) * std::pow(wavelength, 2.0); return 2*std::sqrt(std::max(0.0, x*(1-x))); } //! Sine of the diffraction angle 2-theta, given wavelength. template <typename NumType> af::shared<double> sin_two_theta( af::const_ref<miller::index<NumType> > const& miller_indices, double wavelength) const { af::shared<double> result( miller_indices.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<miller_indices.size();i++) { result[i] = sin_two_theta(miller_indices[i], wavelength); } return result; } template <typename NumType> scitbx::vec3<double> reciprocal_space_vector( miller::index<NumType> const& miller_index) const { uc_mat3 const& frac_mat = fractionalization_matrix(); scitbx::vec3<double> rcv = miller_index * frac_mat; return rcv; } template <typename NumType> af::shared<scitbx::vec3<double> > reciprocal_space_vector( af::const_ref<miller::index<NumType> > const& miller_indices) const { af::shared<scitbx::vec3<double> > result( miller_indices.size(), af::init_functor_null<scitbx::vec3<double> >()); for (std::size_t i = 0; i < miller_indices.size(); i++) { result[i] = reciprocal_space_vector(miller_indices[i]); } return result; } //! Simple measure for the similarity of two unit cells. /*! The result is the mean of the squared differences between basis vectors. The basis vectors are defined by the columns of this->orthogonalization_matrix() and other.orthogonalization_matrix(). */ double bases_mean_square_difference(unit_cell const& other) const { return mean_square_difference(orth_, other.orth_) / 3; } /*! \brief Sort order for alternative settings of otherwise identical orthorhombic cells. */ /*! The cell with the smaller a-parameter is preferred. If the a-parameters are equal, the cell with the smaller b-parameter is preferred. If the a-parameters and b-parameters are equal, the cell with the smaller c-parameter is preferred. The return value is -1 if this is the preferred cell, 1 if other is the preferred cell, and 0 otherwise. The result is meaningless if the two unit cells are not alternative settings; i.e. the two cells must be related to each other by a transformation matrix with determinant 1. */ int compare_orthorhombic( const unit_cell& other) const; /*! \brief Sort order for alternative settings of otherwise identical monoclinic cells. */ /*! unique_axis must be one of: 0 for a-unique, 1 for b-unique, 2 for c-unique. If the absolute value of the difference between the monoclinic angels is less than angular_tolerance compare_orthorhombic() is used to determine the return value (-1, 1, or 0). Otherwise the return value is determined by evaluating the monoclinic angels. For exact details refer to the source code of the implementation ($CCTBX_DIST/cctbx/uctbx/uctbx.cpp). The result is meaningless if the two unit cells are not alternative settings; i.e. the two cells must be related to each other by a transformation matrix with determinant 1. */ int compare_monoclinic( const unit_cell& other, unsigned unique_axis, double angular_tolerance) const; sgtbx::change_of_basis_op const& change_of_basis_op_for_best_monoclinic_beta() const; protected: void init_volume(); void init_reciprocal(); void init_metrical_matrices(); void init_orth_and_frac_matrices(); void init_tensor_rank_2_orth_and_frac_linear_maps(); void initialize(); af::double6 params_; af::double3 sin_ang_; af::double3 cos_ang_; double volume_; af::double6 d_volume_d_params_; uc_sym_mat3 metr_mx_; af::double6 r_params_; af::double3 r_sin_ang_; af::double3 r_cos_ang_; uc_sym_mat3 r_metr_mx_; uc_mat3 frac_; uc_mat3 orth_; af::double6 u_star_to_u_iso_linear_form_; af::double6 u_star_to_u_cif_linear_map_; double u_star_to_u_cart_linear_map_[6*6]; double d_metrical_matrix_d_params_[6*6]; mutable double longest_vector_sq_; mutable double shortest_vector_sq_; // used by reciprocal() unit_cell( af::double6 const& params, af::double3 const& sin_ang, af::double3 const& cos_ang, double volume, uc_sym_mat3 const& metr_mx, af::double6 const& r_params, af::double3 const& r_sin_ang, af::double3 const& r_cos_ang, uc_sym_mat3 const& r_metr_mx); }; /*! \brief Helper class for optimizing d_star_sq computations in loops over a grid of Miller indices. */ template <typename FloatType> class incremental_d_star_sq { public: //! Default contructor. Some data members are not initialized! incremental_d_star_sq() {} //! Initialization from unit_cell object. /*! This copies the elements of the metrical matrix. */ incremental_d_star_sq(unit_cell const& ucell) { initialize(ucell.reciprocal_metrical_matrix()); } //! Stores h0 and performs computations that only involve h0. void update0(int h0) { h0_ = h0; im0_ = (h0_ * h0_) * r_g00_; } //! Stores h1 and performs computations that only involve h0 and h1. void update1(int h1) { h1_ = h1; im1_ = im0_ + (h1_ * h1_) * r_g11_ + (2 * h0_ * h1_) * r_g01_; } //! Returns d_star_sq using (h0,h1,h2). FloatType get(int h2) { return im1_ + (h2 * h2) * r_g22_ + (2 * h0_ * h2) * r_g02_ + (2 * h1_ * h2) * r_g12_; } protected: FloatType r_g00_, r_g11_, r_g22_, r_g01_, r_g02_, r_g12_; int h0_, h1_; FloatType im0_, im1_; void initialize(uc_sym_mat3 const& r_g) { r_g00_ = r_g[0]; r_g11_ = r_g[1]; r_g22_ = r_g[2]; r_g01_ = r_g[3]; r_g02_ = r_g[4]; r_g12_ = r_g[5]; } }; struct distance_mod_1 { fractional<> diff_raw; fractional<> diff_mod; double dist_sq; distance_mod_1() {} distance_mod_1( uctbx::unit_cell const& unit_cell, fractional<> const& site_frac_1, fractional<> const& site_frac_2) : diff_raw(site_frac_1 - site_frac_2), diff_mod(diff_raw.mod_short()), dist_sq(unit_cell.length_sq(diff_mod)) {} scitbx::vec3<int> unit_shifts() const { return fractional<>(diff_mod - diff_raw).unit_shifts(); } }; }} // namespace cctbx::uctbx #endif // CCTBX_UCTBX_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/error.h
.h
2,301
78
/* ***************************************************** THIS IS AN AUTOMATICALLY GENERATED FILE. DO NOT EDIT. ***************************************************** Generated by: scitbx.generate_error_h */ /*! \file Declarations and macros for exception handling. */ #ifndef CCTBX_ERROR_H #define CCTBX_ERROR_H #include <scitbx/error_utils.h> #define CCTBX_CHECK_POINT \ std::cout << __FILE__ << "(" << __LINE__ << ")" << std::endl << std::flush #define CCTBX_CHECK_POINT_MSG(msg) \ std::cout << msg << " @ " __FILE__ << "(" << __LINE__ << ")" << std::endl << std::flush #define CCTBX_EXAMINE(A) \ std::cout << "variable " << #A << ": " << A << std::endl << std::flush //! Common cctbx namespace. namespace cctbx { //! All cctbx exceptions are derived from this class. class error : public ::scitbx::error_base<error> { public: //! General cctbx error message. explicit error(std::string const& msg) throw() : ::scitbx::error_base<error>("cctbx", msg) {} //! Error message with file name and line number. /*! Used by the macros below. */ error(const char* file, long line, std::string const& msg = "", bool internal = true) throw() : ::scitbx::error_base<error>("cctbx", file, line, msg, internal) {} }; //! Special class for "Index out of range." exceptions. /*! These exceptions are propagated to Python as IndexError. */ class error_index : public error { public: //! Default constructor. The message may be customized. explicit error_index(std::string const& msg = "Index out of range.") throw() : error(msg) {} }; } // namespace cctbx //! For throwing an error exception with file name, line number, and message. #define CCTBX_ERROR(msg) \ SCITBX_ERROR_UTILS_REPORT(cctbx::error, msg) //! For throwing an "Internal Error" exception. #define CCTBX_INTERNAL_ERROR() \ SCITBX_ERROR_UTILS_REPORT_INTERNAL(cctbx::error) //! For throwing a "Not implemented" exception. #define CCTBX_NOT_IMPLEMENTED() \ SCITBX_ERROR_UTILS_REPORT_NOT_IMPLEMENTED(cctbx::error) //! Custom cctbx assertion. #define CCTBX_ASSERT(assertion) \ SCITBX_ERROR_UTILS_ASSERT(cctbx::error, CCTBX_ASSERT, assertion) #endif // CCTBX_ERROR_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/sgtbx/utils.h
.h
458
24
#ifndef CCTBX_SGTBX_UTILS_H #define CCTBX_SGTBX_UTILS_H namespace cctbx { namespace sgtbx { namespace utils { int change_denominator( const int *old_num, int old_den, int *new_num, int new_den, int n); class cmp_i_vec { public: cmp_i_vec(std::size_t n) : n_(n) {} bool operator()(const int *a, const int *b) const; private: std::size_t n_; }; }}} // namespace cctbx::sgtbx #endif // CCTBX_SGTBX_UTILS_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/sgtbx/change_of_basis_op.cpp
.cpp
3,290
118
#include <cctbx/sgtbx/change_of_basis_op.h> namespace cctbx { namespace sgtbx { change_of_basis_op::change_of_basis_op( parse_string& symbol, const char* stop_chars, int r_den, int t_den) : c_(0, 0), c_inv_(0, 0) { rt_mx_from_string result( symbol, stop_chars, r_den, t_den, /* enable_xyz */ true, /* enable_hkl */ true, /* enable_abc */ true); if (result.have_hkl) { CCTBX_ASSERT(result.t().is_zero()); c_inv_ = rt_mx(result.r().transpose(), result.t()); c_ = c_inv_.inverse(); } else if (result.have_abc) { c_inv_ = rt_mx(result.r().transpose(), result.t()); c_ = c_inv_.inverse(); } else { c_ = rt_mx(result); c_inv_ = c_.inverse(); } } change_of_basis_op::change_of_basis_op( std::string const& symbol, const char* stop_chars, int r_den, int t_den) : c_(0, 0), c_inv_(0, 0) { parse_string parse_symbol(symbol); *this = change_of_basis_op(parse_symbol, stop_chars, r_den, t_den); } tr_vec change_of_basis_op::operator()( tr_vec const& t, int sign_identity) const { // (C|V)( I|T)(C^-1|W)=( C|CT+V)(C^-1|W)=( I|CT+V+CW)=( I|C(T+W)+V) // (C|V)(-I|T)(C^-1|W)=(-C|CT+V)(C^-1|W)=(-I|CT+V-CW)=(-I|C(T-W)+V) tr_vec tf = t.new_denominator(c_inv_.t().den()); tr_vec tw; if (sign_identity >= 0) tw = tf + c_inv_.t(); else tw = tf - c_inv_.t(); return ( c_.r() * tw + c_.t().scale(c_.r().den())).new_denominator(t.den()); } rot_mx change_of_basis_op::operator()(rot_mx const& r) const { CCTBX_ASSERT(r.den() == 1); return (c_.r() * r * c_inv_.r()).new_denominator(1); } rt_mx change_of_basis_op::operator()(rt_mx const& s) const { CCTBX_ASSERT(s.r().den() == 1); CCTBX_ASSERT(c_.t().den() % s.t().den() == 0); return (c_ * (s.scale(1, c_.t().den() / s.t().den()) * c_inv_)) .new_denominators(s); } rt_mx change_of_basis_op::apply(rt_mx const& s) const { return c_.multiply(s.multiply(c_inv_)); } miller::index<> change_of_basis_op::apply(miller::index<> const& miller_index) const { miller::index<> hr = miller_index * c_inv_.r().num(); if (utils::change_denominator( hr.begin(), c_inv_.r().den(), hr.begin(), 1, 3) != 0) { throw error("Change of basis yields non-integral Miller index."); } return hr; } af::shared<miller::index<> > change_of_basis_op::apply( af::const_ref<miller::index<> > const& miller_indices) const { af::shared<miller::index<> > result((af::reserve(miller_indices.size()))); for(std::size_t i=0;i<miller_indices.size();i++) { result.push_back(apply(miller_indices[i])); } return result; } af::shared<std::size_t> change_of_basis_op::apply_results_in_non_integral_indices( af::const_ref<miller::index<> > const& miller_indices) const { af::shared<std::size_t> result; for(std::size_t i=0;i<miller_indices.size();i++) { miller::index<> hr = miller_indices[i] * c_inv_.r().num(); if (utils::change_denominator( hr.begin(), c_inv_.r().den(), hr.begin(), 1, 3) != 0) { result.push_back(i); } } return result; } }} // namespace cctbx::sgtbx
C++
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/sgtbx/change_of_basis_op.h
.h
10,494
340
#ifndef CCTBX_SGTBX_CHANGE_OF_BASIS_OP_H #define CCTBX_SGTBX_CHANGE_OF_BASIS_OP_H #include <cctbx/sgtbx/rt_mx.h> #include <cctbx/sgtbx/utils.h> #include <cctbx/uctbx.h> namespace cctbx { namespace sgtbx { //! Change-of-basis (transformation) operator. /*! For ease of use, a change-of-basis matrix c() and its inverse c_inv() are grouped by this class. */ class change_of_basis_op { public: //! Initializes the change-of-basis operator with c and c_inv. /*! The input matrices are NOT checked for consistency. */ change_of_basis_op(rt_mx const& c, rt_mx const& c_inv) : c_(c), c_inv_(c_inv) {} //! Initializes the change-of-basis operator with c. /*! The inverse matrix c_inv() is computed by inverting c. An exception is thrown if c is not invertible. */ explicit change_of_basis_op(rt_mx const& c) : c_(c), c_inv_(c.inverse()) {} /*! \brief Initializes the change-of-basis operator with matrix given as xyz, hkl, or abc string. */ /*! An exception is thrown if the given matrix is not invertible. <p> See also: constructor of class rt_mx <p> Not available in Python. */ change_of_basis_op( parse_string& symbol, const char* stop_chars="", int r_den=cb_r_den, int t_den=cb_t_den); /*! \brief Initializes the change-of-basis operator with matrix given as xyz, hkl, or abc string. */ /*! An exception is thrown if the given matrix is not invertible. <p> See also: constructor of class rt_mx */ change_of_basis_op( std::string const& symbol, const char* stop_chars="", int r_den=cb_r_den, int t_den=cb_t_den); //! Initializes the change-of-basis operator with unit matrices. /*! The unit matrices are initialized with the rotation part denominator r_den and the translation part denominator t_den. */ explicit change_of_basis_op(int r_den=cb_r_den, int t_den=cb_t_den) : c_(r_den, t_den), c_inv_(r_den, t_den) {} //! Tests if the change-of-basis operator is valid. /*! A change_of_basis_op is valid only if the rotation part denominator and the translation part denominator of both c() and c_inv() are not zero. */ bool is_valid() const { return c_.is_valid() && c_inv_.is_valid(); } //! Returns a new change-of-basis operator with unit matrices. /*! The new matrices inherit the rotation and translation part denominators. */ change_of_basis_op identity_op() const { return change_of_basis_op(c_.unit_mx(), c_inv_.unit_mx()); } //! Tests if the change-of-basis operator is the identity. bool is_identity_op() const { return c_.is_unit_mx() && c_inv_.is_unit_mx(); } //! Returns a new copy with the denominators r_den and t_den. /*! An exception is thrown if the elements cannot be scaled to the new denominators.<br> r_den or t_den == 0 indicates that the corresponding old denominator is retained. */ change_of_basis_op new_denominators(int r_den, int t_den) const { return change_of_basis_op(c_.new_denominators(r_den, t_den), c_inv_.new_denominators(r_den, t_den)); } /*! Returns a new copy of the operator, but with the denominators of other. */ /*! An exception is thrown if the elements cannot be scaled to the new denominators. */ change_of_basis_op new_denominators(change_of_basis_op const& other) const { return change_of_basis_op(c_.new_denominators(other.c()), c_inv_.new_denominators(other.c_inv())); } //! Returns the change-of-basis matrix. rt_mx const& c() const { return c_; } //! Returns the inverse of the change-of-basis matrix. rt_mx const& c_inv() const { return c_inv_; } //! Returns c() for inv == false, and c_inv() for inv == true. rt_mx const& select(bool inv) const { if (inv) return c_inv_; return c_; } //! Returns a new copy with c() and c_inv() swapped. change_of_basis_op inverse() const { return change_of_basis_op(c_inv_, c_); } //! Applies modulus operation such that 0 <= x < t_den. /*! The operation is applied to the elements of the translation vectors of c() and c_inv(). The vectors are modified in place. */ void mod_positive_in_place() { c_.mod_positive_in_place(); c_inv_.mod_positive_in_place(); } //! Applies modulus operation such that -t_den/2+1 < x <= t_den/2. /*! The operation is applied to the elements of the translation vectors of c() and c_inv(). The vectors are modified in place. */ void mod_short_in_place() { c_.mod_short_in_place(); c_inv_.mod_short_in_place(); } //! Applies modulus operation such that -t_den/2+1 < x <= t_den/2. /*! The operation is applied to the elements of the translation vectors of c() and c_inv(). */ change_of_basis_op mod_short() const { return change_of_basis_op(c_.mod_short(), c_inv_.mod_short()); } //! c().r() * r * c_inv().r(), for r with rotation part denominator 1. /*! The rotation part denominator of the result is 1. <p> Not available in Python. */ rot_mx operator()(rot_mx const& r) const; //! c() * s * c_inv(), for s with rotation part denominator 1. /*! Similar to apply(s), but faster. The translation denominator of the result is equal to the translation denominator of s. <p> Not available in Python. */ rt_mx operator()(rt_mx const& s) const; //! c() * s * c_inv(), for s with any rotation part denominator. /*! Similar to opertor()(). s may have any rotation part denominator or translation part denominator. The denominators of the result are made as small as possible. <p> See also: rt_mx::multiply(), rt_mx::cancel() */ rt_mx apply(rt_mx const& s) const; //! Deprecated. Use cctbx::uctbx::unit_cell::change_basis(cb_op) instead. uctbx::unit_cell apply(uctbx::unit_cell const& unit_cell) const { return unit_cell.change_basis(c_inv().r()); } //! Transforms a Miller index. /*! result = miller_index * c_inv() */ miller::index<> apply(miller::index<> const& miller_index) const; //! Transforms an array of Miller indices. /*! result = miller_indices * c_inv() */ af::shared<miller::index<> > apply(af::const_ref<miller::index<> > const& miller_indices) const; //! Flags Miller indices for which apply() leads to non-integral indices. af::shared<std::size_t> apply_results_in_non_integral_indices( af::const_ref<miller::index<> > const& miller_indices) const; //! c() * (rt_mx(rot_mx(sign_identity), t)) * c_inv() /*! Not available in Python. */ tr_vec operator()(tr_vec const& t, int sign_identity) const; //! Transform fractional coordinates: c() * site_frac template <class FloatType> fractional<FloatType> operator()(fractional<FloatType> const& site_frac) const { return c_ * site_frac; } //! c() = other.c() * c(); c_inv() = c_inv() * other.c_inv(); void update(change_of_basis_op const& other) { c_ = (other.c() * c_).new_denominators(other.c()); c_inv_ = (c_inv_ * other.c_inv()).new_denominators(other.c_inv()); } //! c() = (I|shift) * c(); c_inv() = c_inv() * (I|-shift); /*! Not available in Python. */ void update(tr_vec const& shift) { // (I|S)*(R|T) = (R|T+S) c_ = rt_mx(c_.r(), c_.t() + shift); // (R|T)*(I|-S) = (R|T-R*S) c_inv_ = rt_mx( c_inv_.r(), c_inv_.t() - (c_inv_.r() * shift).new_denominator(c_inv_.t().den())); } //! Multiplication of change-of-basis operators. change_of_basis_op operator*(change_of_basis_op const& rhs) { return change_of_basis_op( (c() * rhs.c()).new_denominators(c()), (rhs.c_inv() * c_inv()).new_denominators(c_inv())); } //! Returns c() in xyz format. /*! See also: rt_mx::as_xyz() */ std::string as_xyz(bool decimal=false, bool t_first=false, const char* symbol_letters="xyz", const char* separator=",") const { return c_.as_xyz(decimal, t_first, symbol_letters, separator); } //! Returns transpose of c_inv() in hkl format. /*! c_inv.t() must be zero. An exception is thrown otherwise. <p> See also: rt_mx::as_xyz(), rot_mx::as_hkl() */ std::string as_hkl( bool decimal=false, const char* letters_hkl="hkl", const char* separator=",") const { CCTBX_ASSERT(c_inv_.t().is_zero()); return c_inv_.r().as_hkl(decimal, letters_hkl, separator); } //! Returns transpose of c_inv() in abc format. /*! See also: rt_mx::as_xyz() */ std::string as_abc(bool decimal=false, bool t_first=false, const char* letters_abc="abc", const char* separator=",") const { return rt_mx(c_inv_.r().transpose(), c_inv_.t()) .as_xyz(decimal, t_first, letters_abc, separator); } //! Returns abc format, or xyz if it is shorter than abc. /*! See also: as_abc(), as_xyz() */ std::string symbol() const { std::string result = as_abc(); std::string alt = as_xyz(); if (result.size() > alt.size()) return alt; return result; } private: rt_mx c_; rt_mx c_inv_; }; }} // namespace cctbx::sgtbx #endif // CCTBX_SGTBX_CHANGE_OF_BASIS_OP_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/sgtbx/rot_mx.cpp
.cpp
3,017
117
#include <cctbx/sgtbx/rot_mx.h> #include <cctbx/sgtbx/utils.h> #include <scitbx/math/gcd.h> namespace cctbx { namespace sgtbx { void throw_unsuitable_rot_mx(const char* file, long line) { throw error_rational_vector(file, line, "Unsuitable value for rational rotation matrix."); } rot_mx rot_mx::new_denominator(int new_den) const { rot_mx result(new_den); if (utils::change_denominator(num_.begin(), den(), result.num_.begin(), new_den, num_.size()) != 0) { throw_unsuitable_rot_mx(__FILE__, __LINE__); } return result; } rot_mx rot_mx::inverse() const { int det_den3 = num_.determinant(); if (det_den3 == 0) throw error("Rotation matrix is not invertible."); return rot_mx( num_.co_factor_matrix_transposed() * (den_*den_), den_) / det_den3; } rot_mx operator/(rot_mx const& lhs, int rhs) { sg_mat3 new_num; for(std::size_t i=0;i<9;i++) { if (lhs.num_[i] % rhs) throw_unsuitable_rot_mx(__FILE__, __LINE__); new_num[i] = lhs.num_[i] / rhs; } return rot_mx(new_num, lhs.den_); } rot_mx rot_mx::cancel() const { int g = den(); for(std::size_t i=0;i<9;i++) g = scitbx::math::gcd_int(g, num_[i]); if (g == 0) return *this; return rot_mx(num_ / g, den() / g); } rot_mx rot_mx::inverse_cancel() const { int det_den3 = num_.determinant(); if (det_den3 == 0) throw error("Rotation matrix is not invertible."); rat d(det_den3, den_); return rot_mx(num_.co_factor_matrix_transposed() * d.denominator(), 1) .divide(d.numerator()); } rot_mx rot_mx::divide(int rhs) const { sg_mat3 new_num; if (rhs < 0) { new_num = -num_; rhs = -rhs; } else { new_num = num_; } return rot_mx(new_num, den_ * rhs).cancel(); } int rot_mx::type() const { int det = num_.determinant(); if (det == -1 || det == 1) { switch (num_.trace()) { case -3: return -1; case -2: return -6; case -1: if (det == -1) return -4; else return 2; case 0: if (det == -1) return -3; else return 3; case 1: if (det == -1) return -2; else return 4; case 2: return 6; case 3: return 1; } } return 0; } int rot_mx::order(int type) const { if (type == 0) type = rot_mx::type(); if (type > 0) return type; if (type % 2) return -type * 2; return -type; } rot_mx rot_mx::accumulate(int type) const { CCTBX_ASSERT(den_ == 1); int ord = order(type); if (ord == 1) return *this; CCTBX_ASSERT(ord != 0); sg_mat3 result(1); sg_mat3 a(num_); result += a; for(int i=2; i < ord; ++i) { a = a*num_; result += a; } return rot_mx(result, 1); } }} // namespace cctbx::sgtbx
C++
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/sgtbx/rt_mx.cpp
.cpp
11,090
380
#include <cctbx/sgtbx/rt_mx.h> #include <scitbx/matrix/row_echelon.h> #include <ctype.h> #include <string.h> namespace cctbx { namespace sgtbx { rt_mx rt_mx::new_denominators(int r_den, int t_den) const { rt_mx result(*this); if (r_den) result.r_ = result.r_.new_denominator(r_den); if (t_den) result.t_ = result.t_.new_denominator(t_den); return result; } rt_mx rt_mx::scale(int factor_r, int factor_t) const { if (factor_t == 0) factor_t = factor_r; return rt_mx(r_.scale(factor_r), t_.scale(factor_t)); } rt_mx rt_mx::inverse() const { rot_mx r_inv = r_.inverse(); tr_vec t_inv = (-r_inv * t_).new_denominator(t_.den()); return rt_mx(r_inv, t_inv); } rt_mx rt_mx::inverse_cancel() const { rot_mx r_inv = r_.inverse_cancel(); tr_vec t_inv = -r_inv.multiply(t_); return rt_mx(r_inv, t_inv); } rt_mx rt_mx::operator+(rt_mx const& rhs) const { return rt_mx(r_ + rhs.r_, t_ + rhs.t_); } rt_mx rt_mx::operator*(rt_mx const& rhs) const { CCTBX_ASSERT(t_.den() == rhs.t_.den()); return rt_mx(r_ * rhs.r_, r_ * rhs.t_ + t_.scale(r_.den())); } rt_mx rt_mx::operator+(tr_vec const& rhs) const { return rt_mx(r_, t_ + rhs); } namespace { void throw_parse_error( parse_string const& input, std::string const& info=": unexpected character") { throw std::invalid_argument( "Parse error" + info + ":\n" + input.format_where_message(/* prefix */ " ")); } int rationalize(double fVal, int& iVal, int den) { if (den == 0) return -1; fVal *= den; if (fVal < 0.) iVal = int(fVal - .5); else iVal = int(fVal + .5); fVal -= iVal; fVal /= den; if (fVal < 0.) fVal = -fVal; if (fVal > .0005) return -1; return 0; } } // namespace <anonymous> rt_mx_from_string::rt_mx_from_string( parse_string& input, const char* stop_chars, int r_den, int t_den, bool enable_xyz, bool enable_hkl, bool enable_abc) : rt_mx(r_den, t_den), have_xyz(false), have_hkl(false), have_abc(false) { int Row = 0; int Column = -1; int Sign = 1; int Mult = 0; double ValR[3]; int i; for(i=0;i<3;i++) ValR[i] = 0.; double ValT = 0.; double Value = 0.; bool have_value = false; const unsigned int P_Add = 0x01u; const unsigned int P_Mult = 0x02u; const unsigned int P_Value = 0x04u; const unsigned int P_XYZ = 0x08u; const unsigned int P_Comma = 0x10u; unsigned int P_mode = P_Add | P_Value | P_XYZ; for (;; input.skip()) { if (strchr(stop_chars, input()) || !isspace(input())) { switch (strchr(stop_chars, input()) ? '\0' : input()) { case '_': break; case '+': Sign = 1; goto ProcessAdd; case '-': Sign = -1; ProcessAdd: if ((P_mode & P_Add) == 0) throw_parse_error(input); if (Column >= 0) ValR[Column] += Value; else ValT += Value; Value = 0.; have_value = false; Column = -1; Mult = 0; P_mode = P_Value | P_XYZ; break; case '*': if ((P_mode & P_Mult) == 0) throw_parse_error(input); Mult = 1; P_mode = P_Value | P_XYZ; break; case '/': case ':': if ((P_mode & P_Mult) == 0) throw_parse_error(input); Mult = -1; P_mode = P_Value; break; case '.': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if ((P_mode & P_Value) == 0) throw_parse_error(input); { const char *beginptr = input.peek(); char *endptr; double V = std::strtod(beginptr, &endptr); if (endptr == beginptr) { throw_parse_error(input); } input.skip((endptr-beginptr)-1); if (Sign == -1) { V = -V; Sign = 1; } if (Mult == 1) Value *= V; else if (Mult == -1) { if (V != 0.) Value /= V; else if (Value != 0.) throw_parse_error(input); } else Value = V; } have_value = true; P_mode = P_Comma | P_Add | P_Mult | P_XYZ; break; case 'X': case 'x': Column = 0; have_xyz = true; goto Process_XYZ; case 'Y': case 'y': Column = 1; have_xyz = true; goto Process_XYZ; case 'Z': case 'z': Column = 2; have_xyz = true; goto Process_XYZ; case 'H': case 'h': Column = 0; have_hkl = true; goto Process_XYZ; case 'K': case 'k': Column = 1; have_hkl = true; goto Process_XYZ; case 'L': case 'l': Column = 2; have_hkl = true; goto Process_XYZ; case 'A': case 'a': Column = 0; have_abc = true; goto Process_XYZ; case 'B': case 'b': Column = 1; have_abc = true; goto Process_XYZ; case 'C': case 'c': Column = 2; have_abc = true; goto Process_XYZ; Process_XYZ: if (have_xyz && !enable_xyz) { throw_parse_error( input, ": x,y,z notation not supported in this context"); } if (have_hkl && !enable_hkl) { throw_parse_error( input, ": h,k,l notation not supported in this context"); } if (have_abc && !enable_abc) { throw_parse_error( input, ": a,b,c notation not supported in this context"); } if (have_xyz && have_hkl) { throw_parse_error(input, ": mix of x,y,z and h,k,l notation"); } if (have_xyz && have_abc) { throw_parse_error(input, ": mix of x,y,z and a,b,c notation"); } if (have_hkl && have_abc) { throw_parse_error(input, ": mix of h,k,l and a,b,c notation"); } if ((P_mode & P_XYZ) == 0) throw_parse_error(input); if (!have_value) { Value = Sign; Sign = 1; } P_mode = P_Comma | P_Add | P_Mult; break; case ',': case ';': if (Row == 2) { throw_parse_error(input, ": too many row expressions"); } case '\0': if ((P_mode & P_Comma) == 0) { throw_parse_error(input, ": unexpected end of input"); } if (Column >= 0) ValR[Column] += Value; else ValT += Value; for(i=0;i<3;i++) { if (rationalize(ValR[i], r()(Row, i), r_den) != 0) { throw_unsuitable_rot_mx(__FILE__, __LINE__); } } if (rationalize(ValT, t()[Row], t_den) != 0) { throw_unsuitable_tr_vec(__FILE__, __LINE__); } Row++; Column = -1; Sign = 1; Mult = 0; for(i=0;i<3;i++) ValR[i] = 0.; ValT = 0.; Value = 0.; have_value = false; P_mode = P_Add | P_Value | P_XYZ; break; default: throw_parse_error(input); } } if (strchr(stop_chars, input())) { break; } } if (Row != 3) throw_parse_error(input, ": not enough row expressions"); } rt_mx::rt_mx(parse_string& symbol, const char* stop_chars, int r_den, int t_den) : r_(0), t_(0) { rt_mx_from_string result( symbol, stop_chars, r_den, t_den, /* enable_xyz */ true, /* enable_hkl */ true, /* enable_abc */ false); if (result.have_hkl) { if (!result.t().is_zero()) { std::ostringstream o; o << "h,k,l matrix symbol must not include a translation part:\n" << " input symbol: \"" << symbol.string() << "\"\n" << " translation part: (" << result.t().as_string(/*decimal*/ false, /*seperator*/ ", ") << ")"; throw std::invalid_argument(o.str()); } r_ = result.r().transpose(); } else r_ = result.r(); t_ = result.t(); } rt_mx::rt_mx(std::string const& symbol, const char* stop_chars, int r_den, int t_den) : r_(0), t_(0) { parse_string parse_symbol(symbol); *this = rt_mx(parse_symbol, stop_chars, r_den, t_den); } rt_mx::rt_mx(scitbx::mat3<double> const& r, scitbx::vec3<double> const& t, int r_den, int t_den) : r_(0), t_(0) { rt_mx result(r_den, t_den); for(std::size_t i=0;i<9;i++) { if (rationalize(r[i], result.r_[i], r_den) != 0) { throw_unsuitable_rot_mx(__FILE__, __LINE__); } } for(std::size_t i=0;i<3;i++) { if (rationalize(t[i], result.t_[i], t_den) != 0) { throw_unsuitable_tr_vec(__FILE__, __LINE__); } } r_ = result.r_; t_ = result.t_; } af::tiny<int, 12> rt_mx::as_int_array() const { af::tiny<int, 12> result; for(std::size_t i=0;i<9;i++) result[i ] = r_[i]; for(std::size_t i=0;i<3;i++) result[i + 9] = t_[i]; return result; } bool rt_mx::is_perpendicular(sg_vec3 const& v) const { return (r().accumulate() * v).is_zero(); } tr_vec rt_mx::t_intrinsic_part() const { int type = r_.type(); return r_.accumulate(type) * t_ / r_.order(type); } tr_vec rt_mx::t_location_part(tr_vec const& wi) const { return wi - t(); } tr_vec rt_mx::t_origin_shift(tr_vec const& wl) const { rot_mx rmi = r_.minus_unit_mx(); rot_mx p(1); af::ref<int, af::mat_grid> ref_rmi(rmi.num().begin(), 3, 3); af::ref<int, af::mat_grid> ref_p(p.num().begin(), 3, 3); scitbx::matrix::row_echelon::form_t(ref_rmi, ref_p); tr_vec pwl = p * wl; tr_vec sh(0); sh.den() = scitbx::matrix::row_echelon::back_substitution_int( ref_rmi, pwl.num().begin(), sh.num().begin()); CCTBX_ASSERT(sh.den() > 0); sh.den() *= pwl.den(); return sh; } rt_mx rt_mx::cancel() const { return rt_mx(r_.cancel(), t_.cancel()); } rt_mx rt_mx::multiply(rt_mx const& rhs) const { if (t().den() == rhs.t().den()) { return rt_mx( (r_ * rhs.r()), (r_ * rhs.t() + t_.scale(r().den()))).cancel(); } else { int f = boost::lcm(t().den(), rhs.t().den()); int l = f / t().den() * r().den(); int r = f / rhs.t().den(); return rt_mx( (r_ * rhs.r()), (r_ * rhs.t().scale(r) + t_.scale(l))).cancel(); } } translation_part_info::translation_part_info(rt_mx const& s) { ip_ = s.t_intrinsic_part(); lp_ = s.t_location_part(ip_); os_ = s.t_origin_shift(lp_); } }} // namespace cctbx::sgtbx
C++
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/sgtbx/parse_string.h
.h
2,961
116
#ifndef CCTBX_SGTBX_PARSE_STRING_H #define CCTBX_SGTBX_PARSE_STRING_H #include <cstddef> #include <string> namespace cctbx { namespace sgtbx { //! Class for communicating string parsing errors. /*! This class is used by functions such as cctbx::sgtbx::space_group::parse_hall_symbol() or a constructor of class cctbx::sgtbx::rt_mx to communitcate errors that are detected during the interpretation of an input string.<br> Intended use:<pre> using namespace cctbx::sgtbx; parse_string hall_symbol("P x"); space_group sg; try { sg.parse_hall_symbol(hall_symbol); } catch (cctbx::error const& e) { std::cout << e.what() << std::endl; std::cout << hall_symbol.string() << std::endl; for (std::size_t i = 0; i < hall_symbol.where(); i++) std::cout << "_"; std::cout << "^" << std::endl; } </pre> This will produce the output:<pre> cctbx Error: Improper symbol for rotational order. P x __^ </pre> */ class parse_string { public: //! Initializes the parse_string with the empty string. parse_string() : pos_(0), marked_pos_(0) {} //! Initializes the parse_string with the input string. explicit parse_string(std::string const& str) : s_(str #if defined(__GNUC__) && __GNUC__ == 3 \ && (__GNUC_MINOR__ == 2 || __GNUC_MINOR__ == 3) +"" // work around gcc 3.2 & 3.3 bug #endif ), pos_(0), marked_pos_(0) {} //! Returns the input string. const char* string() const { return s_.c_str(); } //! Index of last character accessed by the parsing algorithm. std::size_t where() const { return pos_; } //! Support for formatting exceptions. /*! Produces output of the form: P x __^ */ std::string format_where_message(std::string const& prefix) const { std::string result = prefix + s_ + "\n" + prefix; for(std::size_t i=0;i<pos_;i++) result += "_"; result += "^"; return result; } //! For internal use only. char operator()() const { return s_[pos_]; } //! For internal use only. const char* peek() { return s_.c_str() + pos_; } //! For internal use only. char get() { if (pos_ >= s_.size()) return '\0'; return s_[pos_++]; } //! For internal use only. void skip(std::size_t n = 1) { pos_ += n; } //! For internal use only. void set_mark() { marked_pos_ = pos_; } //! For internal use only. void go_to_mark() { pos_ = marked_pos_; } private: std::string s_; std::size_t pos_; std::size_t marked_pos_; }; }} // namespace cctbx::sgtbx #endif // CCTBX_SGTBX_PARSE_STRING_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/sgtbx/rot_mx.h
.h
11,934
411
#ifndef CCTBX_SGTBX_ROT_MX_H #define CCTBX_SGTBX_ROT_MX_H #include <scitbx/sym_mat3.h> #include <cctbx/sgtbx/tr_vec.h> #include <scitbx/matrix/as_xyz.h> namespace cctbx { namespace sgtbx { void throw_unsuitable_rot_mx(const char* file, long line); class rot_mx_info; // forward declaration //! 3x3 rotation matrix. /*! The elements of the matrix are stored as integers and a common denominator. The actual value of an element is obtained by dividing the integer number by the denominator. */ class rot_mx { public: //! Initialization of a diagonal matrix with the given denominator. /*! The diagonal elements are defined as diagonal * denominator. */ explicit rot_mx(int denominator=1, int diagonal=1) : num_(diagonal * denominator), den_(denominator) {} //! Initialization with numerator m and the given denominator. explicit rot_mx(sg_mat3 const& m, int denominator=1) : num_(m), den_(denominator) {} //! Initialization with the given elements and denominator. rot_mx(int m00, int m01, int m02, int m10, int m11, int m12, int m20, int m21, int m22, int denominator = 1) : num_(m00,m01,m02, m10,m11,m12, m20,m21, m22), den_(denominator) {} //! Numerator of the rotation matrix. sg_mat3 const& num() const { return num_; } //! Numerator of the rotation matrix. sg_mat3& num() { return num_; } //! i'th element of the numerator of the rotation matrix. int const& operator[](std::size_t i) const { return num_[i]; } //! i'th element of the numerator of the rotation matrix. int& operator[](std::size_t i) { return num_[i]; } //! (r*3+c)'th element of the numerator of the rotation matrix. int const& operator()(int r, int c) const { return num_(r, c); } //! (r*3+c)'th element of the numerator of the rotation matrix. int& operator()(int r, int c) { return num_(r, c); } //! Denominator of the rotation matrix. int const& den() const { return den_; } //! Denominator of the rotation matrix. int& den() { return den_; } //! True only if both the numerators and the denominators are equal. bool operator==(rot_mx const& rhs) const { if (den_ != rhs.den_) return false; return num_.const_ref().all_eq(rhs.num_.const_ref()); } //! False only if both the numerators and the denominators are equal. bool operator!=(rot_mx const& rhs) const { return !((*this) == rhs); } //! True only if den() != 0. bool is_valid() const { return den_ != 0; } /*! \brief True only if this is a diagonal matrix and all diagonal elements are equal to the denominator. */ bool is_unit_mx() const { return num_ == sg_mat3(den_); } //! This minus the unit matrix. rot_mx minus_unit_mx() const { rot_mx result(*this); for (std::size_t i=0;i<9;i+=4) result[i] -= den_; return result; } //! New rotation matrix with denominator new_den. /*! An exception is thrown if the old rotation matrix cannot be represented using the new denominator. */ rot_mx new_denominator(int new_den) const; //! New rotation matrix with num()*factor and den()*factor. rot_mx scale(int factor) const { if (factor == 1) return *this; return rot_mx(num_ * factor, den_ * factor); } //! Determinant as rational number. /*! An exception is thrown if den() <= 0. */ rat determinant() const { CCTBX_ASSERT(den_ > 0); return rat(num_.determinant(), den_*den_*den_); } //! Inverse of this matrix. /*! An exception is thrown if the result cannot be represented using the denominator den(). */ rot_mx inverse() const; //! New rotation matrix with num().transpose(), den(). rot_mx transpose() const { return rot_mx(num_.transpose(), den_); } //! New rotation matrix with -num(), den(). rot_mx operator-() const { return rot_mx(-num_, den_); } //! Addition of numerators. /*! An exception is thrown if the denominators are not equal. */ friend rot_mx operator+(rot_mx const& lhs, rot_mx const& rhs) { CCTBX_ASSERT(lhs.den_ == rhs.den_); return rot_mx(lhs.num_ + rhs.num_, lhs.den_); } //! Subtraction of numerators. /*! An exception is thrown if the denominators are not equal. */ friend rot_mx operator-(rot_mx const& lhs, rot_mx const& rhs) { CCTBX_ASSERT(lhs.den_ == rhs.den_); return rot_mx(lhs.num_ - rhs.num_, lhs.den_); } //! In-place addition of numerators. /*! An exception is thrown if the denominators are not equal. */ rot_mx& operator+=(rot_mx const& rhs) { CCTBX_ASSERT(den_ == rhs.den_); num_ += rhs.num_; return *this; } //! Matrix multiplication. /*! The denominator of the result is the product lhs.den() * rhs.den(). */ friend rot_mx operator*(rot_mx const& lhs, rot_mx const& rhs) { return rot_mx(lhs.num_ * rhs.num_, lhs.den_ * rhs.den_); } //! Matrix*vector multiplication. /*! The denominator of the result is the product lhs.den() * rhs.den(). */ friend tr_vec operator*(rot_mx const& lhs, tr_vec const& rhs) { return tr_vec(lhs.num_ * rhs.num(), lhs.den_ * rhs.den()); } //! Vector*matrix multiplication. /*! The denominator of the result is the product lhs.den() * rhs.den(). */ friend tr_vec operator*(tr_vec const& lhs, rot_mx const& rhs) { return tr_vec(lhs.num() * rhs.num_, lhs.den() * rhs.den_); } //! Matrix*vector multiplication, numerator only. friend sg_vec3 operator*(rot_mx const& lhs, sg_vec3 const& rhs) { return sg_vec3(lhs.num_ * rhs); } //! New rotation matrix with num()*rhs, den(). friend rot_mx operator*(rot_mx const& lhs, int rhs) { return rot_mx(lhs.num_ * rhs, lhs.den_); } //! New rotation matrix with rhs.num()*lhs, rhs.den(). friend rot_mx operator*(int lhs, rot_mx const& rhs) { return rhs * lhs; } //! In-place multiplication of numerator with rhs. rot_mx& operator*=(int rhs) { num_ *= rhs; return *this; } //! New rotation matrix with num() / rhs, den(). /*! An exception is thrown if the result cannot be represented using den(). */ friend rot_mx operator/(rot_mx const& lhs, int rhs); //! Cancellation of factors. /*! The denominator of the new rotation matrix is made as small as possible. */ rot_mx cancel() const; //! Matrix inversion with cancellation of factors. rot_mx inverse_cancel() const; //! Matrix multiplication with cancellation of factors. rot_mx multiply(rot_mx const& rhs) const { return ((*this) * rhs).cancel(); } //! Matrix*vector multiplication with cancellation of factors. tr_vec multiply(tr_vec const& rhs) const { return ((*this) * rhs).cancel(); } //! num()/rhs,den() with cancellation of factors. rot_mx divide(int rhs) const; //! Rotation-part type (1, 2, 3, 4, 6, -1, -2=m, -3, -4, -6) /*! See also: cctbx::sgtbx::rot_mx_info */ int type() const; //! Rotational order. /*! Number of times the matrix must be multiplied with itself in order to obtain the unit matrix. See also: cctbx::sgtbx::rot_mx_info */ int order(int type=0) const; //! Sum of repeated products of this matrix with itself. /*! identity + this + this*this + ... + this**(order() - 1) Restriction: the denominator must be one. */ rot_mx accumulate(int type=0) const; //! Convenience method for constructing a rot_mx_info instance. rot_mx_info info() const; //! Conversion to a floating-point array. template <typename FloatType> scitbx::mat3<FloatType> as_floating_point(scitbx::type_holder<FloatType>) const { return scitbx::mat3<FloatType>(num_) / FloatType(den_); } //! Conversion to an array with element type double. scitbx::mat3<double> as_double() const { return as_floating_point(scitbx::type_holder<double>()); } //! Conversion to a symbolic expression, e.g. "x,x-y,z". /*! Constants can be formatted as fractional or decimal numbers.<br> E.g. "1/2*x,y,z" or "0.5*x,y,z".<br> symbol_letters must contain three characters that are used to represent x, y, and z, respectively. Typical examples are symbol_letters = "xyz" or symbol_letters = "XYZ".<br> separator is inserted between the terms for two rows. Typical strings used are separator = "," and separator = ", ". */ std::string as_xyz( bool decimal=false, const char* symbol_letters="xyz", const char* separator=",") const { return scitbx::matrix::rational_as_xyz( 3, 3, num_.begin(), den_, static_cast<const int*>(0), 0, decimal, false, symbol_letters, separator); } //! Shorthand for: transpose().as_xyz(decimal, letters_hkl, separator) std::string as_hkl( bool decimal=false, const char* letters_hkl="hkl", const char* separator=",") const { return transpose().as_xyz(decimal, letters_hkl, separator); } /// Transform the given vector template <typename T> scitbx::vec3<T> operator()(scitbx::vec3<T> const &x) const { return (*this)*x; } /// Transform the given symmetric tensor template <typename T> scitbx::sym_mat3<T> operator()(scitbx::sym_mat3<T> const &u) const { scitbx::sym_mat3<T> v = u.tensor_transform(num_); v /= T(den_); return v; } /// Matrix realising a symmetric tensor transform template <typename T> af::tiny<T,6*6> tensor_transform_matrix() const { return tensor_transform_matrix(scitbx::type_holder<T>()); } /// For compatibility with older compilers. template <typename T> af::tiny<T,6*6> tensor_transform_matrix( scitbx::type_holder<T> const&) const { af::tiny<T,6*6> result = num_.tensor_transform_matrix(); result /= T(den_); return result; } private: sg_mat3 num_; int den_; }; /*! \brief Multiplication of rot_mx with a vector of rational or floating-point values. */ /*! Python: __mul__ */ template <typename RatFltType> scitbx::vec3<RatFltType> operator*( rot_mx const& lhs, scitbx::vec3<RatFltType> const& rhs) { scitbx::vec3<RatFltType> result; sg_mat3 const& l = lhs.num(); int d = lhs.den(); for(unsigned i=0;i<3;i++) { result[i] = (l(i,0)*rhs[0] + l(i,1)*rhs[1] + l(i,2)*rhs[2]) / d; } return result; } //! Multiplication of rot_mx with a vector of floating-point values. /*! Python: __rmul__ */ template <typename FloatType> scitbx::vec3<FloatType> operator*(scitbx::vec3<FloatType> const& lhs, rot_mx const& rhs) { return lhs * rhs.num() / rhs.den(); } }} // namespace cctbx::sgtbx #endif // CCTBX_SGTBX_ROT_MX_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/sgtbx/utils.cpp
.cpp
1,220
43
#include <cstddef> #include <cctbx/sgtbx/utils.h> #include <scitbx/array_family/misc_functions.h> namespace cctbx { namespace sgtbx { namespace utils { int change_denominator( const int *old_num, int old_den, int *new_num, int new_den, int n) { for(std::size_t i=0;i<n;i++) { new_num[i] = old_num[i] * new_den; if (new_num[i] % old_den) return -1; new_num[i] /= old_den; } return 0; } bool cmp_i_vec::operator()(const int *a, const int *b) const { using std::size_t; using scitbx::fn::absolute; size_t n0a = 0; for(size_t i=0;i<n_;i++) if (a[i] == 0) n0a++; size_t n0b = 0; for(size_t i=0;i<n_;i++) if (b[i] == 0) n0b++; if (n0a > n0b) return true; if (n0a < n0b) return false; for(size_t i=0;i<n_;i++) { if (a[i] != 0 && b[i] == 0) return true; if (a[i] == 0 && b[i] != 0) return false; } for(size_t i=0;i<n_;i++) { if (absolute(a[i]) < absolute(b[i])) return true; if (absolute(a[i]) > absolute(b[i])) return false; } for(size_t i=0;i<n_;i++) { if (a[i] > b[i]) return true; if (a[i] < b[i]) return false; } return false; } }}} // namespace cctbx::sgtbx::utils
C++
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/sgtbx/tr_vec.cpp
.cpp
1,981
73
#include <cctbx/sgtbx/tr_vec.h> #include <cctbx/sgtbx/utils.h> #include <scitbx/math/gcd.h> namespace cctbx { namespace sgtbx { void throw_unsuitable_tr_vec(const char* file, long line) { throw error_rational_vector(file, line, "Unsuitable value for rational translation vector."); } tr_vec tr_vec::new_denominator(int new_den) const { tr_vec result(new_den); if (utils::change_denominator(num_.begin(), den(), result.num_.begin(), new_den, num_.size()) != 0) { throw_unsuitable_tr_vec(__FILE__, __LINE__); } return result; } tr_vec operator/(tr_vec const& lhs, int rhs) { sg_vec3 new_num; for(std::size_t i=0;i<3;i++) { if (lhs.num_[i] % rhs) throw_unsuitable_tr_vec(__FILE__, __LINE__); new_num[i] = lhs.num_[i] / rhs; } return tr_vec(new_num, lhs.den_); } tr_vec tr_vec::cancel() const { int g = den(); for(std::size_t i=0;i<3;i++) g = scitbx::math::gcd_int(g, num_[i]); if (g == 0) return *this; return tr_vec(num_ / g, den() / g); } tr_vec tr_vec::plus(tr_vec const& rhs) const { tr_vec result(boost::lcm(den(), rhs.den())); int l = result.den() / den(); int r = result.den() / rhs.den(); for(std::size_t i=0;i<3;i++) result[i] = num_[i] * l + rhs[i] * r; return result.cancel(); } tr_vec tr_vec::minus(tr_vec const& rhs) const { tr_vec result(boost::lcm(den(), rhs.den())); int l = result.den() / den(); int r = result.den() / rhs.den(); for(std::size_t i=0;i<3;i++) result[i] = num_[i] * l - rhs[i] * r; return result.cancel(); } std::string tr_vec::as_string(bool decimal, const char* separator) const { std::string result; for(int i=0;i<3;i++) { if (i != 0) result += separator; rat t_frac((*this)[i], den()); result += scitbx::format(t_frac, decimal); } return result; } }} // namespace cctbx::sgtbx
C++
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/sgtbx/basic.h
.h
1,655
59
#ifndef CCTBX_SGTBX_BASIC_H #define CCTBX_SGTBX_BASIC_H #include <scitbx/mat3.h> #include <scitbx/rational.h> #include <cctbx/error.h> namespace cctbx { //! Shorthand for default vec3 type in space group toolbox. typedef scitbx::vec3<int> sg_vec3; //! Shorthand for default mat3 type in space group toolbox. typedef scitbx::mat3<int> sg_mat3; //! Space Group Toolbox namespace. namespace sgtbx { //! Special class for rational vector exceptions. /*! Used by sgtbx::tr_vec, sgtbx::rot_mx */ class error_rational_vector : public error { public: //! Constructor. error_rational_vector(const char* file, long line, std::string const& msg = "") throw() : error(file, line, msg) {} //! Virtual destructor. virtual ~error_rational_vector() throw() {} }; /*! \brief Maximum number of representative rotation matrices for 3-dimensional crystallographic space groups. */ static const std::size_t n_max_repr_rot_mx = 24; //! Default space_group translation vector denominator. const int sg_t_den = 12; //! Default change_of_basis rotation matrix denominator. const int cb_r_den = 12; //! Default change_of_basis translation vector denominator. const int cb_t_den = 144; //! Checks default rotation and translation denominators for consistency. inline void sanity_check() { CCTBX_ASSERT(sg_t_den % 12 == 0); CCTBX_ASSERT(cb_t_den >= 2 * sg_t_den); CCTBX_ASSERT(cb_t_den % sg_t_den == 0); } typedef boost::rational<int> rat; typedef scitbx::vec3<rat> vec3_rat; }} // namespace cctbx::sgtbx #endif // CCTBX_SGTBX_BASIC_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/sgtbx/rt_mx.h
.h
20,588
673
#ifndef CCTBX_SGTBX_RT_MX_H #define CCTBX_SGTBX_RT_MX_H #include <cctbx/sgtbx/rot_mx.h> #include <cctbx/sgtbx/parse_string.h> #include <cctbx/coordinates.h> #include <scitbx/sym_mat3.h> #include <scitbx/math/gcd.h> #include <scitbx/array_family/tiny_types.h> #include <cctbx/import_scitbx_af.h> namespace cctbx { namespace sgtbx { //! Rotation-Translation matrix. /*! r() is the (3x3) rotation part or rotation matrix and t() the (3x1) translation part or translation vector of the symmetry operation. For efficiency, the elements of the matrix and the vector are stored as integer numbers and denominators. The actual value of an element is obtained by dividing the integer number by the corresponding denominator:<br> r()[i] / r().den(), t()[i] / t().den(). */ class rt_mx { public: //! Identity rotation matrix and zero translation vector. /*! The denominators used are r_den and t_den for the rotation part and the translation part, respectively. */ explicit rt_mx(int r_den=1, int t_den=sg_t_den) : r_(r_den), t_(t_den) {} //! Initialization with the given rotation matrix and translation vector. rt_mx(rot_mx const& r, tr_vec const& t) : r_(r), t_(t) {} //! Initialization with the given rotation matrix. /*! The translation part is initialized as the zero translation with the supplied denominator t_den. */ explicit rt_mx(rot_mx const& r, int t_den=sg_t_den) : r_(r), t_(t_den) {} //! Initialization with the given translation vector. /*! The rotation part is initialized as the identity matrix with the supplied denominator r_den. */ explicit rt_mx(tr_vec const& t, int r_den=1) : r_(r_den), t_(t) {} //! Initialization with a symbolic expression, e.g. "x+1/2,y,z". /*! Parsing will stop at any of the characters listed in stop_chars.<br> The denominators of the new rt_mx are r_den and t_den.<br> If an error occurs, an exception is thrown. parse_string can be investigated to locate the input character that triggered the error. */ rt_mx( parse_string& symbol, const char* stop_chars="", int r_den=1, int t_den=sg_t_den); //! Initialize by parsing a symbolic expression, e.g. "x+1/2,y,z". /*! Identical to the constructor that takes a parse_string as the first argument. However, if an exception is thrown there is no way to locate the input character that triggered the error. */ rt_mx( std::string const& symbol, const char* stop_chars="", int r_den=1, int t_den=sg_t_den); //! Initialize with floating point rotation and translation parts. rt_mx( scitbx::mat3<double> const& r, scitbx::vec3<double> const& t, int r_den=1, int t_den=sg_t_den); //! Access to rotation part. rot_mx const& r() const { return r_; }; //! Access to rotation part. rot_mx& r() { return r_; }; //! Access to translation part. tr_vec const& t() const { return t_; }; //! Access to translation part. tr_vec& t() { return t_; }; //! Tests equality. bool operator==(rt_mx const& rhs) const { return !((*this) < rhs) && !(rhs < (*this)); } //! Tests inequality. bool operator!=(rt_mx const& rhs) const { return !((*this) == rhs); } /*! \brief Tests if lhs "is less than" rhs using the same ordering as space_group::make_tidy(). */ bool operator<(rt_mx const& rhs) const; /*! \brief Tests if lhs "is less than or equal" rhs using the same ordering as space_group::make_tidy(). */ bool operator<=(rt_mx const& rhs) const { return (*this == rhs) || (*this < rhs); } /*! \brief Tests if lhs "is greater than" rhs using the same ordering as space_group::make_tidy(). */ bool operator>(rt_mx const& rhs) const; /*! \brief Tests if lhs "is greater than or equal" rhs using the same ordering as space_group::make_tidy(). */ bool operator>=(rt_mx const& rhs) const { return (*this == rhs) || (*this > rhs); } //! Test if the matrix is valid. /*! A rt_mx is valid only if both the rotation denominator and the translation denominator are not zero. */ bool is_valid() const { return r_.is_valid() && t_.is_valid(); } //! New unit matrix. /*! The new matrix inherits r().den() and t().den(). */ rt_mx unit_mx() const { return rt_mx(r().den(), t().den()); } //! Test if the matrix is the unit matrix. bool is_unit_mx() const { return r_.is_unit_mx() && t_.is_zero(); } //! Conversion to a symbolic expression, e.g. "x+1/2,y,z". /*! Constants can be formatted as fractional or decimal numbers.<br> E.g. "x+1/2,y,z" or "x+0.5,y,z".<br> The translation component can appear last or first.<br> E.g. "x+1/2,y,z" or "1/2+x,y,z".<br> symbol_letters must contain three characters that are used to represent x, y, and z, respectively. Typical examples are symbol_letters = "xyz" or symbol_letters = "XYZ". Other letters could be used, but the resulting symbolic expression cannot be translated back with the constructors above.<br> separator is inserted between the terms for two rows. Typical strings used are separator = "," and separator = ", ". */ std::string as_xyz( bool decimal=false, bool t_first=false, const char* symbol_letters="xyz", const char* separator=",") const { return scitbx::matrix::rational_as_xyz( 3, 3, r_.num().begin(), r_.den(), t_.num().begin(), t_.den(), decimal, t_first, symbol_letters, separator); } //! Copy matrix elements to a plain array of int. /*! The 9 elements of the rotation part are copied to elements 0..8 of the plain array. The 3 elements of the translation part are copied to elements 9..11 of the plain array. Use r().den() and t().den() to access the denominators for conversion to floating point representations. <p> See also: as_double_array(), as_float_array() */ af::tiny<int, 12> as_int_array() const; //! Copy matrix elements to a floating point array. /*! The 9 elements of the rotation part are divided by r().den() and copied to elements 0..8 of the array. The 3 elements of the translation part are divided by t().den() and copied to elements 9..11 of the array. <p> See also: as_int_array(), as_double_array(), as_float_array() */ template <class FloatType> af::tiny<FloatType, 12> as_array(scitbx::type_holder<FloatType>) const; //! Copy matrix elements to a plain array of float. /*! See also: as_array(), as_int_array(), as_double_array() */ af::tiny<float, 12> as_float_array() const { return as_array(scitbx::type_holder<float>()); } //! Copy matrix elements to a plain array of double. /*! See also: as_array(), as_int_array(), as_float_array() */ af::tiny<double, 12> as_double_array() const { return as_array(scitbx::type_holder<double>()); } //! Copy with the denominators r_den and t_den. /*! An exception is thrown if the elements cannot be scaled to the new denominators.<br> r_den == 0 or t_den == 0 indicates that the corresponding old denominator is retained. */ rt_mx new_denominators(int r_den, int t_den=0) const; //! Copy of this matrix with the denominators of other. /*! An exception is thrown if the elements cannot be scaled to the new denominators. */ rt_mx new_denominators(rt_mx const& other) const { return new_denominators(other.r().den(), other.t().den()); } //! Multiplies the elements and the denominators by the given factors. /*! if (factor_r == 0) factor_t = factor_r; Not available in Python. */ rt_mx scale(int factor_r, int factor_t=0) const; //! Applies modulus operation such that 0 <= x < t().den(). /*! The operation is applied to the elements of the translation vector. The vector is modified in place. Not available in Python. */ void mod_positive_in_place() { t_ = t_.mod_positive(); } //! Applies modulus operation such that 0 <= x < t().den(). /*! The operation is applied to the elements of the translation vector. A new instance of rt_mx is created. */ rt_mx mod_positive() const { return rt_mx(r_, t_.mod_positive()); } /*! \brief Applies modulus operation such that -t().den()/2+1 < x <= t().den()/2. */ /*! The operation is applied to the elements of the translation vector. The vector is modified in place. Not available in Python. */ void mod_short_in_place() { t_ = t_.mod_short(); } /*! \brief Applies modulus operation such that -t().den()/2+1 < x <= t().den()/2. */ /*! The operation is applied to the elements of the translation vector. A new instance of rt_mx is created. */ rt_mx mod_short() const { return rt_mx(r_, t_.mod_short()); } /*! \brief Tests if the vector v is perpendicular to the axis direction of the rotation part. Not available in Python. */ bool is_perpendicular(sg_vec3 const& v) const; //! Computes the intrinsic (screw or glide) part of the translation part. /*! Let N be the rotation-part type of r(). Following the procedure given by Fischer & Koch (International Tables for Crystallography, Volume A, 1983, Chapter 11), the first step in the analysis of the translation part t() is the decomposition into the intrinsic part wi and the location part wl. For this, (r()|t())^n = (I|t) has to be computed, where the rotational order n = abs(N), except for N = -1 and N = -3. For those two cases, n = -2*N. The intrinsic part is obtained as wi = (1/n)*t.<br> See also: translation_part_info Not available in Python. */ tr_vec t_intrinsic_part() const; //! Computes the location part given the intrinsic part wi. /*! wi is the result of intrinsic_part(). The location part is simply the difference wl = t() - wi.<br> See also: translation_part_info Not available in Python. */ tr_vec t_location_part(tr_vec const& wi) const; //! Computes the origin shift given the location part wl. /*! wl is the result of location_part(). The origin shift is obtained by solving the equation (r()|wl)*x = x for x (see <A HREF="http://journals.iucr.org/a/issues/1999/02/02/au0146/" ><I>Acta Cryst.</I> 1999, <B>A55</B>:383-395</A>). For rotation-part types N > 1 and N = -2, the combination with the axis direction of r() is a convenient description of all fixed points. For the other rotation-part types, the fixed point is unique.<br> See also: translation_part_info Not available in Python. */ tr_vec t_origin_shift(tr_vec const& wl) const; //! Efficient computation of (-I|inv_t) * (r|t). /*! I is the identidy matrix. inv_t is the translation part of a centre of inversion. Not available in Python. */ rt_mx pre_multiply_inv_t(tr_vec const& inv_t) { return rt_mx(-r_, -t_ + inv_t); } //! Computes the inverse matrix. /*! An exception is thrown if the matrix cannot be inverted or if the result cannot be scaled to the rotation part denominator or the translation part denominator. */ rt_mx inverse() const; /*! \brief Similar to /=, but multiplies denominators instead of dividing elements. Not available in Python. */ void pseudo_divide(int rhs) { r_.den() *= rhs; t_.den() *= rhs; } //! Unary minus. rt_mx operator-() const { return rt_mx(-r_, -t_); } //! Addition operator. rt_mx operator+(rt_mx const& rhs) const; //! += operator. rt_mx& operator+=(rt_mx const& rhs) { r_ += rhs.r_; t_ += rhs.t_; return *this; } //! rt_mx + integer vector rt_mx operator+(sg_vec3 const& t) const { return rt_mx(r_, tr_vec(t_.num() + t*t_.den(), t_.den())); } //! Multiplication of homogeneous rt_mx with r().den()=1. /*! The rotation denominator of both matrices must be equal to 1. The translation denominators of the two matrices must be equal. <p> The denominators of the result are equal to the denominators of the operands. <p> operator*() is faster than multiply(). */ rt_mx operator*(rt_mx const& rhs) const; //! Addition of translation vector to translation part. rt_mx operator+(tr_vec const& rhs) const; /*! \brief Refines gridding such that each grid point is mapped onto another grid point by the symmetry operation. */ template <typename GridTupleType> GridTupleType refine_gridding(GridTupleType const& grid) const; //! Reduces denominators by cancellation. /*! The rotation part denominator and the elements of the rotation part are divided by their greatest common denominator. The same procedure is applied to the translation part. */ rt_mx cancel() const; //! Computes the inverse matrix. /*! An exception is thrown if the matrix cannot be inverted. */ rt_mx inverse_cancel() const; //! Multiplication with cancellation for general rt_mx. /*! Similar to opertor*(). However, the operands may have any rotation denominator or translation denominator. <p> The denominators of the result are made as small as possible. <p> See also: cancel() */ rt_mx multiply(rt_mx const& rhs) const; template <typename FloatType> scitbx::vec3<FloatType> operator*(af::tiny_plain<FloatType, 3> const& rhs) const; /// Transform the given vector template <typename T> scitbx::vec3<T> operator()(scitbx::vec3<T> const &x) const { return (*this)*x; } /// Transform the given symmetric tensor template <typename T> scitbx::sym_mat3<T> operator()(scitbx::sym_mat3<T> const &u) const { return r_(u); } /*! \brief Determines unit shifts u such that (r,t+u)*site_frac_2 is closest to site_frac_1. */ template <typename FloatType> scitbx::vec3<int> unit_shifts_minimum_distance( fractional<FloatType> const& site_frac_1, fractional<FloatType> const& site_frac_2) const { return fractional<FloatType>( site_frac_1 - (*this) * site_frac_2).unit_shifts(); } /*! \brief Adds unit shifts u such that (r,t+u)*site_frac_2 is closest to site_frac_1. */ template <typename FloatType> rt_mx add_unit_shifts_minimum_distance( fractional<FloatType> const& site_frac_1, fractional<FloatType> const& site_frac_2) const { return rt_mx(r_, t_ + tr_vec(unit_shifts_minimum_distance( site_frac_1, site_frac_2) * t_.den(), t_.den())); } private: rot_mx r_; tr_vec t_; }; template <class FloatType> af::tiny<FloatType, 12> rt_mx::as_array(scitbx::type_holder<FloatType>) const { af::tiny<FloatType, 12> result; for(std::size_t i=0;i<9;i++) { result[i ] = FloatType(r_[i]) / FloatType(r().den()); } for(std::size_t i=0;i<3;i++) { result[i + 9] = FloatType(t_[i]) / FloatType(t().den()); } return result; } template <typename IntType> IntType norm_denominator(IntType numerator, IntType denominator) { return denominator / scitbx::math::gcd_int(numerator, denominator); } template <typename GridTupleType> GridTupleType rt_mx::refine_gridding(GridTupleType const& grid) const { GridTupleType result; for(std::size_t ir=0;ir<3;ir++) { result[ir] = boost::lcm( grid[ir], norm_denominator(t_[ir], t_.den())); for(std::size_t ic=0;ic<3;ic++) { result[ir] = boost::lcm( result[ir], norm_denominator(this->r_(ir, ic), grid[ic])); } } return result; } /*! \brief Multiplication of rt_mx with a vector of rational or floating-point values. */ /*! Python: __mul__ */ template <typename RatFltType> scitbx::vec3<RatFltType> rt_mx::operator*( af::tiny_plain<RatFltType, 3> const& rhs) const { scitbx::vec3<RatFltType> result; int rd = r_.den(); int td = t_.den(); for(unsigned i=0;i<3;i++) { result[i] = ( r_(i,0) * rhs[0] + r_(i,1) * rhs[1] + r_(i,2) * rhs[2]) / rd + RatFltType(t_[i]) / td; } return result; } //! Parser for xyz expressions. struct rt_mx_from_string : rt_mx { bool have_xyz; bool have_hkl; bool have_abc; rt_mx_from_string() {} rt_mx_from_string( parse_string& input, const char* stop_chars, int r_den, int t_den, bool enable_xyz, bool enable_hkl, bool enable_abc); }; //! Analysis of the translation part of a rotation-translation matrix. /*! Grouping of the results of rt_mx::t_intrinsic_part(), rt_mx::t_location_part() and rt_mx::t_origin_shift(). */ class translation_part_info { public: //! Default constructor. Some data members are not initialized! translation_part_info() {} /*! \brief Determination of intrinsic_part(), location_part() and origin_shift(). */ translation_part_info(rt_mx const& s); //! Intrinsic (srew or glide) part. /*! See rt_mx::t_intrinsic_part() */ tr_vec const& intrinsic_part() const { return ip_; } //! Location part. /*! See rt_mx::t_location_part() */ tr_vec const& location_part() const { return lp_; } //! Origin shift. /*! See rt_mx::t_origin_shift() */ tr_vec const& origin_shift() const { return os_; } private: tr_vec ip_; tr_vec lp_; tr_vec os_; }; //! Symmetry-averaged tensor. /*! reciprocal_space = false: sum[tensor.tensor_transpose_transform(r)] / matrices.size() reciprocal_space = true: sum[tensor.tensor_transform(r)] / matrices.size() over all rotation parts r of matrices. See also: Giacovazzo, Fundamentals of Crystallography 1992, p. 189. Not available in Python. */ template <class FloatType> scitbx::sym_mat3<FloatType> average_tensor( af::const_ref<rt_mx> const& matrices, scitbx::sym_mat3<FloatType> const& tensor, bool reciprocal_space) { scitbx::sym_mat3<FloatType> result(0,0,0,0,0,0); for (std::size_t i=0;i<matrices.size();i++) { scitbx::mat3<FloatType> r = matrices[i].r() .as_floating_point(scitbx::type_holder<FloatType>()); if (reciprocal_space) { result += tensor.tensor_transform(r); } else { result += tensor.tensor_transpose_transform(r); } } return result / static_cast<FloatType>(matrices.size()); } }} // namespace cctbx::sgtbx #endif // CCTBX_SGTBX_RT_MX_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/sgtbx/tr_vec.h
.h
6,560
236
#ifndef CCTBX_SGTBX_TR_VEC_H #define CCTBX_SGTBX_TR_VEC_H #include <cctbx/sgtbx/basic.h> #include <scitbx/math/modulo.h> #include <scitbx/array_family/tiny.h> #include <scitbx/type_holder.h> #include <cctbx/import_scitbx_af.h> namespace cctbx { namespace sgtbx { void throw_unsuitable_tr_vec(const char* file, long line); //! Translation vector. /*! The elements of the vector are stored as integers and a common denominator. The actual value of an element is obtained by dividing the integer number by the denominator. */ class tr_vec { public: /*! \brief Initialization of a 0,0,0-translation with the denominator tr_den. */ explicit tr_vec(int tr_den=sg_t_den) : num_(0,0,0), den_(tr_den) {} /*! \brief Initialization a translation with the integer numerator v and the denominator tr_den. */ explicit tr_vec(sg_vec3 const& v, int tr_den=sg_t_den) : num_(v), den_(tr_den) {} /*! \brief Initialization of a v0,v1,v2-translation with the denominator tr_den. */ tr_vec(int v0, int v1, int v2, int tr_den=sg_t_den) : num_(v0,v1,v2), den_(tr_den) {} //! Numerator of the translation vector. sg_vec3 const& num() const { return num_; } //! Numerator of the translation vector. sg_vec3& num() { return num_; } //! i'th element of the numerator of the translation vector. int const& operator[](std::size_t i) const { return num_[i]; } //! i'th element of the numerator of the translation vector. int& operator[](std::size_t i) { return num_[i]; } //! Denominator of the translation vector. int const& den() const { return den_; } //! Denominator of the translation vector. int& den() { return den_; } //! True only if both the numerators and the denominators are equal. bool operator==(tr_vec const& rhs) const { if (den_ != rhs.den_) return false; return num_.const_ref().all_eq(rhs.num_.const_ref()); } //! False only if both the numerators and the denominators are equal. bool operator!=(tr_vec const& rhs) const { return !((*this) == rhs); } //! True only if den() != 0. bool is_valid() const { return den_ != 0; } //! True only if all elements of the numertor are equal to zero. bool is_zero() const { return num_.is_zero(); } //! New translation vector with denominator new_den. /*! An exception is thrown if the old translation vector cannot be represented using the new denominator. */ tr_vec new_denominator(int new_den) const; //! New translation vector with num()*factor and den()*factor. tr_vec scale(int factor) const { if (factor == 1) return *this; return tr_vec(num_ * factor, den_ * factor); } //! New translation vector with 0 <= num()[i] < den(). tr_vec mod_positive() const { tr_vec result(num_, den_); for(std::size_t i=0;i<3;i++) { result.num_[i] = scitbx::math::mod_positive(result.num_[i], den_); } return result; } //! New translation vector with -den()/2 < num()[i] <= den()/2. tr_vec mod_short() const { tr_vec result(num_, den_); for(std::size_t i=0;i<3;i++) { result.num_[i] = scitbx::math::mod_short(result.num_[i], den_); } return result; } //! New translation vector with -num(), den(). tr_vec operator-() const { return tr_vec(-num_, den_); } //! Addition of numerators. /*! An exception is thrown if the denominators are not equal. */ friend tr_vec operator+(tr_vec const& lhs, tr_vec const& rhs) { CCTBX_ASSERT(lhs.den_ == rhs.den_); return tr_vec(lhs.num_ + rhs.num_, lhs.den_); } //! Subtraction of numerators. /*! An exception is thrown if the denominators are not equal. */ friend tr_vec operator-(tr_vec const& lhs, tr_vec const& rhs) { CCTBX_ASSERT(lhs.den_ == rhs.den_); return tr_vec(lhs.num_ - rhs.num_, lhs.den_); } //! In-place addition of numerators. /*! An exception is thrown if the denominators are not equal. */ tr_vec& operator+=(tr_vec const& rhs) { CCTBX_ASSERT(den_ == rhs.den_); num_ += rhs.num_; return *this; } //! New translation vector with num() * rhs, den(). friend tr_vec operator*(tr_vec const& lhs, int rhs) { return tr_vec(lhs.num_ * rhs, lhs.den_); } //! New translation vector with num() / rhs, den(). /*! An exception is thrown if the result cannot be represented using den(). */ friend tr_vec operator/(tr_vec const& lhs, int rhs); //! New translation vector with rhs.num() * lhs, rhs.den(). friend tr_vec operator*(int const& lhs, tr_vec const& rhs) { return rhs * lhs; } //! Cancellation of factors. /*! The denominator of the new translation vector is made as small as possible. */ tr_vec cancel() const; //! Addition with cancellation of factors. tr_vec plus(tr_vec const& rhs) const; //! Subtraction with cancellation of factors. tr_vec minus(tr_vec const& rhs) const; //! Conversion to a floating-point array. template <typename FloatType> scitbx::vec3<FloatType> as_floating_point(scitbx::type_holder<FloatType>) const { return scitbx::vec3<FloatType>(num_) / FloatType(den_); } //! Conversion to an array with element type double. scitbx::vec3<double> as_double() const { return as_floating_point(scitbx::type_holder<double>()); } //! Conversion to a string with rational or decimal numbers. /*! Python: str() */ std::string as_string(bool decimal=false, const char* separator=",") const; private: sg_vec3 num_; int den_; }; //! Constructor for initialization of constants. struct tr_vec_12 : tr_vec { tr_vec_12(int v0, int v1, int v2) : tr_vec(tr_vec(v0,v1,v2) * (sg_t_den / 12)) {} }; }} // namespace cctbx::sgtbx #endif // CCTBX_SGTBX_TR_VEC_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/uctbx/crystal_orientation.cpp
.cpp
2,295
75
#include <cctbx/crystal_orientation.h> #include <scitbx/math/unimodular_generator.h> namespace cctbx { cctbx::crystal_orientation::crystal_orientation( oc_mat3 const& matrix, bool const& reciprocal_flag): Astar_(reciprocal_flag?matrix:matrix.inverse()){} cctbx::uctbx::unit_cell cctbx::crystal_orientation::unit_cell() const { oc_mat3 direct = direct_matrix(); oc_vec3 p[3]; for (int i=0; i<3; ++i){ p[i] = direct.get_row(i); } return cctbx::uctbx::unit_cell(scitbx::sym_mat3<double>( p[0]*p[0], p[1]*p[1], p[2]*p[2], p[0]*p[1], p[2]*p[0], p[1]*p[2])); } cctbx::uctbx::unit_cell cctbx::crystal_orientation::unit_cell_inverse() const { return unit_cell().reciprocal(); } cctbx::oc_mat3 cctbx::crystal_orientation::direct_matrix() const{ return Astar_.inverse(); } cctbx::oc_mat3 cctbx::crystal_orientation::reciprocal_matrix() const{ return Astar_; } crystal_orientation cctbx::crystal_orientation::change_basis( cctbx::sgtbx::change_of_basis_op const& cb_op) const { return crystal_orientation( Astar_ * (cb_op.c().r().as_double()), reciprocal ); } crystal_orientation cctbx::crystal_orientation::change_basis(oc_mat3 const& rot) const { return crystal_orientation( Astar_ * rot, reciprocal ); } cctbx::oc_mat3 cctbx::crystal_orientation::best_similarity_transformation( crystal_orientation const& other, double const& fractional_length_tolerance, int unimodular_generator_range) const{ scitbx::mat3<double> orientation_similarity(1); //initially the identity double minimum_orientation_bases_zsc = difference_Z_score(other); scitbx::math::unimodular_generator<int> unimodular_generator(unimodular_generator_range); while (!unimodular_generator.at_end()) { oc_mat3 c_inv_r((af::tiny_plain<double, 9>(af::adapt_with_static_cast( unimodular_generator.next())))); crystal_orientation mod_copy = other.change_basis(c_inv_r.inverse()); double R = difference_Z_score(mod_copy); if (R < minimum_orientation_bases_zsc){ minimum_orientation_bases_zsc = R; orientation_similarity = c_inv_r; } } SCITBX_ASSERT(difference_Z_score( other.change_basis(orientation_similarity.inverse())) < fractional_length_tolerance); return orientation_similarity; } } // namespace cctbx
C++
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/uctbx/fast_minimum_reduction.h
.h
11,698
401
#ifndef CCTBX_UCTBX_FAST_MINIMUM_REDUCTION_H #define CCTBX_UCTBX_FAST_MINIMUM_REDUCTION_H #include <cctbx/uctbx.h> #include <cctbx/error.h> #if !defined(CCTBX_UCTBX_FAST_MINIMUM_REDUCTION_OVERZEALOUS_OPTIMIZER) # if defined(__GNUC__) && __GNUC__ == 2 && __GNUC_MINOR__ == 96 # define CCTBX_UCTBX_FAST_MINIMUM_REDUCTION_OVERZEALOUS_OPTIMIZER # include <scitbx/serialization/base_256.h> # endif #endif namespace cctbx { namespace uctbx { //! Specific exception to indicate failure of reduction algorithm. class error_iteration_limit_exceeded : public error { public: error_iteration_limit_exceeded() : error("Iteration limit exceeded.") {} }; //! Specific exception to indicate failure of reduction algorithm. class error_degenerate_unit_cell_parameters : public error { public: error_degenerate_unit_cell_parameters() : error("Degenerate unit cell parameters.") {} }; //! Helper function to disable optimization. float spoil_optimization(float); //! Helper function to disable optimization. double spoil_optimization(double); //! Fast minimum-lengths cell reduction. /*! Based on the algorithm of Gruber (1973), Acta Cryst. A29, 433-440. Tests for equality are removed in order to make the algorithm numerically more stable. However, in some cases the algorithm still oscillates. This situation is analyzed in the implementation below and the cycle is terminated after the action in the false branch of N3. Attention: If this class is instantiated with a FloatType other than float or double a corresponding spoil_optimization() helper function must be defined! */ template <typename FloatType=double, typename IntFromFloatType=int> class fast_minimum_reduction { public: //! Default contructor. Some data members are not initialized! fast_minimum_reduction() {} //! Executes the reduction algorithm. fast_minimum_reduction( uctbx::unit_cell const& unit_cell, std::size_t iteration_limit=100, FloatType multiplier_significant_change_test=16, std::size_t min_n_no_significant_change=2) : multiplier_significant_change_test_( multiplier_significant_change_test), min_n_no_significant_change_(min_n_no_significant_change), iteration_limit_(iteration_limit), r_inv_(scitbx::mat3<IntFromFloatType>(1)), n_iterations_(0), n_no_significant_change_(0), termination_due_to_significant_change_test_(false) { uc_sym_mat3 const& g = unit_cell.metrical_matrix(); a_ = g[0]; b_ = g[1]; c_ = g[2]; d_ = 2*g[5]; e_ = 2*g[4]; f_ = 2*g[3]; last_abc_significant_change_test_ = scitbx::vec3<FloatType>( -a_,-b_,-c_); while (step()); } //! Parameterization of Gruber (1973). af::double6 as_gruber_matrix() const { return af::double6(a_, b_, c_, d_, e_, f_); } //! Parameterization of Niggli. af::double6 as_niggli_matrix() const { return af::double6(a_, b_, c_, d_/2, e_/2, f_/2); } //! Parameterization as used by uctbx::unit_cell::metrical_matrix(). uc_sym_mat3 as_sym_mat3() const { return uc_sym_mat3(a_, b_, c_, f_/2, e_/2, d_/2); } //! Conversion to uctbx::unit_cell. uctbx::unit_cell as_unit_cell() const { return uctbx::unit_cell(as_sym_mat3()); } //! Value as passed to the constructor. std::size_t iteration_limit() const { return iteration_limit_; } //! Value as passed to the constructor. FloatType multiplier_significant_change_test() const { return multiplier_significant_change_test_; } //! Value as passed to the constructor. std::size_t min_n_no_significant_change() const { return min_n_no_significant_change_; } //! Change-of-basis matrix. /*! Compatible with uctbx::unit_cell::change_basis() */ scitbx::mat3<IntFromFloatType> const& r_inv() const { return r_inv_; } //! Number of iterations (actions executed). std::size_t n_iterations() const { return n_iterations_; } /*! \brief Indicates if the reduction was terminated because it was detected that the unit cell lengths did no longer change significantly. */ bool termination_due_to_significant_change_test() const { return termination_due_to_significant_change_test_; } //! Cell type according to International Tables for Crystallography. /*! Possible values: 1 or 2. The value 0 is not possible if the algorithm terminates. */ int type() const { int n_positive = def_test()[1]; if (n_positive == 3) return 1; if (n_positive == 0) return 2; return 0; } protected: // greatest integer which is not greater than x inline IntFromFloatType entier(FloatType const& x) { IntFromFloatType result = static_cast<IntFromFloatType>(x); if (x-result < 0) result--; if (!(x-result < 1)) result++; // work around rounding errors return result; } af::tiny<int, 2> def_test() const { int n_zero = 0; int n_positive = 0; if (0 < d_) n_positive += 1; else if (!(d_ < 0)) n_zero += 1; if (0 < e_) n_positive += 1; else if (!(e_ < 0)) n_zero += 1; if (0 < f_) n_positive += 1; else if (!(f_ < 0)) n_zero += 1; return af::tiny<int, 2>(n_zero, n_positive); } bool def_gt_0() const { af::tiny<int, 2> nz_np = def_test(); return nz_np[1] == 3 || (nz_np[0] == 0 && nz_np[1] == 1); } bool step() { // N1 if (b_ < a_) { n1_action(); } // N2 if (c_ < b_) { n2_action(); return true; } // N3 if (def_gt_0()) { n3_true_action(); } else { n3_false_action(); if (!significant_change_test()) { return false; } } if (b2_action()) return true; if (b3_action()) return true; if (b4_action()) return true; if (b5_action()) return true; return false; } FloatType significant_change_test(FloatType const& new_value, std::size_t i) const { FloatType m_new = multiplier_significant_change_test_ * new_value; FloatType diff = new_value - last_abc_significant_change_test_[i]; FloatType m_new_plus_diff = spoil_optimization(m_new + diff); #if defined(CCTBX_UCTBX_FAST_MINIMUM_REDUCTION_OVERZEALOUS_OPTIMIZER) { char buf[4*sizeof(FloatType)]; scitbx::serialization::base_256::floating_point ::to_string(buf, m_new_plus_diff); scitbx::serialization::base_256::floating_point ::from_string<FloatType> fs(buf); m_new_plus_diff = fs.value; } #endif FloatType m_new_plus_diff_minus_m_new = m_new_plus_diff - m_new; return m_new_plus_diff_minus_m_new != 0; } bool significant_change_test() { if ( significant_change_test(a_, 0) || significant_change_test(b_, 1) || significant_change_test(c_, 2)) { n_no_significant_change_ = 0; } else { n_no_significant_change_++; if (n_no_significant_change_ == min_n_no_significant_change_) { return false; } } last_abc_significant_change_test_ = scitbx::vec3<FloatType>(a_,b_,c_); return true; } void cb_update(scitbx::mat3<IntFromFloatType> const& m) { if (n_iterations_ == iteration_limit_) { throw error_iteration_limit_exceeded(); } r_inv_ = r_inv_ * m; n_iterations_ += 1; } void n1_action() { cb_update(scitbx::mat3<IntFromFloatType>(0,-1,0, -1,0,0, 0,0,-1)); std::swap(a_, b_); std::swap(d_, e_); } void n2_action() { cb_update(scitbx::mat3<IntFromFloatType>(-1,0,0, 0,0,-1, 0,-1,0)); std::swap(b_, c_); std::swap(e_, f_); } void n3_true_action() { scitbx::mat3<IntFromFloatType> m(1); if (d_ < 0) m[0] = -1; if (e_ < 0) m[4] = -1; if (f_ < 0) m[8] = -1; cb_update(m); d_ = scitbx::fn::absolute(d_); e_ = scitbx::fn::absolute(e_); f_ = scitbx::fn::absolute(f_); } void n3_false_action() { scitbx::mat3<IntFromFloatType> m(1); int z = -1; if (0 < d_) m[0] = -1; else if (!(d_ < 0)) z = 0; if (0 < e_) m[4] = -1; else if (!(e_ < 0)) z = 4; if (0 < f_) m[8] = -1; else if (!(f_ < 0)) z = 8; if (m[0]*m[4]*m[8] < 0) { CCTBX_ASSERT(z != -1); m[z] = -1; } cb_update(m); d_ = -scitbx::fn::absolute(d_); e_ = -scitbx::fn::absolute(e_); f_ = -scitbx::fn::absolute(f_); } bool b2_action() { if (!(b_ < scitbx::fn::absolute(d_))) return false; IntFromFloatType j = entier((d_+b_)/(2*b_)); if (j == 0) return false; cb_update(scitbx::mat3<IntFromFloatType>(1,0,0,0,1,-j,0,0,1)); c_ += j*j*b_ - j*d_; d_ -= 2*j*b_; e_ -= j*f_; if (!(0 < c_)) throw error_degenerate_unit_cell_parameters(); return true; } bool b3_action() { if (!(a_ < scitbx::fn::absolute(e_))) return false; IntFromFloatType j = entier((e_+a_)/(2*a_)); if (j == 0) return false; cb_update(scitbx::mat3<IntFromFloatType>(1,0,-j,0,1,0,0,0,1)); c_ += j*j*a_ - j*e_; d_ -= j*f_; e_ -= 2*j*a_; if (!(0 < c_)) throw error_degenerate_unit_cell_parameters(); return true; } bool b4_action() { if (!(a_ < scitbx::fn::absolute(f_))) return false; IntFromFloatType j = entier((f_+a_)/(2*a_)); if (j == 0) return false; cb_update(scitbx::mat3<IntFromFloatType>(1,-j,0,0,1,0,0,0,1)); b_ += j*j*a_ - j*f_; d_ -= j*e_; f_ -= 2*j*a_; if (!(0 < b_)) throw error_degenerate_unit_cell_parameters(); return true; } bool b5_action() { FloatType de = d_ + e_; FloatType fab = f_ + a_ + b_; if (!(de+fab < 0)) return false; IntFromFloatType j = entier((de+fab)/(2*fab)); if (j == 0) return false; cb_update(scitbx::mat3<IntFromFloatType>(1,0,-j,0,1,-j,0,0,1)); c_ += j*j*fab-j*de; d_ -= j*(2*b_+f_); e_ -= j*(2*a_+f_); if (!(0 < c_)) throw error_degenerate_unit_cell_parameters(); return true; } FloatType multiplier_significant_change_test_; std::size_t min_n_no_significant_change_; std::size_t iteration_limit_; scitbx::mat3<IntFromFloatType> r_inv_; std::size_t n_iterations_; std::size_t n_no_significant_change_; bool termination_due_to_significant_change_test_; FloatType a_, b_, c_, d_, e_, f_; scitbx::vec3<FloatType> last_abc_significant_change_test_; }; }} // namespace cctbx::uctbx #endif // CCTBX_UCTBX_FAST_MINIMUM_REDUCTION_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/uctbx/uctbx.cpp
.cpp
16,963
559
#include <cctbx/uctbx/fast_minimum_reduction.h> #include <cctbx/sgtbx/change_of_basis_op.h> #include <scitbx/math/unimodular_generator.h> #include <scitbx/array_family/tiny_algebra.h> namespace cctbx { namespace uctbx { bool unit_cell_angles_are_feasible( scitbx::vec3<double> const& values_deg, double tolerance) { for(unsigned i=0;i<3;i++) { if (values_deg[i] <= tolerance) return false; if (values_deg[i] >= 180-tolerance) return false; } double a = values_deg[0]; double b = values_deg[1]; double g = values_deg[2]; if ( a+b+g >= 360-tolerance) return false; if ( a+b-g <= tolerance) return false; if ( a-b+g <= tolerance) return false; if (-a+b+g <= tolerance) return false; return true; } namespace { void throw_corrupt_metrical_matrix() { throw std::invalid_argument("Corrupt metrical matrix."); } double dot_g(uc_vec3 const& u, uc_sym_mat3 const& g, uc_vec3 const& v) { return u * (g * v); } uc_vec3 cross_g(double sqrt_det_g, uc_sym_mat3 const& g, uc_vec3 const& r, uc_vec3 const& s) { return sqrt_det_g * (g * r).cross(g * s); } double acos_deg(double x) { return scitbx::rad_as_deg(std::acos(x)); } af::double6 parameters_from_metrical_matrix(const double* metrical_matrix) { af::double6 params; for(std::size_t i=0;i<3;i++) { if (metrical_matrix[i] <= 0.) throw_corrupt_metrical_matrix(); params[i] = std::sqrt(metrical_matrix[i]); } params[3] = acos_deg(metrical_matrix[5] / params[1] / params[2]); params[4] = acos_deg(metrical_matrix[4] / params[2] / params[0]); params[5] = acos_deg(metrical_matrix[3] / params[0] / params[1]); return params; } uc_sym_mat3 construct_metrical_matrix( af::double6 const& params, uc_vec3 const& cos_ang) { return uc_sym_mat3( params[0] * params[0], params[1] * params[1], params[2] * params[2], params[0] * params[1] * cos_ang[2], params[0] * params[2] * cos_ang[1], params[1] * params[2] * cos_ang[0]); } } // namespace <anonymous> void unit_cell::init_volume() { /* V = a * b * c * sqrt(1 - cos(alpha)^2 - cos(beta)^2 - cos(gamma)^2 + 2 * cos(alpha) * cos(beta) * cos(gamma)) */ double d = 1.; for(std::size_t i=0;i<3;i++) d -= cos_ang_[i] * cos_ang_[i]; d += 2. * cos_ang_[0] * cos_ang_[1] * cos_ang_[2]; if (d < 0.) throw std::invalid_argument( "Square of unit cell volume is negative."); volume_ = params_[0] * params_[1] * params_[2] * std::sqrt(d); if (volume_ <= 0.) throw std::invalid_argument( "Unit cell volume is zero or negative."); af::double6 &f = d_volume_d_params_; using scitbx::constants::pi_180; double factor = pi_180 * scitbx::fn::pow2(params_[0] * params_[1] * params_[2])/volume_; f[0] = volume_/params_[0]; f[1] = volume_/params_[1]; f[2] = volume_/params_[2]; f[3] = factor * sin_ang_[0] * (cos_ang_[0] - cos_ang_[1]*cos_ang_[2]); f[4] = factor * sin_ang_[1] * (cos_ang_[1] - cos_ang_[0]*cos_ang_[2]); f[5] = factor * sin_ang_[2] * (cos_ang_[2] - cos_ang_[1]*cos_ang_[0]); } void unit_cell::init_reciprocal() { // Transformation Lattice Constants -> Reciprocal Lattice Constants // after Kleber, W., 17. Aufl., Verlag Technik GmbH Berlin 1990, P.352 static const char* error_msg = "Error computing reciprocal unit cell angles."; for(std::size_t i=0;i<3;i++) r_params_[i] = params_[(i + 1) % 3] * params_[(i + 2) % 3] * sin_ang_[i] / volume_; for(std::size_t i=0;i<3;i++) { double denom = sin_ang_[(i + 1) % 3] * sin_ang_[(i + 2) % 3]; if (denom == 0) throw error (error_msg); r_cos_ang_[i] = ( cos_ang_[(i + 1) % 3] * cos_ang_[(i + 2) % 3] - cos_ang_[i]) / denom; } for(std::size_t i=0;i<3;i++) { if (r_cos_ang_[i] < -1 || r_cos_ang_[i] > 1) { throw std::invalid_argument(error_msg); } double a_rad = std::acos(r_cos_ang_[i]); r_params_[i+3] = scitbx::rad_as_deg(a_rad); r_sin_ang_[i] = std::sin(a_rad); r_cos_ang_[i] = std::cos(a_rad); } } void unit_cell::init_orth_and_frac_matrices() { // Crystallographic Basis: D = {a,b,c} // Cartesian Basis: C = {i,j,k} // // PDB convention: // i || a // j is in (a,b) plane // k = i x j double s1rca2 = std::sqrt(1. - r_cos_ang_[0] * r_cos_ang_[0]); if (s1rca2 == 0.) { throw std::invalid_argument( "Reciprocal unit cell alpha angle is zero or extremely close to zero."); } // fractional to cartesian orth_[0] = params_[0]; orth_[1] = cos_ang_[2] * params_[1]; orth_[2] = cos_ang_[1] * params_[2]; orth_[3] = 0.; orth_[4] = sin_ang_[2] * params_[1]; orth_[5] = -sin_ang_[1] * r_cos_ang_[0] * params_[2]; orth_[6] = 0.; orth_[7] = 0.; orth_[8] = sin_ang_[1] * params_[2] * s1rca2; // cartesian to fractional frac_[0] = 1. / params_[0]; frac_[1] = -cos_ang_[2] / (sin_ang_[2] * params_[0]); frac_[2] = -( cos_ang_[2] * sin_ang_[1] * r_cos_ang_[0] + cos_ang_[1] * sin_ang_[2]) / (sin_ang_[1] * s1rca2 * sin_ang_[2] * params_[0]); frac_[3] = 0.; frac_[4] = 1. / (sin_ang_[2] * params_[1]); frac_[5] = r_cos_ang_[0] / (s1rca2 * sin_ang_[2] * params_[1]); frac_[6] = 0.; frac_[7] = 0.; frac_[8] = 1. / (sin_ang_[1] * s1rca2 * params_[2]); } void unit_cell::init_metrical_matrices() { metr_mx_ = construct_metrical_matrix(params_, cos_ang_); r_metr_mx_ = construct_metrical_matrix(r_params_, r_cos_ang_); using scitbx::constants::pi_180; af::tiny_mat_ref<double, 6, 6> f(d_metrical_matrix_d_params_); f.fill(0); f(0,0) = 2*params_[0]; f(1,1) = 2*params_[1]; f(2,2) = 2*params_[2]; f(3,0) = params_[1]*cos_ang_[2]; f(3,1) = params_[0]*cos_ang_[2]; f(3,5) = -params_[0]*params_[1]*sin_ang_[2]*pi_180; f(4,0) = params_[2]*cos_ang_[1]; f(4,2) = params_[0]*cos_ang_[1]; f(4,4) = -params_[0]*params_[2]*sin_ang_[1]*pi_180; f(5,1) = params_[2]*cos_ang_[0]; f(5,2) = params_[1]*cos_ang_[0]; f(5,3) = -params_[1]*params_[2]*sin_ang_[0]*pi_180; } void unit_cell::init_tensor_rank_2_orth_and_frac_linear_maps() { uc_mat3 const &o = orthogonalization_matrix(); af::double6 &f = u_star_to_u_iso_linear_form_; f[0] = o[0]*o[0]; f[1] = o[1]*o[1] + o[4]*o[4]; f[2] = o[2]*o[2] + o[5]*o[5] + o[8]*o[8]; f[3] = 2*o[0]*o[1]; f[4] = 2*o[0]*o[2]; f[5] = 2*(o[1]*o[2] + o[4]*o[5]); f *= 1./3; af::tiny_mat_ref<double, 6, 6> L(u_star_to_u_cart_linear_map_); L.fill(0); L(0,0) = o[0]*o[0]; L(0,1) = o[1]*o[1]; L(0,2) = o[2]*o[2]; L(0,3) = 2*o[0]*o[1]; L(0,4) = 2*o[0]*o[2]; L(0,5) = 2*o[1]*o[2]; L(1,1) = o[4]*o[4]; L(1,2) = o[5]*o[5]; L(1,5) = 2*o[4]*o[5]; L(2,2) = o[8]*o[8]; L(3,1) = o[1]*o[4]; L(3,2) = o[2]*o[5]; L(3,3) = o[0]*o[4]; L(3,4) = o[0]*o[5]; L(3,5) = o[2]*o[4] + o[1]*o[5]; L(4,2) = o[2]*o[8]; L(4,4) = o[0]*o[8]; L(4,5) = o[1]*o[8]; L(5,2) = o[5]*o[8]; L(5,5) = o[4]*o[8]; af::double6 &c = u_star_to_u_cif_linear_map_; c[0] = 1./(r_params_[0] * r_params_[0]); c[1] = 1./(r_params_[1] * r_params_[1]); c[2] = 1./(r_params_[2] * r_params_[2]); c[3] = 1./(r_params_[0] * r_params_[1]); c[4] = 1./(r_params_[0] * r_params_[2]); c[5] = 1./(r_params_[1] * r_params_[2]); } void unit_cell::initialize() { std::size_t i; for(i=0;i<6;i++) { if (params_[i] <= 0.) { throw std::invalid_argument("Unit cell parameter is zero or negative."); } } for(i=3;i<6;i++) { double a_deg = params_[i]; if (a_deg >= 180.) { throw std::invalid_argument( "Unit cell angle is greater than or equal to 180 degrees."); } double a_rad = scitbx::deg_as_rad(a_deg); cos_ang_[i-3] = std::cos(a_rad); sin_ang_[i-3] = std::sin(a_rad); if (sin_ang_[i-3] == 0.) { throw std::invalid_argument( "Unit cell angle is zero or or extremely close to zero."); } } init_volume(); init_reciprocal(); init_metrical_matrices(); init_orth_and_frac_matrices(); init_tensor_rank_2_orth_and_frac_linear_maps(); longest_vector_sq_ = -1.; shortest_vector_sq_ = -1.; } unit_cell::unit_cell(af::small<double, 6> const& parameters) : params_(1,1,1,90,90,90) { std::copy(parameters.begin(), parameters.end(), params_.begin()); initialize(); } unit_cell::unit_cell(af::double6 const& parameters) : params_(parameters) { initialize(); } unit_cell::unit_cell(uc_sym_mat3 const& metrical_matrix) : params_(parameters_from_metrical_matrix(metrical_matrix.begin())) { try { initialize(); } catch (error const&) { throw_corrupt_metrical_matrix(); } } unit_cell::unit_cell(uc_mat3 const& orthogonalization_matrix) : params_(parameters_from_metrical_matrix( orthogonalization_matrix.self_transpose_times_self().begin())) { try { initialize(); } catch (error const&) { throw std::invalid_argument("Corrupt orthogonalization matrix."); } } // used by reciprocal() unit_cell::unit_cell( af::double6 const& params, af::double3 const& sin_ang, af::double3 const& cos_ang, double volume, uc_sym_mat3 const& metr_mx, af::double6 const& r_params, af::double3 const& r_sin_ang, af::double3 const& r_cos_ang, uc_sym_mat3 const& r_metr_mx) : params_(params), sin_ang_(sin_ang), cos_ang_(cos_ang), volume_(volume), metr_mx_(metr_mx), r_params_(r_params), r_sin_ang_(r_sin_ang), r_cos_ang_(r_cos_ang), r_metr_mx_(r_metr_mx), longest_vector_sq_(-1.), shortest_vector_sq_(-1.) { init_orth_and_frac_matrices(); } unit_cell unit_cell::reciprocal() const { return unit_cell( r_params_, r_sin_ang_, r_cos_ang_, 1. / volume_, r_metr_mx_, params_, sin_ang_, cos_ang_, metr_mx_); } double unit_cell::longest_vector_sq() const { if (longest_vector_sq_ < 0.) { longest_vector_sq_ = 0.; int corner[3]; for (corner[0] = 0; corner[0] <= 1; corner[0]++) for (corner[1] = 0; corner[1] <= 1; corner[1]++) for (corner[2] = 0; corner[2] <= 1; corner[2]++) { fractional<> xf; for(std::size_t i=0;i<3;i++) xf[i] = corner[i]; scitbx::math::update_max(longest_vector_sq_, length_sq(xf)); } } return longest_vector_sq_; } double unit_cell::shortest_vector_sq() const { if (shortest_vector_sq_ < 0.) { af::double6 gruber_params = fast_minimum_reduction<>(*this) .as_gruber_matrix(); shortest_vector_sq_ = gruber_params[0]; for(std::size_t i=1;i<3;i++) { scitbx::math::update_min(shortest_vector_sq_, gruber_params[i]); } } return shortest_vector_sq_; } bool unit_cell::is_degenerate(double min_min_length_over_max_length, double min_volume_over_min_length) { if (volume_ == 0) return true; double min_length = std::min(std::min(params_[0], params_[1]), params_[2]); if (volume_ < min_length * min_volume_over_min_length) return true; double max_length = std::max(std::max(params_[0], params_[1]), params_[2]); if (min_length < max_length * min_min_length_over_max_length) return true; return false; } bool unit_cell::is_similar_to(unit_cell const& other, double relative_length_tolerance, double absolute_angle_tolerance, double absolute_length_tolerance) const { using scitbx::fn::absolute; const double* l1 = params_.begin(); const double* l2 = other.params_.begin(); if (absolute_length_tolerance > 0.) { for(std::size_t i=0;i<3;i++) { if (absolute(l1[i] - l2[i]) > absolute_length_tolerance) { return false; } } } else { for(std::size_t i=0;i<3;i++) { if (absolute(std::min(l1[i], l2[i]) / std::max(l1[i], l2[i]) - 1) > relative_length_tolerance) { return false; } } } const double* a1 = l1 + 3; const double* a2 = l2 + 3; for(std::size_t i=0;i<3;i++) { if (absolute(a1[i] - a2[i]) > absolute_angle_tolerance) { return false; } } return true; } af::shared<scitbx::mat3<int> > unit_cell::similarity_transformations( unit_cell const& other, double relative_length_tolerance, double absolute_angle_tolerance, int unimodular_generator_range) const { af::shared<scitbx::mat3<int> > result; scitbx::mat3<int> identity_matrix(1); if (is_similar_to( other, relative_length_tolerance, absolute_angle_tolerance)) { result.push_back(identity_matrix); } scitbx::math::unimodular_generator<int> unimodular_generator(unimodular_generator_range); while (!unimodular_generator.at_end()) { scitbx::mat3<int> c_inv_r = unimodular_generator.next(); unit_cell other_cb = other.change_basis(uc_mat3(c_inv_r)); if (is_similar_to( other_cb, relative_length_tolerance, absolute_angle_tolerance) && c_inv_r != identity_matrix) { result.push_back(c_inv_r); } } return result; } uc_mat3 unit_cell::matrix_cart( sgtbx::rot_mx const& rot_mx) const { return orthogonalization_matrix() * rot_mx.as_double() * fractionalization_matrix(); } unit_cell unit_cell::change_basis(uc_mat3 const& c_inv_r, double r_den) const { if (r_den == 0) { return unit_cell(metr_mx_.tensor_transpose_transform(c_inv_r)); } return unit_cell(metr_mx_.tensor_transpose_transform(c_inv_r/r_den)); } unit_cell unit_cell::change_basis(sgtbx::rot_mx const& c_inv_r) const { return change_basis(c_inv_r.as_double(), 0); } unit_cell unit_cell::change_basis(sgtbx::change_of_basis_op const& cb_op) const { return change_basis(cb_op.c_inv().r().as_double(), 0); } miller::index<> unit_cell::max_miller_indices(double d_min, double tolerance) const { CCTBX_ASSERT(d_min > 0); CCTBX_ASSERT(tolerance >= 0); miller::index<> max_h; for(std::size_t i=0;i<3;i++) { uc_vec3 u(0,0,0); uc_vec3 v(0,0,0); u[(i + 1) % 3] = 1.; v[(i + 2) % 3] = 1.; // length of uxv is not used => sqrt(det(metr_mx)) is simply set to 1 uc_vec3 uxv = cross_g(1., r_metr_mx_, u, v); double uxv2 = dot_g(uxv, r_metr_mx_, uxv); CCTBX_ASSERT(uxv2 != 0); double uxv_abs = std::sqrt(uxv2); CCTBX_ASSERT(uxv_abs != 0); max_h[i] = static_cast<int>(uxv[i] / uxv_abs / d_min + tolerance); } return max_h; } int unit_cell::compare_orthorhombic( const unit_cell& other) const { af::double6 const& lhs = params_; af::double6 const& rhs = other.params_; for(std::size_t i=0;i<3;i++) { if (lhs[i] < rhs[i]) return -1; if (lhs[i] > rhs[i]) return 1; } return 0; } int unit_cell::compare_monoclinic( const unit_cell& other, unsigned unique_axis, double angular_tolerance) const { CCTBX_ASSERT(unique_axis < 3); af::double6 const& lhs = params_; af::double6 const& rhs = other.params_; double lhs_ang = lhs[unique_axis+3]; double rhs_ang = rhs[unique_axis+3]; using scitbx::fn::absolute; if (absolute(lhs_ang - rhs_ang) < angular_tolerance) { return compare_orthorhombic(other); } double lhs_ang_d90 = absolute(lhs_ang - 90); double rhs_ang_d90 = absolute(rhs_ang - 90); if (absolute(lhs_ang_d90 - rhs_ang_d90) > angular_tolerance) { if (lhs_ang_d90 < rhs_ang_d90) return -1; if (lhs_ang_d90 > rhs_ang_d90) return 1; } else { if (lhs_ang > 90 && rhs_ang < 90) return -1; if (lhs_ang < 90 && rhs_ang > 90) return 1; } if (lhs_ang > rhs_ang) return -1; if (lhs_ang < rhs_ang) return 1; return 0; } sgtbx::change_of_basis_op const& unit_cell::change_of_basis_op_for_best_monoclinic_beta() const { static const sgtbx::change_of_basis_op cb_op_identity; static const sgtbx::change_of_basis_op cb_op_acbc("a+c,b,c"); unit_cell alt = change_basis(cb_op_acbc); double beta = params_[4]; double beta_alt = alt.params_[4]; if (beta_alt >= 90 && beta_alt < beta) return cb_op_acbc; return cb_op_identity; } }} // namespace cctbx::uctbx
C++
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/uctbx/spoil_optimization.cpp
.cpp
185
7
namespace cctbx { namespace uctbx { float spoil_optimization(float value) { return value; } double spoil_optimization(double value) { return value; } }} // namespace cctbx::uctbx
C++
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/eltbx/neutron.h
.h
3,514
132
#ifndef CCTBX_ELTBX_NEUTRON_H #define CCTBX_ELTBX_NEUTRON_H #include <string> #include <complex> #include <cctbx/eltbx/xray_scattering/gaussian.h> namespace cctbx { namespace eltbx { namespace neutron { namespace detail { struct raw_record_neutron_news_1992 { const char* label; float bound_coh_scatt_length_real; float bound_coh_scatt_length_imag; float abs_cross_sect; // For 2200 m/s neutrons }; } //! Access to neutron bound scattering lengths & cross-sections. /*! Reference:<br> Neutron News, Vol. 3, No. 3, 1992, pp. 29-37. <p> http://www.ncnr.nist.gov/resources/n-lengths/list.html */ class neutron_news_1992_table { public: //! Default constructor. Calling certain methods may cause crashes! neutron_news_1992_table() : record_(0) {} //! Search internal table for the given element label. /*! If exact == true, the element label must exactly match the tabulated label. However, the lookup is not case-sensitive. <p> See also: eltbx::basic::strip_label() */ explicit neutron_news_1992_table(std::string const& label, bool exact=false); //! Tests if the instance is constructed properly. /*! Shorthand for: label() != 0 <p> Not available in Python. */ bool is_valid() const { return record_->label != 0; } //! Element label from internal table. const char* label() const { return record_->label; } //! Bound coherent scattering length (fm) as a complex number. /*! 1 fm = 1e-15 m */ std::complex<float> bound_coh_scatt_length() const { return std::complex<float>(record_->bound_coh_scatt_length_real, record_->bound_coh_scatt_length_imag); } //! Real part of bound coherent scattering length (fm). /*! 1 fm = 1e-15 m <p> Not available in Python. */ float bound_coh_scatt_length_real() const { return record_->bound_coh_scatt_length_real; } //! Imaginary part of bound coherent scattering length (fm). /*! 1 fm = 1e-15 m <p> Not available in Python. */ float bound_coh_scatt_length_imag() const { return record_->bound_coh_scatt_length_imag; } //! Absorption cross section (barn) for 2200 m/s neutrons. /*! 1 barn = 1e-24 cm^2 */ float abs_cross_sect() const { return record_->abs_cross_sect; } cctbx::eltbx::xray_scattering::gaussian fetch() const { return cctbx::eltbx::xray_scattering::gaussian(record_->bound_coh_scatt_length_real, true); } private: const detail::raw_record_neutron_news_1992* record_; friend class neutron_news_1992_table_iterator; }; /*! \brief Iterator over neutron_news_1992_table entries. */ class neutron_news_1992_table_iterator { public: //! Initialization of the iterator. neutron_news_1992_table_iterator(); //! Retrieves the next entry from the internal table. /*! Use neutron_news_1992_table_iterator::is_valid() to detect end-of-iteration. */ neutron_news_1992_table next(); private: neutron_news_1992_table current_; }; }}} // cctbx::eltbx::neutron #endif // CCTBX_ELTBX_NEUTRON_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/eltbx/xray_scattering.h
.h
11,461
354
#ifndef CCTBX_ELTBX_XRAY_SCATTERING_H #define CCTBX_ELTBX_XRAY_SCATTERING_H #include <cctbx/eltbx/basic.h> #include <cctbx/eltbx/xray_scattering/gaussian.h> #include <boost/optional.hpp> #include <boost/config.hpp> #include <stdexcept> #include <ctype.h> namespace cctbx { namespace eltbx { namespace xray_scattering { static const char *standard_labels[] = { "H", "D", "T", "Hiso", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac", "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "H1-", "D1-", "T1-", "Li1+", "Be2+", "Cval", "O1-", "O2-", "F1-", "Na1+", "Mg2+", "Al3+", "Sival", "Si4+", "Cl1-", "K1+", "Ca2+", "Sc3+", "Ti2+", "Ti3+", "Ti4+", "V2+", "V3+", "V5+", "Cr2+", "Cr3+", "Mn2+", "Mn3+", "Mn4+", "Fe2+", "Fe3+", "Co2+", "Co3+", "Ni2+", "Ni3+", "Cu1+", "Cu2+", "Zn2+", "Ga3+", "Ge4+", "Br1-", "Rb1+", "Sr2+", "Y3+", "Zr4+", "Nb3+", "Nb5+", "Mo3+", "Mo5+", "Mo6+", "Ru3+", "Ru4+", "Rh3+", "Rh4+", "Pd2+", "Pd4+", "Ag1+", "Ag2+", "Cd2+", "In3+", "Sn2+", "Sn4+", "Sb3+", "Sb5+", "I1-", "Cs1+", "Ba2+", "La3+", "Ce3+", "Ce4+", "Pr3+", "Pr4+", "Nd3+", "Pm3+", "Sm3+", "Eu2+", "Eu3+", "Gd3+", "Tb3+", "Dy3+", "Ho3+", "Er3+", "Tm3+", "Yb2+", "Yb3+", "Lu3+", "Hf4+", "Ta5+", "W6+", "Os4+", "Ir3+", "Ir4+", "Pt2+", "Pt4+", "Au1+", "Au3+", "Hg1+", "Hg2+", "Tl1+", "Tl3+", "Pb2+", "Pb4+", "Bi3+", "Bi5+", "Ra2+", "Ac3+", "Th4+", "U3+", "U4+", "U6+", "Np3+", "Np4+", "Np6+", "Pu3+", "Pu4+", "Pu6+", 0 }; inline bool is_reserved_scattering_type_label( std::string const& label) { if (label == "const") return true; if (label == "TX" || label == "XX") return true; if (label == "unknown") return true; return false; } inline void throw_if_reserved_scattering_type_label( std::string const& label) { if (is_reserved_scattering_type_label(label)) { throw std::invalid_argument( "Reserved scattering type label: \""+label+"\""); } } inline boost::optional<std::string> get_standard_label( std::string const& label, bool exact=false, bool optional=false) { if (label == "const") return boost::optional<std::string>(label); if (label == "TX" || label == "XX") return boost::optional<std::string>(label); std::string work_label = basic::strip_label(label, exact); const char* result = 0; int m = 0; for (const char **std_lbl = standard_labels; *std_lbl; std_lbl++) { int i = basic::match_labels(work_label, *std_lbl); if (i < 0 /* exact match */) { return boost::optional<std::string>(*std_lbl); } if (i > m && !isdigit((*std_lbl)[i-1])) { m = i; result = *std_lbl; } } if (exact || result == 0) { if (optional) return boost::optional<std::string>(); throw std::invalid_argument( "Unknown scattering type label: \"" + label + "\""); } return boost::optional<std::string>(result); } inline std::string replace_hydrogen_isotype_labels(std::string standard_label) { if (standard_label == "D" || standard_label == "T" ) return "H"; else if (standard_label == "D1-" || standard_label == "T1-") return "H1-"; return standard_label; } namespace detail { static const float undefined = -99999.; template <std::size_t N> struct raw_table_entry { const char* label; float a[N], b[N], c; }; } //! Coefficients for the Analytical Approximation to the Scattering Factor. /*! Used to work with coefficients from the International Tables Volume C (1992) (template parameter N = 4) and Waasmaier & Kirfel (1995), Acta Cryst. A51, 416-431 (template parameter N = 5). */ template <std::size_t N> class base { public: //! Default constructor. Calling certain methods may cause crashes! base() : table_(0), entry_(0) {} //! Constructor. For internal use only. base(const detail::raw_table_entry<N>* table_raw, const char* table, std::string const& label, bool exact); //! Tests if the instance is constructed properly. /*! Shorthand for: label() != 0 <p> Not available in Python. */ bool is_valid() const { return entry_->label != 0; } //! Label of table. Either "IT1992" or "WK1995". const char* table() const { return table_; } //! Scattering factor label. E.g. "Si4+". const char* label() const { return entry_->label; } //! Fetches the Gaussian terms from the static table. gaussian fetch() const { typedef af::small<double, gaussian::max_n_terms> small_t; return gaussian( small_t(entry_->a, entry_->a+N), small_t(entry_->b, entry_->b+N), entry_->c, true); } protected: const char *table_; const detail::raw_table_entry<N>* entry_; void next_entry(); }; // non-inline constructor template <std::size_t N> base<N>::base(const detail::raw_table_entry<N>* table_raw, const char* table, std::string const& label, bool exact) : table_(table), entry_(0) { throw_if_reserved_scattering_type_label(label); std::string std_lbl = replace_hydrogen_isotype_labels( *get_standard_label(label, exact)); for (const detail::raw_table_entry<N>* entry = table_raw; entry->label; entry++) { if (entry->label == std_lbl) { entry_ = entry; break; } } if (entry_ == 0) { throw std::invalid_argument( "Unknown scattering type label: \"" + label + "\""); } } // non-inline member function template <std::size_t N> void base<N>::next_entry() { if (is_valid()) entry_++; } //! Coefficients for the Analytical Approximation to the Scattering Factor. /*! Coefficients from the International Tables for Crystallography, Volume C, Mathematical, Physical and Chemical Tables, Edited by A.J.C. Wilson, Kluwer Academic Publishers, Dordrecht/Boston/London, 1992. <p> Table 6.1.1.4 (pp. 500-502): Coefficients for analytical approximation to the scattering factors of Tables 6.1.1.1 and 6.1.1.3. <p> Table 6.1.1.4 is a reprint of Table 2.2B, pp. 99-101, International Tables for X-ray Crystallography, Volume IV, The Kynoch Press: Birmingham, England, 1974. There is just one difference for <tt>Tl3+</tt>:<pre> IT Vol IV 1974: a2 = 18.3841 IT Vol C 1992: a2 = 18.3481</pre> <p> The value from IT Vol IV is presumed to be the correct one and used here. <p> If possible, the class xray_scattering::wk1995 should be used instead of this class. The coefficients of Waasmaier & Kirfel give more precise approximations than the coefficients of Volume C and some errors are corrected. <p> See also: xray_scattering::it1992_iterator, xray_scattering::wk1995, xray_scattering::base */ class it1992: public base<4> { public: //! Facilitates meta-programming. typedef base<4> base_type; //! Default constructor. Calling certain methods may cause crashes! it1992() {} //! Looks up coefficients for the given scattering factor label. /*! If exact == true, the scattering factor label must exactly match the tabulated label. However, the lookup is not case-sensitive.<br> E.g., "SI4" will be matched with "Si".<br> "Si4+" and "Si+4" will be matched with "Si4+".<br> See also: eltbx::basic::strip_label() <p> Note that the other methods of this class are inherited from class xray_scattering::base. */ it1992(std::string const& label, bool exact=false); protected: friend class it1992_iterator; }; /*! \brief Iterator over table of Coefficients for the Analytical Approximation to the Scattering Factor, International Tables 1992. */ class it1992_iterator { public: //! Initialization of the iterator. it1992_iterator(); //! Retrieves the next entry from the internal table. /*! Use it1992::is_valid() to detect end-of-iteration. */ it1992 next(); private: it1992 current_; }; //! Coefficients for the Analytical Approximation to the Scattering Factor. /*! Coefficients from Waasmaier & Kirfel (1995), Acta Cryst. A51, 416-431. <p> The original data can be found at: <pre> ftp://wrzx02.rz.uni-wuerzburg.de/pub/local/Crystallography/sfac.dat </pre> File picked up Jul 4, 1995. File verified Sep 12, 2001. <p> Header of "sfac.dat": <pre> - Fitparameters of all atoms/ions (with the excepetion of O1-) from publication "New Analytical Scattering Factor Functions for Free Atoms and Ions", D. Waasmaier & A. Kirfel, Acta Cryst. A 1995, in press) - Fit for O1- based on the tabulated values of Table 2 (D.REZ, P.REZ & I.GRANT, Acta Cryst. (1994), A50, 481-497). - Fits for all other atoms/ions based on the tabulated values of Table 6.1.1.1 (atoms) and Table 6.1.1.3 (ions) (International Tables for Crystallography, Vol. C, 1992). </pre> <p> See also: xray_scattering::wk1995_iterator, xray_scattering::it1992, xray_scattering::base */ class wk1995: public base<5> { public: //! Facilitates meta-programming. typedef base<5> base_type; //! Default constructor. Calling certain methods may cause crashes! wk1995() {} //! Looks up coefficients for the given scattering factor label. /*! If exact == true, the scattering factor label must exactly match the tabulated label. However, the lookup is not case-sensitive.<br> E.g., "SI4" will be matched with "Si".<br> "Si4+" and "Si+4" will be matched with "Si4+".<br> See also: eltbx::basic::strip_label() <p> Note that the other methods of this class are inherited from class base. */ wk1995(std::string const& label, bool exact=false); protected: friend class wk1995_iterator; }; /*! \brief Iterator over table of Coefficients for the Analytical Approximation to the Scattering Factor, Waasmaier & Kirfel 1995. */ class wk1995_iterator { public: //! Initialization of the iterator. wk1995_iterator(); //! Retrieves the next entry from the internal table. /*! Use wk1995::is_valid() to detect end-of-iteration. */ wk1995 next(); private: wk1995 current_; }; }}} // cctbx::eltbx::xray_scattering #endif // CCTBX_ELTBX_XRAY_SCATTERING_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/eltbx/electron_scattering.h
.h
2,870
91
#ifndef CCTBX_ELECTRON_SCATTERING_H #define CCTBX_ELECTRON_SCATTERING_H #include <cctbx/eltbx/basic.h> #include <cctbx/eltbx/xray_scattering.h> #include <boost/optional.hpp> #include <boost/config.hpp> #include <stdexcept> #include <ctype.h> namespace cctbx { namespace eltbx { namespace electron_scattering { //! Coefficients for the Electron Scattering Factor. /* <p> 2008-06-30, translated by L. Lutterotti from L.-M. PENG, G. REN, S. L. DUDAREV & M. J. WHELAN Robust Parameterization of Elastic and Absorptive Electron Atomic Scattering Factors J. Appl. Cryst. A52, 257-276 1996 and L.-M. PENG Electron Scattering Factors of Ions and their Parameterization J. Appl. Cryst. A54, 481-485 1998 Electron scattering factors for atoms up to 6.0 Angstrom^-1 <p> See also: electron_scattering::peng19965_iterator, electron_scattering::peng1996, xray_scattering::base ****** Practical note (adopted from Dorothee Liebschner): ****** To use these parameters one needs to implement the divergent contribution from the unscreened Coulomb potential of the ionic charge. See formula 4 in Acta Cryst. (1998). A54, 481-485. This term is not available in our code. It isn't clear how to do the Fourier Transform of this. So unless we figure this out and make this available, we cannot use the form factors of ions from Peng. The efforts from UCLA people was to approximate the curves for the ions using negative coefficients. Then the divergent charge term is not needed. */ class peng1996: public xray_scattering::base<5> { public: //! Facilitates meta-programming. typedef xray_scattering::base<5> base_type; //! Default constructor. Calling certain methods may cause crashes! peng1996() {} //! Looks up coefficients for the given scattering factor label. /*! If exact == true, the scattering factor label must exactly match the tabulated label. However, the lookup is not case-sensitive.<br> E.g., "SI4" will be matched with "Si".<br> "Si4+" and "Si+4" will be matched with "Si4+".<br> See also: eltbx::basic::strip_label() <p> Note that the other methods of this class are inherited from class base. */ peng1996(std::string const& label, bool exact=false); protected: friend class peng1996_iterator; }; /*! \brief Iterator over table of Coefficients for the Analytical Approximation to the Scattering Factor, Waasmaier & Kirfel 1995. */ class peng1996_iterator { public: //! Initialization of the iterator. peng1996_iterator(); //! Retrieves the next entry from the internal table. /*! Use peng1996::is_valid() to detect end-of-iteration. */ peng1996 next(); private: peng1996 current_; }; }}} // cctbx::eltbx::electron_scattering #endif
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/eltbx/basic.cpp
.cpp
1,293
54
#include <cctbx/eltbx/basic.h> #include <cstddef> #include <ctype.h> namespace cctbx { namespace eltbx { namespace basic { std::string strip_label(std::string const& label, bool exact) { std::string result; std::string::const_iterator l; for (l = label.begin(); l != label.end(); l++) { if (!isspace(*l)) break; } char digit = '\0'; for (; l != label.end(); l++) { if (isspace(*l)) { break; } if (isdigit(*l)) { if (digit != '\0') break; digit = *l; } else if (*l == '+' || *l == '-') { if (digit == '\0') digit = '1'; result += digit; result += *l++; break; } else if (digit != '\0') { break; } else { result += toupper(*l); } } if (exact && l != label.end() && !isspace(*l)) { return ""; } return result; } int match_labels(std::string const& work_label, const char* tab_label) { int i; for (i = 0; i < work_label.size() && tab_label[i]; i++) if (work_label[i] != toupper(tab_label[i])) break; if (i == work_label.size() && tab_label[i] == '\0') return -i; if (i == 1 && isalpha(tab_label[1])) return 0; return i; } }}} // namespace cctbx::eltbx::basic
C++
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/eltbx/neutron.cpp
.cpp
4,453
154
#include <cctbx/eltbx/neutron.h> #include <cctbx/eltbx/basic.h> namespace cctbx { namespace eltbx { namespace neutron { namespace detail { namespace { /* Neutron bound scattering lengths & cross-sections Data from: http://www.ncnr.nist.gov/resources/n-lengths/list.html All of this data was taken from the Special Feature section of neutron scattering lengths and cross sections of the elements and their isotopes in Neutron News, Vol. 3, No. 3, 1992, pp. 29-37. */ const raw_record_neutron_news_1992 table[] = { // BEGIN_COMPILED_IN_REFERENCE_DATA {"H", -3.7390, 0, 0.3326}, {"D", 6.671, 0, 0.000519}, {"He", 3.26, 0, 0.00747}, {"Li", -1.90, 0, 70.5}, {"Be", 7.79, 0, 0.0076}, {"B", 5.30, -0.213, 767.}, {"C", 6.6460, 0, 0.0035}, {"N", 9.36, 0, 1.9}, {"O", 5.803, 0, 0.00019}, {"F", 5.654, 0, 0.0096}, {"Ne", 4.566, 0, 0.039}, {"Na", 3.63, 0, 0.53}, {"Mg", 5.375, 0, 0.063}, {"Al", 3.449, 0, 0.231}, {"Si", 4.1491, 0, 0.171}, {"P", 5.13, 0, 0.172}, {"S", 2.847, 0, 0.53}, {"Cl", 9.5770, 0, 33.5}, {"Ar", 1.909, 0, 0.675}, {"K", 3.67, 0, 2.1}, {"Ca", 4.70, 0, 0.43}, {"Sc", 12.29, 0, 27.5}, {"Ti", -3.438, 0, 6.09}, {"V", -0.3824, 0, 5.08}, {"Cr", 3.635, 0, 3.05}, {"Mn", -3.73, 0, 13.3}, {"Fe", 9.45, 0, 2.56}, {"Co", 2.49, 0, 37.18}, {"Ni", 10.3, 0, 4.49}, {"Cu", 7.718, 0, 3.78}, {"Zn", 5.680, 0, 1.11}, {"Ga", 7.288, 0, 2.75}, {"Ge", 8.185, 0, 2.2}, {"As", 6.58, 0, 4.5}, {"Se", 7.970, 0, 11.7}, {"Br", 6.795, 0, 6.9}, {"Kr", 7.81, 0, 25.}, {"Rb", 7.09, 0, 0.38}, {"Sr", 7.02, 0, 1.28}, {"Y", 7.75, 0, 1.28}, {"Zr", 7.16, 0, 0.185}, {"Nb", 7.054, 0, 1.15}, {"Mo", 6.715, 0, 2.48}, {"Tc", 6.8, 0, 20.}, {"Ru", 7.03, 0, 2.56}, {"Rh", 5.88, 0, 144.8}, {"Pd", 5.91, 0, 6.9}, {"Ag", 5.922, 0, 63.3}, {"Cd", 4.87, -0.70, 2520.}, {"In", 4.065, -0.0539, 193.8}, {"Sn", 6.225, 0, 0.626}, {"Sb", 5.57, 0, 4.91}, {"Te", 5.80, 0, 4.7}, {"I", 5.28, 0, 6.15}, {"Xe", 4.92, 0, 23.9}, {"Cs", 5.42, 0, 29.0}, {"Ba", 5.07, 0, 1.1}, {"La", 8.24, 0, 8.97}, {"Ce", 4.84, 0, 0.63}, {"Pr", 4.58, 0, 11.5}, {"Nd", 7.69, 0, 50.5}, {"Pm", 12.6, 0, 168.4}, {"Sm", 0.80, -1.65, 5922.}, {"Eu", 7.22, -1.26, 4530.}, {"Gd", 6.5, -13.82, 49700.}, {"Tb", 7.38, 0, 23.4}, {"Dy", 16.9, -0.276, 994.}, {"Ho", 8.01, 0, 64.7}, {"Er", 7.79, 0, 159.}, {"Tm", 7.07, 0, 100.}, {"Yb", 12.43, 0, 34.8}, {"Lu", 7.21, 0, 74.}, {"Hf", 7.7, 0, 104.1}, {"Ta", 6.91, 0, 20.6}, {"W", 4.86, 0, 18.3}, {"Re", 9.2, 0, 89.7}, {"Os", 10.7, 0, 16}, {"Ir", 10.6, 0, 425.}, {"Pt", 9.60, 0, 10.3}, {"Au", 7.63, 0, 98.65}, {"Hg", 12.692, 0, 372.3}, {"Tl", 8.776, 0, 3.43}, {"Pb", 9.405, 0, 0.171}, {"Bi", 8.532, 0, 0.0338}, {"Th", 10.31, 0, 7.37}, {"U", 8.417, 0, 7.57}, {0, 0, 0, 0} // END_COMPILED_IN_REFERENCE_DATA }; const raw_record_neutron_news_1992* find_record(std::string const& work_label, bool exact) { int m = 0; const raw_record_neutron_news_1992* matching_record = 0; for (const raw_record_neutron_news_1992* r=table; r->label; r++) { int i = basic::match_labels(work_label, r->label); if (i < 0) return r; if (i > m) { m = i; matching_record = r; } } if (exact || !matching_record) { throw std::invalid_argument("Unknown element label:" + work_label); } return matching_record; } } // namespace <anonymous> } // namespace detail neutron_news_1992_table::neutron_news_1992_table(std::string const& label, bool exact) { std::string work_label = basic::strip_label(label, exact); record_ = detail::find_record(work_label, exact); } neutron_news_1992_table_iterator::neutron_news_1992_table_iterator() : current_("H", true) {} neutron_news_1992_table neutron_news_1992_table_iterator::next() { neutron_news_1992_table result = current_; if (current_.is_valid()) current_.record_++; return result; } }}} // namespace cctbx::eltbx::neutron
C++
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/eltbx/basic.h
.h
1,863
50
#ifndef CCTBX_ELTBX_BASIC_H #define CCTBX_ELTBX_BASIC_H #include <cctbx/error.h> namespace cctbx { //! Element Toolbox namespace. /*! The eltbx is a collection of tables of various x-ray and neutron scattering factors, element names, atomic numbers, atomic weights, ionic radii, and characteristic x-ray wavelengths. Associated with each table are procedures for accessing the tabulated data, e.g. by using interpolation. */ namespace eltbx { namespace basic { //! Strips element label, scattering factor label, or ion label. /*! For internal use only. <p> Returns leading part of atom label. Ignores leading whitespace. Copies input label starting at first non-whitespace. Copying stops at whitespace, second digit, or the characters "+" or "-". Lower case letters are converted to upper case.<br> "na+" is converted to "NA1+", i.e. "1" is implicit.<br> "Si4+A" is converted to "SI4+". <p> If exact == true, copying must stop at a whitespace or end-of-string. Otherwise the empty string is returned. For example, with exact == true "Si4+A" is converted to "". */ std::string strip_label(std::string const& Label, bool exact = false); //! Compares an input label with a label from an internal table. /*! For internal use only. <p> Comparison is case-insensitive.<br> If the labels match exactly, the return value is the number of matching characters multiplied by -1.<br> If only the first characters match and the second character of tab_label is a letter, the return value is 0.<br> Otherwise the return value is the number of matching characters. */ int match_labels(std::string const& work_label, const char* tab_label); }}} // namespace cctbx::eltbx::basic #endif // CCTBX_ELTBX_BASIC_H
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/eltbx/electron_scattering/peng1996.cpp
.cpp
32,880
671
#include <cctbx/eltbx/electron_scattering.h> namespace cctbx { namespace eltbx { namespace electron_scattering { namespace { /* peng1996_raw_table contains the reformatted data 2008-06-30, translated by L. Lutterotti from L.-M. PENG, G. REN, S. L. DUDAREV & M. J. WHELAN Robust Parameterization of Elastic and Absorptive Electron Atomic Scattering Factors J. Appl. Cryst. A52, 257-276 1996 and L.-M. PENG Electron Scattering Factors of Ions and their Parameterization J. Appl. Cryst. A54, 481-485 1998 Electron scattering factors for atoms up to 6.0 Angstrom^-1 */ static const xray_scattering::detail::raw_table_entry<5> peng1996_raw_table[] = { // BEGIN_COMPILED_IN_REFERENCE_DATA { "H", { 0.0088, 0.0449, 0.1481, 0.2356, 0.0914 }, { 0.1152, 1.0867, 4.9755, 16.5591, 43.2743 }, 0 }, { "He", { 0.0084, 0.0443, 0.1314, 0.1671, 0.0666 }, { 0.0596, 0.536, 2.4274, 7.7852, 20.3126 }, 0 }, { "Li", { 0.0478, 0.2048, 0.5253, 1.5225, 0.9853 }, { 0.2258, 2.1032, 12.9349, 50.7501, 136.628 }, 0 }, { "Be", { 0.0423, 0.1874, 0.6019, 1.4311, 0.7891 }, { 0.1445, 1.418, 8.1165, 27.9705, 74.8684 }, 0 }, { "B", { 0.0436, 0.1898, 0.6788, 1.3273, 0.5544 }, { 0.1207, 1.1595, 6.2474, 21.046, 59.3619 }, 0 }, { "C", { 0.0489, 0.2091, 0.7537, 1.142, 0.3555 }, { 0.114, 1.0825, 5.4281, 17.8811, 51.1341 }, 0 }, { "N", { 0.0267, 0.1328, 0.5301, 1.102, 0.4215 }, { 0.0541, 0.5165, 2.8207, 10.6297, 34.3764 }, 0 }, { "O", { 0.0365, 0.1729, 0.5805, 0.8814, 0.3121 }, { 0.0652, 0.6184, 2.9449, 9.6298, 28.2194 }, 0 }, { "F", { 0.0382, 0.1822, 0.5972, 0.7707, 0.213 }, { 0.0613, 0.5753, 2.6858, 8.8214, 25.6668 }, 0 }, { "Ne", { 0.038, 0.1785, 0.5494, 0.6942, 0.1918 }, { 0.0554, 0.5087, 2.2639, 7.3316, 21.6912 }, 0 }, { "Na", { 0.126, 0.6442, 0.8893, 1.8197, 1.2988 }, { 0.1684, 1.715, 8.8386, 50.8265, 147.2073 }, 0 }, { "Mg", { 0.113, 0.5575, 0.9046, 2.158, 1.4735 }, { 0.1356, 1.3579, 6.9255, 32.3165, 92.113 }, 0 }, { "Al", { 0.1165, 0.5504, 1.0179, 2.6295, 1.5711 }, { 0.1295, 1.2619, 6.8242, 28.4577, 88.475 }, 0 }, { "Si", { 0.0567, 0.3365, 0.8104, 2.496, 2.1186 }, { 0.0582, 0.6155, 3.2522, 16.7929, 57.6767 }, 0 }, { "P", { 0.1005, 0.4615, 1.0663, 2.5854, 1.2725 }, { 0.0977, 0.9084, 4.9654, 18.5471, 54.3648 }, 0 }, { "S", { 0.0915, 0.4312, 1.0847, 2.4671, 1.0852 }, { 0.0838, 0.7788, 4.3462, 15.5846, 44.63655 }, 0 }, { "Cl", { 0.0799, 0.3891, 1.0037, 2.3332, 1.0507 }, { 0.0694, 0.6443, 3.5351, 12.5058, 35.8633 }, 0 }, { "Ar", { 0.1044, 0.4551, 1.4232, 2.1533, 0.4459 }, { 0.0853, 0.7701, 4.4684, 14.5864, 41.2474 }, 0 }, { "K", { 0.2149, 0.8703, 2.4999, 2.3591, 3.0318 }, { 0.166, 1.6906, 8.7447, 46.7825, 165.6923 }, 0 }, { "Ca", { 0.2355, 0.9916, 2.3959, 3.7252, 2.5647 }, { 0.1742, 1.8329, 8.8407, 47.4583, 134.9613 }, 0 }, { "Sc", { 0.4636, 2.0802, 2.9003, 1.4193, 2.4323 }, { 0.3682, 4.0312, 22.6493, 71.82, 103.3691 }, 0 }, { "Ti", { 0.2123, 0.896, 2.1765, 3.0436, 2.4439 }, { 0.1399, 1.4568, 6.7534, 33.1168, 101.8238 }, 0 }, { "V", { 0.2369, 1.0774, 2.1894, 3.0825, 1.719 }, { 0.1505, 1.6392, 7.5691, 36.8741, 107.8517 }, 0 }, { "Cr", { 0.197, 0.8228, 2.02, 2.1717, 1.7516 }, { 0.1197, 1.1985, 5.4097, 25.2361, 94.429 }, 0 }, { "Mn", { 0.1943, 0.819, 1.9296, 2.4968, 2.0625 }, { 0.1135, 1.1313, 5.0341, 24.1798, 80.5598 }, 0 }, { "Fe", { 0.1929, 0.8239, 1.8689, 2.3694, 1.906 }, { 0.1087, 1.0806, 4.7637, 22.85, 76.7309 }, 0 }, { "Co", { 0.2186, 0.9861, 1.854, 2.3258, 1.4685 }, { 0.1182, 1.23, 5.4177, 25.7602, 80.8542 }, 0 }, { "Ni", { 0.2313, 1.0657, 1.8229, 2.2609, 1.1883 }, { 0.121, 1.2691, 5.687, 27.0917, 83.0285 }, 0 }, { "Cu", { 0.3501, 1.6558, 1.9582, 0.2134, 1.4109 }, { 0.1867, 1.9917, 11.3396, 53.2619, 63.252 }, 0 }, { "Zn", { 0.178, 0.8096, 1.6744, 1.9499, 1.4495 }, { 0.0876, 0.865, 3.8612, 18.8726, 64.7016 }, 0 }, { "Ga", { 0.2135, 0.9768, 1.6669, 2.5662, 1.679 }, { 0.102, 1.0219, 4.6275, 22.8742, 80.1535 }, 0 }, { "Ge", { 0.2135, 0.9761, 1.6555, 2.8938, 1.6356 }, { 0.0989, 0.9845, 4.5527, 21.5563, 70.3903 }, 0 }, { "As", { 0.2059, 0.9518, 1.6372, 3.049, 1.4756 }, { 0.0926, 0.9182, 4.3291, 19.2996, 58.9329 }, 0 }, { "Se", { 0.1574, 0.7614, 1.4834, 3.0016, 1.7978 }, { 0.0686, 0.6808, 3.1163, 14.3458, 44.0455 }, 0 }, { "Br", { 0.1899, 0.8983, 1.6358, 3.1845, 1.15183 }, { 0.081, 0.7957, 3.9054, 15.7701, 45.6124 }, 0 }, { "Kr", { 0.1742, 0.8447, 1.5944, 3.1507, 1.1338 }, { 0.0723, 0.7123, 3.5192, 13.7724, 39.1148 }, 0 }, { "Rb", { 0.3781, 1.4904, 3.5753, 3.0031, 3.3272 }, { 0.1557, 1.5347, 9.9947, 51.4251, 185.9828 }, 0 }, { "Sr", { 0.3723, 1.4598, 3.5124, 4.4612, 3.3031 }, { 0.148, 1.4643, 9.232, 49.8807, 148.0937 }, 0 }, { "Y", { 0.3234, 1.2737, 3.2115, 4.0563, 3.7962 }, { 0.1244, 1.1948, 7.2756, 34.143, 111.2079 }, 0 }, { "Zr", { 0.2997, 1.1879, 3.1075, 3.974, 3.5769 }, { 0.1121, 1.0638, 6.3891, 28.7081, 97.4289 }, 0 }, { "Nb", { 0.168, 0.937, 2.73, 3.815, 3.0053 }, { 0.0597, 0.6524, 4.4317, 19.554, 85.5011 }, 0 }, { "Mo", { 0.3069, 1.1714, 3.2293, 3.4254, 2.1224 }, { 0.1101, 1.0222, 5.9613, 25.1965, 93.5831 }, 0 }, { "Tc", { 0.2928, 1.1267, 3.1675, 3.6619, 2.5942 }, { 0.102, 0.9481, 5.4713, 23.8153, 82.8991 }, 0 }, { "Ru", { 0.2604, 1.0442, 3.0761, 3.2175, 1.9448 }, { 0.0887, 0.824, 4.8278, 19.8977, 80.4566 }, 0 }, { "Rh", { 0.2713, 1.0556, 3.1416, 3.0451, 1.7179 }, { 0.0907, 0.8324, 4.7702, 19.7862, 80.254 }, 0 }, { "Pd", { 0.2003, 0.8779, 2.6135, 2.8594, 1.0258 }, { 0.0659, 0.6111, 3.5563, 12.7638, 44.4283 }, 0 }, { "Ag", { 0.2739, 1.0503, 3.1564, 2.7543, 1.4328 }, { 0.0881, 0.8028, 4.4451, 18.7011, 79.2633 }, 0 }, { "Cd", { 0.3072, 1.1303, 3.2046, 2.9329, 1.656 }, { 0.0966, 0.8856, 4.6273, 20.6789, 73.4723 }, 0 }, { "In", { 0.3564, 1.3011, 3.2424, 3.4839, 2.0459 }, { 0.1091, 1.0452, 5.09, 24.6578, 88.0513 }, 0 }, { "Sn", { 0.2966, 1.1157, 3.0973, 3.8156, 2.5281 }, { 0.0896, 0.8268, 4.2242, 20.69, 71.3399 }, 0 }, { "Sb", { 0.2725, 1.0651, 2.994, 4.0697, 2.5682 }, { 0.0809, 0.7488, 3.871, 18.88, 60.6499 }, 0 }, { "Te", { 0.2422, 0.9692, 2.8114, 4.1509, 2.8161 }, { 0.0708, 0.6472, 3.3609, 16.0752, 50.1724 }, 0 }, { "I", { 0.2617, 1.0325, 2.8097, 4.4809, 2.319 }, { 0.0749, 0.6914, 3.4634, 16.3603, 48.2522 }, 0 }, { "Xe", { 0.2334, 0.9496, 2.6381, 4.468, 2.502 }, { 0.0655, 0.605, 3.0389, 14.0809, 41.0005 }, 0 }, { "Cs", { 0.5713, 2.4866, 4.9795, 4.0198, 4.4403 }, { 0.1626, 1.8213, 11.1049, 49.0568, 202.9987 }, 0 }, { "Ba", { 0.5229, 2.2874, 4.7243, 5.0807, 5.6389 }, { 0.1434, 1.6019, 9.4511, 42.7685, 148.4969 }, 0 }, { "La", { 0.5461, 2.3856, 5.0653, 5.7601, 4.0463 }, { 0.1479, 1.6552, 10.0059, 47.3245, 145.8464 }, 0 }, { "Ce", { 0.2227, 1.076, 2.9482, 5.8496, 7.1834 }, { 0.0571, 0.5946, 3.2022, 16.4253, 95.703 }, 0 }, { "Pr", { 0.5237, 2.2913, 4.6161, 4.7233, 4.8173 }, { 0.136, 1.5068, 8.8213, 41.9536, 141.2424 }, 0 }, { "Nd", { 0.5368, 2.3301, 4.6058, 4.6621, 4.4622 }, { 0.1378, 1.514, 8.8719, 43.5967, 141.8065 }, 0 }, { "Pm", { 0.5232, 2.2627, 4.4552, 4.4787, 4.5073 }, { 0.1317, 1.4336, 8.3087, 40.601, 135.9196 }, 0 }, { "Sm", { 0.5162, 2.2302, 4.3449, 4.3598, 4.4292 }, { 0.1279, 1.3811, 7.9629, 39.1213, 132.7846 }, 0 }, { "Eu", { 0.5272, 2.2844, 4.3361, 4.3178, 4.0908 }, { 0.1285, 1.3943, 8.1081, 40.9631, 134.1233 }, 0 }, { "Gd", { 0.9664, 3.4052, 5.0803, 1.4991, 4.2528 }, { 0.2641, 2.6586, 16.2213, 80.206, 92.5359 }, 0 }, { "Tb", { 0.511, 2.157, 4.0308, 3.9936, 4.2466 }, { 0.121, 1.2704, 7.1368, 35.0354, 123.5062 }, 0 }, { "Dy", { 0.4974, 2.1097, 3.8906, 3.81, 4.3084 }, { 0.1157, 1.2108, 6.7377, 32.415, 116.9225 }, 0 }, { "Ho", { 0.4679, 1.9693, 3.7191, 3.9632, 4.2432 }, { 0.1069, 1.0994, 5.9769, 27.1491, 96.3119 }, 0 }, { "Er", { 0.5034, 2.1088, 3.8232, 3.7299, 3.8963 }, { 0.1141, 1.1769, 6.6087, 33.4332, 116.4913 }, 0 }, { "Tm", { 0.4839, 2.0262, 3.6851, 3.5874, 4.0037 }, { 0.1081, 1.1012, 6.1114, 30.3728, 110.5988 }, 0 }, { "Yb", { 0.5221, 2.1695, 3.7567, 3.6685, 3.4274 }, { 0.1148, 1.186, 6.752, 35.6807, 118.0692 }, 0 }, { "Lu", { 0.468, 1.9466, 3.5428, 3.849, 3.6594 }, { 0.1015, 1.0195, 5.6058, 27.4899, 95.2846 }, 0 }, { "Hf", { 0.4048, 1.737, 3.3399, 3.9448, 3.7293 }, { 0.0868, 0.8585, 4.6378, 21.69, 80.2408 }, 0 }, { "Ta", { 0.3835, 1.6747, 3.2986, 4.0462, 3.4303 }, { 0.081, 0.802, 4.3545, 19.9644, 73.6337 }, 0 }, { "W", { 0.3661, 1.6191, 3.2455, 4.0856, 3.2064 }, { 0.0761, 0.7543, 4.0952, 18.2886, 68.0967 }, 0 }, { "Re", { 0.3933, 1.6973, 3.4202, 4.1274, 2.6158 }, { 0.0806, 0.7972, 4.4237, 19.5692, 68.7477 }, 0 }, { "Os", { 0.3854, 1.6555, 3.4129, 4.1111, 2.4106 }, { 0.0787, 0.7638, 4.2441, 18.37, 65.1071 }, 0 }, { "Ir", { 0.351, 1.562, 3.2946, 4.0615, 2.4382 }, { 0.0706, 0.6904, 3.8266, 16.0812, 58.7638 }, 0 }, { "Pt", { 0.3083, 1.4158, 2.9662, 3.9349, 2.1709 }, { 0.0609, 0.5993, 3.1921, 12.5285, 49.7675 }, 0 }, { "Au", { 0.3055, 1.3945, 2.9617, 3.899, 2.0026 }, { 0.0596, 0.5827, 3.1035, 11.9693, 47.9106 }, 0 }, { "Hg", { 0.3593, 1.5736, 3.5237, 3.8109, 1.6953 }, { 0.0694, 0.6758, 3.8457, 15.6203, 56.6614 }, 0 }, { "Tl", { 0.3511, 1.5489, 3.5676, 4.09, 2.5251 }, { 0.0672, 0.6522, 3.742, 15.9791, 65.1354 }, 0 }, { "Pb", { 0.354, 1.5453, 3.5975, 4.3152, 2.7743 }, { 0.0668, 0.6465, 3.6968, 16.2056, 61.4909 }, 0 }, { "Bi", { 0.353, 1.5258, 3.5815, 4.5532, 3.0714 }, { 0.0661, 0.6324, 3.5906, 15.9962, 57.576 }, 0 }, { "Po", { 0.3673, 1.5772, 3.7079, 4.8582, 2.844 }, { 0.0678, 0.6527, 3.7396, 17.0668, 55.9789 }, 0 }, { "At", { 0.3547, 1.5206, 3.5621, 5.0184, 3.0075 }, { 0.0649, 0.6188, 3.4696, 15.609, 49.4818 }, 0 }, { "Rn", { 0.4586, 1.7781, 3.9877, 5.7273, 1.546 }, { 0.0831, 0.784, 4.3599, 20.0128, 62.1535 }, 0 }, { "Fr", { 0.8282, 2.9941, 5.6597, 4.9292, 4.2889 }, { 0.1515, 1.6163, 9.7752, 42.848, 190.7366 }, 0 }, { "Ra", { 1.4129, 4.4269, 7.046, -1.0573, 8.643 }, { 0.2921, 3.1381, 19.6767, 102.0436, 113.9798 }, 0 }, { "Ac", { 0.7169, 2.571, 5.1791, 6.3484, 5.6474 }, { 0.1263, 1.29, 7.3686, 32.449, 118.0558 }, 0 }, { "Th", { 0.6958, 2.4936, 5.1269, 6.6988, 5.0799 }, { 0.1211, 1.2247, 6.9398, 30.0991, 105.196 }, 0 }, { "Pa", { 1.2502, 4.2284, 7.0489, 1.139, 5.8222 }, { 0.2415, 2.6442, 16.3313, 73.5757, 91.9401 }, 0 }, { "U", { 0.641, 2.2643, 4.8713, 5.9287, 5.3935 }, { 0.1097, 1.0644, 5.7907, 25.0261, 101.3899 }, 0 }, { "Np", { 0.6938, 2.4652, 5.1227, 5.5965, 4.8543 }, { 0.1171, 1.1757, 6.4053, 27.5217, 103.0482 }, 0 }, { "Pu", { 0.6902, 2.4509, 5.1284, 5.0339, 4.8575 }, { 0.1153, 1.1545, 6.2291, 27.0741, 111.315 }, 0 }, { "Am", { 0.7577, 2.7264, 5.4184, 4.8198, 4.1013 }, { 0.1257, 1.3044, 7.1035, 32.4649, 118.8647 }, 0 }, { "Cm", { 0.7567, 2.7565, 5.4364, 5.1918, 3.5643 }, { 0.1239, 1.2979, 7.0798, 32.7871, 110.1512 }, 0 }, { "Bk", { 0.7492, 2.7267, 5.3521, 5.0369, 3.5321 }, { 0.1217, 1.2651, 6.8101, 31.6088, 106.4853 }, 0 }, { "Cf", { 0.81, 3.0001, 5.4635, 4.1756, 3.5066 }, { 0.131, 1.4038, 7.6057, 34.0186, 90.5226 }, 0 }, // ion now { "H1-", { 1.40E-01, 6.49E-01, 1.37E+00, 3.37E-01, 7.87E-01 }, { 9.84E-01, 8.67E+00, 3.89E+01, 1.11E+02, 1.66E+02 }, 0 }, { "Li1+", { 4.60E-03, 1.65E-02, 4.35E-02, 6.49E-02, 2.70E-02 }, { 3.58E-02, 2.39E-01, 8.79E-01, 2.64E+00, 7.09E+00 }, 0 }, { "Be2+", { 3.40E-03, 1.03E-02, 2.33E-02, 3.25E-02, 1.20E-02 }, { 2.67E-02, 1.62E-01, 5.31E-01, 1.48E+00, 3.88E+00 }, 0 }, { "O1-", { 2.05E-01, 6.28E-01, 1.17E+00, 1.03E+00, 2.90E-01 }, { 3.97E-01, 2.64E+00, 8.80E+00, 2.71E+01, 9.18E+01 }, 0 }, { "O2-", { 4.21E-02, 2.10E-01, 8.52E-01, 1.82E+00, 1.17E+00 }, { 6.09E-02, 5.59E-01, 2.96E+00, 1.15E+01, 3.77E+01 }, 0 }, { "F1-", { 1.34E-01, 3.91E-01, 8.14E-01, 9.28E-01, 3.47E-01 }, { 2.28E-01, 1.47E+00, 4.68E+00, 1.32E+01, 3.60E+01 }, 0 }, { "Na1+", { 2.56E-02, 9.19E-02, 2.97E-01, 5.14E-01, 1.99E-01 }, { 3.97E-02, 2.87E-01, 1.18E+00, 3.75E+00, 1.08E+01 }, 0 }, { "Mg2+", { 2.10E-02, 6.72E-02, 1.98E-01, 3.68E-01, 1.74E-01 }, { 3.31E-02, 2.22E-01, 8.38E-01, 2.48E+00, 6.75E+00 }, 0 }, { "Al3+", { 1.92E-02, 5.79E-02, 1.63E-01, 2.84E-01, 1.14E-01 }, { 3.06E-02, 1.98E-01, 7.13E-01, 2.04E+00, 5.25E+00 }, 0 }, { "Si4+", { 1.92E-01, 2.89E-01, 1.00E-01, -7.28E-02, 1.20E-03 }, { 3.59E-01, 1.96E+00, 9.34E+00, 1.11E+01, 1.34E+01 }, 0 }, { "Cl1-", { 2.65E-01, 5.96E-01, 1.60E+00, 2.69E+00, 1.23E+00 }, { 2.52E-01, 1.56E+00, 6.21E+00, 1.78E+01, 4.78E+01 }, 0 }, { "K1+", { 1.99E-01, 3.96E-01, 9.28E-01, 1.45E+00, 4.50E-01 }, { 1.92E-01, 1.10E+00, 3.91E+00, 9.75E+00, 2.34E+01 }, 0 }, { "Ca2+", { 1.64E-01, 3.27E-01, 7.43E-01, 1.16E+00, 3.07E-01 }, { 1.57E-01, 8.94E-01, 3.15E+00, 7.67E+00, 1.77E+01 }, 0 }, { "Sc3+", { 1.63E-01, 3.07E-01, 7.16E-01, 8.80E-01, 1.39E-01 }, { 1.57E-01, 8.99E-01, 3.06E+00, 7.05E+00, 1.61E+01 }, 0 }, { "Ti2+", { 3.99E-01, 1.04E+00, 1.21E+00, -7.97E-02, 3.52E-01 }, { 3.76E-01, 2.74E+00, 8.10E+00, 1.42E+01, 2.32E+01 }, 0 }, { "Ti3+", { 3.64E-01, 9.19E-01, 1.35E+00, -9.33E-01, 5.89E-01 }, { 3.64E-01, 2.67E+00, 8.18E+00, 1.18E+01, 1.49E+01 }, 0 }, { "Ti4+", { 1.16E-01, 2.56E-01, 5.65E-01, 7.72E-01, 1.32E-01 }, { 1.08E-01, 6.55E-01, 2.38E+00, 5.51E+00, 1.23E+01 }, 0 }, { "V2+", { 3.17E-01, 9.39E-01, 1.49E+00, -1.31E+00, 1.47E+00 }, { 2.69E-01, 2.09E+00, 7.22E+00, 1.52E+01, 1.76E+01 }, 0 }, { "V3+", { 3.41E-01, 8.05E-01, 9.42E-01, 7.83E-02, 1.56E-01 }, { 3.21E-01, 2.23E+00, 5.99E+00, 1.34E+01, 1.69E+01 }, 0 }, { "V5+", { 3.67E-02, 1.24E-01, 2.44E-01, 7.23E-01, 4.35E-01 }, { 3.30E-02, 2.22E-01, 8.24E-01, 2.80E+00, 6.70E+00 }, 0 }, { "Cr2+", { 2.37E-01, 6.34E-01, 1.23E+00, 7.13E-01, 8.59E-02 }, { 1.77E-01, 1.35E+00, 4.30E+00, 1.22E+01, 3.90E+01 }, 0 }, { "Cr3+", { 3.93E-01, 1.05E+00, 1.62E+00, -1.15E+00, 4.07E-01 }, { 3.59E-01, 2.57E+00, 8.68E+00, 1.10E+01, 1.58E+01 }, 0 }, { "Cr4+", { 1.32E-01, 2.92E-01, 7.03E-01, 6.92E-01, 9.59E-02 }, { 1.09E-01, 6.95E-01, 2.39E+00, 5.65E+00, 1.47E+01 }, 0 }, { "Mn2+", { 5.76E-02, 2.10E-01, 6.04E-01, 1.32E+00, 6.59E-01 }, { 3.98E-02, 2.84E-01, 1.29E+00, 4.23E+00, 1.45E+01 }, 0 }, { "Mn3+", { 1.16E-01, 5.23E-01, 8.81E-01, 5.89E-01, 2.14E-01 }, { 1.17E-02, 8.76E-01, 3.06E+00, 6.44E+00, 1.43E+01 }, 0 }, { "Mn4+", { 3.81E-01, 1.83E+00, -1.33E+00, 9.95E-01, 6.18E-02 }, { 3.54E-01, 2.72E+00, 3.47E+00, 5.47E+00, 1.61E+01 }, 0 }, { "Fe2+", { 3.07E-01, 8.38E-01, 1.11E+00, 2.80E-01, 2.77E-01 }, { 2.30E-01, 1.62E+00, 4.87E+00, 1.07E+01, 1.92E+01 }, 0 }, { "Fe3+", { 1.98E-01, 3.87E-01, 8.89E-01, 7.09E-01, 1.17E-01 }, { 1.54E-01, 8.93E-01, 2.62E+00, 6.65E+00, 1.80E+01 }, 0 }, { "Co2+", { 2.13E-01, 4.88E-01, 9.98E-01, 8.28E-01, 2.30E-01 }, { 1.48E-01, 9.39E-01, 2.78E+00, 7.31E+00, 2.07E+01 }, 0 }, { "Co3+", { 3.31E-01, 4.87E-01, 7.29E-01, 6.08E-01, 1.31E-01 }, { 2.67E-01, 1.41E+00, 2.89E+00, 6.45E+00, 1.58E+01 }, 0 }, { "Ni2+", { 3.38E-01, 9.82E-01, 1.32E-02, -3.56E+00, 3.62E+00 }, { 2.37E-01, 1.67E+00, 5.73E+00, 1.14E+01, 1.21E+01 }, 0 }, { "Ni3+", { 3.47E-01, 8.77E-01, 7.90E-01, 5.38E-02, 1.92E-01 }, { 2.60E-01, 1.71E+00, 4.75E+00, 7.51E+00, 1.30E+01 }, 0 }, { "Cu1+", { 3.12E-01, 8.12E-01, 1.11E+00, 7.94E-01, 2.57E-01 }, { 2.01E-01, 1.31E+00, 3.80E+00, 1.05E+01, 2.82E+01 }, 0 }, { "Cu2+", { 2.24E-01, 5.44E-01, 9.70E-01, 7.27E-01, 1.82E-01 }, { 1.45E-01, 9.33E-01, 2.69E+00, 7.11E+00, 1.94E+01 }, 0 }, { "Zn2+", { 2.52E-01, 6.00E-01, 9.17E-01, 6.63E-01, 1.61E-01 }, { 1.61E-01, 1.01E+00, 2.76E+00, 7.08E+00, 1.90E+01 }, 0 }, { "Ga3+", { 3.91E-01, 9.47E-01, 6.90E-01, 7.09E-02, 6.53E-02 }, { 2.64E-01, 1.65E+00, 4.82E+00, 1.07E+01, 1.52E+01 }, 0 }, { "Ge4+", { 3.46E-01, 8.30E-01, 5.99E-01, 9.49E-02, -2.17E-02 }, { 2.32E-01, 1.45E+00, 4.08E+00, 1.32E+01, 2.95E+01 }, 0 }, { "Br1-", { 1.25E-01, 5.63E-01, 1.43E+00, 3.52E+00, 3.22E+00 }, { 5.30E-02, 4.69E-01, 2.15E+00, 1.11E+01, 3.89E+01 }, 0 }, // in the Peng paper there is an error Br+1 instead of Rb+1 { "Rb1+", { 3.68E-01, 8.84E-01, 1.14E+00, 2.26E+00, 8.81E-01 }, { 1.87E-01, 1.12E+00, 3.98E+00, 1.09E+01, 2.66E+01 }, 0 }, { "Sr2+", { 3.46E-01, 8.04E-01, 9.88E-01, 1.89E+00, 6.09E-01 }, { 1.76E-01, 1.04E+00, 3.59E+00, 9.32E+00, 2.14E+01 }, 0 }, { "Y3+", { 4.65E-01, 9.23E-01, 2.41E+00, -2.31E+00, 2.48E+00 }, { 2.40E-01, 1.43E+00, 6.45E+00, 9.97E+00, 1.22E+01 }, 0 }, { "Zr4+", { 2.34E-01, 6.42E-01, 7.47E-01, 1.47E+00, 3.77E-01 }, { 1.13E-01, 7.36E-01, 2.54E+00, 6.72E+00, 1.47E+01 }, 0 }, { "Nb3+", { 3.77E-01, 7.49E-01, 1.29E+00, 1.61E+00, 4.81E-01 }, { 1.84E-01, 1.02E+00, 3.80E+00, 9.44E+00, 2.57E+01 }, 0 }, { "Nb5+", { 8.28E-02, 2.71E-01, 6.54E-01, 1.24E+00, 8.29E-01 }, { 3.69E-02, 2.61E-01, 9.57E-01, 3.94E+00, 9.44E+00 }, 0 }, { "Mo3+", { 4.01E-01, 7.56E-01, 1.38E+00, 1.58E+00, 4.97E-01 }, { 1.91E-01, 1.06E+00, 3.84E+00, 9.38E+00, 2.46E+01 }, 0 }, { "Mo5+", { 4.79E-01, 8.46E-01, 1.56E+01, -1.52E+01, 1.60E+00 }, { 2.41E-01, 1.46E+00, 6.79E+00, 7.13E+00, 1.04E+01 }, 0 }, { "Mo6+", { 2.03E-01, 5.67E-01, 6.46E-01, 1.16E+00, 1.71E-01 }, { 9.71E-02, 6.47E-01, 2.28E+00, 5.61E+00, 1.24E+01 }, 0 }, { "Ru3+", { 4.28E-01, 7.73E-01, 1.55E+00, 1.46E+00, 4.86E-01 }, { 1.91E-01, 1.09E+00, 3.82E+00, 9.08E+00, 2.17E+01 }, 0 }, { "Ru4+", { 2.82E-01, 6.53E-01, 1.14E+00, 1.53E+00, 4.18E-01 }, { 1.25E-01, 7.53E-01, 2.85E+00, 7.01E+00, 1.75E+01 }, 0 }, { "Rh3+", { 3.52E-01, 7.23E-01, 1.50E+00, 1.63E+00, 4.99E-01 }, { 1.51E-01, 8.78E-01, 3.28E+00, 8.16E+00, 2.07E+01 }, 0 }, { "Rh4+", { 3.97E-01, 7.25E-01, 1.51E+00, 1.19E+00, 2.51E-01 }, { 1.77E-01, 1.01E+00, 3.62E+00, 8.56E+00, 1.89E+01 }, 0 }, { "Pd2+", { 9.35E-01, 3.11E+00, 2.46E+01, -4.36E+01, 2.11E+01 }, { 3.93E-01, 4.06E+00, 4.31E+01, 5.40E+01, 6.98E+01 }, 0 }, { "Pd4+", { 3.48E-01, 6.40E-01, 1.22E+00, 1.45E+00, 4.27E-01 }, { 1.51E-01, 8.32E-01, 2.85E+00, 6.59E+00, 1.56E+01 }, 0 }, { "Ag1+", { 5.03E-01, 9.40E-01, 2.17E+00, 1.99E+00, 7.26E-01 }, { 1.99E-01, 1.19E+00, 4.05E+00, 1.13E+01, 3.24E+01 }, 0 }, { "Ag2+", { 4.31E-01, 7.56E-01, 1.72E+00, 1.78E+00, 5.26E-01 }, { 1.75E-01, 9.79E-01, 3.30E+00, 8.24E+00, 2.14E+01 }, 0 }, { "Cd2+", { 4.25E-01, 7.45E-01, 1.73E+00, 1.74E+00, 4.87E-01 }, { 1.68E-01, 9.44E-01, 3.14E+00, 7.84E+00, 2.04E+01 }, 0 }, { "In3+", { 4.17E-01, 7.55E-01, 1.59E+00, 1.36E+00, 4.51E-01 }, { 1.64E-01, 9.60E-01, 3.08E+00, 7.03E+00, 1.61E+01 }, 0 }, { "Sn2+", { 7.97E-01, 2.13E+00, 2.15E+00, -1.64E+00, 2.72E+00 }, { 3.17E-01, 2.51E+00, 9.04E+00, 2.42E+01, 2.64E+01 }, 0 }, { "Sn4+", { 2.61E-01, 6.42E-01, 1.53E+00, 1.36E+00, 1.77E-01 }, { 9.57E-02, 6.25E-01, 2.51E+00, 6.31E+00, 1.59E+01 }, 0 }, { "Sb3+", { 5.52E-01, 1.14E+00, 1.87E+00, 1.36E+00, 4.14E-01 }, { 2.12E-01, 1.42E+00, 4.21E+00, 1.25E+01, 2.90E+01 }, 0 }, { "Sb5+", { 3.77E-01, 5.88E-01, 1.22E+00, 1.18E+00, 2.44E-01 }, { 1.51E-01, 8.12E-01, 2.40E+00, 5.27E+00, 1.19E+01 }, 0 }, { "I1-", { 9.01E-01, 2.80E+00, 5.61E+00, -8.69E+00, 1.26E+01 }, { 3.12E-01, 2.59E+00, 1.41E+01, 3.44E+01, 3.95E+01 }, 0 }, { "Cs1+", { 5.87E-01, 1.40E+00, 1.87E+00, 3.48E+00, 1.67E+00 }, { 2.00E-01, 1.38E+00, 4.12E+00, 1.30E+01, 3.18E+01 }, 0 }, { "Ba2+", { 7.33E-01, 2.05E+00, 2.30E+01, -1.52E+02, 1.34E+02 }, { 2.58E-01, 1.96E+00, 1.18E+01, 1.44E+01, 1.49E+01 }, 0 }, { "La3+", { 4.93E-01, 1.10E+00, 1.50E+00, 2.70E-02, 1.08E+00 }, { 1.67E-01, 1.11E+00, 3.11E+00, 9.61E+00, 2.12E+01 }, 0 }, { "Ce3+", { 5.60E-01, 1.35E+00, 1.59E+00, 2.63E+00, 7.06E-01 }, { 1.90E-01, 1.30E+00, 3.93E+00, 1.07E+01, 2.38E+01 }, 0 }, { "Ce4+", { 4.83E-01, 1.09E+00, 1.34E+00, 2.45E+00, 7.97E-01 }, { 1.65E-01, 1.10E+00, 3.02E+00, 8.85E+00, 1.88E+01 }, 0 }, { "Pr3+", { 6.63E-01, 1.73E+00, 2.35E+00, 3.51E-01, 1.59E+00 }, { 2.26E-01, 1.61E+00, 6.33E+00, 1.10E+01, 1.69E+01 }, 0 }, { "Pr4+", { 5.21E-01, 1.19E+00, 1.33E+00, 2.36E+00, 6.90E-01 }, { 1.77E-01, 1.17E+00, 3.28E+00, 8.94E+00, 1.93E+01 }, 0 }, { "Nd3+", { 5.01E-01, 1.18E+00, 1.45E+00, 2.53E+00, 9.20E-01 }, { 1.62E-01, 1.08E+00, 3.06E+00, 8.80E+00, 1.96E+01 }, 0 }, { "Pm3+", { 4.96E-01, 1.20E+00, 1.47E+00, 2.43E+00, 9.43E-01 }, { 1.56E-01, 1.05E+00, 3.07E+00, 8.56E+00, 1.92E+01 }, 0 }, { "Sm3+", { 5.18E-01, 1.24E+00, 1.43E+00, 2.40E+00, 7.81E-01 }, { 1.63E-01, 1.08E+00, 3.11E+00, 8.52E+00, 1.91E+01 }, 0 }, { "Eu2+", { 6.13E-01, 1.53E+00, 1.84E+00, 2.46E+00, 7.14E-01 }, { 1.90E-01, 1.27E+00, 4.18E+00, 1.07E+01, 2.62E+01 }, 0 }, { "Eu3+", { 4.96E-01, 1.21E+00, 1.45E+00, 2.36E+00, 7.74E-01 }, { 1.52E-01, 1.01E+00, 2.95E+00, 8.18E+00, 1.85E+01 }, 0 }, { "Gd3+", { 4.90E+00, 1.19E-02, 1.42E+00, 2.30E+00, 7.95E-01 }, { 1.48E-01, 9.74E-01, 2.81E+00, 7.78E+00, 1.77E+01 }, 0 }, { "Tb3+", { 5.03E-01, 1.22E+00, 1.42E+00, 2.24E+00, 7.10E-01 }, { 1.50E-01, 9.82E-01, 2.86E+00, 7.77E+00, 1.77E+01 }, 0 }, { "Dy3+", { 5.03E-01, 1.24E+00, 1.44E+00, 2.17E+00, 6.43E-01 }, { 1.48E-01, 9.70E-01, 2.88E+00, 7.73E+00, 1.76E+01 }, 0 }, { "Ho3+", { 4.56E-01, 1.17E+00, 1.43E+00, 2.15E+00, 6.92E-01 }, { 1.29E-01, 8.69E-01, 2.61E+00, 7.24E+00, 1.67E+01 }, 0 }, { "Er3+", { 5.22E-01, 1.28E+00, 1.46E+00, 2.05E+00, 5.08E-01 }, { 1.50E-01, 9.64E-01, 2.93E+00, 7.72E+00, 1.78E+01 }, 0 }, { "Tm3+", { 4.75E-01, 1.20E+00, 1.42E+00, 2.05E+00, 5.84E-01 }, { 1.32E-01, 8.64E-01, 2.60E+00, 7.09E+00, 1.66E+01 }, 0 }, { "Yb2+", { 5.08E-01, 1.37E+00, 1.76E+00, 2.23E+00, 5.84E-01 }, { 1.36E-01, 9.22E-01, 3.12E+00, 8.72E+00, 2.37E+01 }, 0 }, { "Yb3+", { 4.98E-01, 1.22E+00, 1.39E+00, 1.97E-02, 5.59E-01 }, { 1.38E-01, 8.81E-01, 2.63E+00, 6.99E+00, 1.63E+01 }, 0 }, { "Lu3+", { 4.83E-01, 1.21E+00, 1.41E+00, 1.94E+00, 5.22E-01 }, { 1.31E-01, 8.45E-01, 2.57E+00, 6.88E+00, 1.62E+01 }, 0 }, { "Hf4+", { 5.22E-01, 1.22E+00, 1.37E+00, 1.68E+00, 3.12E-01 }, { 1.45E-01, 8.96E-01, 2.74E+00, 6.91E+00, 1.61E+01 }, 0 }, { "Ta5+", { 5.69E-01, 1.26E+00, 9.79E-01, 1.29E+00, 5.51E-01 }, { 1.61E-01, 9.72E-01, 2.76E+00, 5.40E+00, 1.09E+01 }, 0 }, { "W6+", { 1.81E-01, 8.73E-01, 1.18E+00, 1.48E+00, 5.62E-01 }, { 1.18E-02, 4.42E-01, 1.52E+00, 4.35E+00, 9.42E+00 }, 0 }, { "Os4+", { 5.86E-01, 1.31E+00, 1.63E+00, 1.71E+00, 5.40E-01 }, { 1.55E-01, 9.38E-01, 3.19E+00, 7.84E+00, 1.93E+01 }, 0 }, { "Ir3+", { 6.92E-01, 1.37E+00, 1.80E+00, 1.97E+00, 8.04E-01 }, { 1.82E-01, 1.04E+00, 3.47E+00, 8.51E+00, 2.12E+01 }, 0 }, { "Ir4+", { 6.53E-01, 1.29E+00, 1.50E+00, 1.74E+00, 6.83E-01 }, { 1.74E-01, 9.92E-01, 3.14E+00, 7.22E+00, 1.72E+01 }, 0 }, { "Pt2+", { 8.72E-01, 1.68E+00, 2.63E+00, 1.93E+00, 4.75E-01 }, { 2.23E-01, 1.35E+00, 4.99E+00, 1.36E+01, 3.30E+01 }, 0 }, { "Pt4+", { 5.50E-01, 1.21E+00, 1.62E+00, 1.95E+00, 6.10E-01 }, { 1.42E-01, 8.33E-01, 2.81E+00, 7.21E+00, 1.77E+01 }, 0 }, { "Au1+", { 8.11E-01, 1.57E+00, 2.63E+00, 2.68E+00, 9.98E-01 }, { 2.01E-01, 1.18E+00, 4.25E+00, 1.21E+01, 3.44E+01 }, 0 }, { "Au3+", { 7.22E-01, 1.39E+00, 1.94E+00, 1.94E+00, 6.99E-01 }, { 1.84E-01, 1.06E+00, 3.58E+00, 8.56E+00, 2.04E+01 }, 0 }, { "Hg1+", { 7.96E-01, 1.56E+00, 2.72E+00, 2.76E+00, 1.18E+00 }, { 1.94E-01, 1.14E+00, 4.21E+00, 1.24E+01, 3.62E+01 }, 0 }, { "Hg2+", { 7.73E-01, 1.49E+00, 2.45E+00, 2.23E+00, 5.70E-01 }, { 1.91E-01, 1.12E+00, 4.00E+00, 1.08E+01, 2.76E+01 }, 0 }, { "Tl1+", { 8.20E-01, 1.57E+00, 2.78E+00, 2.82E+00, 1.31E+00 }, { 1.97E-01, 1.16E+00, 4.23E+00, 1.27E+01, 3.57E+01 }, 0 }, { "Tl3+", { 8.36E-01, 1.43E+00, 3.94E-01, 2.51E+00, 1.50E+00 }, { 2.08E-01, 1.20E+00, 2.57E+00, 4.86E+00, 1.35E+01 }, 0 }, { "Pb2+", { 7.55E-01, 1.44E+00, 2.48E+00, 2.45E+00, 1.03E+00 }, { 1.81E-01, 1.05E+00, 3.75E+00, 1.06E+01, 2.79E+01 }, 0 }, { "Pb4+", { 5.83E-01, 1.14E+00, 1.60E+00, 2.06E+00, 6.62E-01 }, { 1.44E-01, 7.96E-01, 2.58E+00, 6.22E+00, 1.48E+01 }, 0 }, { "Bi3+", { 7.08E-01, 1.35E+00, 2.28E+00, 2.18E+00, 7.97E-01 }, { 1.70E-01, 9.81E-01, 3.44E+00, 9.41E+00, 2.37E+01 }, 0 }, { "Bi5+", { 6.54E-01, 1.18E+00, 1.25E+00, 1.66E+00, 7.78E-01 }, { 1.62E-01, 9.05E-01, 2.68E+00, 5.14E+00, 1.12E+01 }, 0 }, { "Ra2+", { 9.11E-01, 1.65E+00, 2.53E+00, 3.62E+00, 1.58E+00 }, { 2.04E-01, 1.26E+00, 4.03E+00, 1.26E+01, 3.00E+01 }, 0 }, { "Ac3+", { 9.15E-01, 1.64E+00, 2.26E+00, 3.18E+00, 1.25E+00 }, { 2.05E-01, 1.28E+00, 3.92E+00, 1.13E+01, 2.51E+01 }, 0 }, { "U3+", { 1.14E+00, 2.48E+00, 3.61E+00, 1.13E-02, 9.00E-01 }, { 2.50E-01, 1.84E+00, 7.39E+00, 1.80E+01, 2.27E+01 }, 0 }, { "U4+", { 1.09E+00, 2.32E+00, 1.20E+01, -9.11E+00, 2.15E+00 }, { 2.43E-01, 1.75E+00, 7.79E+00, 8.31E+00, 1.65E+01 }, 0 }, { "U6+", { 6.87E-01, 1.14E+00, 1.83E+00, 2.53E+00, 9.57E-01 }, { 1.54E-01, 8.61E-01, 2.58E+00, 7.70E+00, 1.59E+01 }, 0 }, { 0, { 0., 0., 0., 0., 0. }, { 0., 0., 0., 0., 0. }, 0. } // END_COMPILED_IN_REFERENCE_DATA }; } // namespace <anonymous> peng1996::peng1996(std::string const& label, bool exact) : xray_scattering::base<5>(peng1996_raw_table, "PENG1996", label, exact) {} peng1996_iterator::peng1996_iterator() : current_("H", true) {} peng1996 peng1996_iterator::next() { peng1996 result = current_; current_.next_entry(); return result; } }}} // namespace cctbx::eltbx::electron_scattering
C++
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/eltbx/xray_scattering/form_factor.h
.h
2,284
89
#ifndef CCTBX_ELTBX_XRAY_SCATTERING_FORM_FACTOR_H #define CCTBX_ELTBX_XRAY_SCATTERING_FORM_FACTOR_H #include <scitbx/array_family/shared.h> #include <cctbx/import_scitbx_af.h> namespace cctbx { namespace eltbx { //! X-ray scattering tables. namespace xray_scattering { //! Helper. template<class Derived> class isotropic_form_factor_mixin { Derived const & heir() const { return static_cast<Derived const &>(*this); } public: /*! \brief Value at the point stol (sin-theta-over-lambda), given stol^2. */ /*! See also: at_stol(), at_d_star(), at_d_star_sq(), uctbx::unit_cell::stol() */ double at_stol_sq(double stol_sq) const { return heir().at_x_sq(stol_sq); } /*! \brief Value at the point stol (sin-theta-over-lambda). */ /*! See also: at_stol_sq(), at_d_star(), at_d_star_sq(), */ double at_stol(double stol) const { return heir().at_x_sq(stol * stol); } /*! \brief Value at the point d_star (1/d), given d_star^2. */ /*! See also: at_stol_sq(), at_stol(), at_d_star(), uctbx::unit_cell::d_star_sq() */ double at_d_star_sq(double d_star_sq) const { return heir().at_x_sq(d_star_sq / 4); } /*! \brief Value at the points d_star (1/d), given d_star^2. */ /*! See also: at_stol_sq(), at_stol(), at_d_star(), uctbx::unit_cell::d_star_sq() */ af::shared<double> at_d_star_sq(af::const_ref<double> const& d_star_sq) const { af::shared<double> result(d_star_sq.size(), af::init_functor_null<double>()); for(std::size_t i=0;i<d_star_sq.size();i++) { result[i] = at_d_star_sq(d_star_sq[i]); } return result; } /*! \brief Value at the point d_star (1/d). */ /*! See also: at_stol_sq(), at_stol(), at_d_star_sq(), uctbx::unit_cell::d_star_sq() */ double at_d_star(double d_star) const { return heir().at_x_sq(d_star * d_star / 4); } }; }}} // cctbx::eltbx::xray_scattering #endif // GUARD
Unknown
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/eltbx/xray_scattering/wk1995.cpp
.cpp
38,938
693
#include <cctbx/eltbx/xray_scattering.h> namespace cctbx { namespace eltbx { namespace xray_scattering { namespace { /* wk1995_raw_table contains the reformatted data found in ftp://wrzx02.rz.uni-wuerzburg.de/pub/local/Crystallography/sfac.dat File picked up Jul 4, 1995. File verified Sep 12, 2001. */ static const detail::raw_table_entry<5> wk1995_raw_table[] = { // BEGIN_COMPILED_IN_REFERENCE_DATA { "H", // added entry, not part of original sfac.dat // 5-Gaussian fit based on ITC 2006 Table 6.1.1.2. // Data point added for fit: stol=6, y=0, with sigma=0.0005 for // all data points. // max(gaussian_fit.significant_relative_errors()): 0.00991125937956 { -0.117103661459, 0.00934859438867, 0.270068598623, 0.284341399492, 0.552871721265 }, { 3.05984661463, 0.746557743911, 3.29178616951, 32.6456509125, 11.5463566492 }, 0. }, // SDS { "Hiso", { 0.413048, 0.294953, 0.187491, 0.080701, 0.023736 }, { 15.569946, 32.398468, 5.711404, 61.889874, 1.334118 }, 0.000049 }, // isolated atom { "He", { 0.732354, 0.753896, 0.283819, 0.190003, 0.039139 }, { 11.553918, 4.595831, 1.546299, 26.463964, 0.377523 }, 0.000487 }, { "Li", { 0.974637, 0.158472, 0.811855, 0.262416, 0.790108 }, { 4.334946, 0.342451, 97.102966, 201.363831, 1.409234 }, 0.002542 }, { "Be", { 1.533712, 0.638283, 0.601052, 0.106139, 1.118414 }, { 42.662079, 0.595420, 99.106499, 0.151340, 1.843093 }, 0.002511 }, { "B", { 2.085185, 1.064580, 1.062788, 0.140515, 0.641784 }, { 23.494068, 1.137894, 61.238976, 0.114886, 0.399036 }, 0.003823 }, { "C", { 2.657506, 1.078079, 1.490909, -4.241070, 0.713791 }, { 14.780758, 0.776775, 42.086842, -0.000294, 0.239535 }, 4.297983 }, { "N", { 11.893780, 3.277479, 1.858092, 0.858927, 0.912985 }, { 0.000158, 10.232723, 30.344690, 0.656065, 0.217287 }, -11.804902 }, { "O", { 2.960427, 2.508818, 0.637853, 0.722838, 1.142756 }, { 14.182259, 5.936858, 0.112726, 34.958481, 0.390240 }, 0.027014 }, { "F", { 3.511943, 2.772244, 0.678385, 0.915159, 1.089261 }, { 10.687859, 4.380466, 0.093982, 27.255203, 0.313066 }, 0.032557 }, { "Ne", { 4.183749, 2.905726, 0.520513, 1.135641, 1.228065 }, { 8.175457, 3.252536, 0.063295, 21.813910, 0.224952 }, 0.025576 }, { "Na", { 4.910127, 3.081783, 1.262067, 1.098938, 0.560991 }, { 3.281434, 9.119178, 0.102763, 132.013947, 0.405878 }, 0.079712 }, { "Mg", { 4.708971, 1.194814, 1.558157, 1.170413, 3.239403 }, { 4.875207, 108.506081, 0.111516, 48.292408, 1.928171 }, 0.126842 }, { "Al", { 4.730796, 2.313951, 1.541980, 1.117564, 3.154754 }, { 3.628931, 43.051167, 0.095960, 108.932388, 1.555918 }, 0.139509 }, { "Si", { 5.275329, 3.191038, 1.511514, 1.356849, 2.519114 }, { 2.631338, 33.730728, 0.081119, 86.288643, 1.170087 }, 0.145073 }, { "P", { 1.950541, 4.146930, 1.494560, 1.522042, 5.729711 }, { 0.908139, 27.044952, 0.071280, 67.520187, 1.981173 }, 0.155233 }, { "S", { 6.372157, 5.154568, 1.473732, 1.635073, 1.209372 }, { 1.514347, 22.092527, 0.061373, 55.445175, 0.646925 }, 0.154722 }, { "Cl", { 1.446071, 6.870609, 6.151801, 1.750347, 0.634168 }, { 0.052357, 1.193165, 18.343416, 46.398396, 0.401005 }, 0.146773 }, { "Ar", { 7.188004, 6.638454, 0.454180, 1.929593, 1.523654 }, { 0.956221, 15.339877, 15.339862, 39.043823, 0.062409 }, 0.265954 }, { "K", { 8.163991, 7.146945, 1.070140, 0.877316, 1.486434 }, { 12.816323, 0.808945, 210.327011, 39.597652, 0.052821 }, 0.253614 }, { "Ca", { 8.593655, 1.477324, 1.436254, 1.182839, 7.113258 }, { 10.460644, 0.041891, 81.390381, 169.847839, 0.688098 }, 0.196255 }, { "Sc", { 1.476566, 1.487278, 1.600187, 9.177463, 7.099750 }, { 53.131023, 0.035325, 137.319489, 9.098031, 0.602102 }, 0.157765 }, { "Ti", { 9.818524, 1.522646, 1.703101, 1.768774, 7.082555 }, { 8.001879, 0.029763, 39.885422, 120.157997, 0.532405 }, 0.102473 }, { "V", { 10.473575, 1.547881, 1.986381, 1.865616, 7.056250 }, { 7.081940, 0.026040, 31.909672, 108.022842, 0.474882 }, 0.067744 }, { "Cr", { 11.007069, 1.555477, 2.985293, 1.347855, 7.034779 }, { 6.366281, 0.023987, 23.244839, 105.774498, 0.429369 }, 0.065510 }, { "Mn", { 11.709542, 1.733414, 2.673141, 2.023368, 7.003180 }, { 5.597120, 0.017800, 21.788420, 89.517914, 0.383054 }, -0.147293 }, { "Fe", { 12.311098, 1.876623, 3.066177, 2.070451, 6.975185 }, { 5.009415, 0.014461, 18.743040, 82.767876, 0.346506 }, -0.304931 }, { "Co", { 12.914510, 2.481908, 3.466894, 2.106351, 6.960892 }, { 4.507138, 0.009126, 16.438129, 76.987320, 0.314418 }, -0.936572 }, { "Ni", { 13.521865, 6.947285, 3.866028, 2.135900, 4.284731 }, { 4.077277, 0.286763, 14.622634, 71.966080, 0.004437 }, -2.762697 }, { "Cu", { 14.014192, 4.784577, 5.056806, 1.457971, 6.932996 }, { 3.738280, 0.003744, 13.034982, 72.554794, 0.265666 }, -3.254477 }, { "Zn", { 14.741002, 6.907748, 4.642337, 2.191766, 38.424042 }, { 3.388232, 0.243315, 11.903689, 63.312130, 0.000397 }, -36.915829 }, { "Ga", { 15.758946, 6.841123, 4.121016, 2.714681, 2.395246 }, { 3.121754, 0.226057, 12.482196, 66.203621, 0.007238 }, -0.847395 }, { "Ge", { 16.540613, 1.567900, 3.727829, 3.345098, 6.785079 }, { 2.866618, 0.012198, 13.432163, 58.866047, 0.210974 }, 0.018726 }, { "As", { 17.025642, 4.503441, 3.715904, 3.937200, 6.790175 }, { 2.597739, 0.003012, 14.272119, 50.437996, 0.193015 }, -2.984117 }, { "Se", { 17.354071, 4.653248, 4.259489, 4.136455, 6.749163 }, { 2.349787, 0.002550, 15.579460, 45.181202, 0.177432 }, -3.160982 }, { "Br", { 17.550570, 5.411882, 3.937180, 3.880645, 6.707793 }, { 2.119226, 16.557184, 0.002481, 42.164009, 0.162121 }, -2.492088 }, { "Kr", { 17.655279, 6.848105, 4.171004, 3.446760, 6.685200 }, { 1.908231, 16.606236, 0.001598, 39.917473, 0.146896 }, -2.810592 }, { "Rb", { 8.123134, 2.138042, 6.761702, 1.156051, 17.679546 }, { 15.142385, 33.542667, 0.129372, 224.132507, 1.713368 }, 1.139548 }, { "Sr", { 17.730219, 9.795867, 6.099763, 2.620025, 0.600053 }, { 1.563060, 14.310868, 0.120574, 135.771317, 0.120574 }, 1.140251 }, { "Y", { 17.792040, 10.253252, 5.714949, 3.170516, 0.918251 }, { 1.429691, 13.132816, 0.112173, 108.197029, 0.112173 }, 1.131787 }, { "Zr", { 17.859772, 10.911038, 5.821115, 3.512513, 0.746965 }, { 1.310692, 12.319285, 0.104353, 91.777542, 0.104353 }, 1.124859 }, { "Nb", { 17.958399, 12.063054, 5.007015, 3.287667, 1.531019 }, { 1.211590, 12.246687, 0.098615, 75.011948, 0.098615 }, 1.123452 }, { "Mo", { 6.236218, 17.987711, 12.973127, 3.451426, 0.210899 }, { 0.090780, 1.108310, 11.468720, 66.684151, 0.090780 }, 1.108770 }, { "Tc", { 17.840963, 3.428236, 1.373012, 12.947364, 6.335469 }, { 1.005729, 41.901382, 119.320541, 9.781542, 0.083391 }, 1.074784 }, { "Ru", { 6.271624, 17.906738, 14.123269, 3.746008, 0.908235 }, { 0.077040, 0.928222, 9.555345, 35.860680, 123.552246 }, 1.043992 }, { "Rh", { 6.216648, 17.919739, 3.854252, 0.840326, 15.173498 }, { 0.070789, 0.856121, 33.889484, 121.686691, 9.029517 }, 0.995452 }, { "Pd", { 6.121511, 4.784063, 16.631683, 4.318258, 13.246773 }, { 0.062549, 0.784031, 8.751391, 34.489983, 0.784031 }, 0.883099 }, { "Ag", { 6.073874, 17.155437, 4.173344, 0.852238, 17.988686 }, { 0.055333, 7.896512, 28.443739, 110.376106, 0.716809 }, 0.756603 }, { "Cd", { 6.080986, 18.019468, 4.018197, 1.303510, 17.974669 }, { 0.048990, 7.273646, 29.119284, 95.831207, 0.661231 }, 0.603504 }, { "In", { 6.196477, 18.816183, 4.050479, 1.638929, 17.962912 }, { 0.042072, 6.695665, 31.009790, 103.284348, 0.610714 }, 0.333097 }, { "Sn", { 19.325171, 6.281571, 4.498866, 1.856934, 17.917318 }, { 6.118104, 0.036915, 32.529045, 95.037186, 0.565651 }, 0.119024 }, { "Sb", { 5.394956, 6.549570, 19.650681, 1.827820, 17.867832 }, { 33.326523, 0.030974, 5.564929, 87.130966, 0.523992 }, -0.290506 }, { "Te", { 6.660302, 6.940756, 19.847015, 1.557175, 17.802427 }, { 33.031654, 0.025750, 5.065547, 84.101616, 0.487660 }, -0.806668 }, { "I", { 19.884502, 6.736593, 8.110516, 1.170953, 17.548716 }, { 4.628591, 0.027754, 31.849096, 84.406387, 0.463550 }, -0.448811 }, { "Xe", { 19.978920, 11.774945, 9.332182, 1.244749, 17.737501 }, { 4.143356, 0.010142, 28.796200, 75.280685, 0.413616 }, -6.065902 }, { "Cs", { 17.418674, 8.314444, 10.323193, 1.383834, 19.876251 }, { 0.399828, 0.016872, 25.605827, 233.339676, 3.826915 }, -2.322802 }, { "Ba", { 19.747343, 17.368477, 10.465718, 2.592602, 11.003653 }, { 3.481823, 0.371224, 21.226641, 173.834274, 0.010719 }, -5.183497 }, { "La", { 19.966019, 27.329655, 11.018425, 3.086696, 17.335455 }, { 3.197408, 0.003446, 19.955492, 141.381973, 0.341817 }, -21.745489 }, { "Ce", { 17.355122, 43.988499, 20.546650, 3.130670, 11.353665 }, { 0.328369, 0.002047, 3.088196, 134.907654, 18.832960 }, -38.386017 }, { "Pr", { 21.551311, 17.161730, 11.903859, 2.679103, 9.564197 }, { 2.995675, 0.312491, 17.716705, 152.192825, 0.010468 }, -3.871068 }, { "Nd", { 17.331244, 62.783924, 12.160097, 2.663483, 22.239950 }, { 0.300269, 0.001320, 17.026001, 148.748993, 2.910268 }, -57.189842 }, { "Pm", { 17.286388, 51.560162, 12.478557, 2.675515, 22.960947 }, { 0.286620, 0.001550, 16.223755, 143.984512, 2.796480 }, -45.973682 }, { "Sm", { 23.700363, 23.072214, 12.777782, 2.684217, 17.204367 }, { 2.689539, 0.003491, 15.495437, 139.862473, 0.274536 }, -17.452166 }, { "Eu", { 17.186195, 37.156837, 13.103387, 2.707246, 24.419271 }, { 0.261678, 0.001995, 14.787360, 134.816299, 2.581883 }, -31.586687 }, { "Gd", { 24.898117, 17.104952, 13.222581, 3.266152, 48.995213 }, { 2.435028, 0.246961, 13.996325, 110.863091, 0.001383 }, -43.505684 }, { "Tb", { 25.910013, 32.344139, 13.765117, 2.751404, 17.064405 }, { 2.373912, 0.002034, 13.481969, 125.836510, 0.236916 }, -26.851971 }, { "Dy", { 26.671785, 88.687576, 14.065445, 2.768497, 17.067781 }, { 2.282593, 0.000665, 12.920230, 121.937187, 0.225531 }, -83.279831 }, { "Ho", { 27.150190, 16.999819, 14.059334, 3.386979, 46.546471 }, { 2.169660, 0.215414, 12.213148, 100.506783, 0.001211 }, -41.165253 }, { "Er", { 28.174887, 82.493271, 14.624002, 2.802756, 17.018515 }, { 2.120995, 0.000640, 11.915256, 114.529938, 0.207519 }, -77.135223 }, { "Tm", { 28.925894, 76.173798, 14.904704, 2.814812, 16.998117 }, { 2.046203, 0.000656, 11.465375, 111.411980, 0.199376 }, -70.839813 }, { "Yb", { 29.676760, 65.624069, 15.160854, 2.830288, 16.997850 }, { 1.977630, 0.000720, 11.044622, 108.139153, 0.192110 }, -60.313812 }, { "Lu", { 30.122866, 15.099346, 56.314899, 3.540980, 16.943729 }, { 1.883090, 10.342764, 0.000780, 89.559250, 0.183849 }, -51.049416 }, { "Hf", { 30.617033, 15.145351, 54.933548, 4.096253, 16.896156 }, { 1.795613, 9.934469, 0.000739, 76.189705, 0.175914 }, -49.719837 }, { "Ta", { 31.066359, 15.341823, 49.278297, 4.577665, 16.828321 }, { 1.708732, 9.618455, 0.000760, 66.346199, 0.168002 }, -44.119026 }, { "W", { 31.507900, 15.682498, 37.960129, 4.885509, 16.792112 }, { 1.629485, 9.446448, 0.000898, 59.980675, 0.160798 }, -32.864574 }, { "Re", { 31.888456, 16.117104, 42.390297, 5.211669, 16.767591 }, { 1.549238, 9.233474, 0.000689, 54.516373, 0.152815 }, -37.412682 }, { "Os", { 32.210297, 16.678440, 48.559906, 5.455839, 16.735533 }, { 1.473531, 9.049695, 0.000519, 50.210201, 0.145771 }, -43.677956 }, { "Ir", { 32.004436, 1.975454, 17.070105, 15.939454, 5.990003 }, { 1.353767, 81.014175, 0.128093, 7.661196, 26.659403 }, 4.018893 }, { "Pt", { 31.273891, 18.445440, 17.063745, 5.555933, 1.575270 }, { 1.316992, 8.797154, 0.124741, 40.177994, 1.316997 }, 4.050394 }, { "Au", { 16.777390, 19.317156, 32.979683, 5.595453, 10.576854 }, { 0.122737, 8.621570, 1.256902, 38.008820, 0.000601 }, -6.279078 }, { "Hg", { 16.839890, 20.023823, 28.428564, 5.881564, 4.714706 }, { 0.115905, 8.256927, 1.195250, 39.247227, 1.195250 }, 4.076478 }, { "Tl", { 16.630795, 19.386616, 32.808571, 1.747191, 6.356862 }, { 0.110704, 7.181401, 1.119730, 90.660263, 26.014978 }, 4.066939 }, { "Pb", { 16.419567, 32.738590, 6.530247, 2.342742, 19.916475 }, { 0.105499, 1.055049, 25.025890, 80.906593, 6.664449 }, 4.049824 }, { "Bi", { 16.282274, 32.725136, 6.678302, 2.694750, 20.576559 }, { 0.101180, 1.002287, 25.714146, 77.057549, 6.291882 }, 4.040914 }, { "Po", { 16.289164, 32.807171, 21.095163, 2.505901, 7.254589 }, { 0.098121, 0.966265, 6.046622, 76.598068, 28.096128 }, 4.046556 }, { "At", { 16.011461, 32.615547, 8.113899, 2.884082, 21.377867 }, { 0.092639, 0.904416, 26.543257, 68.372963, 5.499512 }, 3.995684 }, { "Rn", { 16.070229, 32.641106, 21.489658, 2.299218, 9.480184 }, { 0.090437, 0.876409, 5.239687, 69.188477, 27.632641 }, 4.020977 }, { "Fr", { 16.007385, 32.663830, 21.594351, 1.598497, 11.121192 }, { 0.087031, 0.840187, 4.954467, 199.805801, 26.905106 }, 4.003472 }, { "Ra", { 32.563690, 21.396671, 11.298093, 2.834688, 15.914965 }, { 0.801980, 4.590666, 22.758972, 160.404388, 0.083544 }, 3.981773 }, { "Ac", { 15.914053, 32.535042, 21.553976, 11.433394, 3.612409 }, { 0.080511, 0.770669, 4.352206, 21.381622, 130.500748 }, 3.939212 }, { "Th", { 15.784024, 32.454899, 21.849222, 4.239077, 11.736191 }, { 0.077067, 0.735137, 4.097976, 109.464111, 20.512138 }, 3.922533 }, { "Pa", { 32.740208, 21.973675, 12.957398, 3.683832, 15.744058 }, { 0.709545, 4.050881, 19.231543, 117.255005, 0.074040 }, 3.886066 }, { "U", { 15.679275, 32.824306, 13.660459, 3.687261, 22.279434 }, { 0.071206, 0.681177, 18.236156, 112.500038, 3.930325 }, 3.854444 }, { "Np", { 32.999901, 22.638077, 14.219973, 3.672950, 15.683245 }, { 0.657086, 3.854918, 17.435474, 109.464485, 0.068033 }, 3.769391 }, { "Pu", { 33.281178, 23.148544, 15.153755, 3.031492, 15.704215 }, { 0.634999, 3.856168, 16.849735, 121.292038, 0.064857 }, 3.664200 }, { "Am", { 33.435162, 23.657259, 15.576339, 3.027023, 15.746100 }, { 0.612785, 3.792942, 16.195778, 117.757004, 0.061755 }, 3.541160 }, { "Cm", { 15.804837, 33.480801, 24.150198, 3.655563, 15.499866 }, { 0.058619, 0.590160, 3.674720, 100.736191, 15.408296 }, 3.390840 }, { "Bk", { 15.889072, 33.625286, 24.710381, 3.707139, 15.839268 }, { 0.055503, 0.569571, 3.615472, 97.694786, 14.754303 }, 3.213169 }, { "Cf", { 33.794075, 25.467693, 16.048487, 3.657525, 16.008982 }, { 0.550447, 3.581973, 14.357388, 96.064972, 0.052450 }, 3.005326 }, { "H1-", { 0.702260, 0.763666, 0.248678, 0.261323, 0.023017 }, { 23.945604, 74.897919, 6.773289, 233.583450, 1.337531 }, 0.000425 }, { "Li1+", { 0.432724, 0.549257, 0.376575, -0.336481, 0.976060 }, { 0.260367, 1.042836, 7.885294, 0.260368, 3.042539 }, 0.001764 }, { "Be2+", { 3.055430, -2.372617, 1.044914, 0.544233, 0.381737 }, { 0.001226, 0.001227, 1.542106, 0.456279, 4.047479 }, -0.653773 }, { "Cval", { 1.258489, 0.728215, 1.119856, 2.168133, 0.705239 }, { 10.683769, 0.208177, 0.836097, 24.603704, 58.954273 }, 0.019722 }, { "O1-", { 3.106934, 3.235142, 1.148886, 0.783981, 0.676953 }, { 19.868080, 6.960252, 0.170043, 65.693512, 0.630757 }, 0.046136 }, { "O2-", { 3.990247, 2.300563, 0.607200, 1.907882, 1.167080 }, { 16.639956, 5.636819, 0.108493, 47.299709, 0.379984 }, 0.025429 }, { "F1-", { 0.457649, 3.841561, 1.432771, 0.801876, 3.395041 }, { 0.917243, 5.507803, 0.164955, 51.076206, 15.821679 }, 0.069525 }, { "Na1+", { 3.148690, 4.073989, 0.767888, 0.995612, 0.968249 }, { 2.594987, 6.046925, 0.070139, 14.122657, 0.217037 }, 0.045300 }, { "Mg2+", { 3.062918, 4.135106, 0.853742, 1.036792, 0.852520 }, { 2.015803, 4.417941, 0.065307, 9.669710, 0.187818 }, 0.058851 }, { "Al3+", { 4.132015, 0.912049, 1.102425, 0.614876, 3.219136 }, { 3.528641, 7.378344, 0.133708, 0.039065, 1.644728 }, 0.019397 }, { "Sival", { 2.879033, 3.072960, 1.515981, 1.390030, 4.995051 }, { 1.239713, 38.706276, 0.081481, 93.616333, 2.770293 }, 0.146030 }, /* was "Siva" */ { "Si4+", { 3.676722, 3.828496, 1.258033, 0.419024, 0.720421 }, { 1.446851, 3.013144, 0.064397, 0.206254, 5.970222 }, 0.097266 }, { "Cl1-", { 1.061802, 7.139886, 6.524271, 2.355626, 35.829403 }, { 0.144727, 1.171795, 19.467655, 60.320301, 0.000436 }, -34.916603 }, { "K1+", { -17.609339, 1.494873, 7.150305, 10.899569, 15.808228 }, { 18.840979, 0.053453, 0.812940, 22.264105, 14.351593 }, 0.257164 }, { "Ca2+", { 8.501441, 12.880483, 9.765095, 7.156669, 0.711160 }, { 10.525848, -0.004033, 0.010692, 0.684443, 27.231771 }, -21.013187 }, { "Sc3+", { 7.104348, 1.511488, -53.669773, 38.404816, 24.532240 }, { 0.601957, 0.033386, 12.572138, 10.859736, 14.125230 }, 0.118642 }, { "Ti2+", { 7.040119, 1.496285, 9.657304, 0.006534, 1.649561 }, { 0.537072, 0.031914, 8.009958, 201.800293, 24.039482 }, 0.150362 }, { "Ti3+", { 36.587933, 7.230255, -9.086077, 2.084594, 17.294008 }, { 0.000681, 0.522262, 5.262317, 15.881716, 6.149805 }, -35.111282 }, { "Ti4+", { 45.355537, 7.092900, 7.483858, -43.498817, 1.678915 }, { 9.252186, 0.523046, 13.082852, 10.193876, 0.023064 }, -0.110628 }, { "V2+", { 7.754356, 2.064100, 2.576998, 2.011404, 7.126177 }, { 7.066315, 0.014993, 7.066308, 22.055786, 0.467568 }, -0.533379 }, { "V3+", { 9.958480, 1.596350, 1.483442, -10.846044, 17.332867 }, { 6.763041, 0.056895, 17.750029, 0.328826, 0.388013 }, 0.474921 }, { "V5+", { 15.575018, 8.448095, 1.612040, -9.721855, 1.534029 }, { 0.682708, 5.566640, 10.527077, 0.907961, 0.066667 }, 0.552676 }, { "Cr2+", { 10.598877, 1.565858, 2.728280, 0.098064, 6.959321 }, { 6.151846, 0.023519, 17.432816, 54.002388, 0.426301 }, 0.049870 }, { "Cr3+", { 7.989310, 1.765079, 2.627125, 1.829380, 6.980908 }, { 6.068867, 0.018342, 6.068887, 16.309284, 0.420864 }, -0.192123 }, { "Mn2+", { 11.287712, 26.042414, 3.058096, 0.090258, 7.088306 }, { 5.506225, 0.000774, 16.158575, 54.766354, 0.375580 }, -24.566132 }, { "Mn3+", { 6.926972, 2.081342, 11.128379, 2.375107, -0.419287 }, { 0.378315, 0.015054, 5.379957, 14.429586, 0.004939 }, -0.093713 }, { "Mn4+", { 12.409131, 7.466993, 1.809947, -12.138477, 10.780248 }, { 0.300400, 0.112814, 12.520756, 0.168653, 5.173237 }, 0.672146 }, { "Fe2+", { 11.776765, 11.165097, 3.533495, 0.165345, 7.036932 }, { 4.912232, 0.001748, 14.166556, 42.381958, 0.341324 }, -9.676919 }, { "Fe3+", { 9.721638, 63.403847, 2.141347, 2.629274, 7.033846 }, { 4.869297, 0.000293, 4.867602, 13.539076, 0.338520 }, -61.930725 }, { "Co2+", { 6.993840, 26.285812, 12.254289, 0.246114, 4.017407 }, { 0.310779, 0.000684, 4.400528, 35.741447, 12.536393 }, -24.796852 }, { "Co3+", { 6.861739, 2.678570, 12.281889, 3.501741, -0.179384 }, { 0.309794, 0.008142, 4.331703, 11.914167, 11.914167 }, -1.147345 }, { "Ni2+", { 12.519017, 37.832058, 4.387257, 0.661552, 6.949072 }, { 3.933053, 0.000442, 10.449184, 23.860998, 0.283723 }, -36.344471 }, { "Ni3+", { 13.579366, 1.902844, 12.859268, 3.811005, -6.838595 }, { 0.313140, 0.012621, 3.906407, 10.894311, 0.344379 }, -0.317618 }, { "Cu1+", { 12.960763, 16.342150, 1.110102, 5.520682, 6.915452 }, { 3.576010, 0.000975, 29.523218, 10.114283, 0.261326 }, -14.849320 }, { "Cu2+", { 11.895569, 16.344978, 5.799817, 1.048804, 6.789088 }, { 3.378519, 0.000924, 8.133653, 20.526524, 0.254741 }, -14.878383 }, { "Zn2+", { 13.340772, 10.428857, 5.544489, 0.762295, 6.869172 }, { 3.215913, 0.001413, 8.542680, 21.891756, 0.239215 }, -8.945248 }, { "Ga3+", { 13.123875, 35.288189, 6.126979, 0.611551, 6.724807 }, { 2.809960, 0.000323, 6.831534, 16.784311, 0.212002 }, -33.875122 }, { "Ge4+", { 6.876636, 6.779091, 9.969591, 3.135857, 0.152389 }, { 2.025174, 0.176650, 3.573822, 7.685848, 16.677574 }, 1.086542 }, { "Br1-", { 17.714310, 6.466926, 6.947385, 4.402674, -0.697279 }, { 2.122554, 19.050768, 0.152708, 58.690361, 58.690372 }, 1.152674 }, { "Rb1+", { 17.684320, 7.761588, 6.680874, 2.668883, 0.070974 }, { 1.710209, 14.919863, 0.128542, 31.654478, 0.128543 }, 1.133263 }, { "Sr2+", { 17.694973, 1.275762, 6.154252, 9.234786, 0.515995 }, { 1.550888, 30.133041, 0.118774, 13.821799, 0.118774 }, 1.125309 }, { "Y3+", { 46.660366, 10.369686, 4.623042, -62.170834, 17.471146 }, { -0.019971, 13.180257, 0.176398, -0.016727, 1.467348 }, 19.023842 }, { "Zr4+", { 6.802956, 17.699253, 10.650647, -0.248108, 0.250338 }, { 0.096228, 1.296127, 11.240715, -0.219259, -0.219021 }, 0.827902 }, { "Nb3+", { 17.714323, 1.675213, 7.483963, 8.322464, 11.143573 }, { 1.172419, 30.102791, 0.080255, -0.002983, 10.456687 }, -8.339573 }, { "Nb5+", { 17.580206, 7.633277, 10.793497, 0.180884, 67.837921 }, { 1.165852, 0.078558, 9.507652, 31.621656, -0.000438 }, -68.024780 }, { "Mo3+", { 7.447050, 17.778122, 11.886068, 1.997905, 1.789626 }, { 0.072000, 1.073145, 9.834720, 28.221746, -0.011674 }, -1.898764 }, { "Mo5+", { 7.929879, 17.667669, 11.515987, 0.500402, 77.444084 }, { 0.068856, 1.068064, 9.046229, 26.558945, -0.000473 }, -78.056595 }, { "Mo6+", { 34.757683, 9.653037, 6.584769, -18.628115, 2.490594 }, { 1.301770, 7.123843, 0.094097, 1.617443, 12.335434 }, 1.141916 }, { "Ru3+", { 17.894758, 13.579529, 10.729251, 2.474095, 48.227997 }, { 0.902827, 8.740579, 0.045125, 24.764954, -0.001699 }, -51.905243 }, { "Ru4+", { 17.845776, 13.455084, 10.229087, 1.653524, 14.059795 }, { 0.901070, 8.482392, 0.045972, 23.015272, -0.004889 }, -17.241762 }, { "Rh3+", { 17.758621, 14.569813, 5.298320, 2.533579, 0.879753 }, { 0.841779, 8.319533, 0.069050, 23.709131, 0.069050 }, 0.960843 }, { "Rh4+", { 17.716188, 14.446654, 5.185801, 1.703448, 0.989992 }, { 0.840572, 8.100647, 0.068995, 22.357307, 0.068995 }, 0.959941 }, { "Pd2+", { 6.122282, 15.651012, 3.513508, 9.060790, 8.771199 }, { 0.062424, 8.018296, 24.784275, 0.776457, 0.776457 }, 0.879336 }, { "Pd4+", { 6.152421, -96.069023, 31.622141, 81.578255, 17.801403 }, { 0.063951, 11.090354, 13.466152, 9.758302, 0.783014 }, 0.915874 }, { "Ag1+", { 6.091192, 4.019526, 16.948174, 4.258638, 13.889437 }, { 0.056305, 0.719340, 7.758938, 27.368349, 0.719340 }, 0.785127 }, { "Ag2+", { 6.401808, 48.699802, 4.799859, -32.332523, 16.356710 }, { 0.068167, 0.942270, 20.639496, 1.100365, 6.883131 }, 1.068247 }, { "Cd2+", { 6.093711, 43.909691, 17.041306, -39.675117, 17.958918 }, { 0.050624, 8.654143, 15.621396, 11.082067, 0.667591 }, 0.664795 }, { "In3+", { 6.206277, 18.497746, 3.078131, 10.524613, 7.401234 }, { 0.041357, 6.605563, 18.792250, 0.608082, 0.608082 }, 0.293677 }, { "Sn2+", { 6.353672, 4.770377, 14.672025, 4.235959, 18.002131 }, { 0.034720, 6.167891, 6.167879, 29.006456, 0.561774 }, -0.042519 }, { "Sn4+", { 15.445732, 6.420892, 4.562980, 1.713385, 18.033537 }, { 6.280898, 0.033144, 6.280899, 17.983601, 0.557980 }, -0.172219 }, { "Sb3+", { 10.189171, 57.461918, 19.356573, 4.862206, -45.394096 }, { 0.089485, 0.375256, 5.357987, 22.153736, 0.297768 }, 1.516108 }, { "Sb5+", { 17.920622, 6.647932, 12.724075, 1.555545, 7.600591 }, { 0.522315, 0.029487, 5.718210, 16.433775, 5.718204 }, -0.445371 }, { "I1-", { 20.010330, 17.835524, 8.104130, 2.231118, 9.158548 }, { 4.565931, 0.444266, 32.430672, 95.149040, 0.014906 }, -3.341004 }, { "Cs1+", { 19.939056, 24.967621, 10.375884, 0.454243, 17.660248 }, { 3.770511, 0.004040, 25.311275, 76.537766, 0.384730 }, -19.394306 }, { "Ba2+", { 19.750200, 17.513683, 10.884892, 0.321585, 65.149834 }, { 3.430748, 0.361590, 21.358307, 70.309402, 0.001418 }, -59.618172 }, { "La3+", { 19.688887, 17.345703, 11.356296, 0.099418, 82.358124 }, { 3.146211, 0.339586, 18.753832, 90.345459, 0.001072 }, -76.846909 }, { "Ce3+", { 26.593231, 85.866432, -6.677695, 12.111847, 17.401903 }, { 3.280381, 0.001012, 4.313575, 17.868504, 0.326962 }, -80.313423 }, { "Ce4+", { 17.457533, 25.659941, 11.691037, 19.695251, -16.994749 }, { 0.311812, -0.003793, 16.568687, 2.886395, -0.008931 }, -3.515096 }, { "Pr3+", { 20.879841, 36.035797, 12.135341, 0.283103, 17.167803 }, { 2.870897, 0.002364, 16.615236, 53.909359, 0.306993 }, -30.500784 }, { "Pr4+", { 17.496082, 21.538509, 20.403114, 12.062211, -7.492043 }, { 0.294457, -0.002742, 2.772886, 15.804613, -0.013556 }, -9.016722 }, { "Nd3+", { 17.120077, 56.038139, 21.468307, 10.000671, 2.905866 }, { 0.291295, 0.001421, 2.743681, 14.581367, 22.485098 }, -50.541992 }, { "Pm3+", { 22.221066, 17.068142, 12.805423, 0.435687, 52.238770 }, { 2.635767, 0.277039, 14.927315, 45.768017, 0.001455 }, -46.767181 }, { "Sm3+", { 15.618565, 19.538092, 13.398946, -4.358811, 24.490461 }, { 0.006001, 0.306379, 14.979594, 0.748825, 2.454492 }, -9.714854 }, { "Eu2+", { 23.899035, 31.657497, 12.955752, 1.700576, 16.992199 }, { 2.467332, 0.002230, 13.625002, 35.089481, 0.253136 }, -26.204315 }, { "Eu3+", { 17.758327, 33.498665, 24.067188, 13.436883, -9.019134 }, { 0.244474, -0.003901, 2.487526, 14.568011, -0.015628 }, -19.768026 }, { "Gd3+", { 24.344999, 16.945311, 13.866931, 0.481674, 93.506378 }, { 2.333971, 0.239215, 12.982995, 43.876347, 0.000673 }, -88.147179 }, { "Tb3+", { 24.878252, 16.856016, 13.663937, 1.279671, 39.271294 }, { 2.223301, 0.227290, 11.812528, 29.910065, 0.001527 }, -33.950317 }, { "Dy3+", { 16.864344, 90.383461, 13.675473, 1.687078, 25.540651 }, { 0.216275, 0.000593, 11.121207, 26.250975, 2.135930 }, -85.150650 }, { "Ho3+", { 16.837524, 63.221336, 13.703766, 2.061602, 26.202621 }, { 0.206873, 0.000796, 10.500283, 24.031883, 2.055060 }, -58.026505 }, { "Er3+", { 16.810127, 22.681061, 13.864114, 2.294506, 26.864477 }, { 0.198293, 0.002126, 9.973341, 22.836388, 1.979442 }, -17.513460 }, { "Tm3+", { 16.787500, 15.350905, 14.182357, 2.299111, 27.573771 }, { 0.190852, 0.003036, 9.602934, 22.526880, 1.912862 }, -10.192087 }, { "Yb2+", { 28.443794, 16.849527, 14.165081, 3.445311, 28.308853 }, { 1.863896, 0.183811, 9.225469, 23.691355, 0.001463 }, -23.214935 }, { "Yb3+", { 28.191629, 16.828087, 14.167848, 2.744962, 23.171774 }, { 1.842889, 0.182788, 9.045957, 20.799847, 0.001759 }, -18.103676 }, { "Lu3+", { 28.828693, 16.823227, 14.247617, 3.079559, 25.647667 }, { 1.776641, 0.175560, 8.575531, 19.693701, 0.001453 }, -20.626528 }, { "Hf4+", { 29.267378, 16.792543, 14.785310, 2.184128, 23.791996 }, { 1.697911, 0.168313, 8.190025, 18.277578, 0.001431 }, -18.820383 }, { "Ta5+", { 29.539469, 16.741854, 15.182070, 1.642916, 16.437447 }, { 1.612934, 0.160460, 7.654408, 17.070732, 0.001858 }, -11.542459 }, { "W6+", { 29.729357, 17.247808, 15.184488, 1.154652, 0.739335 }, { 1.501648, 0.140803, 6.880573, 14.299601, 14.299618 }, 3.945157 }, { "Os4+", { 17.113485, 15.792370, 23.342392, 4.090271, 7.671292 }, { 0.131850, 7.288542, 1.389307, 19.629425, 1.389307 }, 3.988390 }, { "Ir3+", { 31.537575, 16.363338, 15.597141, 5.051404, 1.436935 }, { 1.334144, 7.451918, 0.127514, 21.705648, 0.127515 }, 4.009459 }, { "Ir4+", { 30.391249, 16.146996, 17.019068, 4.458904, 0.975372 }, { 1.328519, 7.181766, 0.127337, 19.060146, 1.328519 }, 4.006865 }, { "Pt2+", { 31.986849, 17.249048, 15.269374, 5.760234, 1.694079 }, { 1.281143, 7.625512, 0.123571, 24.190826, 0.123571 }, 4.032512 }, { "Pt4+", { 41.932713, 16.339224, 17.653894, 6.012420, -12.036877 }, { 1.111409, 6.466086, 0.128917, 16.954155, 0.778721 }, 4.094551 }, { "Au1+", { 32.124306, 16.716476, 16.814100, 7.311565, 0.993064 }, { 1.216073, 7.165378, 0.118715, 20.442486, 53.095985 }, 4.040792 }, { "Au3+", { 31.704271, 17.545767, 16.819551, 5.522640, 0.361725 }, { 1.215561, 7.220506, 0.118812, 20.050970, 1.215562 }, 4.042679 }, { "Hg1+", { 28.866837, 19.277540, 16.776051, 6.281459, 3.710289 }, { 1.173967, 7.583842, 0.115351, 29.055994, 1.173968 }, 4.068430 }, { "Hg2+", { 32.411079, 18.690371, 16.711773, 9.974835, -3.847611 }, { 1.162980, 7.329806, 0.114518, 22.009489, 22.009493 }, 4.052869 }, { "Tl1+", { 32.295044, 16.570049, 17.991013, 1.535355, 7.554591 }, { 1.101544, 0.110020, 6.528559, 52.495068, 20.338634 }, 4.054030 }, { "Tl3+", { 32.525639, 19.139185, 17.100321, 5.891115, 12.599463 }, { 1.094966, 6.900992, 0.103667, 18.489614, -0.001401 }, -9.256075 }, { "Pb2+", { 27.392647, 16.496822, 19.984501, 6.813923, 5.233910 }, { 1.058874, 0.106305, 6.708123, 24.395554, 1.058874 }, 4.065623 }, { "Pb4+", { 32.505657, 20.014240, 14.645661, 5.029499, 1.760138 }, { 1.047035, 6.670321, 0.105279, 16.525040, 0.105279 }, 4.044678 }, { "Bi3+", { 32.461437, 19.438683, 16.302486, 7.322662, 0.431704 }, { 0.997930, 6.038867, 0.101338, 18.371586, 46.361046 }, 4.043703 }, { "Bi5+", { 16.734028, 20.580494, 9.452623, 61.155834, -34.041023 }, { 0.105076, 4.773282, 11.762162, 1.211775, 1.619408 }, 4.113663 }, { "Ra2+", { 4.986228, 32.474945, 21.947443, 11.800013, 10.807292 }, { 0.082597, 0.791468, 4.608034, 24.792431, 0.082597 }, 3.956572 }, { "Ac3+", { 15.584983, 32.022125, 21.456327, 0.757593, 12.341252 }, { 0.077438, 0.739963, 4.040735, 47.525002, 19.406845 }, 3.838984 }, { "Th4+", { 15.515445, 32.090691, 13.996399, 12.918157, 7.635514 }, { 0.074499, 0.711663, 3.871044, 18.596891, 3.871044 }, 3.831122 }, { "U3+", { 15.360309, 32.395657, 21.961290, 1.325894, 14.251453 }, { 0.067815, 0.654643, 3.643409, 39.604965, 16.330570 }, 3.706622 }, { "U4+", { 15.355091, 32.235306, 0.557745, 14.396367, 21.751173 }, { 0.067789, 0.652613, 42.354237, 15.908239, 3.553231 }, 3.705863 }, { "U6+", { 15.333844, 31.770849, 21.274414, 13.872636, 0.048519 }, { 0.067644, 0.646384, 3.317894, 14.650250, 75.339699 }, 3.700591 }, { "Np3+", { 15.378152, 32.572132, 22.206125, 1.413295, 14.828381 }, { 0.064613, 0.631420, 3.561936, 37.875511, 15.546129 }, 3.603370 }, { "Np4+", { 15.373926, 32.423019, 21.969994, 0.662078, 14.969350 }, { 0.064597, 0.629658, 3.476389, 39.438942, 15.135764 }, 3.603039 }, { "Np6+", { 15.359986, 31.992825, 21.412458, 0.066574, 14.568174 }, { 0.064528, 0.624505, 3.253441, 67.658318, 13.980832 }, 3.600942 }, { "Pu3+", { 15.356004, 32.769127, 22.680210, 1.351055, 15.416232 }, { 0.060590, 0.604663, 3.491509, 37.260635, 14.981921 }, 3.428895 }, { "Pu4+", { 15.416219, 32.610569, 22.256662, 0.719495, 15.518152 }, { 0.061456, 0.607938, 3.411848, 37.628792, 14.464360 }, 3.480408 }, { "Pu6+", { 15.436506, 32.289719, 14.726737, 15.012391, 7.024677 }, { 0.061815, 0.606541, 3.245363, 13.616438, 3.245364 }, 3.502325 }, { 0, { 0., 0., 0., 0., 0. }, { 0., 0., 0., 0., 0. }, 0. } // END_COMPILED_IN_REFERENCE_DATA }; } // namespace <anonymous> wk1995::wk1995(std::string const& label, bool exact) : base<5>(wk1995_raw_table, "WK1995", label, exact) {} wk1995_iterator::wk1995_iterator() : current_("H", true) {} wk1995 wk1995_iterator::next() { wk1995 result = current_; current_.next_entry(); return result; } }}} // namespace cctbx::eltbx::xray_scattering
C++
3D
YellProgram/Yell
lib/cctbx_stubs/cctbx/eltbx/xray_scattering/gaussian.h
.h
1,664
62
#ifndef CCTBX_ELTBX_XRAY_SCATTERING_GAUSSIAN_H #define CCTBX_ELTBX_XRAY_SCATTERING_GAUSSIAN_H #include <cctbx/eltbx/xray_scattering/form_factor.h> #include <scitbx/math/gaussian/sum.h> #include <cctbx/import_scitbx_af.h> namespace cctbx { namespace eltbx { namespace xray_scattering { class gaussian : public scitbx::math::gaussian::sum<double>, public isotropic_form_factor_mixin<gaussian> { public: typedef scitbx::math::gaussian::sum<double> base_t; //! Default constructor. Some data members are not initialized! gaussian() {} //! Initialization given an instance of the base type. gaussian(base_t const& gaussian_sum) : base_t(gaussian_sum) {} //! Initialization of the constant. explicit gaussian(double c, bool use_c=true) : base_t(c, use_c) {} //! Initialization of the terms and optionally the constant. /*! If c is different from zero use_c will automatically be set to true. */ gaussian( af::small<double, base_t::max_n_terms> const& a, af::small<double, base_t::max_n_terms> const& b, double c=0, bool use_c=false) : base_t(a, b, c, use_c) {} //! Initialization of the terms and optionally the constant. /*! If c is different from zero use_c will automatically be set to true. */ gaussian( af::const_ref<double> const& ab, double c=0, bool use_c=false) : base_t(ab, c, use_c) {} }; }}} // cctbx::eltbx::xray_scattering #endif // CCTBX_ELTBX_XRAY_SCATTERING_GAUSSIAN_H
Unknown
3D
pymodproject/pymod
CHANGELOG.md
.md
2,585
46
# PyMod 3 Changelog This file contains descriptions of changes of new PyMod 3 releases. ## Version 3.0.2 (17/8/2020) - Added the possibility to import results from HH-suite output files (HHR and A3M). - Added compatibility for pyside2 (thanks to Thomas Holder). - Fixed the requirements for fully compatible PyMOL versions (see the README.md file). ## Version 3.0.1 (15/6/2020) - Fixed the PDB fetching functionality (updated to HTTPS urls on RCSB). ## Version 3.0.0 (22/5/2020) - Updated the PyMod GUI using PyQt5. - Homology modeling using MODELLER. Implemented various changes, some of them are: - Customize the optimization schedule of MODELLER. - Customize the MODELLER objective function terms. - Added the GA341 scoring function for model evaluation. - When building oligomeric models, added the SOAP-PP scoring function for interfaces evaluation. - Added sortable tables for model evaluation. - Added the possibility to use parallel jobs when building multiple models. - Solved a series of bugs which did not allow to use some PDB structures as templates. - Added the possibility to perform loop modeling (with MODELLER) for elements that have a 3D structure loaded in PyMod/PyMOL. - Added the SCR_FIND protocol (for analyzing the conservation in multiple structural alignments). - Added the possibility to use the following HMMER programs: - phmmer, jackhmmer, hmmsearch (for searching protein sequence databases) - hmmscan (for searching profile HMM databases). hmmscan can be used as a tool to assign Pfam domain families. - Added an easy-to-use dialog to install all PyMod external tools. - Added an easy-to-use dialog to update the sequence databases for the external tools of PyMod. - Added a contact/distance map viewer feature. - Added a series of other small functionalities and fixes (please refer to the updated PyMod manual for a full list of them). ## Version 2.0.8 (2/11/2017) - Introduced a series of fixes to add compatibility to PyMOL 2.0. ## Version 2.0.7 (2/12/2016) - Fixed a bug that changed the atom order of structures when performing CE alignments with PyMOL. ## Version 2.0.6 (21/11/2016) - When coloring structures by residue properties, all atom types of a residue are now colored with the same color, allowing better visualization of surfaces. ## Version 2.0.5 (13/11/2016) - Added back the possibility to use the NCBI QBLAST server to perform a BLAST search after the NCBI switched its services to the HTTPS protocol. ## Version 2.0.4 (7/11/2016) - Added the possibility to save and load PyMod projects.
Markdown
3D
pymodproject/pymod
scripts/build_pymol_plugin.py
.py
1,512
43
""" Script for building a PyMOL plugin ZIP file for PyMod 3. You must run this in the root folder of the repository. """ import os import argparse import datetime import zipfile # Parses the commandline. parser = argparse.ArgumentParser() parser.add_argument("-r", "--revision", help="Number of the plugin revision for this day.", type=int, default=None) parser.add_argument("-p", "--pymod_plugin_dirpath", help="Path of the 'pymod3' directory.", type=str, default="pymod3") cmd = parser.parse_args() # Name of the PyMOL plugin file ZIP file. if cmd.revision is None: plugin_archive_name = "pymod3.zip" else: current_date = datetime.datetime.now() plugin_archive_name = "pymod3_%s_%s_%s_rev_%s.zip" % (current_date.day, current_date.month, current_date.year, cmd.revision) target_filepath = plugin_archive_name # Actually writes the plugin ZIP file. print("- Building a PyMOL plugin file from directory: %s" % cmd.pymod_plugin_dirpath) walk_data = os.walk(cmd.pymod_plugin_dirpath) with zipfile.ZipFile(target_filepath, 'w', zipfile.ZIP_DEFLATED) as z_fh: for root, dirs, files in walk_data: for filename in files: if filename.endswith(".pyc"): continue z_fh.write(os.path.join(root, filename)) print("- Completed. PyMOL plugin file written: %s" % target_filepath)
Python
3D
pymodproject/pymod
pymod3/__init__.py
.py
12,531
305
########################################################################### # Copyright (C) 2020 Giacomo Janson, Alessandro Paiardini # Copyright (C) 2016-2019 Giacomo Janson, Chengxin Zhang, Alessandro Paiardini # Copyright (C) 2011-2012 Emanuele Bramucci & Alessandro Paiardini, # Francesco Bossa, Stefano Pascarella # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this library; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ########################################################################### """ PyMod 3: PyMOL Front-end to MODELLER and various other bioinformatics tools. """ # Module first imported by the PyMOL plugin system. Contains: # - code to check for the presence of Python libraries needed for PyMod to work. # - code to initialize PyMod as a PyMOL plugin. #-------------------------- # Check Python libraries. - #-------------------------- import os import sys from importlib import util import shutil from pymol import cmd # Gets the Python version. python_version = sys.version_info.major python_minor_version = "%s.%s" % (sys.version_info.major, sys.version_info.minor) python_micro_version = "%s.%s.%s" % (sys.version_info.major, sys.version_info.minor, sys.version_info.micro) # Checks for dependencies. try: # Checks for some Qt bindings in PyMOL. from pymol.Qt import QtWidgets def showerror(title, message): QtWidgets.QMessageBox.critical(None, title, message) has_gui = "qt" pyqt_found = True except ImportError: # Checks for Tkinter. try: if python_version == 3: # Python 3. from tkinter.messagebox import showerror else: # Python 2. from tkMessageBox import showerror has_gui = "tkinter" except ImportError: # On some open source builds, tkinter is missing. has_gui = None pyqt_found = False try: import numpy numpy_found = True except ImportError: numpy_found = False try: import Bio biopython_found = True except ImportError: biopython_found = False # Sets the version of the PyMod plugin. __pymod_version__ = "3.0" __revision__ = "2" __version__ = float(__pymod_version__ + __revision__.replace(".", "")) pymod_plugin_name = "PyMod " + __pymod_version__ #---------------------------------------- # Initialize the PyMod plugin in PyMOL. - #---------------------------------------- def __init_plugin__(app): """ Initializes the plugin in the plugin menu of PyMOL 3. """ # Adds a "PyMod" item to the plugin menu of PyMOL. try: from pymol.plugins import addmenuitemqt addmenuitemqt(pymod_plugin_name, startup_pymod) # Adds a "PyMod" item to the legacy plugin menu of PyMOL. except ImportError: app.menuBar.addmenuitem('Plugin', 'command', pymod_plugin_name, label=pymod_plugin_name, command=lambda a=app: startup_pymod(a)) def startup_pymod(app=None): """ Executed when clicking on the 'PyMod' item in PyMOL's plugin menu. """ if has_gui is None: print("\n# No GUI library (either Tkinter or Qt bindings) was found. PyMod" " can not be launched.") return None # Check if a PyMod main window is already open. if pyqt_found: try: for widget in QtWidgets.QApplication.instance().topLevelWidgets(): if hasattr(widget, "is_pymod_main_window") and widget.isVisible(): title = "PyMod Error" message = ("PyMod is already running. Please close its main" " window or restart PyMOL in order to launch it again.") showerror(title, message) return None except Exception as e: pass # Checks if Python 3 is available. if python_version != 3: title = "Python Version Error" message = "PyMod %s requires Python 3. Your current Python version is %s." % (__pymod_version__, python_micro_version) showerror(title, message) return None # Checks the PyMOL version. pymol_version = float(".".join(cmd.get_version()[0].split(".")[0:2])) if pymol_version < 2.3: title = "PyMOL Version Error" message = "PyMod %s requires a PyMOL version of 2.3 or higher. Your current PyMOL version is %s." % (__pymod_version__, pymol_version) showerror(title, message) return None # Checks for PyQt. if not pyqt_found: title = "Import Error" message = "PyQt5 is not installed on your system. Please install it in order to use PyMod." showerror(title, message) return None # Checks if NumPy and Biopython (PyMod core Python dependencies) are present before launching # PyMod. if not numpy_found: title = "Import Error" message = "NumPy is not installed on your system. Please install it in order to use PyMod." showerror(title, message) return None if not biopython_found: title = "Import Error" message = "Biopython is not installed on your system. Please install it in order to use PyMod." showerror(title, message) return None # Adds to the sys.path the directory where the PyMod module is located. pymod_plugin_dirpath = os.path.dirname(__file__) if os.path.isdir(pymod_plugin_dirpath): sys.path.append(pymod_plugin_dirpath) # Attempts to import MODELLER from the default sys.path. modeller_spec = util.find_spec("modeller") parallel_modeller = False # A flag, when set as 'True' MODELLER parallel jobs can be used. # MODELLER can be imported. if modeller_spec is not None: parallel_modeller = True # MODELLER can not be imported. Tries to import it from a PyMod conda # pseudo-environment. else: # Adds to the sys.path the PyMod conda environment directory. Used to import # modules fetched by conda within PyMod. from pymod_lib import pymod_os_specific pymod_env_dirpath = pymod_os_specific.get_pymod_cfg_paths()[3] # Checks if a directory for a PyMod conda pseudo-environment exists. if os.path.isdir(pymod_env_dirpath): if sys.platform in ("linux", "darwin"): conda_lib_dirpath_list = [os.path.join(pymod_env_dirpath, "lib", "python%s" % python_minor_version), os.path.join(pymod_env_dirpath, "lib", "python%s" % python_minor_version, "lib-dynload"), os.path.join(pymod_env_dirpath, "lib", "python%s" % python_minor_version, "site-packages")] path_extend_list = [] elif sys.platform == "win32": dll_dirpath = os.path.join(pymod_env_dirpath, "Lib", "site-packages") conda_lib_dirpath_list = [os.path.join(pymod_env_dirpath, "Library", "modeller", "modlib"), dll_dirpath] path_extend_list = [os.path.join(pymod_env_dirpath, "Scripts"), pymod_env_dirpath, dll_dirpath] else: conda_lib_dirpath_list = [] path_extend_list = [] # Add the environment directories to the sys.path of Python. for conda_lib_dirpath in conda_lib_dirpath_list: sys.path.append(conda_lib_dirpath) # Also add new directories to the PATH to use the MODELLER DLLs. if path_extend_list: os.environ["PATH"] += os.pathsep.join(path_extend_list) os.environ["HDF5_DISABLE_VERSION_CHECK"] = "1" # Prevents problems with hdf5 libraries versions. # Edit the 'modslave.py' file of MODELLER in the PyMod environment directory # (the user's original MODELLER files will remain untouched) so that the # MODELLER version installed in the PyMod environment directory can be # used to run parallel jobs. This operation will be performed only once, # that is, the first time PyMod is launched after MODELLER has been # installed through the GUI of the plugin. try: # Gets the installation directory of MODELLER. This can be acquired # also if the MODELLER key is not valid. from modeller import config modeller_bin_dirpath = os.path.join(config.install_dir, "bin") modslave_filepath = os.path.join(modeller_bin_dirpath, "modslave.py") modslave_bak_filepath = os.path.join(modeller_bin_dirpath, "modslave.py.bak") # Checks if the modslave file is present. if os.path.isfile(modslave_filepath): # Checks if the backup modslave file is present (if it already # exists, then PyMod has already modified the original modslave # file). if not os.path.isfile(modslave_bak_filepath): print("\n# Configuring the MODELLER modslave.py in the PyMod environment.") print("- modslave.py file found at: %s" % modslave_filepath) # Build a backup copy of the original modslave file. print("- Backing up the modslave.py file.") shutil.copy(modslave_filepath, modslave_bak_filepath) # Gets the content from the old modslave file. with open(modslave_filepath, "r") as m_fh: modfile_lines = m_fh.readlines() insert_idx = 1 for line_idx, line in enumerate(modfile_lines): if line.startswith("import sys"): print("- Found insert line") insert_idx = line_idx + 1 break # This will add the paths above also to the 'modslave.py' # file, so that MODELLER can be imported in child processes. import_lines = ['\n# Added by the PyMod installer.\n', 'import os\n', 'import sys\n\n', 'conda_lib_dirpath_list = %s\n' % repr(conda_lib_dirpath_list), 'path_extend_list = %s\n\n' % repr(path_extend_list), 'for path in conda_lib_dirpath_list:\n', ' sys.path.append(path)\n', 'os.environ["PATH"] += os.pathsep.join(path_extend_list)\n', 'os.environ["HDF5_DISABLE_VERSION_CHECK"] = "1"\n', '# End of the code inserted by PyMod.\n'] modfile_lines = modfile_lines[:insert_idx] + import_lines + modfile_lines[insert_idx:] # Edits the modslave file. with open(modslave_filepath, "w") as m_fh: m_fh.writelines(modfile_lines) print("- Finishing.") parallel_modeller = True except Exception as e: print("- Could not import MODELLER from the PyMod environment: %s." % e) # Actually launches PyMod. from pymod_lib import pymod_main pymod_main.pymod_launcher(app=app, pymod_plugin_name=pymod_plugin_name, pymod_version=__pymod_version__, pymod_revision=__revision__, parallel_modeller=parallel_modeller)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_os_specific.py
.py
14,317
406
# Copyright 2016 by Chengxin Zhang, Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Module for cross-platform compatibility. """ import os, sys import platform import re import subprocess import shutil import zipfile import struct import urllib.request, urllib.error, urllib.parse from datetime import datetime from pymod_lib import pymod_vars ##################################################################### # Directories managment. # ##################################################################### def get_home_dir(): if sys.platform=="win32": d=os.path.join(os.environ["HOMEDRIVE"],os.environ["HOMEPATH"]) else: d=os.getenv("HOME") if d and os.path.isdir(d): return d else: sys.stderr.write("Error! Cannot locate home folder!\n") return os.getcwd() # def check_user_permissions(file_to_check): # if os.access(file_to_check, os.W_OK): # return True # else: # return False # def is_writable(dirname): # """ # Taken from the 'plugin.installation' module of PyMOL (since version 1.5.0.5). # """ # path = os.path.join(dirname, '__check_writable') # try: # f = open(path, 'wb') # f.close() # os.remove(path) # return True # except (IOError, OSError): # return False def get_pymod_cfg_paths(): home_dirpath = get_home_dir() cfg_directory_path = os.path.join(home_dirpath, pymod_vars.pymod_cfg_dirname) pymod_envs_dirpath = os.path.join(cfg_directory_path, pymod_vars.pymod_envs_dirname) pymod_env_dirpath = os.path.join(pymod_envs_dirpath, pymod_vars.pymod_env_name) pymod_pkgs_dirpath = os.path.join(cfg_directory_path, pymod_vars.pymod_pkgs_dirname) return home_dirpath, cfg_directory_path, pymod_envs_dirpath, pymod_env_dirpath, pymod_pkgs_dirpath ##################################################################### # Find external tools on users' systems. # ##################################################################### def pymod_which(executable, paths=None): """ Find 'executable' in the directories listed in 'path'. """ if sys.platform == "win32": ext=".exe" else: ext="" if not paths: paths=os.environ["PATH"] paths=paths.split(os.pathsep) if sys.platform == "darwin" and not "/usr/local/bin" in paths and os.path.isdir("/usr/local/bin"): paths.append("/usr/local/bin") exe_full_path=None # MODELLER. if executable == "modeller": # return directory on windows # try to locate modX.XX from importable modeller try: import modeller modinstall=os.sep.join(os.path.realpath(modeller.__file__).split(os.sep)[:-3]) except: modinstall=None if modinstall: version=modinstall.split(os.sep)[-1].lstrip('modeller-') exe_full_path=find_executable("mod"+version,paths) if not exe_full_path and sys.platform!="win32": pattern = re.compile("^mod[0-9]{1,2}[.v][0-9]+$") for p in [p for p in set(paths) if p and os.path.isdir(p)]: f_list=[os.path.join(p,f) for f in os.listdir(p) if \ os.path.isfile(os.path.join(p,f)) and pattern.match(f)] if f_list: exe_full_path=os.path.realpath(f_list[-1]) break # On Windows, use the Python interpreter to run modeller scripts. # TODO: locate win32 modeller when architecture is different elif not exe_full_path and sys.platform=="win32": # pattern=re.compile("^Python[0-9]{2}$") # for p in os.listdir(os.environ["HOMEDRIVE"]+'\\'): # if pattern.match(p): # f=os.sep.join([os.environ["HOMEDRIVE"],p,"python.exe"]) # if os.path.isfile(f): # exe_full_path=f # break pass # elif executable in ["TMalign","TMalign.exe","tmalign","tmalign.exe"]: # exe_full_path=find_executable("TMalign"+ext,paths) # if not exe_full_path: # exe_full_path=find_executable("TMscore"+ext,paths) # # elif executable in ["dssp","dssp.exe"]: # exe_full_path=find_executable(executable,paths) # if not exe_full_path: # exe_full_path=find_executable("mk"+executable,paths) elif executable=="clustalw": if sys.platform=="win32": if os.getenv("ProgramFiles(x86)"): p=os.getenv("ProgramFiles(x86)") else: # clustalw2 for win is 32bit only p=os.getenv("ProgramFiles") paths.append(os.path.join(p,"ClustalW2")) exe_full_path=find_executable("clustalw2"+ext,paths) if not exe_full_path: exe_full_path=find_executable("clustalw"+ext,paths) elif executable in ["psiblast","blast_plus"]: if sys.platform=="win32": for p in set([os.getenv("ProgramFiles(x86)"),os.getenv("ProgramFiles"),os.getenv("programw6432")]): if p: ncbi_path=os.path.join(p,"NCBI") if os.path.isdir(ncbi_path): for d in os.listdir(ncbi_path): if d.startswith("blast"): blast_path=os.path.join(ncbi_path,d,"bin") if os.path.isdir(blast_path): paths=[blast_path]+paths exe_full_path=find_executable("psiblast"+ext,paths) if not exe_full_path: exe_full_path=find_executable("blastpgp"+ext,paths) elif executable == "hmmer": exe_full_path=find_executable("phmmer"+ext,paths) else: # executable in [muscle,clustalo,predator], clustalw on posix exe_full_path=find_executable(executable+ext,paths) return exe_full_path # might be None def find_executable(executable,paths=[]): exe_full_path=None for p in [p for p in set(paths) if p and os.path.isdir(p)]: f=os.path.join(p,executable) if os.path.isfile(f): exe_full_path=os.path.abspath(f) break # If the executble was not found, try to use the 'which' progam. if not exe_full_path and os.name == 'posix': try: exe_full_path = subprocess.check_output(["which",executable]).rstrip("\n") except: pass return exe_full_path ##################################################################### # Python libraries. # ##################################################################### def check_importable_modeller(get_exception=False): """ Checks if systemwide MODELLER can be imported. If it can be imported, returns its version. """ try: import modeller import _modeller import modeller.automodel from modeller.scripts import complete_pdb if hasattr(modeller, "__version__"): hasmodeller = modeller.__version__ elif hasattr(_modeller, "mod_short_version_get"): hasmodeller = _modeller.mod_short_version_get() else: hasmodeller = "unknown" if not get_exception: return hasmodeller else: return None except Exception as e: if not get_exception: return "" else: return e def check_valid_pyqt(): try: import PyQt5 pyqt5_version_str = PyQt5.QtCore.PYQT_VERSION_STR pyqt5_version = float(".".join(pyqt5_version_str.split(".")[0:2])) pyqt5_version_major = float(pyqt5_version_str.split(".")[0]) pyqt5_version_minor = float(pyqt5_version_str.split(".")[1]) valid_version = pyqt5_version_minor < 13 return valid_version except Exception as e: return False ##################################################################### # Archives. # ##################################################################### def zip_directory(directory_path, zipfile_path): """ Zips a directory. This function will ignore empty subdirectories inside the directory to zip. """ if not os.path.isdir(directory_path): raise Exception("The target path (%s) is not a directory." % directory_path) directory_name = os.path.basename(directory_path) directory_parent = os.path.dirname(directory_path) directory_name_count = directory_path.split(os.path.sep).count(directory_name) zipfile_handle = zipfile.ZipFile(zipfile_path, 'w', zipfile.ZIP_DEFLATED) for root, dirs, files in os.walk(directory_path): for f in files: # Build the relative path of the zipped file. dir_index_in_root = 0 for i,dirname in enumerate(root.split(os.path.sep)): if dirname == directory_name: dir_index_in_root += 1 if dir_index_in_root == directory_name_count: index_to_use = i break # absolute_path = os.path.join(root, f) # relative_path = absolute_path[len(directory_parent)+len(os.path.sep):] # z.write(absolute_path, relative_path) relative_path = os.path.sep.join(root.split(os.path.sep)[index_to_use:]) zipfile_handle.write(os.path.join(root, f), os.path.join(relative_path, f)) zipfile_handle.close() ##################################################################### # Files names and document viewing. # ##################################################################### def clean_file_name(file_name): """ Replaces characters not allowed in Windows. The '/' character is invalid on UNIX and the ':' on Mac OS. Used in 'build_header_string()' in 'pymod_main.py'. """ return re.sub("""[\\\\/:*?"<>|']""", "_", file_name) def get_exe_file_name(program_name, force_not_extended=False): if sys.platform == "win32" and not force_not_extended: program_name += ".exe" return program_name def open_document_with_default_viewer(document_path): # MAC. if sys.platform.startswith('darwin'): subprocess.call(('open', document_path)) # WIN. elif os.name == 'nt': os.startfile(document_path) # Other UNIX. elif os.name == 'posix': subprocess.call(('xdg-open', document_path)) ##################################################################### # Commandline. # ##################################################################### def build_commandline_path_string(file_path): if is_unix(): return "'%s'" % (file_path) elif sys.platform == "win32": return '"%s"' % (file_path) else: return program_path def build_commandline_file_argument(argument, path_name, extension=None): if extension: extension = "." + extension else: extension = "" return """ -%s %s""" % (argument, build_commandline_path_string(path_name+extension)) ##################################################################### # Operating systems and architectures. # ##################################################################### os_names_dict = {"win32": "Windows", "darwin": "Mac OS X", "linux": "Linux"} def get_python_architecture(): # "32" for x86 """ Gets the architecture of the PyMOL built in which PyMod is running. "64" for x86-64. """ return str(8*struct.calcsize("P")) def get_os_architecture(): if sys.platform == "win32": if 'PROGRAMFILES(X86)' in os.environ: return "64" else: return "32" else: return platform.architecture()[0][0:2] def is_unix(): if sys.platform == "linux2" or sys.platform == "darwin" or os.name == "posix": return True else: return False def get_unicode_support(): ucs="0" if hasattr(sys,"maxunicode"): if sys.maxunicode==65535: ucs="2" elif sys.maxunicode==1114111: ucs="4" return ucs def get_mac_ver(): """ Gets the version of Mac OS X. """ mac_ver = platform.mac_ver()[0] # On some PyMOL builds from Schrodinger the platform.mac_ver()[0] returns an empty string. if not mac_ver: r = subprocess.Popen("sw_vers -productVersion", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).communicate() mac_ver = r[0].rstrip() return mac_ver def get_linux_distribution(): """ Gets the Linux distribution name. """ # subprocess.check_call("lsb_release -ic") if not float(get_python_version()) >= 2.7: return platform.linux_distribution()[0] else: return platform.dist()[0] def get_python_version(): return sys.version[:3] ##################################################################### # Internet connection. # ##################################################################### def check_network_connection(remote_address, timeout=None): try: if timeout is None: response = urllib.request.urlopen(remote_address) else: response = urllib.request.urlopen(remote_address, timeout=timeout) return True except urllib.error.URLError: #as a last resort in countries where Google is banned... try: response = urllib.request.urlopen("https://www.baidu.com/", timeout=5) return True except: return False ##################################################################### # Dates and times. # ##################################################################### def get_formatted_date(): return datetime.today().strftime('%d/%m/%Y (%H:%M)') #)'%d/%m/%Y (%H:%M:%S)')
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_residue.py
.py
4,524
139
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Residues of sequences and structures in PymMod. """ from pymod_lib.pymod_vars import feature_types class PyMod_residue: """ Class for a residue of PyMod element. """ def __init__(self, three_letter_code, one_letter_code, index=None, seq_index=None, db_index=None): self.three_letter_code = three_letter_code self.one_letter_code = one_letter_code self.full_name = three_letter_code self.index = index self.seq_index = seq_index self.db_index = db_index # "Database" index: for elements with a 3D structure in # PyMOL, it is the PDB residue index. self.pymod_element = None self.color_seq = None # Color for the sequence in the main window. Contains an RGB code. self.color_str = None # Color for the 3D structure loaded in PyMOL. Contains a color name. self.custom_color = None # Used to attribute a residue a particular color. # These attributes store the colors used at some time for a residue, so that when temporarily # changing its color, it can be colored back to its original color. self._color_seq = None self._color_str = None self._custom_color = None self.secondary_structure = None self.psipred_result = None self.campo_score = None self.dope_score = None self.scr_score = None # Features. self.features = dict([(ft, []) for ft in feature_types]) def __repr__(self): return self.one_letter_code+'__'+str(self.index) def is_polymer_residue(self): """ Check if the residue is part of a polymer chain, or a ligand molecule/atom. """ return not self.is_water() and not self.is_ligand() def is_standard_residue(self): return isinstance(self, PyMod_standard_residue) def is_water(self): return isinstance(self, PyMod_water_molecule) def is_ligand(self): return isinstance(self, PyMod_ligand) def is_modified_residue(self): return isinstance(self, PyMod_modified_residue) def is_heteroresidue(self, exclude_water=True): if exclude_water: return self.is_non_water_heteroresidue() else: return issubclass(self.__class__, PyMod_heteroresidue) def is_non_water_heteroresidue(self): return issubclass(self.__class__, PyMod_heteroresidue) and not self.is_water() def get_pymol_selector(self): """ Gets the correspondig selector in PyMOL. """ # Selectors that work: # # /1UBI_Chain_A//A/LEU`43/CA # # 1UBI_Chain_A and resi 43 return "%s and resi %s" % (self.pymod_element.get_pymol_selector(), self.db_index) def get_id_in_aligned_sequence(self): # Only polymer residues can be included in alignments. assert self.is_polymer_residue() res_counter = 0 index = self.pymod_element.get_polymer_residues().index(self) for i, p in enumerate(self.pymod_element.my_sequence): if p != "-": if index == res_counter: return i res_counter += 1 return None def get_parent_structure_chain_id(self): return self.pymod_element.get_chain_id() def get_default_color(self): if self.color_str is None: return self.pymod_element.my_color else: return self.color_str # Used in the "Search subsequence" feature of PyMod. def store_current_colors(self): self._color_seq = self.color_seq self._color_str = self.color_str self._custom_color = self.custom_color def revert_original_colors(self): self.color_seq = self._color_seq self.color_str = self._color_str self.custom_color = self._custom_color class PyMod_standard_residue(PyMod_residue): hetres_type = None class PyMod_heteroresidue(PyMod_residue): hetres_type = "?" class PyMod_ligand(PyMod_heteroresidue): hetres_type = "ligand" class PyMod_modified_residue(PyMod_heteroresidue): hetres_type = "modified residue" class PyMod_water_molecule(PyMod_heteroresidue): hetres_type = "water"
Python
3D
pymodproject/pymod
pymod3/pymod_lib/__init__.py
.py
0
0
null
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_exceptions.py
.py
2,028
74
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Exceptions to be used within PyMod. """ class PyModInvalidFile(Exception): """ Used when a sequence or structure file containing some error is opened. """ pass class PyModUnknownFile(Exception): """ Used when a sequence or structure file containing some error is opened. """ pass class PyModMissingStructure(Exception): """ Used when trying to access the 3D structure data of an element which lacks a structure. """ pass class PyModSequenceConflict(Exception): """ Used when updating the amino acid sequence of an element with a sequence with different amino acids. """ pass class PyModInterruptedProtocol(Exception): """ Used when interrupting a running protocol. """ pass def catch_protocol_exception(function): """ Function used as a decorator to catch the exceptions raised when running methods of protocols. """ def wrapper(self, *args, **kwargs): # Launches the method of the protocol. try: return function(self, *args, **kwargs) # The protocol is quitted by the user while the method is running, do not show any meesage. except PyModInterruptedProtocol as e: self.quit_protocol() return None # The protocol stops because an exception was raised in the method, show an error message. except Exception as e: # Shows an error message. title = "%s Error" % self.protocol_name message = "%s stopped because of the following error: %s" % (self.protocol_name, str(e)) self.pymod.main_window.show_error_message(title, message) self.quit_protocol() return None return wrapper
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_element_feature.py
.py
2,660
72
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. class Element_feature: def __init__(self, id, name, start, end, description='', feature_type='None', color=None): self.start = start self.end = end self.id = id self.name = name self.feature_type = feature_type self.description = description self.color = color self.show = False # Show in PyMod main window. def __repr__(self): return str(self.__dict__) def get_feature_dict(self): return {"start": self.start, "end": self.end, "id": self.id, "name": self.name, "feature_type": self.feature_type, "description": self.description,} class Domain_feature(Element_feature): def __init__(self, id, name, start, end, evalue, color=None, description='', is_derived=False, offset=(0, 0)): Element_feature.__init__(self, id, name, start, end, description, feature_type='domain') self.domain_color = color self.evalue = evalue self.element = None self.full_name = "%s_%s_%s" % (self.name, self.start, self.end) # Initially is always set to 'False'. It will be set to 'True' when the copy of a # 'Domain_feature' object is assigned to a split domain element derived from an original # query sequence. self.is_derived = is_derived self.offset = offset # symmetric, nterm offset and cterm offset if the seq is split into domains if self.is_derived: # Store the original start/end values from the parent. self.parent_start = self.start self.parent_end = self.end # Updates the values to suite the new cropped domain sequence. new_startindex = max(0, self.start-self.offset[0]) self.start -= new_startindex self.end -= new_startindex else: self.parent_start = None self.parent_end = None self.show = True def get_feature_dict(self): return {"id": self.id, "name": self.name, "start": self.start, "end": self.end, "evalue": self.evalue, "color": self.domain_color, "description": self.description, "is_derived": self.is_derived, "offset": self.offset, }
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_vars.py
.py
44,711
812
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Module contaning variables and function used throughout the PyMod plugin. """ ################################################################################################### # Paths. # ################################################################################################### # Name of the PyMod configuration directory. pymod_cfg_dirname = ".pymod" # Name of the Directory containing a subdir with the PyMod conda environment. pymod_envs_dirname = "pymod_envs" # Name of the PyMod conda environment. pymod_env_name = "pymod_env" # Name of the conda packages directory for PyMod. pymod_pkgs_dirname = "pymod_pkgs" # Tools directories names. blast_databases_dirname = "blast_databases" hmmer_databases_dirname = "hmmer_databases" hmmscan_databases_dirname = "hmmscan_databases" # Log filenames. data_installer_log_filename = "download_log.txt" ################################################################################################### # Define some variabiles used throughout the PyMod. # ################################################################################################### # Tuple containing ids of the algorithms used to perform sequence alignments. sequence_alignment_tools = ("clustalw", "clustalo", "muscle","salign-seq") # And structural alignments. structural_alignment_tools = ("ce", "salign-str") # Dictionaries for algorithms names. algs_full_names_dict = { # Similarity searches. "blast": "NCBI BLAST", "blastp": "BLAST", "psi-blast": "PSI-BLAST", "phmmer": "PHMMER", "jackhmmer": "JACKHMMER", "hmmsearch": "HMMSEARCH", # Alignments. "clustalw": "ClustalW", "clustalo": "Clustal Omega", "muscle": "MUSCLE", "salign-seq": "SALIGN", "salign-str": "SALIGN", "ce": "CE-alignment", "imported": "Imported", "joined": "Joined" } can_show_rmsd_matrix = ("ce","salign-str") can_show_guide_tree = ("clustalw","clustalo") can_show_dendrogram = ("salign-seq","salign-str") can_use_scr_find = ("ce","salign-str") ################################################################################################### # PyMod elements information. # ################################################################################################### unique_index_header_formatted = "_%s_tpm" unique_index_header_regex = r"_\d+_tpm" structure_temp_name = "__%s_structure_full__.pdb" # "__%s_structure_temp__" structure_chain_temp_name = "__%s_structure_chain_%s__.pdb" # "__%s_structure_temp_chain_%s__" copied_chain_name = "cobj_%s" ################################################################################################### # File formats supported in PyMod. # ################################################################################################### # The keys are the name of the alignment file format and values are the extension for those # alignment file. alignment_extensions_dictionary = { "fasta": "fasta", "pir": "ali", "clustal": "aln", "stockholm": "sto", "pymod": "txt"} ################################################################################################### # GUI data. # ################################################################################################### yesno_dict = {"Yes": True, "No": False} structural_alignment_warning = ("It looks like that the input alignment you chose was not built through" " a structural alignment algorithm. Please note that a %s analysis" " is only suited for structural alignments where all the 3D structures are" " superposed in PyMOL. It's results are only meaningful in such cases." " If your input structures are already aligned in PyMOL, you can safely" " ignore this warning.") ################################################################################################### # Tool specific data. # ################################################################################################### # PSIPRED. psipred_output_extensions = (".ss2", ".horiz") psipred_element_dict = {"H": "alpha helix", "E": "beta sheet", "C": "aperiodic"} ################################################################################################### # Substitution Matrices. # ################################################################################################### try: from Bio.Align import substitution_matrices biopython_18 = True except: biopython_18 = False from Bio.SubsMat import MatrixInfo if biopython_18: list_of_matrices = substitution_matrices.load() # Create a dict of matrices. The keys are the matrices names # # HOW TO GET MATRIX: e.g. dict_of_matrices["BLOSUM62"] dict_of_matrices = {} for matrix in list_of_matrices: items = substitution_matrices.load(matrix).items() dict_of_matrices[matrix] = {} for item in items: dict_of_matrices[matrix][item[0]] = item[1] # PAM120 manually addedd, missing in Biopython. dict_of_matrices["PAM120"] = {('W', 'F'): -1, ('L', 'R'): -4, ('S', 'P'): 1, ('V', 'T'): 0, ('Q', 'Q'): 6, ('N', 'A'): -1, ('Z', 'Y'): -5, ('W', 'R'): 1, ('Q', 'A'): -1, ('S', 'D'): 0, ('H', 'H'): 7, ('S', 'H'): -2, ('H', 'D'): 0, ('L', 'N'): -4, ('W', 'A'): -7, ('Y', 'M'): -4, ('G', 'R'): -4, ('Y', 'I'): -2, ('Y', 'E'): -5, ('B', 'Y'): -3, ('Y', 'A'): -4, ('V', 'D'): -3, ('B', 'S'): 0, ('Y', 'Y'): 8, ('G', 'N'): 0, ('E', 'C'): -7, ('Y', 'Q'): -5, ('Z', 'Z'): 4, ('V', 'A'): 0, ('C', 'C'): 9, ('M', 'R'): -1, ('V', 'E'): -3, ('T', 'N'): 0, ('P', 'P'): 6, ('V', 'I'): 3, ('V', 'S'): -2, ('Z', 'P'): -1, ('V', 'M'): 1, ('T', 'F'): -4, ('V', 'Q'): -3, ('K', 'K'): 5, ('P', 'D'): -3, ('I', 'H'): -4, ('I', 'D'): -3, ('T', 'R'): -2, ('P', 'L'): -3, ('K', 'G'): -3, ('M', 'N'): -3, ('P', 'H'): -1, ('F', 'Q'): -6, ('Z', 'G'): -2, ('X', 'L'): -2, ('T', 'M'): -1, ('Z', 'C'): -7, ('X', 'H'): -2, ('D', 'R'): -3, ('B', 'W'): -6, ('X', 'D'): -2, ('Z', 'K'): -1, ('F', 'A'): -4, ('Z', 'W'): -7, ('F', 'E'): -7, ('D', 'N'): 2, ('B', 'K'): 0, ('X', 'X'): -2, ('F', 'I'): 0, ('B', 'G'): 0, ('X', 'T'): -1, ('F', 'M'): -1, ('B', 'C'): -6, ('Z', 'I'): -3, ('Z', 'V'): -3, ('S', 'S'): 3, ('L', 'Q'): -2, ('W', 'E'): -8, ('Q', 'R'): 1, ('N', 'N'): 4, ('W', 'M'): -6, ('Q', 'C'): -7, ('W', 'I'): -6, ('S', 'C'): 0, ('L', 'A'): -3, ('S', 'G'): 1, ('L', 'E'): -4, ('W', 'Q'): -6, ('H', 'G'): -4, ('S', 'K'): -1, ('Q', 'N'): 0, ('N', 'R'): -1, ('H', 'C'): -4, ('Y', 'N'): -2, ('G', 'Q'): -3, ('Y', 'F'): 4, ('C', 'A'): -3, ('V', 'L'): 1, ('G', 'E'): -1, ('G', 'A'): 1, ('K', 'R'): 2, ('E', 'D'): 3, ('Y', 'R'): -5, ('M', 'Q'): -1, ('T', 'I'): 0, ('C', 'D'): -7, ('V', 'F'): -3, ('T', 'A'): 1, ('T', 'P'): -1, ('B', 'P'): -2, ('T', 'E'): -2, ('V', 'N'): -3, ('P', 'G'): -2, ('M', 'A'): -2, ('K', 'H'): -2, ('V', 'R'): -3, ('P', 'C'): -4, ('M', 'E'): -3, ('K', 'L'): -4, ('V', 'V'): 5, ('M', 'I'): 1, ('T', 'Q'): -2, ('I', 'G'): -4, ('P', 'K'): -2, ('M', 'M'): 8, ('K', 'D'): -1, ('I', 'C'): -3, ('Z', 'D'): 3, ('F', 'R'): -5, ('X', 'K'): -2, ('Q', 'D'): 1, ('X', 'G'): -2, ('Z', 'L'): -3, ('X', 'C'): -4, ('Z', 'H'): 1, ('B', 'L'): -4, ('B', 'H'): 1, ('F', 'F'): 8, ('X', 'W'): -5, ('B', 'D'): 4, ('D', 'A'): 0, ('S', 'L'): -4, ('X', 'S'): -1, ('F', 'N'): -4, ('S', 'R'): -1, ('W', 'D'): -8, ('V', 'Y'): -3, ('W', 'L'): -3, ('H', 'R'): 1, ('W', 'H'): -3, ('H', 'N'): 2, ('W', 'T'): -6, ('T', 'T'): 4, ('S', 'F'): -3, ('W', 'P'): -7, ('L', 'D'): -5, ('B', 'I'): -3, ('L', 'H'): -3, ('S', 'N'): 1, ('B', 'T'): 0, ('L', 'L'): 5, ('Y', 'K'): -5, ('E', 'Q'): 2, ('Y', 'G'): -6, ('Z', 'S'): -1, ('Y', 'C'): -1, ('G', 'D'): 0, ('B', 'V'): -3, ('E', 'A'): 0, ('Y', 'W'): -2, ('E', 'E'): 5, ('Y', 'S'): -3, ('C', 'N'): -5, ('V', 'C'): -3, ('T', 'H'): -3, ('P', 'R'): -1, ('V', 'G'): -2, ('T', 'L'): -3, ('V', 'K'): -4, ('K', 'Q'): 0, ('R', 'A'): -3, ('I', 'R'): -2, ('T', 'D'): -1, ('P', 'F'): -5, ('I', 'N'): -2, ('K', 'I'): -3, ('M', 'D'): -4, ('V', 'W'): -8, ('W', 'W'): 12, ('M', 'H'): -4, ('P', 'N'): -2, ('K', 'A'): -2, ('M', 'L'): 3, ('K', 'E'): -1, ('Z', 'E'): 4, ('X', 'N'): -1, ('Z', 'A'): -1, ('Z', 'M'): -2, ('X', 'F'): -3, ('K', 'C'): -7, ('B', 'Q'): 0, ('X', 'B'): -1, ('B', 'M'): -4, ('F', 'C'): -6, ('Z', 'Q'): 4, ('X', 'Z'): -1, ('F', 'G'): -5, ('B', 'E'): 3, ('X', 'V'): -1, ('F', 'K'): -7, ('B', 'A'): 0, ('X', 'R'): -2, ('D', 'D'): 5, ('W', 'G'): -8, ('Z', 'F'): -6, ('S', 'Q'): -2, ('W', 'C'): -8, ('W', 'K'): -5, ('H', 'Q'): 3, ('L', 'C'): -7, ('W', 'N'): -4, ('S', 'A'): 1, ('L', 'G'): -5, ('W', 'S'): -2, ('S', 'E'): -1, ('H', 'E'): -1, ('S', 'I'): -2, ('H', 'A'): -3, ('S', 'M'): -2, ('Y', 'L'): -2, ('Y', 'H'): -1, ('Y', 'D'): -5, ('E', 'R'): -3, ('X', 'P'): -2, ('G', 'G'): 5, ('G', 'C'): -4, ('E', 'N'): 1, ('Y', 'T'): -3, ('Y', 'P'): -6, ('T', 'K'): -1, ('A', 'A'): 3, ('P', 'Q'): 0, ('T', 'C'): -3, ('V', 'H'): -3, ('T', 'G'): -1, ('I', 'Q'): -3, ('Z', 'T'): -2, ('C', 'R'): -4, ('V', 'P'): -2, ('P', 'E'): -2, ('M', 'C'): -6, ('K', 'N'): 1, ('I', 'I'): 6, ('P', 'A'): 1, ('M', 'G'): -4, ('T', 'S'): 2, ('I', 'E'): -3, ('P', 'M'): -3, ('M', 'K'): 0, ('I', 'A'): -1, ('P', 'I'): -3, ('R', 'R'): 6, ('X', 'M'): -2, ('L', 'I'): 1, ('X', 'I'): -1, ('Z', 'B'): 2, ('X', 'E'): -1, ('Z', 'N'): 0, ('X', 'A'): -1, ('B', 'R'): -2, ('B', 'N'): 3, ('F', 'D'): -7, ('X', 'Y'): -3, ('Z', 'R'): -1, ('F', 'H'): -3, ('B', 'F'): -5, ('F', 'L'): 0, ('X', 'Q'): -1, ('B', 'B'): 4} else: list_of_matrices = ['BLOSUM45', 'BLOSUM50', 'BLOSUM62', 'BLOSUM80', 'BLOSUM90', 'PAM250', 'PAM30', 'PAM120'] dict_of_names = {'BLOSUM45': MatrixInfo.blosum45, 'BLOSUM50': MatrixInfo.blosum50, 'BLOSUM62': MatrixInfo.blosum62, 'BLOSUM80': MatrixInfo.blosum80, 'BLOSUM90': MatrixInfo.blosum90, 'PAM250': MatrixInfo.pam250, 'PAM30': MatrixInfo.pam30, 'PAM120': MatrixInfo.pam120} # Create a dict of matrices. The keys are the matrices names # # HOW TO GET MATRIX: e.g. dict_of_matrices["BLOSUM62"] dict_of_matrices = {} for matrix in list_of_matrices: items = dict_of_names[matrix] dict_of_matrices[matrix] = items # PAM120 manually addedd, missing in Biopython. dict_of_matrices["PAM120"] = {('W', 'F'): -1, ('L', 'R'): -4, ('S', 'P'): 1, ('V', 'T'): 0, ('Q', 'Q'): 6, ('N', 'A'): -1, ('Z', 'Y'): -5, ('W', 'R'): 1, ('Q', 'A'): -1, ('S', 'D'): 0, ('H', 'H'): 7, ('S', 'H'): -2, ('H', 'D'): 0, ('L', 'N'): -4, ('W', 'A'): -7, ('Y', 'M'): -4, ('G', 'R'): -4, ('Y', 'I'): -2, ('Y', 'E'): -5, ('B', 'Y'): -3, ('Y', 'A'): -4, ('V', 'D'): -3, ('B', 'S'): 0, ('Y', 'Y'): 8, ('G', 'N'): 0, ('E', 'C'): -7, ('Y', 'Q'): -5, ('Z', 'Z'): 4, ('V', 'A'): 0, ('C', 'C'): 9, ('M', 'R'): -1, ('V', 'E'): -3, ('T', 'N'): 0, ('P', 'P'): 6, ('V', 'I'): 3, ('V', 'S'): -2, ('Z', 'P'): -1, ('V', 'M'): 1, ('T', 'F'): -4, ('V', 'Q'): -3, ('K', 'K'): 5, ('P', 'D'): -3, ('I', 'H'): -4, ('I', 'D'): -3, ('T', 'R'): -2, ('P', 'L'): -3, ('K', 'G'): -3, ('M', 'N'): -3, ('P', 'H'): -1, ('F', 'Q'): -6, ('Z', 'G'): -2, ('X', 'L'): -2, ('T', 'M'): -1, ('Z', 'C'): -7, ('X', 'H'): -2, ('D', 'R'): -3, ('B', 'W'): -6, ('X', 'D'): -2, ('Z', 'K'): -1, ('F', 'A'): -4, ('Z', 'W'): -7, ('F', 'E'): -7, ('D', 'N'): 2, ('B', 'K'): 0, ('X', 'X'): -2, ('F', 'I'): 0, ('B', 'G'): 0, ('X', 'T'): -1, ('F', 'M'): -1, ('B', 'C'): -6, ('Z', 'I'): -3, ('Z', 'V'): -3, ('S', 'S'): 3, ('L', 'Q'): -2, ('W', 'E'): -8, ('Q', 'R'): 1, ('N', 'N'): 4, ('W', 'M'): -6, ('Q', 'C'): -7, ('W', 'I'): -6, ('S', 'C'): 0, ('L', 'A'): -3, ('S', 'G'): 1, ('L', 'E'): -4, ('W', 'Q'): -6, ('H', 'G'): -4, ('S', 'K'): -1, ('Q', 'N'): 0, ('N', 'R'): -1, ('H', 'C'): -4, ('Y', 'N'): -2, ('G', 'Q'): -3, ('Y', 'F'): 4, ('C', 'A'): -3, ('V', 'L'): 1, ('G', 'E'): -1, ('G', 'A'): 1, ('K', 'R'): 2, ('E', 'D'): 3, ('Y', 'R'): -5, ('M', 'Q'): -1, ('T', 'I'): 0, ('C', 'D'): -7, ('V', 'F'): -3, ('T', 'A'): 1, ('T', 'P'): -1, ('B', 'P'): -2, ('T', 'E'): -2, ('V', 'N'): -3, ('P', 'G'): -2, ('M', 'A'): -2, ('K', 'H'): -2, ('V', 'R'): -3, ('P', 'C'): -4, ('M', 'E'): -3, ('K', 'L'): -4, ('V', 'V'): 5, ('M', 'I'): 1, ('T', 'Q'): -2, ('I', 'G'): -4, ('P', 'K'): -2, ('M', 'M'): 8, ('K', 'D'): -1, ('I', 'C'): -3, ('Z', 'D'): 3, ('F', 'R'): -5, ('X', 'K'): -2, ('Q', 'D'): 1, ('X', 'G'): -2, ('Z', 'L'): -3, ('X', 'C'): -4, ('Z', 'H'): 1, ('B', 'L'): -4, ('B', 'H'): 1, ('F', 'F'): 8, ('X', 'W'): -5, ('B', 'D'): 4, ('D', 'A'): 0, ('S', 'L'): -4, ('X', 'S'): -1, ('F', 'N'): -4, ('S', 'R'): -1, ('W', 'D'): -8, ('V', 'Y'): -3, ('W', 'L'): -3, ('H', 'R'): 1, ('W', 'H'): -3, ('H', 'N'): 2, ('W', 'T'): -6, ('T', 'T'): 4, ('S', 'F'): -3, ('W', 'P'): -7, ('L', 'D'): -5, ('B', 'I'): -3, ('L', 'H'): -3, ('S', 'N'): 1, ('B', 'T'): 0, ('L', 'L'): 5, ('Y', 'K'): -5, ('E', 'Q'): 2, ('Y', 'G'): -6, ('Z', 'S'): -1, ('Y', 'C'): -1, ('G', 'D'): 0, ('B', 'V'): -3, ('E', 'A'): 0, ('Y', 'W'): -2, ('E', 'E'): 5, ('Y', 'S'): -3, ('C', 'N'): -5, ('V', 'C'): -3, ('T', 'H'): -3, ('P', 'R'): -1, ('V', 'G'): -2, ('T', 'L'): -3, ('V', 'K'): -4, ('K', 'Q'): 0, ('R', 'A'): -3, ('I', 'R'): -2, ('T', 'D'): -1, ('P', 'F'): -5, ('I', 'N'): -2, ('K', 'I'): -3, ('M', 'D'): -4, ('V', 'W'): -8, ('W', 'W'): 12, ('M', 'H'): -4, ('P', 'N'): -2, ('K', 'A'): -2, ('M', 'L'): 3, ('K', 'E'): -1, ('Z', 'E'): 4, ('X', 'N'): -1, ('Z', 'A'): -1, ('Z', 'M'): -2, ('X', 'F'): -3, ('K', 'C'): -7, ('B', 'Q'): 0, ('X', 'B'): -1, ('B', 'M'): -4, ('F', 'C'): -6, ('Z', 'Q'): 4, ('X', 'Z'): -1, ('F', 'G'): -5, ('B', 'E'): 3, ('X', 'V'): -1, ('F', 'K'): -7, ('B', 'A'): 0, ('X', 'R'): -2, ('D', 'D'): 5, ('W', 'G'): -8, ('Z', 'F'): -6, ('S', 'Q'): -2, ('W', 'C'): -8, ('W', 'K'): -5, ('H', 'Q'): 3, ('L', 'C'): -7, ('W', 'N'): -4, ('S', 'A'): 1, ('L', 'G'): -5, ('W', 'S'): -2, ('S', 'E'): -1, ('H', 'E'): -1, ('S', 'I'): -2, ('H', 'A'): -3, ('S', 'M'): -2, ('Y', 'L'): -2, ('Y', 'H'): -1, ('Y', 'D'): -5, ('E', 'R'): -3, ('X', 'P'): -2, ('G', 'G'): 5, ('G', 'C'): -4, ('E', 'N'): 1, ('Y', 'T'): -3, ('Y', 'P'): -6, ('T', 'K'): -1, ('A', 'A'): 3, ('P', 'Q'): 0, ('T', 'C'): -3, ('V', 'H'): -3, ('T', 'G'): -1, ('I', 'Q'): -3, ('Z', 'T'): -2, ('C', 'R'): -4, ('V', 'P'): -2, ('P', 'E'): -2, ('M', 'C'): -6, ('K', 'N'): 1, ('I', 'I'): 6, ('P', 'A'): 1, ('M', 'G'): -4, ('T', 'S'): 2, ('I', 'E'): -3, ('P', 'M'): -3, ('M', 'K'): 0, ('I', 'A'): -1, ('P', 'I'): -3, ('R', 'R'): 6, ('X', 'M'): -2, ('L', 'I'): 1, ('X', 'I'): -1, ('Z', 'B'): 2, ('X', 'E'): -1, ('Z', 'N'): 0, ('X', 'A'): -1, ('B', 'R'): -2, ('B', 'N'): 3, ('F', 'D'): -7, ('X', 'Y'): -3, ('Z', 'R'): -1, ('F', 'H'): -3, ('B', 'F'): -5, ('F', 'L'): 0, ('X', 'Q'): -1, ('B', 'B'): 4} ################################################################################################### # Color dictionaries. # ################################################################################################### def convert_rgb_to_hex(rgb_tuple): """ Converts an RGB color code (scaled from 0 to 1) to its corresponding HEX code. """ rgb_tuple = [int(i*255) for i in rgb_tuple] hexa = [format(c, "02x") for c in rgb_tuple] return "#" + "".join(hexa) def convert_hex_to_rgb(hex_string): hex_string = hex_string.lstrip("#") return tuple(int(hex_string[i:i+2], 16)/255.0 for i in (0, 2, 4)) #-------------------------- # Regular colors palette. - #-------------------------- # PyMod color palette. pymod_regular_colors_list = ['red', 'green', 'blue', 'yellow', 'violet', 'cyan', 'salmon', 'pink', 'magenta', 'orange', 'purple', 'firebrick', 'chocolate', 'gray', 'white'] pymod_regular_colors_dict = {'red': "#ff0000", 'green': "#00ff00", 'blue': "#0000ff", 'yellow': "#ffff00", 'violet': "#ee82ee", 'cyan': "#00ffff", 'salmon': "#fa8072", 'pink': "#ffc0cb", 'magenta': "#ff00ff", 'orange': "#ffa500", 'purple': "#a020f0", 'firebrick': "#b22222", 'chocolate': "#d2691e", 'gray': "#bebebe", 'white': "#ffffff",} # PyMOL color cycle. # pymol_full_color_cycle = [ # "carbon", # "cyan", # "lightmagenta", # "yellow", # "salmon", # "hydrogen", # "slate", # "orange", # "lime", # "deepteal", # "hotpink", # "yelloworange", # "violetpurple", # "grey70", # "marine", # "olive", # "smudge", # "teal", # "dirtyviolet", # "wheat", # "deepsalmon", # "lightpink", # "aquamarine", # "paleyellow", # "limegreen", # "skyblue", # "warmpink", # "limon", # "violet", # "bluewhite", # "greencyan", # "sand", # "forest", # "lightteal", # "darksalmon", # "splitpea", # "raspberry", # "grey50", # "deepblue", # "brown"] # PyMOL colors palette. Used to color structures loaded in PyMOL. Takes only a certain number of # colors from the full cycle. pymol_regular_colors_list = [ "carbon", "cyan", "lightmagenta", "yellow", "salmon", "hydrogen", "slate", "orange", "lime", "deepteal", "hotpink", "yelloworange", "violetpurple", "grey70", "marine", "olive", "smudge", "teal", "dirtyviolet", "wheat"] # Obtained from: https://pymolwiki.org/index.php/Color_Values pymol_regular_colors_dict_rgb = { "carbon": (0.2, 1.0, 0.2), "cyan": (0.0, 1.0, 1.0), "lightmagenta": (1.0, 0.2, 0.8), "yellow": (1.0, 1.0, 0.0), "salmon": (1.0, 0.6, 0.6), "hydrogen": (0.9, 0.9, 0.9), "slate": (0.5, 0.5, 1.0), "orange": (1.0, 0.5, 0.0), "lime": (0.5, 1.0, 0.5), "deepteal": (0.1, 0.6, 0.6), "hotpink": (1.0, 0.0, 0.5), "yelloworange": (1.0, 0.87, 0.37), "violetpurple": (0.55, 0.25, 0.60), "grey70": (0.7, 0.7, 0.7), "marine": (0.0, 0.5, 1.0), "olive": (0.77, 0.70, 0.00), "smudge": (0.55, 0.70, 0.40), "teal": (0.00, 0.75, 0.75), "dirtyviolet": (0.70, 0.50, 0.50), "wheat": (0.99, 0.82, 0.65)} # PyMOL light colors palette. Used to color multiple chains models. pymol_light_colors_prefix = "l" pymol_light_colors_list = [pymol_light_colors_prefix +"_"+c for c in pymol_regular_colors_list] pymol_light_colors_dict_rgb = { pymol_light_colors_prefix + "_carbon": (0.80, 1.0, 0.80), # (0.94, 1.0, 0.94), pymol_light_colors_prefix + "_cyan": (0.80, 1.0, 1.0), pymol_light_colors_prefix + "_lightmagenta": (1.0, 0.75, 0.94), pymol_light_colors_prefix + "_yellow": (1.0, 1.0, 0.8), pymol_light_colors_prefix + "_salmon": (1.0, 0.86, 0.86), pymol_light_colors_prefix + "_hydrogen": (0.98, 0.98, 0.98), pymol_light_colors_prefix + "_slate": (0.85, 0.85, 1.0), pymol_light_colors_prefix + "_orange": (1.0, 0.9, 0.7), pymol_light_colors_prefix + "_lime": (0.85, 1.0, 0.85), pymol_light_colors_prefix + "_deepteal": (0.7, 0.95, 0.95), pymol_light_colors_prefix + "_hotpink": (1.0, 0.8, 0.98), pymol_light_colors_prefix + "_yelloworange": (1.0, 0.94, 0.70), pymol_light_colors_prefix + "_violetpurple": (0.58, 0.5, 0.60), pymol_light_colors_prefix + "_grey70": (0.87, 0.87, 0.87), pymol_light_colors_prefix + "_marine": (0.7, 0.98, 1.0), pymol_light_colors_prefix + "_olive": (0.77, 0.75, 0.63), pymol_light_colors_prefix + "_smudge": (0.65, 0.70, 0.62), pymol_light_colors_prefix + "_teal": (0.56, 0.75, 0.75), pymol_light_colors_prefix + "_dirtyviolet": (0.70, 0.62, 0.62), pymol_light_colors_prefix + "_wheat": (0.99, 0.92, 0.87)} #----------------------------- # Single amino acids colors. - #----------------------------- # Starts to define color dictionaries for amminoacids. # residue_color_dict = { # "A": "blue", # "L": "blue", # "I": "blue", # "M": "blue", # "W": "blue", # "F": "blue", # "V": "blue", # "T": "green", # "N": "green", # "Q": "green", # "S": "green", # "P": "yellow", # "G": "orange", # "R": "red", # "K": "red", # "C": "pink", # "D": "magenta", # "E": "magenta", # "H": "cyan", # "Y": "cyan", # "X": "white", # "-": "white"} #-------------------------------------------------------------------------- # Used to color residues according to their secondary structure. - #-------------------------------------------------------------------------- # Observed secondary structure. pymol_obs_sec_str_name = "pymod_oss" sec_str_color_dict = { pymol_obs_sec_str_name + "_H": (1.0, 0.0, 0.0), # PyMOL helix: red. pymol_obs_sec_str_name + "_S": (1.0, 1.0, 0.0), # PyMOL sheet: yellow. pymol_obs_sec_str_name + "_L": (0.0, 1.0, 0.0), # PyMOL aperiodic: green. pymol_obs_sec_str_name + "_" : (1.0, 1.0, 1.0), pymol_obs_sec_str_name + "_None" : (1.0, 1.0, 1.0)} # Predicted secondary structure. pymol_psipred_color_name = "pymod_psipred" # Generates names like: 'pymod_psipred_8_H' (the name of the color with which residues predicted in # an helix with confidence score of 8 will be colored). psipred_color_dict = { # Helices. pymol_psipred_color_name + "_9_H": (1.0, 0.0, 0.0), pymol_psipred_color_name + "_8_H": (1.0, 0.098039215686274508, 0.098039215686274508), pymol_psipred_color_name + "_7_H": (1.0, 0.20000000000000001, 0.20000000000000001), pymol_psipred_color_name + "_6_H": (1.0, 0.29803921568627451, 0.29803921568627451), pymol_psipred_color_name + "_5_H": (1.0, 0.40000000000000002, 0.40000000000000002), pymol_psipred_color_name + "_4_H": (1.0, 0.50196078431372548, 0.50196078431372548), pymol_psipred_color_name + "_3_H": (1.0, 0.59999999999999998, 0.59999999999999998), pymol_psipred_color_name + "_2_H": (1.0, 0.70196078431372544, 0.70196078431372544), pymol_psipred_color_name + "_1_H": (1.0, 0.80000000000000004, 0.80000000000000004), pymol_psipred_color_name + "_0_H": (1.0, 0.90196078431372551, 0.90196078431372551), # Sheets. pymol_psipred_color_name + "_9_E": (1.0, 1.0, 0.0), pymol_psipred_color_name + "_8_E": (1.0, 1.0, 0.098039215686274508), pymol_psipred_color_name + "_7_E": (1.0, 1.0, 0.20000000000000001), pymol_psipred_color_name + "_6_E": (1.0, 1.0, 0.29803921568627451), pymol_psipred_color_name + "_5_E": (1.0, 1.0, 0.40000000000000002), pymol_psipred_color_name + "_4_E": (1.0, 1.0, 0.50196078431372548), pymol_psipred_color_name + "_3_E": (1.0, 1.0, 0.59999999999999998), pymol_psipred_color_name + "_2_E": (1.0, 1.0, 0.70196078431372544), pymol_psipred_color_name + "_1_E": (1.0, 1.0, 0.80000000000000004), pymol_psipred_color_name + "_0_E": (1.0, 1.0, 0.90196078431372551), # Aperiodic. pymol_psipred_color_name + "_9_C": (0.0, 1.0, 0.0), pymol_psipred_color_name + "_8_C": (0.098039215686274508, 1.0, 0.098039215686274508), pymol_psipred_color_name + "_7_C": (0.20000000000000001, 1.0, 0.20000000000000001), pymol_psipred_color_name + "_6_C": (0.29803921568627451, 1.0, 0.29803921568627451), pymol_psipred_color_name + "_5_C": (0.40000000000000002, 1.0, 0.40000000000000002), pymol_psipred_color_name + "_4_C": (0.50196078431372548, 1.0, 0.50196078431372548), pymol_psipred_color_name + "_3_C": (0.59999999999999998, 1.0, 0.59999999999999998), pymol_psipred_color_name + "_2_C": (0.70196078431372544, 1.0, 0.70196078431372544), pymol_psipred_color_name + "_1_C": (0.80000000000000004, 1.0, 0.80000000000000004), pymol_psipred_color_name + "_0_C": (0.90196078431372551, 1.0, 0.90196078431372551) } #--------------------------------------------------- # A dictionary containing colors for CAMPO scores. - #--------------------------------------------------- pymol_campo_color_name = "pymod_campo" campo_color_dict = { pymol_campo_color_name + "_None": (1,1,1), # (1,1,1), pymol_campo_color_name + "_1": (0.0, 0.1588235294117647, 1.0), # (0.0, 0.0, 0.5), pymol_campo_color_name + "_2": (0.0, 0.50392156862745097, 1.0), # (0.0, 0.0, 0.94563279857397498), pymol_campo_color_name + "_3": (0.0, 0.83333333333333337, 1.0), # (0.0, 0.29999999999999999, 1.0), pymol_campo_color_name + "_4": (0.21189120809614148, 1.0, 0.75585072738772952), # (0.0, 0.69215686274509802, 1.0), pymol_campo_color_name + "_5": (0.49019607843137247, 1.0, 0.47754585705249841), # (0.16129032258064513, 1.0, 0.80645161290322587), pymol_campo_color_name + "_6": (0.75585072738772918, 1.0, 0.2118912080961417), # (0.49019607843137247, 1.0, 0.47754585705249841), pymol_campo_color_name + "_7": (1.0, 0.9012345679012348, 0.0), # (0.80645161290322565, 1.0, 0.16129032258064513), pymol_campo_color_name + "_8": (1.0, 0.58169934640522891, 0.0), # (1.0, 0.7705156136528688, 0.0), pymol_campo_color_name + "_9": (1.0, 0.27668845315904156, 0.0), # (1.0, 0.40740740740740755, 0.0), pymol_campo_color_name + "_10": (0.8743315508021392, 0.0, 0.0) # (0.94563279857397531, 0.029774872912127992, 0.0) } #-------------------------- # SCR_FIND values colors. - #-------------------------- pymol_scr_color_name = "pymod_scr" scr_color_dict = { pymol_scr_color_name + "_None": (1,1,1), pymol_scr_color_name + "_1": (0.8743315508021392, 0.0, 0.0), pymol_scr_color_name + "_2": (1.0, 0.27668845315904156, 0.0), pymol_scr_color_name + "_3": (1.0, 0.58169934640522891, 0.0), pymol_scr_color_name + "_4": (1.0, 0.9012345679012348, 0.0), pymol_scr_color_name + "_5": (0.75585072738772918, 1.0, 0.2118912080961417), pymol_scr_color_name + "_6": (0.49019607843137247, 1.0, 0.47754585705249841), pymol_scr_color_name + "_7": (0.21189120809614148, 1.0, 0.75585072738772952), pymol_scr_color_name + "_8": (0.0, 0.83333333333333337, 1.0), pymol_scr_color_name + "_9": (0.0, 0.50392156862745097, 1.0), pymol_scr_color_name + "_10": (0.0, 0.1588235294117647, 1.0)} #----------------------------------------------------- # A dictionary containing colors for entropy scores. - #----------------------------------------------------- pymol_entropy_color_name = "pymod_entropy" entropy_color_dict = { pymol_entropy_color_name + "_None": (1.0, 1.0, 1.0), pymol_entropy_color_name + "_9": (0.5490196078431373, 0.0392156862745098, 0.6431372549019608), pymol_entropy_color_name + "_8": (0.6627450980392157, 0.13725490196078433, 0.5843137254901961), pymol_entropy_color_name + "_7": (0.7607843137254902, 0.23921568627450981, 0.5019607843137255), pymol_entropy_color_name + "_6": (0.8431372549019608, 0.3411764705882353, 0.4196078431372549), pymol_entropy_color_name + "_5": (0.9137254901960784, 0.4470588235294118, 0.3411764705882353), pymol_entropy_color_name + "_4": (0.9686274509803922, 0.5215686274509804, 0.054901960784313725), pymol_entropy_color_name + "_3": (0.9921568627450981, 0.6862745098039216, 0.19215686274509805), pymol_entropy_color_name + "_2": (0.984313725490196, 0.8274509803921568, 0.1411764705882353), pymol_entropy_color_name + "_1": (0.9372549019607843, 0.9725490196078431, 0.12941176470588237) } # # Consurf color scheme. # def get_rgb_tuple(t): # return tuple([i/255.0 for i in t]) # # entropy_color_dict = { # pymol_entropy_color_name + "_None": (0.7, 0.7, 0.7), # pymol_entropy_color_name + "_9": get_rgb_tuple((15, 199, 207)), # pymol_entropy_color_name + "_8": get_rgb_tuple((143, 255, 255)), # pymol_entropy_color_name + "_7": get_rgb_tuple((208, 255, 255)), # pymol_entropy_color_name + "_6": get_rgb_tuple((224, 255, 255)), # pymol_entropy_color_name + "_5": get_rgb_tuple((255, 255, 255)), # pymol_entropy_color_name + "_4": get_rgb_tuple((255, 232, 240)), # pymol_entropy_color_name + "_3": get_rgb_tuple((240, 199, 223)), # pymol_entropy_color_name + "_2": get_rgb_tuple((235, 118, 157)), # pymol_entropy_color_name + "_1": get_rgb_tuple((159, 32, 95)), # } #---------------------------- # Pair conservation colors. - #---------------------------- pymol_pc_color_name = "pymod_pc" pc_color_dict = { pymol_pc_color_name + "_0": (1.0, 1.0, 1.0), pymol_pc_color_name + "_1": (1.0, 0.75, 0.75), pymol_pc_color_name + "_2": (1.0, 0.30, 0.30), # (1.0, 0.25, 0.25), } #---------------------- # DOPE values colors. - #---------------------- pymol_dope_color_name = "pymod_dope" dope_color_dict = { pymol_dope_color_name + "_None": (1,1,1), pymol_dope_color_name + "_1": (0.0, 0.1588235294117647, 1.0), pymol_dope_color_name + "_2": (0.0, 0.50392156862745097, 1.0), pymol_dope_color_name + "_3": (0.0, 0.83333333333333337, 1.0), pymol_dope_color_name + "_4": (0.21189120809614148, 1.0, 0.75585072738772952), pymol_dope_color_name + "_5": (0.49019607843137247, 1.0, 0.47754585705249841), pymol_dope_color_name + "_6": (0.75585072738772918, 1.0, 0.2118912080961417), pymol_dope_color_name + "_7": (1.0, 0.9012345679012348, 0.0), pymol_dope_color_name + "_8": (1.0, 0.58169934640522891, 0.0), pymol_dope_color_name + "_9": (1.0, 0.27668845315904156, 0.0), pymol_dope_color_name + "_10": (0.8743315508021392, 0.0, 0.0)} #------------------ # Domains colors. - #------------------ domain_colors_dict = {'01_limegreen': (0.5, 1.0, 0.5), '02_yellow': (1.0, 1.0, 0.0), '03_red': (1.0, 0.0, 0.0), '04_marineblue': (0.0, 0.5, 1.0), '05_magenta': (1.0, 0.2, 0.8), '06_yelloworange': (1.0, 0.87, 0.37), '07_lightblue': (0.0, 0.8333333333333334, 1.0), '08_lightgreen': (0.7558507273877292, 1.0, 0.2118912080961417), '09_lightyellow': (1.0, 1.0, 0.9019607843137255), '10_orange': (1.0, 0.5816993464052289, 0.0), '11_violetpurple': (0.55, 0.25, 0.6), '12_slate': (0.5, 0.5, 1.0), '13_smudge': (0.55, 0.7, 0.4)} domain_color_orderedkeys = list(domain_colors_dict.keys()) domain_color_orderedkeys.sort() domain_colors_ordered = [(k, domain_colors_dict[k]) for k in domain_color_orderedkeys] #------------------------------- # Hydrophobicity scale colors. - #------------------------------- # Initiliazes the hydrophobicity scale colors in PyMOL. pymol_polarity_color_name = "pymod_h" # Kyte and Doolittle: J Mol Biol. 1982 May 5;157(1):105-32. kyte_doolittle_h_dictionary = { pymol_polarity_color_name + '_A': (1.0, 0.59607843137254901, 0.59607843137254901), pymol_polarity_color_name + '_C': (1.0, 0.4392156862745098, 0.4392156862745098), pymol_polarity_color_name + '_E': (0.2196078431372549, 0.2196078431372549, 1.0), pymol_polarity_color_name + '_D': (0.2196078431372549, 0.2196078431372549, 1.0), pymol_polarity_color_name + '_G': (0.90980392156862744, 0.90980392156862744, 1.0), pymol_polarity_color_name + '_F': (1.0, 0.37647058823529411, 0.37647058823529411), pymol_polarity_color_name + '_I': (1.0, 0.0, 0.0), pymol_polarity_color_name + '_H': (0.28235294117647058, 0.28235294117647058, 1.0), pymol_polarity_color_name + '_K': (0.13333333333333333, 0.13333333333333333, 1.0), pymol_polarity_color_name + '_M': (1.0, 0.5725490196078431, 0.5725490196078431), pymol_polarity_color_name + '_L': (1.0, 0.14901960784313728, 0.14901960784313728), pymol_polarity_color_name + '_N': (0.2196078431372549, 0.2196078431372549, 1.0), pymol_polarity_color_name + '_Q': (0.2196078431372549, 0.2196078431372549, 1.0), pymol_polarity_color_name + '_P': (0.64313725490196072, 0.64313725490196072, 1.0), pymol_polarity_color_name + '_S': (0.82352941176470584, 0.82352941176470584, 1.0), pymol_polarity_color_name + '_R': (0.0, 0.0, 1.0), pymol_polarity_color_name + '_T': (0.84705882352941175, 0.84705882352941175, 1.0), pymol_polarity_color_name + '_W': (0.80000000000000004, 0.80000000000000004, 1.0), pymol_polarity_color_name + '_V': (1.0, 0.062745098039215685, 0.062745098039215685), pymol_polarity_color_name + '_Y': (0.71372549019607845, 0.71372549019607845, 1.0), pymol_polarity_color_name + '_X': (1.0, 1.0, 1.0)} # Fauchere and Pliska: Eur. J. Med. Chem. 18:369-375(1983). fauchere_pliska_h_scale = { pymol_polarity_color_name + '_A': (1.0, 0.27450980392156865, 0.27450980392156865), pymol_polarity_color_name + '_C': (1.0, 0.0, 0.0), pymol_polarity_color_name + '_E': (0.0, 0.0, 1.0), pymol_polarity_color_name + '_D': (0.0, 0.0, 1.0), pymol_polarity_color_name + '_G': (0.36862745098039218, 0.36862745098039218, 1.0), pymol_polarity_color_name + '_F': (1.0, 0.0, 0.0), pymol_polarity_color_name + '_I': (1.0, 0.0, 0.0), pymol_polarity_color_name + '_H': (0.0, 0.0, 1.0), pymol_polarity_color_name + '_K': (0.0, 0.0, 1.0), pymol_polarity_color_name + '_M': (1.0, 0.21176470588235319, 0.21176470588235319), pymol_polarity_color_name + '_L': (1.0, 0.0, 0.0), pymol_polarity_color_name + '_N': (0.0, 0.0, 1.0), pymol_polarity_color_name + '_Q': (0.0, 0.0, 1.0), pymol_polarity_color_name + '_P': (0.0, 0.0, 1.0), pymol_polarity_color_name + '_S': (0.12549019607843137, 0.12549019607843137, 1.0), pymol_polarity_color_name + '_R': (0.0, 0.0, 1.0), pymol_polarity_color_name + '_T': (0.18823529411764706, 0.18823529411764706, 1.0), pymol_polarity_color_name + '_W': (0.062745098039215685, 0.062745098039215685, 1.0), pymol_polarity_color_name + '_V': (1.0, 0.0, 0.0), pymol_polarity_color_name + '_Y': (0.0, 0.0, 1.0), pymol_polarity_color_name + '_X': (1.0, 1.0, 1.0)} # This is the color dictionary actually used in PyMod. polarity_color_dict = kyte_doolittle_h_dictionary #----------------------------- # Residue type color scheme. - #----------------------------- _residue_type_color_dict = {"HY": (1.0, 1.0, 1.0), # "#ffffff", Hydrophobic. "BA": (0.12156862745098039, 0.4666666666666667, 0.7058823529411765), # "#1f77b4". Basic. "AC": (0.8392156862745098, 0.15294117647058825, 0.1568627450980392), # "#d62728". Acid. "PO": (1.0, 0.4980392156862745, 0.054901960784313725), # "#ff7f0e". Polar. "AR": (0.17254901960784313, 0.6274509803921569, 0.17254901960784313), # "#2ca02c". Aromatic. # "FL": (0.5803921568627451, 0.403921568627451, 0.7411764705882353), # "#9467bd". Flexible. "FL": (0.7372549019607844, 0.7411764705882353, 0.13333333333333333), # "#bcbd22". Flexible. "X": (0.4980392156862745, 0.4980392156862745, 0.4980392156862745), # "#7f7f7f". Other residues. } pymol_residue_type_color_name = "pymod_restype" residue_type_color_dict = { pymol_residue_type_color_name + '_A': _residue_type_color_dict["HY"], pymol_residue_type_color_name + '_C': _residue_type_color_dict["HY"], pymol_residue_type_color_name + '_E': _residue_type_color_dict["AC"], pymol_residue_type_color_name + '_D': _residue_type_color_dict["AC"], pymol_residue_type_color_name + '_G': _residue_type_color_dict["FL"], pymol_residue_type_color_name + '_F': _residue_type_color_dict["AR"], pymol_residue_type_color_name + '_I': _residue_type_color_dict["HY"], pymol_residue_type_color_name + '_H': _residue_type_color_dict["AR"], pymol_residue_type_color_name + '_K': _residue_type_color_dict["BA"], pymol_residue_type_color_name + '_M': _residue_type_color_dict["HY"], pymol_residue_type_color_name + '_L': _residue_type_color_dict["HY"], pymol_residue_type_color_name + '_N': _residue_type_color_dict["PO"], pymol_residue_type_color_name + '_Q': _residue_type_color_dict["PO"], pymol_residue_type_color_name + '_P': _residue_type_color_dict["FL"], pymol_residue_type_color_name + '_S': _residue_type_color_dict["PO"], pymol_residue_type_color_name + '_R': _residue_type_color_dict["BA"], pymol_residue_type_color_name + '_T': _residue_type_color_dict["PO"], pymol_residue_type_color_name + '_W': _residue_type_color_dict["AR"], pymol_residue_type_color_name + '_V': _residue_type_color_dict["HY"], pymol_residue_type_color_name + '_Y': _residue_type_color_dict["AR"], pymol_residue_type_color_name + '_X': _residue_type_color_dict["X"]} #--------------------------------------------- # Viridis colormap, adapted from matplotlib. - #--------------------------------------------- viridis_colors = [ [0.267004, 0.004874, 0.329415], [0.272594, 0.025563, 0.353093], [0.277018, 0.050344, 0.375715], [0.280267, 0.073417, 0.397163], [0.282327, 0.094955, 0.417331], [0.283197, 0.11568, 0.436115], [0.282884, 0.13592, 0.453427], [0.281412, 0.155834, 0.469201], [0.278826, 0.17549, 0.483397], [0.275191, 0.194905, 0.496005], [0.270595, 0.214069, 0.507052], [0.265145, 0.232956, 0.516599], [0.258965, 0.251537, 0.524736], [0.252194, 0.269783, 0.531579], [0.244972, 0.287675, 0.53726], [0.237441, 0.305202, 0.541921], [0.229739, 0.322361, 0.545706], [0.221989, 0.339161, 0.548752], [0.214298, 0.355619, 0.551184], [0.206756, 0.371758, 0.553117], [0.19943, 0.387607, 0.554642], [0.192357, 0.403199, 0.555836], [0.185556, 0.41857, 0.556753], [0.179019, 0.433756, 0.55743], [0.172719, 0.448791, 0.557885], [0.166617, 0.463708, 0.558119], [0.160665, 0.47854, 0.558115], [0.154815, 0.493313, 0.55784], [0.149039, 0.508051, 0.55725], [0.143343, 0.522773, 0.556295], [0.13777, 0.537492, 0.554906], [0.132444, 0.552216, 0.553018], [0.127568, 0.566949, 0.550556], [0.123463, 0.581687, 0.547445], [0.120565, 0.596422, 0.543611], [0.119423, 0.611141, 0.538982], [0.120638, 0.625828, 0.533488], [0.12478, 0.640461, 0.527068], [0.132268, 0.655014, 0.519661], [0.143303, 0.669459, 0.511215], [0.157851, 0.683765, 0.501686], [0.175707, 0.6979, 0.491033], [0.196571, 0.711827, 0.479221], [0.220124, 0.725509, 0.466226], [0.24607, 0.73891, 0.452024], [0.274149, 0.751988, 0.436601], [0.304148, 0.764704, 0.419943], [0.335885, 0.777018, 0.402049], [0.369214, 0.788888, 0.382914], [0.404001, 0.800275, 0.362552], [0.440137, 0.811138, 0.340967], [0.477504, 0.821444, 0.318195], [0.515992, 0.831158, 0.294279], [0.555484, 0.840254, 0.269281], [0.595839, 0.848717, 0.243329], [0.636902, 0.856542, 0.21662], [0.678489, 0.863742, 0.189503], [0.720391, 0.87035, 0.162603], [0.762373, 0.876424, 0.137064], [0.804182, 0.882046, 0.114965], [0.845561, 0.887322, 0.099702], [0.886271, 0.892374, 0.095374], [0.926106, 0.89733, 0.104071], [0.964894, 0.902323, 0.123941] ] viridis_colors_hex = [convert_rgb_to_hex(c) for c in viridis_colors] ################################################################################################### # PyMod elements features. # ################################################################################################### feature_types = ["domains", "sequence"] ################################################################################################### # Standard bioinformatics dictionaries and lists. # ################################################################################################### # Containers of the letters representing amminoacids in sequences. prot_one_to_three_code = { "G": "GLY", "A": "ALA", "L": "LEU", "I" : "ILE", "R" : "ARG", "K" : "LYS", "M" : "MET", "C" : "CYS", "Y" : "TYR", "T" : "THR", "P" : "PRO", "S" : "SER", "W" : "TRP", "D" : "ASP", "E" : "GLU", "N" : "ASN", "Q" : "GLN", "F" : "PHE", "H" : "HIS", "V" : "VAL"} # Code for the 20 standard amminoacids. code_standard = { 'ALA':'A', 'VAL':'V', 'PHE':'F', 'PRO':'P', 'MET':'M', 'ILE':'I', 'LEU':'L', 'ASP':'D', 'GLU':'E', 'LYS':'K', 'ARG':'R', 'SER':'S', 'THR':'T', 'TYR':'Y', 'HIS':'H', 'CYS':'C', 'ASN':'N', 'GLN':'Q', 'TRP':'W', 'GLY':'G' } # Code for standard nucleic acids residues. nucleic_acids_dictionary = { # Deoxyribonucleotides as defined in PDB records. # ' DA':'a',' DT':'t',' DG':'g',' DC':'c', ' DA':'A',' DT':'T',' DG':'G',' DC':'C', # Ribonucleotides. # ' A':'a',' U':'u',' G':'g',' C':'c' ' A':'A',' U':'U',' G':'G',' C':'C' } code_standard.update(nucleic_acids_dictionary) ################################################################################################### # Updated data dictionaries for the new version. # ################################################################################################### #------------ # Proteins. - #------------ # One letter. prot_standard_one_letter = ("A","C","D","E","F","G","H","I","K","L","M","N","P","Q","R","S","T","V","W","Y") prot_standard_one_letter_set = set(prot_standard_one_letter) prot_standard_and_x_one_letter = ("A","C","D","E","F","G","H","I","K","L","M","N","P","Q","R","S","T","V","W","Y","X") prot_standard_and_x_one_letter_set = set(prot_standard_and_x_one_letter) non_prot_standard_regex = "[^ACDEFGHIKLMNPQRSTVWY-]" non_prot_standard_and_x_regex = "[^ACDEFGHIKLMNPQRSTVWYX-]" # Three letters. prot_standard_three_letters = ("ALA","CYS","ASP","GLU","PHE","GLY","HIS","ILE","LYS","LEU","MET","ASN","PRO","GLN","ARG","SER","THR","VAL","TRP","TYR") prot_standard_three_letters_set = set(prot_standard_three_letters) prot_standard_and_x_three_letters = ("ALA","CYS","ASP","GLU","PHE","GLY","HIS","ILE","LYS","LEU","MET","ASN","PRO","GLN","ARG","SER","THR","VAL","TRP","TYR","XXX") prot_standard_and_x_three_letters_set = set(prot_standard_and_x_three_letters) # Dictionaries. prot_standard_and_x_one_to_three_dict = { "G": "GLY", "A": "ALA", "L": "LEU", "I": "ILE", "R": "ARG", "K": "LYS", "M": "MET", "C": "CYS", "Y": "TYR", "T": "THR", "P": "PRO", "S": "SER", "W": "TRP", "D": "ASP", "E": "GLU", "N": "ASN", "Q": "GLN", "F": "PHE", "H": "HIS", "V": "VAL", "X": "XXX" } prot_standard_and_x_three_to_one_dict = { 'ALA': 'A', 'VAL': 'V', 'PHE': 'F', 'PRO': 'P', 'MET': 'M', 'ILE': 'I', 'LEU': 'L', 'ASP': 'D', 'GLU': 'E', 'LYS': 'K', 'ARG': 'R', 'SER': 'S', 'THR': 'T', 'TYR': 'Y', 'HIS': 'H', 'CYS': 'C', 'ASN': 'N', 'GLN': 'Q', 'TRP': 'W', 'GLY': 'G', 'XXX': 'X' } def get_prot_one_to_three(one_letter_code): if one_letter_code in prot_standard_and_x_one_letter_set: return prot_standard_and_x_one_to_three_dict.get(one_letter_code) else: return "XXX" def get_prot_three_to_one(three_letter_code): if three_letter_code in prot_standard_and_x_three_letters_set: return prot_standard_and_x_three_to_one_dict.get(three_letter_code) else: return "X" #-------------------- # Heteroatoms data. - #-------------------- std_amino_acid_backbone_atoms = set(("N", "CA", "C")) mod_amino_acid_backbone_atoms = set(("N2", "C1", "C2")) modified_residue_one_letter = "X" ligand_one_letter = "x" water_one_letter = "w" # Heteroatoms to be shown as spheres in PyMOL. sphere_hetres_names = set((" BA", " BR", " CA", " CD", " CO", " CU", " CL", "IOD", " K", " MG", " MN", " NA", " NI", " ZN", "OXY"))
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_tool.py
.py
13,763
359
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Classes used to control PyMod tools (the external programs that PyMod uses). """ import os from . import pymod_os_specific as pmos from pymod_lib.pymod_gui.shared_gui_components_qt import askyesno_qt from pymol.Qt import QtWidgets ##################################################################### # Tools classes. # ##################################################################### class Tool: """ A base class to represent a Tool, an external program used by PyMod. """ def __init__(self, tool_name, tool_full_name): # Id of the tool. Example: 'clustalo'. self.name = tool_name # Full name of the tool. Example: 'Clustal Omega'. self.full_name = tool_full_name # A list of 'Tool_parameter' class objects. self.parameters = [] def show_message_method(self, title, message): """ Method used to display messages raised when using the tool. """ self.pymod.main_window.show_error_message(title, message) def initialize_parameters(self, parameter_list): """ Used to populate the 'self.parameter' attribute with a list of object of the Tool_parameter class and its child classes. """ self.parameters = [] # Reinitializes. for p in parameter_list: p.set_parent_tool(self) self.parameters.append(p) def __getitem__(self, parameter_name): for parameter in self.parameters: if parameter.name == parameter_name: return parameter raise KeyError("'%s' tool does not have a parameter named: '%s'" % (self.name, parameter_name)) class Executable_tool(Tool): #-------------------- # Executable files. - #-------------------- def tool_file_exists(self, parameter_name="exe_file_path"): """ Check if the executable is defined in the PyMod options and if the file exists. """ if self[parameter_name].get_value(): return os.path.isfile(self[parameter_name].get_value()) else: return False def tool_file_not_found(self, parameter_name="exe_file_path"): # If the exe file path is defined in the PyMod configurations but the file does not exists. if self[parameter_name].get_value(): title = "%s is Missing" % (self.full_name) message = "The %s path specified in the PyMod Options Window ('%s') does not exists on your system. If you want to use this function please specify an existent %s executable path in the Options of PyMod." % (self.full_name, self[parameter_name].get_value(), self.full_name) # If the exe file path is not defined in the PyMod configurations. else: title = "%s Path is Missing" % (self.full_name) message = "%s executable path is missing from the PyMod Options. If you want to use this function please install %s and specify its path in the PyMod Options Window." % (self.full_name, self.full_name) self.show_message_method(title, message) #------------------------------------- # Directories with executable files. - #------------------------------------- def tool_dir_exists(self, parameter_name="exe_dir_path"): """ Check if the executable is defined in the PyMod options and if the file exists. """ if self[parameter_name].get_value(): return os.path.isdir(self[parameter_name].get_value()) else: return False def tool_dir_not_found(self, parameter_name="exe_dir_path", message=None): if self[parameter_name].get_value(): title = "%s Path not Found" % (self.full_name) _message = "The %s executables directory specified in the PyMod Options Window ('%s') does not exists on your system. If you want to use this function please specify an existent %s executables directory in the Options of PyMod." % (self.full_name, self[parameter_name].get_value(), self.full_name) else: title = "%s Path is Missing" % (self.full_name) _message = "%s executable path is missing from the PyMod Options. If you want to use this function please install %s and specify its path in the PyMod Options Window." % (self.full_name, self.full_name) message = _message if message == None else message self.show_message_method(title, message) ##################################################################### # Tool parameters classes. # ##################################################################### class Tool_parameter: """ A base class to represent a parameter of a Tool. Its child classes will be used throughout the plugin to represent different types of options of PyMod tools. """ widget_type = None def __init__(self, paramater_name, parameter_full_name, default_value=None, editable=True, auto_find=False, show_widget=True): # Full name of the parameter. This will be displayed in the PyMod options window. # Example: "Executable File". self.full_name = parameter_full_name # Id of the parameter. Example: "exe_full_path" self.name = paramater_name # The value of the parameter. Example: "/usr/bin/clustalo" self.value = None # Execution mode. It can be "local", "remote", "both", "mixed". # self.execution_mode = parameter_execution_mode # This will be set through the 'set_parent_tool()' method. self.parent_tool = None # If this argument is specified in the constructor, its value will be the one to be returned # by the 'get_starting_value()' method of this class. This is used in order to set the value # of the parameter in the PyMod options window when PyMod is started for the first time. self.default_value = default_value # If 'True' allows to edit the paramater values from the PyMod options window. self.editable = editable # If 'True' allows to automatically guess the value of the parameter. self.auto_find = auto_find # If 'False' the widgets for the parameter will not be shown (used for "hidden" options). self.show_widget = show_widget def set_parent_tool(self, parent_tool): self.parent_tool = parent_tool def __repr__(self): return self.value def get_value(self): return self.value def set_value(self, new_value): self.value = new_value def get_starting_value(self): """ Used to set the value of options in the PyMod options window when it is built. """ # If PyMod is launched for the first time try to get a default value. if self.value == None: # If the parameter default value was defined in the object constructor this method will # return this value stored in 'self.default_value'. # Alternatively, the 'guess_first_session_value()' method is called to guess the starting # value. if not self.default_value == None: starting_text = self.default_value else: starting_text = self.guess_first_session_value() # Else get the value obtained from the PyMod main configuration file. else: starting_text = self.value return starting_text ############################################## # Methods to be overridden in child classes. # ############################################## def guess_first_session_value(self): """ This method will try to guess a parameter value when PyMod is started for the first time. This will be overridden in the child classes of the 'Tool_parameter' class in order to be able to retrieve different information. """ return "" def auto_find_command(self): """ Override in child classes. """ pass def can_be_updated_from_gui(self): if not self.show_widget: # Does not interface with the GUI. return False if not self.editable: # The value is displayed in the GUI, but is not editable. return False if self.widget_type == "show_status": # Only show the status. return False return True class Tool_path(Tool_parameter): """ A class to represent a path on the user's machine (both a file or a directory). """ path_type = None widget_type = "path_entryfield" def auto_find_command(self, etry): """ Automatically find the tool value and ask whether to set it in the GUI. """ auto_find_results = self.guess_first_session_value() tool_param_text = "%s '%s'" % (self.parent_tool.full_name, self.full_name) if auto_find_results: message = ("%s was found in one of the system's directories (at: %s)." " Would you like to use this file and set its value in the PyMod" " Options window?" % (tool_param_text, auto_find_results)) answer = askyesno_qt("File Automatically Found", message, parent=self.parent_tool.pymod.get_qt_parent()) if answer: etry.setText(str(auto_find_results)) else: message = ("%s was not found in any of the system's directories. Please" " manually specify its path in the PyMod Options window through" " the 'Browse' button." % (tool_param_text)) self.parent_tool.pymod.main_window.show_info_message("File Not Found", message) class Tool_file(Tool_path): """ A class to represent a file path on the user machine. """ path_type = "file" class Tool_exec_file(Tool_file): """ A class to represent a executable file path on the user machine. """ def guess_first_session_value(self): """ Automatically finds exe_full_path on the user's machine. Most tools have the same executable file name. """ value = pmos.pymod_which(self.parent_tool.name) # 'pymod_which' returns 'None' if it doesn't find the executable. if value == None: value = "" return value class Tool_directory(Tool_path): """ A class to represent a directory path on the user machine. """ path_type = "directory" class Tool_exec_directory(Tool_directory): """ A class to represent a directory path on the user machine containing executable files. """ def guess_first_session_value(self): """ Similar to 'Tool_exec_file' 'guess_first_session_value' method, but this one returns the name of the directory of an executable file localized by 'pymod_which'. """ value = pmos.pymod_which(self.parent_tool.name) if value == None: value = "" else: value = os.path.dirname(value) return value ################################################################################################### # Program specific classes. # ################################################################################################### ##################################################################### # MODELLER tool classes. # ##################################################################### # Tool. class Modeller_tool(Executable_tool): def check_exception(self): """ Checks if MODELLER can be launched, either internally or externally. Returns a 'None' value if MODELLER can be imported, otherwise returns an error message containing the string describing the type of exception raised. """ modeller_exception = pmos.check_importable_modeller(get_exception=True) if modeller_exception is not None: if issubclass(modeller_exception.__class__, ImportError): # isinstance(modeller_exception, ImportError): error_message = ("MODELLER is missing. Please installed MODELLER if you want to use" " this function.") else: error_message = ("MODELLER is present on your system, but it could not be imported" " in PyMod for the following reason:\n\n%s" % modeller_exception) else: error_message = None return error_message def run_internally(self): """ Checks if users want to run MODELLER internally. In PyMod 3, it is always set to 'True'. """ return self["use_importable_modeller"].get_value() # Parameters. class Use_importable_modeller(Tool_parameter): widget_type = "show_status" def get_status(self): # Text of the label to inform the user if MODELLER libs can be imported in PyMOL. text_to_show = "Status: " if pmos.check_importable_modeller(): text_to_show += "Available" status = True else: text_to_show += "Not available" status = False return text_to_show, status def guess_first_session_value(self): return True
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_element.py
.py
35,954
955
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Module implementing classes to represent "PyMod elements", that is each sequence or alignment loaded in the PyMod main window. """ import os from . import pymod_vars as pmdt from .pymod_seq import seq_manipulation from .pymod_seq import seq_conservation from .pymod_seq.seq_headers import check_fetchable_pdb_from_header from .pymod_residue import PyMod_standard_residue from .pymod_exceptions import PyModMissingStructure, PyModSequenceConflict ################################################################################################### # PYMOD ELEMENTS. # ################################################################################################### class PyMod_element: """ A base that stores all the informations of a sequence or sequence cluster. """ cluster = False def __init__(self, header=None, description=None, color="white" ): #---------------------------------------- # Indices and PyMod_element properties. - #---------------------------------------- # It is a unique id to identify each element. It is given by the "unique_index" of the # "pymod" object. This values will be assigned when the element is added to the list of # PyMod_element objects by the '.add_element_to_pymod' method of the PyMod class. self.unique_index = None self.mother = None self.list_of_children = [] self.blast_query = False self.lead = False self.bridge = False #-------------------------- # Sequences and residues. - #-------------------------- self.my_sequence = None #-------------------------------------------------------------------------------- # Headers (name of the sequences and clusters displayed throughout the plugin). - #-------------------------------------------------------------------------------- # The full original header. self.original_header = header self.my_header = header self.my_header_root = header self.compact_header = header self.compact_header_root = header self.compact_header_prefix = "" # Check if a PDB can be fetched for this element from its name. can_be_fetched_results = check_fetchable_pdb_from_header(self.original_header) if can_be_fetched_results == None: self.pdb_can_be_fetched = False self.pdb_id = None self.pdb_chain = None else: self.pdb_can_be_fetched = True self.pdb_id = can_be_fetched_results[0] self.pdb_chain = can_be_fetched_results[1] #-------------------------------- # Descriptions and annotations. - #-------------------------------- self.description = description self.annotations = {} #---------------------------------------------- # Appearance and intercations with the users. - #---------------------------------------------- # Its value is False when the sequence header is not selected, it becomes True when the user # selects the sequence by left-clicking on its header. self.selected = False # Defines the way the sequence has to be colored. self.color_by = "regular" self._color_by = "regular" # Name of the color of the sequence when its "color_by" attribute is set to "regular". self.my_color = color #------------------- # Alignment files. - #------------------- self.tree_file_path = None self.tree_file_name = None ################################################################# # Methods for managing PyMod clusters. # ################################################################# def __repr__(self): return self.my_header + ' ' + self.__class__.__name__ def is_cluster(self): return self.cluster def is_mother(self): if self.is_cluster() and self.list_of_children: return True else: return False def is_child(self, exclude_root_element=True): if self.mother: if exclude_root_element and self.is_root_child(): return False else: return True else: return False def is_root(self): return isinstance(self, PyMod_root_element) def is_root_child(self): return self.mother.is_root() def is_root_sequence(self): return self.is_root_child() and not self.is_cluster() def get_ancestor(self, exclude_root_element=True): if self.is_child(exclude_root_element): if self.mother.get_ancestor(exclude_root_element): return self.mother.get_ancestor(exclude_root_element) else: return self.mother return None def get_descendants(self): descendants = [] for d in self.get_children(): descendants.append(d) if d.is_mother(): descendants.extend(d.get_descendants()) return descendants def filter_for_sequences(method): def filterer(self, sequences_only=False): if sequences_only: return [e for e in method(self, sequences_only) if not e.is_cluster()] else: return method(self, sequences_only) return filterer @filter_for_sequences def get_siblings(self, sequences_only=False): if not self.mother: return [] else: return [c for c in self.mother.list_of_children if c != self] def extract_to_upper_level(self): """ Extracts an element to the upper level. Overridden by subclasses. """ new_mother = self.mother.mother self.remove_all_lead_statuses() new_mother.add_child(self) def delete(self): mother = self.mother mother.remove_child(self) ################################################################# # Check element properties. # ################################################################# def has_structure(self): """ This will be overridden in 'PyMod_sequence_element' classes. """ return False ################################################################# # Cluster leads. # ################################################################# def set_as_lead(self): self.remove_all_lead_statuses() self.lead = True def set_as_query(self): self.remove_all_lead_statuses() self.blast_query = True def remove_all_lead_statuses(self): self.lead = False self.blast_query = False def is_blast_query(self): return self.blast_query def is_lead(self): return self.lead or self.blast_query def is_bridge(self): return self.bridge ################################################################# # Headers formatting. # ################################################################# def get_unique_index_header(self): return pmdt.unique_index_header_formatted % self.unique_index ################################################################# # Colors. # ################################################################# def store_current_color(self): self._color_by = self.color_by def revert_original_color(self): self.color_by = self._color_by ################################################################################################### # CLUSTERS. # ################################################################################################### class _PyMod_cluster_element(PyMod_element): """ Cluster elements represent the 'alignment' elements in the PyMod main window. They take one row in the main window exactly like sequence elements and behave similarly. """ cluster = True def __init__(self, sequence=None, header=None, algorithm=None, cluster_type="generic", cluster_id=None, description=None, color=""): PyMod_element.__init__(self, header, description=description, color=color) self.algorithm = algorithm self.cluster_type = cluster_type self.cluster_id = cluster_id self.initial_number_of_sequences = None self.my_sequence = sequence self.rmsd_dict = None def add_children(self, children): # TODO: use the 'set_initial_number_of_sequences' argument. if not hasattr(children, "__iter__"): children = [children] for child in children: self.add_child(child) if self.initial_number_of_sequences == None: self.initial_number_of_sequences = len(children) def add_child(self, child): # Remove from the old mother. if child.is_child(exclude_root_element=False): old_mother = child.mother old_mother.remove_child(child) # Add to new mother. child.mother = self self.list_of_children.append(child) def remove_child(self, child): self.list_of_children.remove(child) child.remove_all_lead_statuses() def get_children(self): return self.list_of_children def get_lead(self): for child in self.get_children(): if child.is_lead(): return child return None def update_stars(self, adjust_elements=False): self.my_sequence = seq_conservation.compute_stars(self.get_children(), adjust_elements=adjust_elements) def remove_gap_only_columns(self): seq_manipulation.remove_gap_only_columns(self.get_children()) def adjust_aligned_children_length(self): seq_manipulation.adjust_aligned_elements_length(self.get_children()) ################################################################# # Alignment files. # ################################################################# def get_tree_file_path(self): return self.tree_file_path def set_tree_file_path(self, tree_file_path): self.tree_file_path = tree_file_path self.tree_file_name = os.path.basename(tree_file_path) def update_alignment_files(self, alignments_dirpath): if self.tree_file_path is not None and self.tree_file_name is not None: self.tree_file_path = os.path.join(alignments_dirpath, self.tree_file_name) ################################################################################################### # SEQUENCES. # ################################################################################################### class _PyMod_sequence_element(PyMod_element): """ The objects of this class are the sequences (both from sequences and structure files) that appear on the left column or alignments elements. """ def __init__(self, sequence=None, header="", residues=None, description=None, color="white"): PyMod_element.__init__(self, header=header, description=description, color=color) # TODO: cleans up the sequence. pass #---------------------------------------- # Builds the residues and the sequence. - #---------------------------------------- self.my_sequence = sequence self.residues = residues self._polymer_residues = None if self.residues == None and self.my_sequence == None: raise Exception("Either a sequence or a residues list must be provided.") elif self.residues != None and self.my_sequence != None: raise Exception("Can not accept both a sequence and a residues list.") # If the residues list is not provided, build it through the sequence provided in the # constructor. elif self.residues == None and self.my_sequence != None: self.set_residues_from_sequence() elif self.residues != None and self.my_sequence == None: self.set_sequence_from_residues() # Update residues information with indices. self.update_residues_information() #---------------------------------------------------- # Other sequence- or structure-related information. - #---------------------------------------------------- self.initialize_additional_information() def initialize_additional_information(self): # A PyMod element with an associated structure will have a 'PyMod_structure' object assigned # to this attribute. self.structure = None # Boolean flags to define if a sequence has some secondary structure assigned to it. self.assigned_secondary_structure = False self.predicted_secondary_structure = False # Store various type of data for an element. self._has_campo_scores = False self._has_entropy_scores = False self._has_pc_scores = False self._has_dope_scores = False # Contain the features (e.g.: domains) of an element. self.features = dict([(ft, []) for ft in pmdt.feature_types]) self.features_count = 0 self.features_selectors_list = [] # Stores the id of the domain analysis session in which an element was analysed. self.domain_analysis_id = None # When a query element is split in its domains, the derived PyMod elements will be stored # in this list. self.derived_domains_list = [] # When a query element is split in its domains, the PyMod element derived from the # splitting will receive the corresponding 'Domain_feature' object which will be assigned to # this attribute. self.splitted_domain = None # Checks if the element is a protein or a nucleic acid by checking the names of its residues. self.polymer_type = "protein" nucleotides = [nt for nt in list(pmdt.nucleic_acids_dictionary.keys())] for r in self.residues: if r.is_standard_residue() and r.three_letter_code in nucleotides: self.polymer_type = "nucleic_acid" break self.color_by = "regular" def add_feature(self, new_feature): """ Used when adding a feature to a sequence. """ self.features[new_feature.feature_type].append(new_feature) feature_start = int(new_feature.start) feature_end = int(new_feature.end) for r_index, res in enumerate(self.get_polymer_residues()): if feature_start <= r_index <= feature_end: res.features[new_feature.feature_type].append(new_feature) new_feature.element = self self.features_count += 1 def add_domain_feature(self, domain_feature): """ Used when adding a domain feature to a sequence. """ self.features["domains"].append(domain_feature) domain_start = int(domain_feature.start) domain_end = int(domain_feature.end) for r_index, res in enumerate(self.get_polymer_residues()): if domain_start <= r_index < domain_end: res.features["domains"].append(domain_feature) domain_feature.element = self if domain_feature.is_derived: self.splitted_domain = domain_feature def get_domains_features(self): return [feat for feat in self.features["domains"] if not feat.is_derived] def clear_domains(self): self.features["domains"] = [] for r in self.residues: r.features["domains"] = [] self.splitted_domain = None self.derived_domains_list = [] def clear_features(self): self.features["sequence"] = [] for r in self.residues: r.features["sequence"] = [] self.features_selectors_list = [] def clear_derived_domains(self): self.derived_domains_list = [] def set_residues_from_sequence(self): self.residues = [] self._polymer_residues = None for letter in self.my_sequence: if letter != "-": self.residues.append(PyMod_standard_residue(one_letter_code=letter, three_letter_code=pmdt.get_prot_one_to_three(letter))) def set_sequence_from_residues(self): my_sequence = "" for res in self.residues: if res.is_polymer_residue(): my_sequence += res.one_letter_code self.my_sequence = my_sequence def update_residues_information(self): polymer_residue_count = 0 for i,res in enumerate(self.residues): res.index = i # Index considering also heteroresidues in the sequences. res.seq_index = polymer_residue_count # Index considering only the polymer sequence. if res.is_polymer_residue(): polymer_residue_count += 1 if res.db_index == None: res.db_index = i + 1 res.pymod_element = self ############################################################################################### # Sequence related. # ############################################################################################### def set_sequence(self, new_sequence, permissive=False): """ Updates the sequence of a PyMod element with a string provided in the 'new_sequence' argument. The gapless versions of the new and old sequences will always be compared. If 'permissive' is set to 'False' and if the old and new sequences do not match, an exception will be raised. If 'permissive' is set to 'True', the new sequence will overwrite the old one and all the attributes and features of the PyMod element (residue scores, domains, etc...) will be lost. """ current_sequence_ungapped = self.my_sequence.replace("-","") new_sequence_ungapped = new_sequence.replace("-","") if new_sequence_ungapped != current_sequence_ungapped: if not permissive: print("# Sequence:", self.my_header) print("# New:", new_sequence_ungapped) print("# Old:", current_sequence_ungapped) raise PyModSequenceConflict("The new sequence does not match with the previous one.") else: self.set_new_sequence(new_sequence) else: self.my_sequence = new_sequence def set_new_sequence(self, new_sequence): """ Overwrites the old sequence with a new one. Also sets up again the residues of the element, thus removing any previous information. """ self.my_sequence = new_sequence self.set_residues_from_sequence() self.update_residues_information() self.initialize_additional_information() def trackback_sequence(self, sequence_to_align): ali = seq_manipulation.global_pairwise_alignment(self.my_sequence.replace("-", ""), sequence_to_align) self.set_sequence(ali["seq1"]) return ali["seq1"], ali["seq2"] ############################################################################################### # Residues related. # ############################################################################################### def get_polymer_residues(self): """ Get the "polymer residues" of a PyMod element. These residues are the ones actually showed in the sequence loaded in PyMod main window an comprise standard amino acid residues and modified residues (such as a phospho-serine), represented by an X. """ if self._polymer_residues is None: # Stores the list, for fast access when doing multiple calls. self._polymer_residues = [r for r in self.residues if r.is_polymer_residue()] return self._polymer_residues def get_polymer_sequence_string(self): return "".join([res.one_letter_code for res in self.get_polymer_residues()]) def get_standard_residues(self): return [r for r in self.residues if r.is_polymer_residue() and not r.is_modified_residue()] def get_heteroresidues(self, exclude_water=True): return [r for r in self.residues if r.is_heteroresidue(exclude_water=exclude_water)] def get_waters(self): return [r for r in self.residues if r.is_water()] def has_waters(self): return len(self.get_waters()) > 0 def get_residues(self, standard=True, ligands=False, modified_residues=True, water=False): list_of_residues = [] for res in self.residues: if res.is_standard_residue() and standard: list_of_residues.append(res) elif res.is_ligand() and ligands: list_of_residues.append(res) elif res.is_modified_residue() and modified_residues: list_of_residues.append(res) elif res.is_water() and water: list_of_residues.append(res) return list_of_residues def get_residue_by_index(self, index, aligned_sequence_index=False, only_polymer=True): """ Returns a residue having the index provided in the 'index' argument in the sequence. """ if aligned_sequence_index: index = seq_manipulation.get_residue_id_in_gapless_sequence(self.my_sequence, index) if index is None: raise KeyError(index) if only_polymer: return self.get_polymer_residues()[index] else: return self.residues[index] def get_residue_by_db_index(self, db_index): for res in self.residues: if res.db_index == db_index: return res raise KeyError(db_index) ############################################################################################### # Structure related. # ############################################################################################### def set_structure(self, structure_object): self.structure = structure_object self.structure.set_pymod_element(self) def has_structure(self): return self.structure != None def check_structure(method): """ Decorator method to check if PyMod_element object hasn an associated 3D structure. """ def checker(self, *args, **config): if not self.has_structure(): raise PyModMissingStructure("The element does not have a structure.") return method(self, *args, **config) return checker @check_structure def remove_structure(self): self.structure = None @check_structure def rename_chain_structure_files(self, chain_structure_file): self.set_initial_chain_file(chain_structure_file) self.set_current_chain_file(chain_structure_file) @check_structure def set_initial_chain_file(self, initial_chain_file): self.structure.initial_chain_file_path = initial_chain_file self.structure.initial_chain_file_name = os.path.basename(self.structure.initial_chain_file_path) @check_structure def set_current_chain_file(self, current_chain_file): self.structure.current_chain_file_path = current_chain_file self.structure.current_chain_file_name = os.path.basename(self.structure.current_chain_file_path) @check_structure def update_all_structure_paths(self, structure_dirpath): try: self.structure.initial_chain_file_path = os.path.join(structure_dirpath, self.structure.initial_chain_file_name) self.structure.current_chain_file_path = os.path.join(structure_dirpath, self.structure.current_chain_file_name) self.structure.current_full_file_path = os.path.join(structure_dirpath, self.structure.current_full_file_name) # Compatibility with old PyMod versions which did not have the "*_file_name" attributes. except AttributeError: pass @check_structure def rename_file_name_root(self, file_name_root): self.structure.file_name_root = file_name_root @check_structure def get_structure_file(self, basename_only=True, strip_extension=False, initial_chain_file=False, full_file=False): """ Returns the name of the structure file of the element. 'basename_only': if 'True' returns only the basename of the structure file. 'strip_extension': if 'True' removes the extension to the from the returned file path. 'initial_chain_file': if 'True' returns the structure file of the original chain (with its original atomic coordinates). If 'False' returns the current structure file of the chain (with modified atomic coordinates if the structure has been superposed). 'full_file': if 'True' returns the file path of the original PDB file of the structure (the PDB file containing the chain of the element along any other chain belonging to other elements). """ assert(not (initial_chain_file and full_file)) if initial_chain_file: result = self.structure.initial_chain_file_path elif full_file: result = self.structure.current_full_file_path else: result = self.structure.current_chain_file_path if basename_only: result = os.path.basename(result) if strip_extension: result = os.path.splitext(result)[0] return result @check_structure def get_chain_id(self): return self.structure.chain_id @check_structure def get_chain_numeric_id(self): return self.structure.numeric_chain_id ################################################################# # PyMOL related. # ################################################################# @check_structure def get_pymol_selector(self): return os.path.splitext(os.path.basename(self.structure.initial_chain_file_path))[0] ################################################################# # Structural features. # ################################################################# @check_structure def get_disulfides(self): return self.structure.disulfides_list @check_structure def has_disulfides(self): return self.structure.disulfides_list != [] @check_structure def add_disulfide(self, disulfide=None): self.structure.disulfides_list.append(disulfide) ############################################################################################### # Annotation related. # ############################################################################################### def has_assigned_secondary_structure(self): return bool(self.assigned_secondary_structure) def has_predicted_secondary_structure(self): return bool(self.predicted_secondary_structure) def has_campo_scores(self): return self._has_campo_scores def has_entropy_scores(self): return self._has_entropy_scores def has_pc_scores(self): return self._has_pc_scores def has_dope_scores(self): return self._has_dope_scores def has_domains(self, only_original=False): if only_original: return self.features["domains"] and self.splitted_domain == None else: return self.features["domains"] def has_features(self): return self.features["sequence"] def pdb_is_fetchable(self): return self.pdb_can_be_fetched def can_be_modeled(self): r = False # Exlude cluster elements (alignments and BLAST-searches). if not self.is_cluster(): r = True return r def is_suitable_template(self): return self.has_structure() # TODO: and sequence.is_model != True: def is_model(self): return isinstance(self, PyMod_model_element) class PyMod_root_element(_PyMod_cluster_element): pass class _PyMod_model_element(_PyMod_sequence_element): def __init__(self, model_root_name, *args, **configs): self.model_root_name = model_root_name _PyMod_sequence_element.__init__(self, *args, **configs) ################################################################################################### # CLASSES FOR EXTENDING PYMOD ELEMENTS TO CONTROL DATA OF THE PLUGIN. # ################################################################################################### class Added_PyMod_element: """ A mixin class for PyMod elements storing information about the whole PyMod plugin. It extends their methods so that they will also control other elements of PyMod. """ def initialize(self, pymod): self.pymod = pymod def set_as_lead(self): """ Also remove other lead statuses from siblings, since there can be only one lead per cluster. """ for sibling in self.get_siblings(): sibling.remove_all_lead_statuses() super(Added_PyMod_element, self).set_as_lead() def set_as_query(self): for sibling in self.get_siblings(): sibling.remove_all_lead_statuses() super(Added_PyMod_element, self).set_as_query() def extract_to_upper_level(self, place_below_mother=True): """ Extract elements from their clusters. Also changes the position of the item in the list of PyMod elements. """ old_mother_index = self.pymod.get_pymod_element_index_in_container(self.mother) + 1 super(Added_PyMod_element, self).extract_to_upper_level() if place_below_mother: self.pymod.change_pymod_element_list_index(self, old_mother_index) # Allows to show the widgets if the child element was in collapsed cluster. self.widget_group.show = True # Hides the child signes. self.widget_group.cluster_button.setVisible(False) def delete(self): """ Used to remove definitively an element from PyMod. """ # Delete its structure in PyMOL. if self.has_structure(): self.pymod.delete_pdb_file_in_pymol(self) # Delete its children. if self.is_mother(): children = self.get_children() for c in children[:]: c.delete() # Actually delete the element. super(Added_PyMod_element, self).delete() ################################################################################################### # CLASSES FOR EXTENDING PYMOD ELEMENTS BEHAVIOUR TO CONTROL PYMOD GUI. # ################################################################################################### class PyMod_element_GUI(Added_PyMod_element): """ A mixin class extending the behaviour of 'PyMod_element' objects, so that their methods will also control the elements' widgets in PyMod main window. """ def initialize(self, *args, **configs): Added_PyMod_element.initialize(self, *args, **configs) # Builds for it some GUI widgets to show in PyMod window. They will be gridded later. self.pymod.main_window.add_pymod_element_widgets(self) def remove_all_lead_statuses(self): # self.show_collapsed_mother_widgets() super(PyMod_element_GUI, self).remove_all_lead_statuses() # Removes the cluster button of leads of collapsed clusters. self.widget_group.cluster_button.set_visibility() def set_as_lead(self): super(PyMod_element_GUI, self).set_as_lead() self.widget_group.cluster_button.set_visibility() def extract_to_upper_level(self, *args, **configs): """ Extract elements from their clusters. Also modifies its widgets and those of their parents. """ # self.show_collapsed_mother_widgets() super(PyMod_element_GUI, self).extract_to_upper_level(*args, **configs) def delete(self, *args, **configs): """ Delete an element. """ # self.show_collapsed_mother_widgets() super(PyMod_element_GUI, self).delete(*args, **configs) # Remove the element widgets. self.pymod.main_window.delete_element_widgets(self) def show_collapsed_mother_widgets(self): """ If the element is a lead of a collapsed cluster, then show the widgets of the cluster (which were hidden) after the element lead element is extracted. """ if self.is_lead() and self.pymod.main_window.is_collapsed_cluster(self.mother): self.mother.widget_group.show = True def add_child(self, child, *args, **configs): super(PyMod_element_GUI, self).add_child(child, *args, **configs) # If the cluster is not collapsed, show the widgets of the children. if not self.pymod.main_window.is_collapsed_cluster(self): child.widget_group.show = True # If the cluster is collapsed hide it. else: child.widget_group.hide_widgets() def __getstate__(self): """ Called by pickle when dumping an object to a file. """ return pymod_getstate(self) ################################################################################################### # CLASSES ACTUALLY USED IN THE PLUGIN. # ################################################################################################### class PyMod_cluster_element(PyMod_element_GUI, _PyMod_cluster_element): pass class PyMod_sequence_element(PyMod_element_GUI, _PyMod_sequence_element): pass class PyMod_model_element(PyMod_element_GUI, _PyMod_model_element): pass ################################################################################################### # Pickling behaviour. # ################################################################################################### # Attributes which can not be pickled because they contain PyQt or Tkinter objects. Used when saving # Python objects in order to save a PyMod session. pymod_element_unpickable_elements = ["widget_group", "pymod"] pymod_unpickable_elements = [] unpickable_attributes = pymod_element_unpickable_elements + pymod_unpickable_elements def pymod_getstate(obj): d = dict(obj.__dict__) for k in unpickable_attributes: if k in d: del d[k] return d
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_threading.py
.py
9,130
267
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Module to display a dialog with a progressbar used when running those functions of PyMod where a time-consuming process is executed. In this way the GUI will not be blocked during the execution of the process. """ import os import sys import subprocess import time from pymol.Qt import QtCore, QtWidgets from pymod_lib.pymod_exceptions import PyModInterruptedProtocol class PyMod_protocol_thread(QtCore.QThread): """ Class for a 'QThread' to launch a function where a time-consuming process is executed. It is used when showing a 'Protocol_exec_dialog' dialog. """ # Signals. terminate_thread_signal = QtCore.pyqtSignal(int) exception_thread_signal = QtCore.pyqtSignal(Exception) def set_params(self, function, args, wait_start, wait_end): self.function = function self.args = args self.wait_start = wait_start self.wait_end = wait_end def run(self): if self.wait_start is not None: time.sleep(self.wait_start) # Attempts to execute the function in this thread. try: if type(self.args) is dict: self.function(**self.args) else: self.function(*self.args) self._wait_end() self.terminate_thread_signal.emit(0) # Terminate sucessully. # If there was an error, emit the exception, so that it can be handled in the main thread. except Exception as e: self._wait_end() self.exception_thread_signal.emit(e) # Terminate by raising an exception. def _wait_end(self): if self.wait_end is not None: time.sleep(self.wait_end) class Protocol_exec_dialog(QtWidgets.QDialog): """ A dialog with a progress bar used when running long and time-consuming functions in PyMod. """ is_pymod_window = True def __init__(self, app, pymod, function, args, wait_start=0.15, wait_end=0.15, wait_close=0.20, title="Running a new protocol", label_text="Running. Please wait for the protocol to complete.", lock=False, lock_title="Can not Exit", lock_message="Can not safely exit. Please wait for the threa to complete.", progress=True, stdout_silence=False, stdout_filepath=None, backend="qthread"): QtWidgets.QDialog.__init__(self, parent=app) self.main_window = app self.pymod = pymod self.function = function self.args = args self.wait_start = wait_start # Time to wait before the protocol is actually executed. self.wait_end = wait_end # Time to wait after the protocol completes. self.wait_close = wait_close # Time to wait before the dialog closes. self.title = title self.label_text = label_text self.lock = lock self.lock_title = lock_title self.lock_message = lock_message self.progress = progress self.error = None if not backend in ("qthread", "python"): raise KeyError("Unknown 'backend': %s" % backend) self.backend = backend self.initUI() self.setModal(True) # Set the type of dialog. # Revert the terminal output to a file. self.stdout_filepath = stdout_filepath # Silence all stdout. self.stdout_silence = stdout_silence self._revert_stdout = self.stdout_silence or self.stdout_filepath is not None # Protocol thread. if self.backend == "qthread": self.p_thread = PyMod_protocol_thread() self.p_thread.set_params(self.function, self.args, self.wait_start, self.wait_end) self.p_thread.terminate_thread_signal.connect(self.on_terminate_thread_signal) self.p_thread.exception_thread_signal.connect(self.on_exception_thread_signal) # self.worker = QtCore.QObject() # self.worker.moveToThread(self.p_thread) elif self.backend == "python": # self.p_thread = threading.Thread(target=self.function, # args=self.args, # daemon=True) raise NotImplementedError def initUI(self): self.setWindowTitle(self.title) vertical_layout = QtWidgets.QVBoxLayout() self.thread_progressbar = QtWidgets.QProgressBar(self) if self.progress: self.thread_progressbar.setMinimum(0) self.thread_progressbar.setMaximum(0) progressbar_label = "Computing..." # "Wait for the protocol to complete." self.thread_progressbar.setFormat(progressbar_label) self.thread_progressbar.setValue(0) vertical_layout.addWidget(self.thread_progressbar) self.thread_progress_label = QtWidgets.QLabel(self.label_text, self) self.thread_progress_label.setWordWrap(True) vertical_layout.addWidget(self.thread_progress_label) # Button for canceling the execution of the thread. horizontal_layout = QtWidgets.QHBoxLayout() self.cancel_button = QtWidgets.QPushButton('Cancel', self) self.cancel_button.clicked.connect(self.on_cancel_button_click) self.cancel_button.setEnabled(not self.lock) horizontal_layout.addWidget(self.cancel_button) vertical_layout.addLayout(horizontal_layout) self.setLayout(vertical_layout) def exec_(self): """ Opens the dialog and performs checks on the errors at the end. """ # Redirect stdout. if self._revert_stdout: original_stdout = sys.stdout if self.stdout_silence: sys.stdout = open(os.devnull, "w") else: sys.stdout = open(self.stdout_filepath, "w") # Starts the thread before showing the progress dialog. self.p_thread.start() QtWidgets.QDialog.exec_(self) # Revert stdout. if self._revert_stdout: sys.stdout.close() sys.stdout = original_stdout # Complete. if self.wait_close is not None: time.sleep(self.wait_close) self.check_error() def check_error(self): """ Checks if there was an exception in the child thread. """ if self.error is None: return None else: # If there was an exception, then raise it in the main thread. raise self.error def get_cancel_exception(self): """ Getr the exception raised when interrupting a protocol. """ return PyModInterruptedProtocol("Interrupted the protocol") # Interactions with the buttons. def on_cancel_button_click(self): """ Stops the protocol thread and provides an exception to stop the execution in the main thread. """ self.on_exception_thread_signal(self.get_cancel_exception()) def closeEvent(self, evnt): # Closes the dialog. if not self.lock: # The user clicked the "close" button on the window. if evnt.spontaneous(): self._on_exception_thread_signal(self.get_cancel_exception()) super(Protocol_exec_dialog, self).closeEvent(evnt) # Can not close the dialog when the user clicks on it. else: # Inactivates the "close" button on the window. if evnt.spontaneous(): evnt.ignore() # Interactions with the thread. def on_terminate_thread_signal(self, status): """ The thread has successfully terminated, closes the dialog. """ if status == 0: self.close() else: raise NotImplementedError def on_exception_thread_signal(self, e): """ An exception has been raised while executing the protocol. Stores the exception raised in the protocol thread, so that it can be raised in the main thread. Then closes the dialog, so that the exception can be raised. """ self._on_exception_thread_signal(e) self.close() def _on_exception_thread_signal(self, e): self.error = e self._terminate_threads() def _terminate_threads(self): if self.p_thread.isRunning(): # self.worker.stop() self.p_thread.terminate() # self.p_thread.quit() # self.p_thread.wait() def keyPressEvent(self, event): """ By overriding this method, the dialog will not close when pressing the "esc" key. """ if event.key() == QtCore.Qt.Key_Escape: pass else: QtWidgets.QDialog.keyPressEvent(self, event)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_seq/seq_star_alignment.py
.py
17,236
488
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Module implementing functions to merge alignments and simplified center star alignments. """ import re from pymod_lib.pymod_vars import dict_of_matrices import Bio.pairwise2 from Bio import SeqIO from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord # matrix = matlist.blosum62.copy() matrix = dict_of_matrices["BLOSUM62"] matrix.update({("X", "X"): 5}) [matrix.update({("-", i): -10}) for i in "QWERTYIPASDFGHKLXCVNM"] [matrix.update({(i, "-"): -10}) for i in "QWERTYIPASDFGHKLXCVNM"] def _get_matrix_val(ca, cb): if (ca, cb) in matrix: return matrix[(ca, cb)] elif (cb, ca) in matrix: return matrix[(cb, ca)] else: return 0 def global_pairwise_alignment_cs(seq1, seq2, gop=10, gep=0.2): # Function for scoring aligned residues. sf = _get_matrix_val # Preparing this object for affine gap penalty scoring greatly speeds up the alignment execution. pf = Bio.pairwise2.affine_penalty(open=-gop, extend=-gep) # Actually performs the alignment. ali = Bio.pairwise2.align.globalcc(seq1, seq2, sf, pf, pf) return ali[0][0], ali[0][1] def build_center_star_alignment(seqs, pairwise_alis=None, verbose=False): n_tot_alis = int(len(seqs)*(len(seqs)-1)/2) # Use the caller-supplied pairwise alignments. if pairwise_alis != None: if not len(pairwise_alis) == n_tot_alis: raise ValueError("Provided %s parwise alignments, but %s were needed." % (len(pairwise_alis), n_tot_alis)) # Build from scratch the pairwise alignments. else: pairwise_alis = [] for seq_i_id, seq_i in enumerate(seqs): for seq_j_id, seq_j in enumerate(seqs[seq_i_id:]): if seq_j_id == 0: continue if verbose: print("*", seq_i, seq_j) aliseq_i, aliseq_j = global_pairwise_alignment_cs(seq_i, seq_j) pairwise_alis.append((aliseq_i, aliseq_j)) # Prepares the center star blocks. cs_seq = seqs[0].replace("-", "") cs_blocks = ["."] for aa in cs_seq: cs_blocks.append(aa) cs_blocks.append(".") blocks_list = [cs_blocks] #---------------------------------------------------------------------------------------------- # Build the blocks. - #---------------------------------------------------------------------------------------------- n_cs_alis = len(seqs)-1 for pairwise_ali_i, pairwise_ali in enumerate(pairwise_alis[:n_cs_alis]): os_seq = pairwise_ali[1].replace("-", "") os_seq_p = seqs[pairwise_ali_i+1].replace("-", "") if not os_seq == os_seq_p: raise ValueError("Sequences mismatch: %s/%s." % (os_seq, os_seq_p)) matches_dict = {} os_insertions_dict = {} cs_res_count = 0 os_res_count = 0 for cs_p, os_p in zip(*pairwise_ali): if verbose: print(cs_p, os_p) # Match. if cs_p != "-" and os_p != "-": matches_dict[cs_res_count] = os_res_count # Insertion in the center star. elif cs_p != "-" and os_p == "-": pass # Insertion in the other sequence. elif cs_p == "-" and os_p != "-": if cs_res_count in os_insertions_dict.keys(): os_insertions_dict[cs_res_count].append(os_res_count) else: os_insertions_dict[cs_res_count] = [os_res_count] # Double gap. elif cs_p == "-" and os_p == "-": raise ValueError("Gap only column encountered in alignment: %s" % repr(pairwise_ali)) if cs_p != "-": cs_res_count += 1 if os_p != "-": os_res_count += 1 if verbose: print(matches_dict) print(os_insertions_dict) # Recontructs the other sequence blocks. os_blocks = ["."] for aa in cs_seq: os_blocks.append("-") os_blocks.append(".") cs_block_count = 0 for aa_i, aa in enumerate(cs_seq+"-"): # Adds a gap character to take into C-terminal insertions. if aa_i in os_insertions_dict: os_blocks[cs_block_count] = "".join([os_seq[i] for i in os_insertions_dict[aa_i]]) cs_block_count += 1 if aa_i in matches_dict: os_blocks[cs_block_count] = os_seq[matches_dict[aa_i]] cs_block_count += 1 if verbose: print(os_blocks) print(cs_blocks) print("") blocks_list.append(os_blocks) if verbose: print("\n# Results") #---------------------------------------------------------------------------------------------- # Build the final alignment. - #---------------------------------------------------------------------------------------------- ali_seqs = [[] for i in range(0, len(seqs))] for block_index in range(0, len(cs_blocks)): # Add the matches. if verbose: print(cs_blocks[block_index], [b[block_index] for b in blocks_list]) # Add insertions. if cs_blocks[block_index] == ".": all_insertions_dict = [] res_insertions_ids = [] for b_i, b in enumerate(blocks_list): if b[block_index] != ".": all_insertions_dict.append(b[block_index]) res_insertions_ids.append(b_i) else: all_insertions_dict.append("-") if len(res_insertions_ids) > 0: max_insertion_len = max([len(ins) for ins in all_insertions_dict]) # Insertions are short, no need to refine them. if max_insertion_len <= 3 or len(res_insertions_ids) == 1: pass # Refine an insertion block. else: refine_seqs = [all_insertions_dict[ins_id] for ins_id in res_insertions_ids] if verbose: print("\n= Refining:", refine_seqs) # Performs a center star alignment with the inserted fragments in order to # align them. refine_seqs = build_center_star_alignment(refine_seqs) for ins_id_i, ins_id in enumerate(res_insertions_ids): all_insertions_dict[ins_id] = refine_seqs[ins_id_i] max_insertion_len = max([len(ins) for ins in all_insertions_dict]) # Actually include the insertions in the alignment. for s, ins in zip(ali_seqs, all_insertions_dict): s.append(ins.ljust(max_insertion_len, "-")) else: for s, b in zip(ali_seqs, blocks_list): s.append(b[block_index]) ali_seqs = ["".join(s) for s in ali_seqs] if verbose: print("") for ali_seq in ali_seqs: print(ali_seq) return ali_seqs def _all_positions_are_gaps(pos_list): for p in pos_list: if p != "-": return False return True def save_cstar_alignment(seqs, all_ids, pairwise_alis, output_filepath=None, verbose=False): """ Performs a center star alignment between a list of sequences. seqs: must contain a list of gapless sequences. The first one is assumed to be the center star. all_ids: must contain a list of ids associated to the sequences in 'seqs'. pairwise_alis: must contain a list of n*(n-1)/2 elements, where n=len(seqs). Eache element represents an alignment between two sequences. For example, if we have seqs = ["A", "B", "C", "D", "E"] 'pairwise_alis' must contain the following tuples, each corresponding to a pairwise alignment between two sequences: pairwise_alis = [("A", "B"), ("A", "C"), ("A", "D"), ("A", "E"), ("B", "C"), ("B", "D"), ("B", "E"), ("C", "D"), ("C", "E"), ("D", "E")] Instead of providing tuples, a 'None' element can be provided for alignments in which the center star is not present (in the examples above, all the tuples where "A" is not present). output_filepath: alignment filepath where the center star alignment will be written (in clustal format). """ # Remove gap-only columns from pairwise alignments, if necessary. if pairwise_alis != None: for pairwise_ali_id, pairwise_ali in enumerate(pairwise_alis[:]): if pairwise_ali != None: if len(pairwise_ali[0]) != len(pairwise_ali[1]): raise ValueError("Sequences are not aligned: \n%s\n%s" % (pairwise_ali[0], pairwise_ali[1])) columns_to_remove = [] for i in range(0, min([len(s) for s in pairwise_ali])): if _all_positions_are_gaps([s[i] for s in pairwise_ali]): columns_to_remove.append(i) if len(columns_to_remove) > 0: list_seqs = [list(s) for s in pairwise_ali] for columns_removed, i in enumerate(columns_to_remove): for s in list_seqs: s.pop(i-columns_removed) pairwise_alis[pairwise_ali_id] = ("".join(list_seqs[0]), "".join(list_seqs[1])) # Actually builds the center star alignment. msa_0 = build_center_star_alignment(seqs=seqs, pairwise_alis=pairwise_alis, verbose=verbose) max_length = max([len(si) for si in msa_0]) msa_0 = [si.ljust(max_length, "-") for si in msa_0] # Saves the alignment. seq_records = [] for aliseq, rec_id in zip(msa_0, all_ids): seq_records.append(SeqRecord(Seq(str(aliseq)), id=rec_id)) if output_filepath != None: SeqIO.write(seq_records, output_filepath, "clustal") return seq_records if __name__ == "__main__": pairwise_alis = [("AAAA-", "BBB-B"), ("AA----AA", "-CCCCCCC"), ("AA---AA-", "--CCADDD"), # ("A-A-A-A", # "EEEEEE-"), None, None, None, # None, # None, # None ] build_center_star_alignment( # seqs=["AAAA", "BBBB", "CCCCC", "DDD", "EEEEEE"], seqs=["AAAA", "BBBB", "CCCCCCC", "CCADDD", ], pairwise_alis=pairwise_alis, verbose=True, ) ################################################################################################### # Join alignments. # ################################################################################################### def _get_ali_dicts(msa, verbose=False): msa_1_seq_1 = msa[0] match_cols_dict_1 = {} insertion_cols_dict_1 = {} res_1_count = 0 in_insertion = False for ai in range(0, len(msa_1_seq_1)): if verbose: print([s[ai] for s in msa]) if msa_1_seq_1[ai] != "-": match_cols_dict_1[res_1_count] = [s[ai] for s in msa[1:]] res_1_count += 1 in_insertion = False if msa_1_seq_1[ai] == "-": if in_insertion: insertion_cols_dict_1[res_1_count].append([s[ai] for s in msa]) else: insertion_cols_dict_1[res_1_count] = [[s[ai] for s in msa]] in_insertion = True return match_cols_dict_1, insertion_cols_dict_1 def _get_complete_block(j_seq, msa, match_cols_dict, insertion_cols_dict): anchor_block = ["."] p_count = 0 for p1 in j_seq: if p1 != "-": if p_count in insertion_cols_dict: anchor_block[-1] = insertion_cols_dict[p_count] anchor_block.append([p1] + match_cols_dict[p_count]) p_count += 1 else: anchor_block.append(["-"]*len(msa)) anchor_block.append(".") if p_count in insertion_cols_dict: anchor_block[-1] = insertion_cols_dict[p_count] return anchor_block def join_alignments(j_msa, msa_l, verbose=False): """ Join two multiple sequence alignments provided in 'msa_l' using an "anchor" pairwise alignment provided in 'j_msa'. j_msa: must contain a pairwise alignment between two "anchor" sequences. For example: j_msa = ["AAA-AA", "DD-DDD"] msa_l: must contain list with two multiple sequence alignments in which the first sequences must be the anchor sequences. For example: msa_l = [ ["AAAA-A", "-BBBBB", "CCC-CC"], ["-DD-DDD", "E-EEEE-", "F-FF-FF"], ] Note how in the first multiple sequence alignment, the first sequence is the first anchor in 'j_msa' (that is, "AAAAA"). In the second multiple sequence alignment, the first sequence is the second anchor in 'j_msa' (that is, "DDDDD"). return new_msa: Returns a list with all the sequences present in 'msa_l' aligned according to the new alignment. """ if len(j_msa) > 2: raise ValueError("The anchor alignment can have only two sequences (%s provided)." % len(j_msa)) for a_i, a in enumerate(j_msa): a_seq = a.replace("-", "") msa_seq = msa_l[a_i][0].replace("-", "") if not a_seq == msa_seq: raise ValueError("The anchor sequences provided in 'j_msa' and 'msa_l' are not the same: \n%s\n%s." % (a_seq, msa_seq)) match_cols_dict_1, insertion_cols_dict_1 = _get_ali_dicts(msa_l[0], verbose=False) match_cols_dict_2, insertion_cols_dict_2 = _get_ali_dicts(msa_l[1], verbose=False) if verbose: print(match_cols_dict_1, insertion_cols_dict_1) print(match_cols_dict_2, insertion_cols_dict_2) print("") print(j_msa[0]) print(j_msa[1]) print("") # Prepares the anchor blocks. anchor_block_1 = _get_complete_block(j_msa[0], msa_l[0], match_cols_dict_1, insertion_cols_dict_1) # print (anchor_block_1, len(anchor_block_1)) anchor_block_2 = _get_complete_block(j_msa[1], msa_l[1], match_cols_dict_2, insertion_cols_dict_2) # print (anchor_block_2, len(anchor_block_2)) if verbose: print("\n###") for a in msa_l[0]: print(a) print("") print("\n###") for a in msa_l[1]: print(a) print("") # Actually rebuilts the full alignment. alignment_matrix = [] for b1, b2 in zip(anchor_block_1, anchor_block_2): if verbose: print(b1, b2) if b1 == "." and b2 == ".": pass elif b1 == "." and b2 != ".": for si in b2: alignment_column = ["-"]*len(msa_l[0]) + si alignment_matrix.append(alignment_column) elif b1 != "." and b2 == ".": for si in b1: alignment_column = si + ["-"]*len(msa_l[1]) alignment_matrix.append(alignment_column) elif b1 != "-" and b2 != "-": if type(b1[0]) != list and type(b2[0]) != list: alignment_column = b1 + b2 alignment_matrix.append(alignment_column) else: if type(b1[0]) == list: for si in b1: alignment_column = si + ["-"]*len(msa_l[1]) alignment_matrix.append(alignment_column) if type(b2[0]) == list: for si in b2: alignment_column = ["-"]*len(msa_l[0]) + si alignment_matrix.append(alignment_column) new_msa = [[] for i in range(0, len(msa_l[0]) + len(msa_l[1]) )] for c in alignment_matrix: for ci, s in zip(c, new_msa): s.append(ci) if verbose: print("\n@ Results") print(alignment_matrix) for s in new_msa: print("".join(s)) new_msa = ["".join(s) for s in new_msa] return new_msa if __name__ == "__main__": j_msa = ("AAAAAA-A", "-DDDD-DD") msa_l = [("AAAAA-AA", "B-BBBBB-", "CCCCCCC-" ), ("-DD-D--DDD", "EEEE-EE---")] results = join_alignments(j_msa=j_msa, msa_l=msa_l, verbose=True) print("") for s in results: print(s)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_seq/__init__.py
.py
0
0
null
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_seq/seq_io.py
.py
5,243
129
# Copyright 2016 by Chengxin Zhang, Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Sequences input and output. """ import os from Bio import SeqIO from Bio.Seq import Seq from Bio.SeqRecord import SeqRecord from pymod_lib import pymod_vars from pymod_lib.pymod_seq import seq_manipulation def build_sequence_file(elements, sequences_filepath, file_format="fasta", remove_indels=True, unique_indices_headers=False, use_structural_information=False, same_length=True, first_element=None): """ Builds a sequence file (the format is specified in the alignment_"format" argument) that will contain the sequences supplied in the "elements" which has to contain a list of "PyMod_element" class objects. """ output_file_handler = open(sequences_filepath, 'w') if same_length: seq_manipulation.adjust_aligned_elements_length(elements) if first_element != None: elements.remove(first_element) elements.insert(0, first_element) if file_format == "fasta": for element in elements: header, sequence = get_id_and_sequence_to_print(element, remove_indels, unique_indices_headers) # Write an output in FASTA format to the output_file_handler given as argument. print(">"+header, file=output_file_handler) for i in range(0, len(sequence), 60): print(sequence[i:i+60], file=output_file_handler) print("", file=output_file_handler) elif file_format == "pir": for element in elements: header, sequence = get_id_and_sequence_to_print(element, remove_indels, unique_indices_headers) sequence += '*' structure='' if element.has_structure() and use_structural_information: structure=element.get_structure_file() chain=element.get_chain_id() if not structure: # sequence print(">P1;"+ header, file=output_file_handler) print("sequence:"+header+":::::::0.00:0.00", file=output_file_handler) else: # structure print(">P1;"+header, file=output_file_handler) print("structure:"+structure+":.:"+chain+":.:"+chain+":::-1.00:-1.00", file=output_file_handler) for ii in range(0,len(sequence),75): print(sequence[ii:ii+75].replace("X","."), file=output_file_handler) elif file_format in ("clustal", "stockholm"): records = [] for element in elements: header, sequence = get_id_and_sequence_to_print(element, remove_indels, unique_indices_headers) records.append(SeqRecord(Seq(str(sequence)), id=header)) SeqIO.write(records, output_file_handler, file_format) elif file_format == "pymod": for element in elements: header, sequence = get_id_and_sequence_to_print(element, remove_indels, unique_indices_headers) print(header, sequence, file=output_file_handler) else: output_file_handler.close() raise Exception("Unknown file format: %s" % file_format) output_file_handler.close() def get_id_and_sequence_to_print(pymod_element, remove_indels=True, unique_indices_headers=False): sequence = pymod_element.my_sequence if remove_indels: sequence = sequence.replace("-","") if not unique_indices_headers: header = pymod_element.my_header else: header = pymod_element.get_unique_index_header() # child.my_header.replace(':','_') return header, sequence def convert_sequence_file_format(input_filepath, input_format, output_format, output_filename=None): """ Converts an sequence file specified in the 'input_format' argument in an alignment file in the format specified in the 'output_format'. """ input_file_basename = os.path.basename(input_filepath) input_file_name = os.path.splitext(input_file_basename)[0] if not output_filename: output_file_basename = "%s.%s" % (input_file_name, pymod_vars.alignment_extensions_dictionary[output_format]) else: output_file_basename = "%s.%s" % (output_filename, pymod_vars.alignment_extensions_dictionary[output_format]) output_file_handler = open(os.path.join(os.path.dirname(input_filepath), output_file_basename), "w") if input_format == "pymod": input_file_handler = open(input_filepath, "r") records = [SeqRecord(Seq(l.split(" ")[1].rstrip("\n\r")), id=l.split(" ")[0]) for l in input_file_handler.readlines()] else: input_file_handler = open(input_filepath, "r") records = list(SeqIO.parse(input_file_handler, input_format)) if output_format == "pymod": lines = [] for i in [(rec.id, rec.seq) for rec in records]: lines.append(str(i[0])+'\n') lines.append(str(i[1])+'\n') output_file_handler.writelines(lines) else: SeqIO.write(records, output_file_handler, output_format) input_file_handler.close() output_file_handler.close()
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_seq/seq_manipulation.py
.py
10,155
282
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. import re import Bio from pymod_lib import pymod_vars ################################################################################################### # Some useful functions used in the plugin. # ################################################################################################### def compute_sequence_identity(seq1, seq2, toss_modres = False, return_matches=False): """ Computes the identity [(identical residues)/(total matches in the alignment)] between two aligned sequences. If 'toss_modres' is set to 'True', 'X' in sequences will be replaced with '-' so that the mdofied residues in PDB chain sequences will not be used to compute the sequence identity. """ sequence_identity = 0.0 identical_positions = 0.0 aligned_positions = 0.0 if toss_modres: seq1 = seq1.replace("X","-") seq2 = seq2.replace("X","-") if str(seq1) != str(seq2): # Computes the identity the two sequences. Range only for the shortest sequence. for i in range( min(len(seq1),len(seq2)) ): if seq1[i] != "-" and seq2[i] != "-": aligned_positions += 1 if seq1[i] == seq2[i]: identical_positions += 1 try: sequence_identity = (identical_positions/aligned_positions)*100 except ZeroDivisionError: sequence_identity = 0.0 # If the two sequence are the same, just return 1 (or 100). else: sequence_identity = (1.0/1.0)*100 if not return_matches: return round(sequence_identity,2) else: return round(sequence_identity,2), identical_positions def get_residue_id_in_aligned_sequence(aligned_sequence, real_id): """ aligned_sequence: a sequence with indels. real_id: the id (position -1) of the residue in the gapless sequence. returns: the id (position -1) of the same residue in the alignment (the sequence + indels). """ assert( len(str(aligned_sequence).replace("-","")) >= real_id ) real_counter = 0 for i,p in enumerate(aligned_sequence): if p != "-": if real_counter == real_id: return i else: real_counter += 1 def get_residue_id_in_gapless_sequence(aligned_sequence, id_in_alignment): """ This does the opposite of the function above. aligned_sequence: a sequence with indels. id_in_alignment: the id (position -1) of the same residue in the alignment (the sequence + indels). returns: the id (position -1) of the residue in the gapless sequence. """ assert(len(aligned_sequence) >= id_in_alignment) residue_counter = 0 real_id = None for (k, r) in enumerate(aligned_sequence): if k != id_in_alignment: if r != "-": residue_counter += 1 else: if r != "-": real_id = residue_counter break return real_id def find_residue_conservation(template_seq, target_seq, real_id): """ Takes two aligned sequences, a "template" and a "target", and sees if a residue with the id "i" of the template is conserved in the target. """ # seq_counter: real id of the residue # k: id of the residue in the alignment alignment_position = get_residue_id_in_aligned_sequence(template_seq,real_id) return template_seq[alignment_position] == target_seq[alignment_position] def get_leading_gaps(sequence, index): gap_counter = 0 for i, position in enumerate(sequence[index:]): if i != 0: if position == "-": gap_counter += 1 else: break return gap_counter def global_pairwise_alignment(seq1, seq2, toss_modres=False): """ If seq1 contains gaps, also aseq1 will maintain these gaps. """ import Bio.pairwise2 # The original version was: globalms(seq1, seq2, 2, -1, -.5, -.1) ali = Bio.pairwise2.align.globalms(seq1, seq2, 2, # match score. -2, # mismatch score. -5, # gap opening. -.5 # gap extension. ) aseq1 = ali[0][0] aseq2 = ali[0][1] seqid, matches = compute_sequence_identity(aseq1, aseq2, return_matches=True, toss_modres=toss_modres) return {"seq1": aseq1, "seq2": aseq2, "id": seqid, "matches": matches} def get_limit_residues_ids(seq1, seq2): c1 = 0 c2 = 0 s1a = None # first match residue id of sequence 1 e1a = None # last match residue id of sequence 2 s2a = None e2a = None last_match_position = 0 for p1, p2 in zip(seq1, seq2): if p1 != "-" and p2 != "-": if s1a != None: s1a = c1 s2a = c2 else: e1a = c1 e2a = c2 if p1 != "-": c1 += 1 if p2 != "-": c2 += 1 return {"s1a": s1a, "e1a": e1a,"s2a": s2a, "e2a": e2a} ####################### # Alignments. # ####################### def adjust_aligned_elements_length(elements, remove_right_indels=True): if len(set([len(e.my_sequence) for e in elements])) == 1: return False # First remove indels at the end of the sequences. if remove_right_indels: for e in elements: e.my_sequence = str(e.my_sequence).rstrip("-") # Then pad each sequence with the right number of indels to make them of the same length as # the longest sequence. max_length = max([len(e.my_sequence) for e in elements]) for e in elements: e.my_sequence = str(e.my_sequence).ljust(max_length,"-") # e.set_sequence(str(e.my_sequence).ljust(max_length,"-"), permissive=False) def all_positions_are_gaps(column): for i in column: if i != "-": return False return True def remove_gap_only_columns(cluster): """ Remove the columns containing only gaps in the child elements of a PyMod cluster element. """ children = cluster.get_children() list_seqs = [list(s.my_sequence) for s in children] columns_to_remove = [] for i in range(0, min([len(s) for s in list_seqs])): if all_positions_are_gaps([s[i] for s in list_seqs]): columns_to_remove.append(i) for columns_removed, i in enumerate(columns_to_remove): for s in list_seqs: s.pop(i-columns_removed) for child, list_seq in zip(children, list_seqs): child.my_sequence = "".join(list_seq) ####################### # Clean up sequences. # ####################### def clean_sequence_from_input(sequence): # sequence = sequence.replace("Z","X") # ambiguity, E or Q # sequence = sequence.replace("B","X") # ambiguity, D or N # sequence = sequence.replace("J","X") # ambiguity, I or L # sequence = sequence.replace("O","X") # pyrrolysine # sequence = sequence.replace("U","X") # selenocysteine # sequence = sequence.replace(".","X") # selenocysteine cleaned_seq = re.sub(pymod_vars.non_prot_standard_regex, pymod_vars.modified_residue_one_letter, clean_white_spaces_from_input(sequence)) return cleaned_seq.upper() def clean_white_spaces_from_input(string): return string.replace('\n','').replace('\r','').replace(' ','').replace('\t','') def check_correct_sequence(sequence, remove_indels=True): """ Check if string contains any characters not belonging to the standard protein residues alphabet (plus the 'X' characters for heteroresidues.) """ non_protein_character_found = False if remove_indels: sequence = sequence.replace("-", "") for c in sequence: if not c in pymod_vars.prot_standard_and_x_one_letter: non_protein_character_found = True if non_protein_character_found: return False else: return True def get_invalid_characters_list(sequence, remove_indels=True): """ Check if string contains any characters not belonging to the standard protein residues alphabet (plus the 'X' characters for heteroresidues.) """ non_protein_character_found = False invalid_characters_list = [] if remove_indels: sequence = sequence.replace("-","") for c in sequence: if not c in pymod_vars.prot_standard_and_x_one_letter: invalid_characters_list.append(c) return invalid_characters_list ################################################################################################### # Classes for standard bioinformatics operations. # ################################################################################################### def one2three(letter): """ Returns a three letter code for a residue corresponding to a one letter symbol. """ if letter in pymod_vars.prot_one_to_three_code: return pymod_vars.prot_one_to_three_code[letter] else: return "???" def three2one(res, force_standard_parent=False): """ Returns a one letter symbol corresponding to a three letter code for a residue. If 'force_standard_parent' is set to 'True', if the three letter code of a modified residue is supplied, the method will attempt to return the code of the corresponding unmodified residue. """ # Try to set modified residues of the protein with the letter belonging to the unmodified # residue if not force_standard_parent: # If it is any kind of known modified amminoacid set it as its original non # modified amminoacid if res in pymod_vars.code_standard: return pymod_vars.code_standard[res] else: return "X" else: pass
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_seq/seq_conservation.py
.py
3,888
111
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Methods to compute conservation values in an alignment column. """ def get_conservation_symbol(column): """ Calculate the conservation symbol for an alignment based on the positively scoring groups that occur in the Gonnet Pam250 matrix (see: http://www.clustal.org/download/clustalx_help.html). Takes as an input an alignment column represented by a list. "*" indicates positions which have a single, fully conserved residue. ":" indicates that one of the following 'strong' groups is fully conserved: STA, NEQK, NHQK, NDEQ, QHRK, MILV, MILF, HY, FYW "." indicates that one of the following 'weaker' groups is fully conserved: CSA, ATV, SAG, STNK, STPA, SGND, SNDEQK, NDEQHK, NEQHRK, FVLIM, HFY """ symbol = "-" # If there is a gap in that position of the alignment, then the symbol is automatically a # "-". if "-" in column: symbol = "-" else: # If it is really slow try to use frozenset. residues = set(column) # All residues in the column are identical: full conservation. if len(residues) == 1: symbol = "*" else: # Strong conservation. if residues.issubset("STA"): symbol = ":" elif residues.issubset("NEQK"): symbol = ":" elif residues.issubset("NHQK"): symbol = ":" elif residues.issubset("NDEQ"): symbol = ":" elif residues.issubset("QHRK"): symbol = ":" elif residues.issubset("MILV"): symbol = ":" elif residues.issubset("MILF"): symbol = ":" elif residues.issubset("HY"): symbol = ":" elif residues.issubset("FYW"): symbol = ":" # Weak conservation. elif residues.issubset("CSA"): symbol = "." elif residues.issubset("ATV"): symbol = "." elif residues.issubset("SAG"): symbol = "." elif residues.issubset("STNK"): symbol = "." elif residues.issubset("STPA"): symbol = "." elif residues.issubset("SGND"): symbol = "." elif residues.issubset("SNDEQK"): symbol = "." elif residues.issubset("NDEQHK"): symbol = "." elif residues.issubset("NEQHRK"): symbol = "." elif residues.issubset("FVLIM"): symbol = "." elif residues.issubset("HFY"): symbol = "." return symbol def compute_stars(elements, adjust_elements=False): """ Computes the "stars" of an alignment. """ if adjust_elements: for e in elements: e.my_sequence = e.my_sequence.rstrip("-") max_length = max([len(e.my_sequence) for e in elements]) for e in elements: e.my_sequence = e.my_sequence.ljust(max_length, "-") sequences = [e.my_sequence for e in elements] # str(e.my_sequence) if not adjust_elements: minimum_length = max([len(s) for s in sequences]) # min([len(s) for s in sequences]) else: minimum_length = max_length stars = "" for i in range(0, minimum_length): column = [_get_ali_char(s, i) for s in sequences] # column = [s[i] for s in sequences] stars += get_conservation_symbol(column) return stars def _get_ali_char(seq, i): if len(seq) > i: return seq[i] else: return "-"
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_seq/seq_headers.py
.py
3,994
112
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Operations on the names and ids of the sequences loaded in PyMod. """ import re headers_max_length = 50 max_compact_header_length = 35 # Old PyMod: 11, 10. def get_header_string(header_str): header_str = header_str.split(" ")[0] header_str = header_str[0:headers_max_length] return header_str def get_compact_header_string(header_str): """ This is needed to build a compact version of the headers that will be used in various instances (for example when the identity matrix table for some alignment is displayed, or when assigning the name of ouputs files). """ #---------------------------------- # Uniprot (sp/tr) and gi entries. - #---------------------------------- # From something like "sp|Q9H492|MLP3A_HUMAN" it will build "sp|Q92622". if header_str.startswith("sp|") or header_str.startswith("tr|") or header_str.startswith("gi|"): so = re.search(r'(\w{2})\|(\S{6,9})\|([\w\d\_\-|\.]{3,20})', header_str) # so = re.search(r'(\w{2})\|(\S{6,9})\|', header_str) if so: compact_header = so.group(1)+"|"+so.group(2) # +"|" # compact_header = compact_header+"|"+so.group(3) # +"|" # compact_header = compact_header.rstrip("|") else: compact_header = crop_header(header_str) #---------------------------------------------------------------------- # Sequences imported from PDB files using the open_pdb_file() method. - #---------------------------------------------------------------------- elif header_str[-8:-1] == "_chain_": if len(header_str) == 12: # If it is the name of sequence with a 4 letter PDB id. compact_header=header_str[0:4]+"_"+header_str[-1] else: compact_header=crop_header(header_str[0:-8])+"_"+header_str[-1] #----------------------------------------------- # Other kind of headers. Just crop the header. - #----------------------------------------------- else: compact_header = crop_header(header_str) return compact_header def crop_header(h): return h[0:max_compact_header_length] def is_uniprotkb_fasta_header(self, header): pass def check_fetchable_pdb_from_header(header): # First check for the following format: "1UBI_A" or "1_1UBI_A" # match = re.match("([a-zA-Z0-9]{4})_([A-Z])$", header) match = re.match("([\d]+_)*([a-zA-Z0-9]{4})_([A-Z])$", header) if match: groups = match.groups() pdb_code = groups[1] pdb_chain = groups[2] # Then checks for the following format (found in BLAST databases files): # gi|157830059|pdb|1ASH|A (at the time of the old PyMod version) # pdb|1ASH|A (at the time of the new PyMod version) else: try: header_fields = header.split("|") if header_fields[0] == "pdb": pdb_code = header_fields[1] if header_fields[2] != "": pdb_chain = header_fields[2][0] else: return None elif header_fields[2] == "pdb": pdb_code = header_fields[3] if header_fields[4] != "": pdb_chain = header_fields[4][0] else: return None elif header_fields[4] == "pdb": pdb_code = header_fields[5] if header_fields[6][0] != "": pdb_chain = header_fields[6][0] else: return None else: return None except IndexError: return None return str(pdb_code), str(pdb_chain) # Unicode strings are not recognized by MODELLER.
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_structure/__init__.py
.py
28,889
595
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Module with classes to represent the 3D structures loaded in PyMod. """ import os import shutil import warnings import math from Bio.PDB import PDBParser, PDBIO from Bio.PDB.PDBIO import Select try: from Bio.PDB.vectors import calc_dihedral except ImportError: # Old Biopython versions. from Bio.PDB.Vector import calc_dihedral from pymod_lib import pymod_vars from pymod_lib.pymod_seq import seq_manipulation from pymod_lib import pymod_element from pymod_lib import pymod_residue class Select_chain_and_first_model(Select): """ This class is needed to write new PDB files with only a single chain of the first model of the Biopython object parsed by 'Bio.PDB.PDBIO'. """ def __init__(self,chain_id): self.chain_id = chain_id def accept_chain(self, chain): if chain.get_id() == self.chain_id: return True else: return False def accept_model(self,model): if model.id == 0: return True else: return False class Parsed_pdb_file: """ Class to represent a parsed PDB file, which information can be used to add 'PyMod_sequence_element' with structures to PyMod. """ # counter = 0 parsed_file_code = "parsed_by_pymod" blank_chain_character = "X" def __init__(self, pymod, pdb_file_path, output_directory="", new_file_name=None, copy_original_file=True, save_chains_files=True): # self.list_of_structure_dicts = [] self.pymod = pymod #------------------------------------------------------------------------------------ # Defines the name of the files which will be built from the parsed structure file. - #------------------------------------------------------------------------------------ self.output_directory = output_directory # Directory where the output files (such as the split chains files) are going to be built. self.original_pdb_file_path = pdb_file_path # Path of the original structure file on the user's system. self.original_base_name = os.path.splitext(os.path.basename(self.original_pdb_file_path))[0] # Original basename. # Define the name of the structures files derived from the original file. if not new_file_name: self.structure_file_name = self.original_base_name else: self.structure_file_name = os.path.splitext(os.path.basename(new_file_name))[0] #------------------------------------------------------------------------------------- # Initially copies the full PDB file in the ouptut directory using a temporary name. - #------------------------------------------------------------------------------------- copied_full_file_path = os.path.join(self.output_directory, self._get_full_structure_file_name()) if copy_original_file and not os.path.isfile(copied_full_file_path): shutil.copy(self.original_pdb_file_path, copied_full_file_path) #------------------------------ # Parses the header manually. - #------------------------------ pass #-------------------------------------------------------------------------------- # Split the sequence in chains, get the sequences and residues using Biopython. - #-------------------------------------------------------------------------------- warnings.simplefilter("ignore") # Actually parses the original structure file on the user's system. parsed_file_handle = open(self.original_pdb_file_path, "r") # Creates a biopython 'Structure' object and starts to take informations from it. self.parsed_biopython_structure = PDBParser(PERMISSIVE=1, QUIET=True).get_structure(self.parsed_file_code, parsed_file_handle) parsed_file_handle.close() # The items of this list will contain information used to build the elements to be loaded # in PyMod. list_of_parsed_chains = [] # ligands_ids = [] # Ligand heteroatoms and water molecules ids. # Starts to iterate through the models in the biopython object. for model in self.parsed_biopython_structure.get_list(): for chain in model.get_list(): parsed_chain = {"original_id": None, # Chain ID in the PDB file. "pymod_id": None, # The ID assigned in PyMod. "residues": [], "file_name": None, "file_path": None, "found_blank_chain": None, "has_standard_residues": False} # Assigns a blank "X" chain id for PDB structures that do not specify chains id. if chain.id != " ": parsed_chain["pymod_id"] = chain.id parsed_chain["found_blank_chain"] = False elif chain.id == " ": chain.id = self.blank_chain_character parsed_chain["pymod_id"] = self.blank_chain_character parsed_chain["found_blank_chain"] = True # Starts to build the sequences by parsing through every residue of the chain. for residue in chain: # Gets the 3 letter name of the current residue. resname = residue.get_resname() # get_id() returns something like: ('H_SCN', 1101, ' '). The first item is # the hetfield: 'H_SCN' for an HETRES, while ' ' for a normal residue. The # second item is the id of the residue according to the PDB file. hetfield, pdb_position = residue.get_id()[0:2] # For HETATM residues. if hetfield[0] == "H": # Check if the current HETRES is a modified residue. Modified residues will # be added to the sequence. if self._check_modified_residue(residue, chain): parsed_chain["residues"].append(pymod_residue.PyMod_modified_residue(three_letter_code=resname, one_letter_code=pymod_vars.modified_residue_one_letter, db_index=pdb_position)) else: parsed_chain["residues"].append(pymod_residue.PyMod_ligand(three_letter_code=resname, one_letter_code=pymod_vars.ligand_one_letter, db_index=pdb_position)) # For water molecules. elif hetfield == "W": parsed_chain["residues"].append(pymod_residue.PyMod_water_molecule(three_letter_code=resname, one_letter_code=pymod_vars.water_one_letter, db_index=pdb_position)) # For standard amino acid residues. Adds them to the sequence. else: parsed_chain["residues"].append(pymod_residue.PyMod_standard_residue(three_letter_code=resname, one_letter_code=seq_manipulation.three2one(resname), db_index=pdb_position)) parsed_chain["has_standard_residues"] = True # Only adds the chain to PyMod if it has at least one standard residue. if parsed_chain["has_standard_residues"]: list_of_parsed_chains.append(parsed_chain) # Stops after having parsed the first "model" in the biopython "Structure". This is # needed to import only the first model of multimodel files (such as NMR files). break #---------------------------------------------------------------------- # Build 'PyMod_elements' object for each chain of the structure file. - #---------------------------------------------------------------------- self.list_of_pymod_elements = [] self.list_of_chains_structure_args = [] for numeric_chain_id, parsed_chain in enumerate(list_of_parsed_chains): # Defines the path of the element chain structure file. Initially uses a temporary name # for the file names. When the structures will be loaded in PyMod/PyMOL they will be # renamed using the header of the PyMod element. parsed_chain["file_name"] = self._get_structure_chain_file_name(parsed_chain["pymod_id"]) parsed_chain["file_path"] = os.path.join(self.output_directory, parsed_chain["file_name"]) # Builds the new 'PyMod_element'. The header will be used to rename the chains once They # are loaded in PyMod/PyMOL. new_element_header = self._get_new_pymod_element_header(parsed_chain["pymod_id"], parsed_chain["found_blank_chain"]) new_element = self._build_pymod_element(residues=parsed_chain["residues"], element_header=new_element_header, color=self._get_chain_color(numeric_chain_id)) # Builds the new structure for the PyMod element. new_structure = PyMod_structure(file_name_root=self.structure_file_name, full_file_path=copied_full_file_path, chain_file_path=parsed_chain["file_path"], chain_id=parsed_chain["pymod_id"], numeric_chain_id=numeric_chain_id, original_structure_file_path=self.original_pdb_file_path, original_structure_id=self.pymod.pdb_counter) new_element.set_structure(new_structure) self.list_of_pymod_elements.append(new_element) self.list_of_chains_structure_args.append(new_structure) #------------------------------------------------------------------------------------ # Saves a PDB file with only the current chain of the first model of the structure. - #------------------------------------------------------------------------------------ if save_chains_files: io = PDBIO() io.set_structure(self.parsed_biopython_structure) for element in self.list_of_pymod_elements: saved_structure_filepath = element.get_structure_file(basename_only=False) io.save(saved_structure_filepath, Select_chain_and_first_model(element.get_chain_id())) #----------------------------------------- # Fix the chain's PDB file if necessary. - #----------------------------------------- # Checks if there are any ligands or water molecules before the polypeptide # chain atoms. found_lig = False reorder_structure_file = False for residue in element.get_residues(standard=True, modified_residues=True, ligands=True, water=True): if residue.is_polymer_residue(): if found_lig: reorder_structure_file = True break if not residue.is_polymer_residue(): found_lig = True # Reorder the residues in the structure file, so that the polymeric residues are put # first and the ligands and water molecules for last. if reorder_structure_file: np_hetatms = element.get_residues(standard=False, modified_residues=False, ligands=True, water=True) np_hetatms_ids = [h.db_index for h in np_hetatms] pol_lines = [] # This will be populated with the polymer chain lines. np_hetatms_lines = [] # This will be populated with the non-polymer heteroatom lines. str_fh = open(saved_structure_filepath, "r") for line_i, line in enumerate(str_fh): if line.startswith(("HETATM", "ATOM")): db_index = int(line[22:26]) if db_index in np_hetatms_ids: np_hetatms_lines.append(line) else: pol_lines.append(line) str_fh.close() # Rewrite the structure file with the new atom order. str_fh = open(saved_structure_filepath, "w") atm_count = 1 for l in pol_lines + np_hetatms_lines: str_fh.write(l[0:6] + str(atm_count).rjust(5, " ") + l[11:]) atm_count += 1 str_fh.write("TER" + str(atm_count).rjust(8, " ") + l[17:26].rjust(15, " ") + "\n") str_fh.write("END\n") str_fh.close() warnings.simplefilter("always") #------------------------------- # Finds the disulfide bridges. - #------------------------------- self._assign_disulfide_bridges() #------------- # Completes. - #------------- self.pymod.pdb_counter += 1 def _correct_chain_id(self, chain_id): if chain_id != " ": return chain_id else: return self.blank_chain_character def get_pymod_elements(self): return self.list_of_pymod_elements def get_chains_ids(self): return [struct.chain_id for struct in self.list_of_chains_structure_args] def get_pymod_element_by_chain(self, chain_id): for e in self.list_of_pymod_elements: if e.get_chain_id() == chain_id: return e raise KeyError("No element with chain '%s' was built from the parsed PDB file." % chain_id) ################################################################# # Check if a residue is part of a molecule. # ################################################################# peptide_bond_distance = 1.8 def _check_modified_residue(self, residue, chain): """ Returns 'True' if the residue is a modified residue, 'False' if is a ligand. """ if not self._check_polypetide_atoms(residue): return False # Checks if the heteroresidue is forming a peptide bond with its C carboxy atom. has_carboxy_link = self._find_links(residue, chain, self._get_carboxy_atom, self._get_amino_atom, "N") # Checks if the heteroresidue is forming a peptide bond with its N amino atom. has_amino_link = self._find_links(residue, chain, self._get_amino_atom, self._get_carboxy_atom, "C") return has_carboxy_link or has_amino_link def _check_polypetide_atoms(self, residue): """ Checks if a residue has the necessary atoms to make peptide bonds. """ return pymod_vars.std_amino_acid_backbone_atoms < set(residue.child_dict.keys()) or pymod_vars.mod_amino_acid_backbone_atoms < set(residue.child_dict.keys()) def _find_links(self, residue, chain, get_residue_atom, get_neighbour_atom, link="N"): # Get either the N amino or C carboxy atom of the residue. residue_atom = get_residue_atom(residue) if residue_atom == None: return None # Find other residues in the chain having an atom which can make a peptide bond with the # 'residue' provided in the argument. neighbour_atoms = [] for res in chain: if not res == residue: neighbour_atom = get_neighbour_atom(res) if neighbour_atom != None: neighbour_atoms.append(neighbour_atom) # Check if there is a neighbour atom close enough to make a peptide bond with it. If such # atom is found, the residue is a part of a polypeptide chain. for atom in neighbour_atoms: distance = atom - residue_atom if distance < 1.8: return True return False def _get_carboxy_atom(self, residue): return self._get_atom_by_type(residue, ("C", "C1")) def _get_amino_atom(self, residue): return self._get_atom_by_type(residue, ("N", "N2")) def _get_atom_by_type(self, residue, atom_types_tuple): for atom_type in atom_types_tuple: if atom_type in residue.child_dict: if not residue.child_dict[atom_type].is_disordered(): return residue.child_dict[atom_type] return None ################################################################# # Build files and PyMod elements from the parsed structure. # ################################################################# def _get_new_pymod_element_header(self, chain_id, found_blank_chain=False, compact_names=False): if not compact_names: parsed_chain_name = "%s_chain_%s.pdb" % (self.structure_file_name, chain_id) else: if not found_blank_chain: parsed_chain_name = "%s_%s.pdb" % (self.structure_file_name, chain_id) else: parsed_chain_name = "%s.pdb" % (self.structure_file_name) return os.path.splitext(parsed_chain_name)[0] def _get_structure_chain_file_name(self, chain_id): return pymod_vars.structure_chain_temp_name % (self.pymod.pdb_counter, chain_id) def _get_full_structure_file_name(self): return pymod_vars.structure_temp_name % self.pymod.pdb_counter def _build_pymod_element(self, residues, element_header, color): return self.pymod.build_pymod_element(pymod_element.PyMod_sequence_element, residues=residues, header=element_header, color=color) def _get_chain_color(self, chain_number): list_of_model_chains_colors = pymod_vars.pymol_regular_colors_list return list_of_model_chains_colors[chain_number % len(list_of_model_chains_colors)] ################################################################# # Analyze structural features. # ################################################################# def _assign_disulfide_bridges(self): """ Assigns disulfide bridges to the PyMod elements built from the parsed structure file. """ list_of_disulfides = get_disulfide_bridges_of_structure(self.parsed_biopython_structure) for dsb in list_of_disulfides: # Get the chain of the first SG atom. dsb_chain_i = self._correct_chain_id(dsb["chain_i"]) # Get the chain of the second SG. dsb_chain_j = self._correct_chain_id(dsb["chain_j"]) new_dsb = Disulfide_bridge(cys1=dsb["residue_i"][1], cys2=dsb["residue_j"][1], cys1_seq_index=self.get_pymod_element_by_chain(dsb_chain_i).get_residue_by_db_index(dsb["residue_i"][1]).seq_index, cys2_seq_index=self.get_pymod_element_by_chain(dsb_chain_j).get_residue_by_db_index(dsb["residue_j"][1]).seq_index, cys1_chain=dsb_chain_i, cys2_chain=dsb_chain_j, distance=dsb["distance"], chi3_dihedral=dsb["chi3_dihedral"]) # For intrachain residues. if dsb_chain_i == dsb_chain_j: self.get_pymod_element_by_chain(dsb_chain_i).add_disulfide(disulfide=new_dsb) # For interchain residues. else: self.get_pymod_element_by_chain(dsb_chain_j).add_disulfide(disulfide=new_dsb) self.get_pymod_element_by_chain(dsb_chain_i).add_disulfide(disulfide=new_dsb) class Parsed_model_pdb_file(Parsed_pdb_file): def __init__(self, pymod, pdb_file_path, model_root_name="", **configs): self.model_root_name = model_root_name Parsed_pdb_file.__init__(self, pymod, pdb_file_path, **configs) def _build_pymod_element(self, residues, element_header, color): return self.pymod.build_pymod_element(pymod_element.PyMod_model_element, residues=residues, header=element_header, color=color, model_root_name=self.model_root_name) class PyMod_structure: def __init__(self, file_name_root, full_file_path, chain_file_path, chain_id, original_structure_file_path, original_structure_id, numeric_chain_id=0): # File paths of the full structure files (the file containing all the chains of the # structure) of the PyMod element. self.current_full_file_path = full_file_path self.current_full_file_name = os.path.basename(self.current_full_file_path) # Base name assigned in the constructor of the 'Parsed_pdb_file' class. self.file_name_root = file_name_root # File paths of the structure files of the chain of the PyMod element. self.initial_chain_file_path = chain_file_path self.initial_chain_file_name = os.path.basename(self.initial_chain_file_path) self.current_chain_file_path = self.initial_chain_file_path self.current_chain_file_name = os.path.basename(self.current_chain_file_path) self.chain_id = chain_id # File path of the original structure file on the user's system. This file will only be # copied, not actually edited. self.original_structure_file_path = original_structure_file_path self.original_structure_id = original_structure_id # Numeric index to report where the chain is in the structure file. self.numeric_chain_id = numeric_chain_id self.disulfides_list = [] self.pymod_element = None def set_pymod_element(self, pymod_element): self.pymod_element = pymod_element ################################################################################################### # Classes for several structural features of macromolecules. # ################################################################################################### class Disulfide_bridge: """ Class for disulfide bridges. """ def __init__(self, cys1=0, cys2=0, cys1_chain=None, cys2_chain=None, cys1_seq_index=0, cys2_seq_index=0, distance=0, chi3_dihedral=0): # The id of the first cysteine residue in the PDB file. self.cys1 = cys1 self.cys1_chain = cys1_chain self.cys2 = cys2 self.cys1_pdb_index = cys1 self.cys2_pdb_index = cys2 self.cys2_chain = cys2_chain self.distance = distance self.chi3_dihedral = chi3_dihedral # This sets the number of the cysteine in the sequence created by Pymod. Most often it is # different from the number from the PDB file. self.cys1_seq_index = cys1_seq_index self.cys2_seq_index = cys2_seq_index # The following attribute can be either "intrachain" (the 2 cys belong to the same # polypeptide chain) or "interchain" (the 2 cys belong to two different polypeptide chains). if self.cys1_chain == self.cys2_chain: self.type = "intrachain" elif self.cys1_chain != self.cys2_chain: self.type = "interchain" ################################################################################################### # Analysis of structures. # ################################################################################################### class Disulfide_analyser: """ Uses Biopython to find the disulfides bridges in the molecules in a parsed structure file. """ # Parameters for disulfide bridges definition. disulfide_min_sg_distance = 1.5 disulfide_max_sg_distance = 3.0 min_chi3_dihedral_value = math.pi/2.0 * 0.5 max_chi3_dihedral_value = math.pi/2.0 * 1.5 def __init__(self): self.parsed_biopython_structure = None def set_parsed_biopython_structure(self, parsed_biopython_structure): self.parsed_biopython_structure = parsed_biopython_structure def get_disulfide_bridges(self): # Starts to iterate through the S gamma atoms in the biopython object. list_of_sg_atoms = [atom for atom in list(self.parsed_biopython_structure.get_list())[0].get_atoms() if atom.id == "SG"] self.list_of_disulfides = [] for si, atomi in enumerate(list_of_sg_atoms): for sj, atomj in enumerate(list_of_sg_atoms[si:]): if not atomi == atomj: # Gets the distance between two SG atoms. ij_distance = atomi - atomj # Filter for the distances. if ij_distance >= self.disulfide_min_sg_distance and ij_distance <= self.disulfide_max_sg_distance: # Computes the Cbi-Sgi-Sgj-Cbj dihedral angle (also called the chi3 angle). cbi_vector = atomi.get_parent()["CB"].get_vector() sgi_vector = atomi.get_vector() sgj_vector = atomj.get_vector() cbj_vector = atomj.get_parent()["CB"].get_vector() chi3_dihedral = calc_dihedral(cbi_vector, sgi_vector, sgj_vector, cbj_vector) chi3_dihedral = abs(chi3_dihedral) # Filters for chi3 angle values. if chi3_dihedral >= self.min_chi3_dihedral_value and chi3_dihedral <= self.max_chi3_dihedral_value: self.list_of_disulfides.append({# Measurements. "distance": ij_distance, "chi3_dihedral":chi3_dihedral, # *180.0/math.pi # Atoms. "atom_i": atomi, "atom_j": atomj, # Residues ids. "residue_i": atomi.get_parent().id, "residue_j": atomj.get_parent().id, # Chain ids. "chain_i": atomi.get_parent().get_parent().id, "chain_j": atomj.get_parent().get_parent().id}) return self.list_of_disulfides def get_disulfide_bridges_of_structure(parsed_biopython_structure): """ Quickly gets information about the disulfide bridges contained in a structure file. """ dsba = Disulfide_analyser() dsba.set_parsed_biopython_structure(parsed_biopython_structure) return dsba.get_disulfide_bridges() ################################################################################################### # Manipulation of structure files. # ################################################################################################### class PDB_joiner: """ A class to joins more than one PDB file in one single file. Usage example: j = PDB_joiner(["file_chain_A.pdb", "file_chain_B.pdb"]) j.join() j.write("file.pdb") """ def __init__(self, list_of_structure_files): self.list_of_structure_files = list_of_structure_files self.output_file_lines = [] self.atom_counter = 1 def join(self): for structure_file in self.list_of_structure_files: with open(structure_file, "r") as sfh: lines = [self._modify_atom_index(line) for line in sfh.readlines() if self._accept_atom_line(line)] if lines[-1].startswith("ATOM"): lines.append(self._build_ter_line(lines[-1])) self.output_file_lines.extend(lines) # TODO: add an 'END' line. def write(self, output_file_path): output_file_handle = open(output_file_path, "w") output_file_handle.writelines(self.output_file_lines) output_file_handle.close() def _accept_atom_line(self, line): return line.startswith("ATOM") or line.startswith("HETATM") def _build_atom_line(self, line, new_atom_index): return "%s%s%s" % (line[:6], str(new_atom_index).rjust(5), line[11:]) def _build_ter_line(self, last_atom_line): return "TER %s %s" % (last_atom_line[6:11], last_atom_line[17:26]) def _build_end_line(self, end_line): return "END" def _modify_atom_index(self, line): new_line = self._build_atom_line(line, self.atom_counter) self.atom_counter += 1 return new_line def join_pdb_files(list_of_structure_files, output_file_path): """ Quickly joins several PDB files using the 'PDB_joiner' class. """ j = PDB_joiner(list_of_structure_files) j.join() j.write(output_file_path)
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_main/_installer.py
.py
57,791
1,361
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Module for automatically downloading and installing the external PyMod tools (BLAST+, HMMER, Clustal, MUSCLE, psipred, ksdssp) and the MODELLER conda package. """ import os import sys import shutil import re import subprocess import zipfile import urllib.request import json import importlib import time from pymol import cmd from pymol.Qt import QtCore, QtWidgets from pymod_lib.pymod_os_specific import (get_python_architecture, get_os_architecture, get_formatted_date, get_exe_file_name, get_home_dir, check_network_connection, check_importable_modeller) from pymod_lib.pymod_vars import (blast_databases_dirname, hmmer_databases_dirname, hmmscan_databases_dirname, data_installer_log_filename) from pymod_lib.pymod_gui.shared_gui_components_qt import askyesno_qt, askopenfile_qt import warnings # Installer parameters. tools_installer_log_filename = "pymod_installer_log.txt" allowed_platforms = ("linux", "darwin", "win32") packages_url_dict = {"linux": "https://github.com/pymodproject/pymod/releases/download/v3.0/linux_pymod_3.0_installer_bundle.zip", "darwin": "https://github.com/pymodproject/pymod/releases/download/v3.0/macos_pymod_3.0_installer_bundle.zip", "win32": "https://github.com/pymodproject/pymod/releases/download/v3.0/windows_pymod_3.0_installer_bundle.zip"} use_external_tools_local_install = False python_minor_version = "%s.%s" % (sys.version_info.major, sys.version_info.minor) def catch_errors_installer_threads(function): """ Catches errors in the installer threads and closes the dialogs. """ def wrapper(self, *args, **kwargs): try: return function(self, *args, **kwargs) except Exception as e: self.emit_exception.emit(e) return wrapper class PyMod_installer: """ Mixin class to extend the main PyMod class with an automatic installer for PyMod components. """ def launch_components_installation(self, event=None): """ Called when selecting the installer option from PyMod main menu. """ #----------------------------------------------- # Checks if the installation can be performed. - #----------------------------------------------- # Check the internet connection, as the installation requires to download packages from the # internet. if not check_network_connection("https://google.com", timeout=3): # "http://216.58.192.142" has_network = False if not use_external_tools_local_install: message = ("An internet connection is not available. The automatic installation" " of PyMod Components requires a connection to download their" " packages. Please use an internet connection if you want to perform" " the automatic installation.") self.main_window.show_error_message("Installation Error", message) else: has_network = True # Check if the user's system supports installation of components. if sys.platform not in allowed_platforms: message = ("Your operating system ('%s') is not supported by the automatic PyMod" " Installer. You need to install PyMod components manually. Please" " refer to the PyMod documentation for details about manual installation" " of PyMod components." % (sys.platform)) self.main_window.show_error_message("Installation Error", message) return None #--------------------------------------------------------------- # Get some parameters before proceeding with the installation. - #--------------------------------------------------------------- # Get the specs of the user's system. python_arch = get_python_architecture() os_arch = get_os_architecture() # Checks if the OS as a 64 bit architecture. if os_arch != "64": message = ("Your operating system has a %s bit architecture. The PyMod Installer" " fully supports only systems with a 64 bit architecture. You may be" " able to install MODELLER through Conda (if you have an incentive" " PyMOL build) but you will not be able to download most of the" " external tools of PyMod (BLAST+, HMMER, Clustal, MUSCLE, psipred, ksdssp)." " If you need to use these tools, you will have to install and" " configure them manually. Please refer to the PyMod documentation" " for details on how to do it." % (os_arch)) self.main_window.show_warning_message("Installation Warning", message) # Checks if the external tools directory exists and is empty. On PyMod first session, it # should exists and be empty. external_tools_dirpath = os.path.join(self.current_pymod_dirpath, self.external_tools_dirname) populated_tools_dir = False if os.path.isdir(external_tools_dirpath): populated_tools_dir = bool(os.listdir(external_tools_dirpath)) # Check if Conda is integrated in PyMOL. try: import conda has_conda = True except ImportError: has_conda = False # Get the status of MODELLER. try: import modeller # MODELLER is installed correctly. modeller_status = "installed" except: modeller_spec = importlib.util.find_spec("modeller") # MODELLER is not installed. if modeller_spec is None: modeller_status = "missing" # License key is probably invalid. else: try: import modeller except ImportError as e: error = e print(f"Error importing some_library: {e}") except Exception as e: error = e print(f"An unexpected error occurred: {e}") if "DLL load failed" in str(error) or "dll" in str(error): modeller_status = "broken-modeller" else: modeller_status = "broken" # Show the installation options dialog. install_options_dialog = Installation_options_dialog(pymod=self, populated_tools_dir=populated_tools_dir, has_conda=has_conda, modeller_status=modeller_status, has_network=has_network, os_arch=os_arch) install_options_dialog.setModal(True) install_options_dialog.exec_() install_modeller_flag = install_options_dialog.get_modeller_cb() external_tools_flag = install_options_dialog.get_external_tools_state() if not install_options_dialog.proceed_flag: return None #---------------------------------------------- # Dialogs to actually install the components. - #---------------------------------------------- # External tools installation. if external_tools_flag: # Show the external components download dialog. install_dialog = External_components_dialog(pymod=self, url=packages_url_dict[sys.platform], os_arch=os_arch, local_mode=use_external_tools_local_install) install_dialog.setModal(True) install_dialog.exec_() # Finishes the installation. if install_dialog.complete_status: self.get_parameters_from_configuration_file() # MODELLER installation. if install_modeller_flag: # Show the MODELLER installation download dialog. if modeller_status == "missing": install_dialog = Install_MODELLER_dialog(pymod=self) install_dialog.setModal(True) install_dialog.exec_() elif modeller_status == "broken-modeller": install_dialog = Install_MODELLER_dialog(pymod=self) install_dialog.setModal(True) install_dialog.exec_() # Asks the MODELLER license key. elif modeller_status == "broken": modeller_key = get_modeller_license_key_dialog(pymod=self) if modeller_key is None: return None try: modeller_config_filepath = set_modeller_license_key(modeller_key) message = ("The license key was sucessfully inserted in the MODELLER" " configuration file (at: '%s'). Please restart PyMOL to" " check if the key is valid and if MODELLER was correctly" " installed." % modeller_config_filepath) self.main_window.show_info_message("License Key Set", message) except Exception as e: message = ("Could not insert the MODELLER license key because of the" " following error: %s" % e) self.main_window.show_error_message("MODELLER Error", message) ################################################################################################### # Qt Dialogs. # ################################################################################################### class Installer_dialog_mixin: """ Mixin class to be incorporated in all the installation process dialogs. """ def keyPressEvent(self, event): """ By overriding this method, the dialog will not close when pressing the "esc" key. """ if event.key() == QtCore.Qt.Key_Escape: pass else: QtWidgets.QDialog.keyPressEvent(self, event) ################################ # Installation options dialog. # ################################ class Installation_options_dialog(Installer_dialog_mixin, QtWidgets.QDialog): """ Dialog to select the components to install. This is shown when launching the installer from the PyMod main window. """ is_pymod_window = True def __init__(self, pymod, populated_tools_dir, has_conda, modeller_status, has_network, os_arch): self.pymod = pymod QtWidgets.QDialog.__init__(self, parent=self.pymod.main_window) self.populated_tools_dir = populated_tools_dir self.external_tools_dirpath = os.path.join(pymod.current_pymod_dirpath, pymod.external_tools_dirname) self.has_conda = has_conda self.modeller_status = modeller_status self.has_network = has_network self.os_arch = os_arch self.proceed_flag = False self.initUI() # self.resize(QtCore.QSize(500, 180)) # (450, 140), (470, 180) def initUI(self): self.setWindowTitle('PyMod Tools Installation Options') vertical_layout = QtWidgets.QVBoxLayout() # Installation options label. self.download_info_label = QtWidgets.QLabel("Select components to install:", self) # self.download_info_label.setStyleSheet(label_style_1) vertical_layout.addWidget(self.download_info_label) # Install external tools checkbutton. if self.os_arch == "64": if self.has_network: external_tools_label = "External Tools (BLAST+, HMMER, Clustal, MUSCLE, psipred, ksdssp)" external_tools_cb_status = True external_tools_cb_checked = not self.populated_tools_dir else: external_tools_label = "External Tools (can not install, no internet connection)" external_tools_cb_status = False external_tools_cb_checked = False else: external_tools_label = "External Tools (can not install, only 64 bit OS are supported)" external_tools_cb_status = False external_tools_cb_checked = False self.external_tools_cb = QtWidgets.QCheckBox(external_tools_label, self) self.external_tools_cb.setChecked(external_tools_cb_checked) self.external_tools_cb.setEnabled(external_tools_cb_status) # self.external_tools_cb.setStyleSheet(label_font_1) vertical_layout.addWidget(self.external_tools_cb) # Install MODELLER checkbutton. install_modeller_label = None install_modeller_cb_status = None # Decide which actions to perform according to MODELLER status. fix_modeller_label = "Fix MODELLER (set licence key)" unknown_modeller_status_label = "Unknown MODELLER status" if self.modeller_status == "installed": install_modeller_label = "MODELLER (already installed)" install_modeller_cb_status = False else: if self.has_network: if self.has_conda: if self.modeller_status == "missing": install_modeller_label = "MODELLER (through Conda)" install_modeller_cb_status = True elif self.modeller_status == "broken": install_modeller_label = fix_modeller_label install_modeller_cb_status = True elif self.modeller_status == "broken-modeller": install_modeller_label = "MODELLER (through Conda)" install_modeller_cb_status = True else: install_modeller_label = unknown_modeller_status_label install_modeller_cb_status = False else: install_modeller_label = "MODELLER (can not install automatically, PyMOL has no Conda)" install_modeller_cb_status = False else: if self.modeller_status == "missing": install_modeller_label = "MODELLER (can not install automatically, no internet connection)" install_modeller_cb_status = False elif self.modeller_status == "broken": install_modeller_label = fix_modeller_label install_modeller_cb_status = True else: install_modeller_label = unknown_modeller_status_label install_modeller_cb_status = False self.install_modeller_cb = QtWidgets.QCheckBox(install_modeller_label, self) self.install_modeller_cb.setChecked(install_modeller_cb_status) self.install_modeller_cb.setEnabled(install_modeller_cb_status) # self.install_modeller_cb.setStyleSheet(label_font_1) # self.install_modeller_cb.stateChanged.connect(lambda:self.click_button(self.install_modeller_cb)) vertical_layout.addWidget(self.install_modeller_cb) vertical_layout.addStretch(1) # m = 10 # vertical_layout.setContentsMargins(m, m, m, m) # Button for starting the installation. horizontal_layout = QtWidgets.QHBoxLayout() self.start_button = QtWidgets.QPushButton('Start', self) # self.start_button.setStyleSheet(label_style_2) self.start_button.clicked.connect(self.on_button_click) horizontal_layout.addWidget(self.start_button) if not external_tools_cb_status and not install_modeller_cb_status: self.start_button.setEnabled(False) # Button for obtaining installation information. self.info_button = QtWidgets.QPushButton('Info', self) # self.info_button.setStyleSheet(label_style_2) self.info_button.clicked.connect(self.on_info_button_click) horizontal_layout.addWidget(self.info_button) horizontal_layout.addStretch(1) # Button for canceling the installation. self.cancel_button = QtWidgets.QPushButton('Cancel', self) # self.cancel_button.setStyleSheet(label_style_2) self.cancel_button.clicked.connect(self.on_cancel_button_click) horizontal_layout.addWidget(self.cancel_button) vertical_layout.addLayout(horizontal_layout) self.setLayout(vertical_layout) # Interactions with the buttons. def on_button_click(self): if not (self.external_tools_cb.isChecked() or self.install_modeller_cb.isChecked()): title = "Installation Warning" message = "Please select on the two components in order to proceed to their installation." self.pymod.main_window.show_warning_message(title, message) return None if self.populated_tools_dir and self.external_tools_cb.isChecked(): title = 'Installation Warning' message = ("Looks like that your PyMod External Tools directory (%s) is not empty." " This might mean that you have already installed some PyMod External" " Tools in that directory (either manually, or by using this same automatic" " installer before). Performing the automatic External Tools installation" " will overwrite that directory and all files within it will be lost. Would you" " like to proceed with the automatic installation?" % self.external_tools_dirpath) reply = askyesno_qt(title, message, self.pymod.get_qt_parent()) if not reply: return None self.proceed_flag = True self.close() def on_cancel_button_click(self): self.proceed_flag = False self.close() def on_info_button_click(self): message = ("By using this dialog you can automatically install PyMod Components.\n\n" "External Tools installation: if you decide to install the 'External Tools' (the first" " checkbutton in the dialog), PyMod will download a ZIP file (%s) containing all the" " executable and data files of the components and it will configure them so that they can be" " readily used in the plugin.\n\n" "MODELLER installation: if you decide to install MODELLER (the second checkbutton)," " PyMod will use the Conda package manager to download and install MODELLER. This" " function is accessible only if your PyMOL build is integrated with a Conda package" " manager (see PyMod manual for more details). Please note that you need a MODELLER" " licence key to perform this operation (which can be readily obtained from" " https://salilab.org/modeller/registration.html)." % (packages_url_dict[sys.platform])) self.pymod.main_window.show_info_message("PyMod Components Installation", message) # Get parameters from the GUI. def get_external_tools_state(self): return self.external_tools_cb.isChecked() def get_modeller_cb(self): return self.install_modeller_cb.isChecked() ############################################## # Download progress and installation dialog. # ############################################## class External_tools_download_thread(QtCore.QThread): """ Runs a download thread to download PyMod components. """ # Signals. update_progressbar = QtCore.pyqtSignal(int) get_current_size = QtCore.pyqtSignal(int, str) get_total_size = QtCore.pyqtSignal(int) emit_exception = QtCore.pyqtSignal(Exception) signal_start_install = QtCore.pyqtSignal(int) def set_params(self, url, download_path): self.url = url self.download_path = download_path self.block_size = 8192 self.write_mode = "wb" @catch_errors_installer_threads def run(self): # Connects with the web server. with urllib.request.urlopen(self.url) as http_resp: file_size = http_resp.headers["Content-Length"] if file_size is None: file_size = 0 else: file_size = int(file_size) self.get_total_size.emit(file_size) with open(self.download_path, self.write_mode) as o_fh: file_size_dl = 0 chunks_count = 0 while True: buffer_data = http_resp.read(self.block_size) file_size_dl += len(buffer_data) # Updates the fraction in the progressbar. if file_size != 0: # Can compute a fraction of the total size of the file to download. frac = file_size_dl/file_size*100 self.update_progressbar.emit(int(frac)) # Updates the MB values in the progressbar. if chunks_count % 100 == 0: self.get_current_size.emit(file_size_dl, "update") else: self.get_current_size.emit(0, "pass") if not buffer_data: break o_fh.write(buffer_data) chunks_count += 1 # Completes and updates the GUI. self.get_current_size.emit(file_size_dl, "completed") self.update_progressbar.emit(100) # Wait a little bit of time. time.sleep(0.5) self.signal_start_install.emit(0) class External_tools_installation_thread(QtCore.QThread): """ Runs a installation thread to install PyMod components. """ # Signals. complete_installation = QtCore.pyqtSignal(int) emit_exception = QtCore.pyqtSignal(Exception) # Name of the PyMod tools present in the installer package. tool_names = ["clustalw", "muscle", "clustalo", "blast_plus", "psipred", "ksdssp", "hmmer"] # Name of the data directories of the installer. data_components_names = [blast_databases_dirname, hmmer_databases_dirname] def set_params(self, archive_filepath, backup_archive_filepath, pymod_dirpath, pymod_cfg_file_path, external_tools_dirname, data_dirname, os_arch, use_blast_v5_databases=False, from_main_window=True): self.archive_filepath = archive_filepath self.backup_archive_filepath = backup_archive_filepath self.pymod_dirpath = pymod_dirpath self.pymod_cfg_file_path = pymod_cfg_file_path self.external_tools_dirname = external_tools_dirname self.data_dirname = data_dirname self.os_arch = os_arch self.use_blast_v5_databases = use_blast_v5_databases if self.use_blast_v5_databases: self.default_psipred_db = "swissprot" else: self.default_psipred_db = "swissprot_v4" self.from_main_window = from_main_window self.pymod_external_tools_dirpath = os.path.join(self.pymod_dirpath, self.external_tools_dirname) self.pymod_data_dirpath = os.path.join(self.pymod_dirpath, self.data_dirname) @catch_errors_installer_threads def run(self): """ Unzips the archive containing the files of PyMod external tools. """ #----------------------------------------------------------- # Builds a directory where to extract the temporary files. - #----------------------------------------------------------- pymod_files_dirpath = os.path.join(os.path.dirname(self.archive_filepath), "installation_files") source_pymod_files_dirpath = os.path.join(pymod_files_dirpath, "pymod_files") if os.path.isdir(pymod_files_dirpath): shutil.rmtree(pymod_files_dirpath) os.mkdir(pymod_files_dirpath) if self.backup_archive_filepath is not None: shutil.copy(self.backup_archive_filepath, self.archive_filepath) #----------------------------------------- # Check if the file is a valid zip file. - #----------------------------------------- if not zipfile.is_zipfile(self.archive_filepath): raise TypeError("The '%s' file is not a zip file." % self.archive_filepath) #--------------------------------------------- # Extract the file to a temporary directory. - #--------------------------------------------- shutil.unpack_archive(self.archive_filepath, pymod_files_dirpath, format="zip") #------------------------------------------------------------- # Put PyMod tools executable files in the right directories. - #------------------------------------------------------------- source_external_tools_dirpath = os.path.join(source_pymod_files_dirpath, self.external_tools_dirname, str(self.os_arch)) # Build an 'external_tools' directory. if os.path.isdir(self.pymod_external_tools_dirpath): shutil.rmtree(self.pymod_external_tools_dirpath) os.mkdir(self.pymod_external_tools_dirpath) # Copy all tools files. installed_tools_list = [] for tool_name in self.tool_names: tool_source_dirpath = os.path.join(source_external_tools_dirpath, tool_name) if not os.path.isdir(tool_source_dirpath): continue installed_tools_list.append(tool_name) tool_dest_dirpath = os.path.join(self.pymod_external_tools_dirpath, tool_name) # Copy the files in the target PyMod directory. shutil.move(tool_source_dirpath, tool_dest_dirpath) # Change executable file permissions on UNIX systems. if os.name == "posix" and tool_name in ("clustalw", "clustalo", "muscle", "ksdssp", "psipred", "blast_plus", "hmmer"): for exec_file in os.listdir(os.path.join(tool_dest_dirpath, "bin")): command = "chmod 777 '%s'" % (os.path.join(tool_dest_dirpath, "bin", exec_file)) proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).communicate() # Leave a log file in the data directory to store installation information. with open(os.path.join(self.pymod_external_tools_dirpath, tools_installer_log_filename), "w") as l_fh: l_fh.write(get_formatted_date() + "\n") #------------------------------------------------- # Put PyMod data files in the right directories. - #------------------------------------------------- # Istall PyMod tools (except MODELLER). source_data_dirpath = os.path.join(source_pymod_files_dirpath, self.data_dirname) # Build a 'data' directory and its subdirectories. if not os.path.isdir(self.pymod_data_dirpath): os.mkdir(self.pymod_data_dirpath) for comp_name in self.data_components_names: comp_dirpath = os.path.join(self.pymod_data_dirpath, comp_name) if not os.path.isdir(comp_dirpath): os.mkdir(comp_dirpath) # Moves the files of all components. last_downloaded_dict = {} for comp_name in self.data_components_names: component_source_dirpath = os.path.join(source_data_dirpath, comp_name) component_dest_dirpath = os.path.join(self.pymod_data_dirpath, comp_name) # Copy the files in the target PyMod directory. for element_name in os.listdir(component_source_dirpath): if not ("swissprot" in element_name or "pdbaa" in element_name): continue element_source_dirpath = os.path.join(component_source_dirpath, element_name) element_dest_dirpath = os.path.join(component_dest_dirpath, element_name) # Moves directories. if os.path.isdir(element_source_dirpath): if os.path.isdir(element_dest_dirpath): shutil.rmtree(element_dest_dirpath) shutil.move(element_source_dirpath, element_dest_dirpath) # Moves files. if os.path.isfile(element_source_dirpath): if os.path.isfile(element_dest_dirpath): os.remove(element_dest_dirpath) shutil.move(element_source_dirpath, element_dest_dirpath) # Leave a log file in the data directory to store the date of installation. last_downloaded_dict = {} # Gets the download dates from the installer files. source_db_downloa_filepath = os.path.join(source_data_dirpath, data_installer_log_filename) if os.path.isfile(source_db_downloa_filepath): with open(source_db_downloa_filepath, "r") as l_fh: last_downloaded_dict = json.loads(l_fh.read()) # Gets the download dates of additional databases components from the PyMod data directory # file. db_download_filepath = os.path.join(self.pymod_data_dirpath, data_installer_log_filename) if os.path.isfile(db_download_filepath): with open(db_download_filepath, "r") as l_fh: old_last_downloaded_dict = json.loads(l_fh.read()) for k in old_last_downloaded_dict: if not k in last_downloaded_dict: last_downloaded_dict[k] = old_last_downloaded_dict[k] # Writes the log file. with open(db_download_filepath, "w") as l_fh: l_fh.write(json.dumps(last_downloaded_dict)) #------------------------------------- # Updating PyMod configuration file. - #------------------------------------- # Loads the configuration file. with open(self.pymod_cfg_file_path, "r") as c_fh: config_dict = json.loads(c_fh.read()) # Tools with only one executable. for tool_name in ("clustalw", "clustalo", "muscle", "ksdssp"): if not tool_name in installed_tools_list: continue config_dict[tool_name] = {} tool_exe_filepath = os.path.join(self.pymod_external_tools_dirpath, tool_name, "bin", get_exe_file_name(tool_name)) config_dict[tool_name]["exe_file_path"] = tool_exe_filepath # Tools with multiple executables and databases. for tool_name in ("blast_plus", "hmmer", "psipred"): if not tool_name in installed_tools_list: continue config_dict[tool_name] = {} tool_exe_dirpath = os.path.join(self.pymod_external_tools_dirpath, tool_name, "bin") config_dict[tool_name]["exe_dir_path"] = tool_exe_dirpath if tool_name == "blast_plus": config_dict[tool_name]["database_dir_path"] = os.path.join(self.pymod_data_dirpath, blast_databases_dirname) elif tool_name == "hmmer": config_dict[tool_name]["database_dir_path"] = os.path.join(self.pymod_data_dirpath, hmmer_databases_dirname) config_dict[tool_name]["hmmscan_db_dir_path"] = os.path.join(self.pymod_data_dirpath, hmmscan_databases_dirname) elif tool_name == "psipred": config_dict[tool_name]["database_dir_path"] = os.path.join(self.pymod_data_dirpath, blast_databases_dirname, self.default_psipred_db) # Psipred data directory. if "psipred" in installed_tools_list: config_dict["psipred"]["data_dir_path"] = os.path.join(self.pymod_external_tools_dirpath, "psipred", "data") # MODELLER. # config_dict["modeller"] = {"use_importable_modeller": True} # Writes the configuration file. with open(self.pymod_cfg_file_path, "w") as c_fh: c_fh.write(json.dumps(config_dict)) #---------------------------- # Cleaning temporary files. - #---------------------------- shutil.rmtree(pymod_files_dirpath) os.remove(self.archive_filepath) #------------------------------------------------------------------ # Updates the GUI so that the user can complete the installation. - #------------------------------------------------------------------ if self.from_main_window: self.complete_installation.emit(0) class External_components_dialog(Installer_dialog_mixin, QtWidgets.QDialog): """ A dialog to download from GitHub an archive with binary files for the external tools of PyMod. """ is_pymod_window = True def __init__(self, pymod, url, os_arch, local_mode=False): self.pymod = pymod QtWidgets.QDialog.__init__(self, parent=self.pymod.main_window) download_path = os.path.join(pymod.temp_directory_dirpath, "pymod_files.zip") self.local_mode = local_mode # Performs "local" installation. self.backup_download_path = None if self.local_mode: backup_download_path = askopenfile_qt("Select archive file", name_filter="*.zip", parent=self.get_qt_parent()) if backup_download_path == "" or not os.path.isfile(backup_download_path): self.pymod.main_window.show_warning_message("Input Warning", "Invalid archive file.") else: self.backup_download_path = backup_download_path self.mb_label = "0" self.tot_label = "0" self.total_size = None self.complete_status = False self.initUI() # Initializes the download thread. self.dl_thread = External_tools_download_thread() self.dl_thread.update_progressbar.connect(self.on_update_progressbar) self.dl_thread.set_params(url, download_path) self.dl_thread.get_current_size.connect(self.on_get_current_size) self.dl_thread.get_total_size.connect(self.on_get_total_size) self.dl_thread.emit_exception.connect(self.on_emit_exception) self.dl_thread.signal_start_install.connect(self.start_install_thread) # Initializes the installation thread. self.inst_thread = External_tools_installation_thread() # self.inst_thread.update_progressbar.connect(self.on_update_progressbar) self.inst_thread.set_params(archive_filepath=download_path, pymod_dirpath=pymod.current_pymod_dirpath, pymod_cfg_file_path=pymod.cfg_file_path, external_tools_dirname=pymod.external_tools_dirname, data_dirname=pymod.data_dirname, os_arch=os_arch, backup_archive_filepath=self.backup_download_path, use_blast_v5_databases=self.pymod.use_blast_v5_databases) self.inst_thread.complete_installation.connect(self.on_complete_installation) self.inst_thread.emit_exception.connect(self.on_emit_exception) def initUI(self): self.setWindowTitle('Download and Install External Tools') vertical_layout = QtWidgets.QVBoxLayout() self.download_progressbar = QtWidgets.QProgressBar(self) # self.progress.setGeometry(0, 0, 340, 25) self.download_progressbar.setMaximum(100) if not self.local_mode: progressbar_text = "Click the button to start components download and installation" else: if self.backup_download_path is not None: progressbar_text = "Click the button to start components installation" else: progressbar_text = "Invalid archive file" self.download_progressbar.setFormat("") self.download_progressbar.setValue(0) vertical_layout.addWidget(self.download_progressbar) self.progressbar_label = QtWidgets.QLabel(progressbar_text) vertical_layout.addWidget(self.progressbar_label) # Button for starting the installation. horizontal_layout = QtWidgets.QHBoxLayout() if not self.local_mode: start_button_text = 'Start Download' else: if self.backup_download_path is not None: start_button_text = 'Start Installation' else: start_button_text = 'Exit Installation' self.start_button = QtWidgets.QPushButton(start_button_text, self) # self.start_button.setStyleSheet(label_style_2) self.start_button.clicked.connect(self.on_button_click) horizontal_layout.addWidget(self.start_button) horizontal_layout.addStretch(1) # Button for canceling the installation. self.cancel_button = QtWidgets.QPushButton('Cancel', self) # self.cancel_button.setStyleSheet(label_style_2) self.cancel_button.clicked.connect(self.on_cancel_button_click) horizontal_layout.addWidget(self.cancel_button) vertical_layout.addLayout(horizontal_layout) self.setLayout(vertical_layout) # Interactions with the buttons. def on_button_click(self): # The installation has not been launched yet. if not self.complete_status: # Remote installation. if not self.local_mode: self.dl_thread.start() self.download_progressbar.setFormat("Connecting...") self.progressbar_label.setText("") self.start_button.setEnabled(False) # Local installation. else: if self.backup_download_path is not None: self.start_install_thread() self.start_button.setEnabled(False) else: self.close() # The installation has been already launched. else: self.close() def on_cancel_button_click(self): self._terminate_threads() self.close() def closeEvent(self, evnt): self._terminate_threads() def _terminate_threads(self): if self.dl_thread.isRunning(): self.dl_thread.terminate() if self.inst_thread.isRunning(): self.inst_thread.terminate() # Interactions with the download thread. def on_get_total_size(self, value): """ Gets the total size of the archive to download. """ self.total_size = value self.tot_label = self._convert_to_mb_string(value) if self.total_size == 0: pass def on_update_progressbar(self, value): """ Updates the percentage in the progressbar. """ self.download_progressbar.setValue(value) def on_get_current_size(self, value, state): """ Updates the MB values in the progressbar. """ if not state in ("update", "pass", "completed"): raise KeyError(state) if state in ("update", "completed"): self.mb_label = self._convert_to_mb_string(value) if self.total_size != 0: if state == "completed": self.download_progressbar.setFormat( "Download Completed: %p% (" + self.mb_label + " of " + self.tot_label + " MB)") else: self.download_progressbar.setFormat( "Download Progress: %p% (" + self.mb_label + " of " + self.tot_label + " MB)") else: if state == "completed": self.download_progressbar.setFormat("Download Completed: " + self.mb_label + " MB") else: self.download_progressbar.setFormat("Download Progress: " + self.mb_label + " MB of ???") def _convert_to_mb_string(self, value): if 0 <= value < 100000: round_val = 3 elif 100000 <= value: round_val = 1 else: ValueError(value) return str(round(value/1000000.0, round_val)) # Interactions with the installation thread. def start_install_thread(self, signal=0): self.inst_thread.start() # self.download_progressbar.setRange(0, 0) # self.download_progressbar.reset() self.download_progressbar.setValue(0) self.download_progressbar.setFormat("Unzipping (please wait...)") self.start_button.setText("Finish Installation") def on_complete_installation(self): self.download_progressbar.setValue(100) self.download_progressbar.setFormat("Installation Completed Successfully") self.start_button.setEnabled(True) self.cancel_button.setEnabled(False) self.complete_status = True def on_emit_exception(self, e): """ Quit the threads and close the installation dialog. """ self._terminate_threads() message = "There was an error: %s" % str(e) if hasattr(e, "url"): message += " (%s)." % e.url else: message += "." message += " Quitting the installation process." self.pymod.main_window.show_error_message("Installation Error", message) self.close() ############################ # Install MODELLER dialog. # ############################ class MODELLER_conda_install_thread(QtCore.QThread): """ Runs an installation thread to download the MODELLER conda package. """ # Signals. complete_installation = QtCore.pyqtSignal(dict) def set_params(self, pymod_envs_dirpath, pymod_env_dirpath, pymod_pkgs_dirpath): self.pymod_envs_dirpath = pymod_envs_dirpath self.pymod_env_dirpath = pymod_env_dirpath self.pymod_pkgs_dirpath = pymod_pkgs_dirpath def set_modeller_key(self, modeller_key): self.modeller_key = modeller_key def run(self): mod_install_result = perform_modeller_installation(self.modeller_key, self.pymod_envs_dirpath, self.pymod_env_dirpath, self.pymod_pkgs_dirpath) self.complete_installation.emit(mod_install_result) def perform_modeller_installation(modeller_key, pymod_envs_dirpath, pymod_env_dirpath, pymod_pkgs_dirpath, uninstall=False): try: print("\n# Installing the MODELLER conda package.") # Uses the conda python module. import conda.cli.python_api as conda_api # Gets environment information. info_results = conda_api.run_command(conda_api.Commands.INFO, "--json") conda_info_dict = json.loads(info_results[0]) # NOTE: installing modeller on the default PyMOL environment sometimes causes # problems in PyMOL < 2.5.7, therefore it is safer to install it in a PyMod "pseudo" conda # environment. pymol_version_for_modeller = tuple(map(int, cmd.get_version()[0].split('.')[:3])) minimum_pymol_version = (2, 5, 5) install_modeller_in_root_conda_env = False # Adds the salilab channel. This should write a .condarc file in the user's home. print("- Adding 'salilab' to the conda channels.") conda_api.run_command(conda_api.Commands.CONFIG, "--add", "channels", "salilab") # Uninstalls MODELLER if necessary. Not actually used right now in PyMod. if uninstall: stdout = conda_api.run_command(conda_api.Commands.REMOVE, "modeller") # Checks if we are in windows: if os.name == 'nt': # Checks if the conda root has write permissions. if "root_writable" in conda_info_dict: root_writable = conda_info_dict["root_writable"] else: root_writable = False # Checks if the user has Admin privileges. if "is_windows_admin" in conda_info_dict: is_windows_admin = conda_info_dict["is_windows_admin"] else: is_windows_admin = False # Checks if PyMOL version is > 2.5.5. In this case, Modeller will be installed on the default PyMOL environment if pymol_version_for_modeller > minimum_pymol_version: print("Your PyMOL version is %s, modeller will be installed in root PyMOL conda env" % str(cmd.get_version()[0])) install_modeller_in_root_conda_env = True else: print("Your PyMOL version is %s, modeller will be installed in a new conda env" % str(cmd.get_version()[0])) install_modeller_in_root_conda_env = False # if we are in other OS, modeller will be installed in new conda env anyway: else: install_modeller_in_root_conda_env = False # Sets an environmental variable which will be used by conda to edit the MODELLER # configuration file. print("- Setting the MODELLER key as an environmental variable.") os.environ["KEY_MODELLER"] = modeller_key # Edit the condarc file and builds a new conda environment for PyMod. if not install_modeller_in_root_conda_env: # Add an environment directory. print("- Adding a writable envs directory.") if os.path.isdir(pymod_envs_dirpath): shutil.rmtree(pymod_envs_dirpath) os.mkdir(pymod_envs_dirpath) conda_api.run_command(conda_api.Commands.CONFIG, "--add", "envs_dirs", pymod_envs_dirpath) # Add a packages directory. print("- Adding a writable pkgs directory.") if os.path.isdir(pymod_pkgs_dirpath): shutil.rmtree(pymod_pkgs_dirpath) os.mkdir(pymod_pkgs_dirpath) conda_api.run_command(conda_api.Commands.CONFIG, "--add", "pkgs_dirs", pymod_pkgs_dirpath) # Creates a new environment. Use the same Python version of the Python # used in PyMOL. print("- Creating a new python %s conda environment for PyMod modules -" % python_minor_version) conda_api.run_command(conda_api.Commands.CREATE, "-p", pymod_env_dirpath, "--no-default-packages", "python=%s" % python_minor_version) # Installs the MODELLER package. # Checks if windows: if os.name == 'nt': if install_modeller_in_root_conda_env: if not root_writable and not is_windows_admin: # message print("You must run PyMOL as Administrator in order to install Modeller!") return {"successful": False, "error": "You must run PyMOL as Administrator in order to install Modeller!\n \ Please right-click the PyMOL icon and select 'Run as Administrator'"} else: print("- Installing the 'modeller' conda package in root conda env") stdout = conda_api.run_command(conda_api.Commands.INSTALL, "modeller") else: print("- Installing the 'modeller' conda package in a new conda env %s" % str(pymod_env_dirpath)) stdout = conda_api.run_command(conda_api.Commands.INSTALL, "-p", pymod_env_dirpath, "modeller") # other OS: else: if not install_modeller_in_root_conda_env: print("- Installing the 'modeller' conda package in a new conda env %s" % str(pymod_env_dirpath)) stdout = conda_api.run_command(conda_api.Commands.INSTALL, "-p", pymod_env_dirpath, "modeller") else: print("- Installing the 'modeller' conda package in root conda env") stdout = conda_api.run_command(conda_api.Commands.INSTALL, "modeller") print("- The 'modeller' package was successfully installed.") # Removes the temporary directories from the .condarc file. if not install_modeller_in_root_conda_env: conda_api.run_command(conda_api.Commands.CONFIG, "--remove", "envs_dirs", pymod_envs_dirpath) conda_api.run_command(conda_api.Commands.CONFIG, "--remove", "pkgs_dirs", pymod_pkgs_dirpath) return {"successful": True, "error": None} except Exception as e: return {"successful": False, "error": e} class Install_MODELLER_dialog(Installer_dialog_mixin, QtWidgets.QDialog): """ Dialog to install the MODELLER conda package. """ is_pymod_window = True def __init__(self, pymod): self.pymod = pymod QtWidgets.QDialog.__init__(self, parent=self.pymod.main_window) self.complete_status = False self.initUI() self.adjustSize() # Initializes the package installation thread. self.mod_conda_thread = MODELLER_conda_install_thread() self.mod_conda_thread.complete_installation.connect(self.on_complete_installation) self.mod_conda_thread.set_params(pymod_envs_dirpath=pymod.pymod_envs_dirpath, pymod_env_dirpath=pymod.pymod_env_dirpath, pymod_pkgs_dirpath=pymod.pymod_pkgs_dirpath) def initUI(self): self.setWindowTitle('Install MODELLER package') # Installation progress bar. vertical_layout = QtWidgets.QVBoxLayout() self.mod_install_progressbar = QtWidgets.QProgressBar(self) self.mod_install_progressbar.setMaximum(100) vertical_layout.addWidget(self.mod_install_progressbar) # Installation progress label. self.mod_install_label = QtWidgets.QLabel("Click the button to start the MODELLER package installation", self) # self.mod_install_label.setStyleSheet(label_style_2) vertical_layout.addWidget(self.mod_install_label) # Button for starting the installation. horizontal_layout = QtWidgets.QHBoxLayout() self.start_button = QtWidgets.QPushButton('Start Installation', self) # self.start_button.setStyleSheet(label_style_2) self.start_button.clicked.connect(self.on_button_click) horizontal_layout.addWidget(self.start_button) horizontal_layout.addStretch(1) # Button for canceling the installation. self.cancel_button = QtWidgets.QPushButton('Cancel', self) # self.cancel_button.setStyleSheet(label_style_2) self.cancel_button.clicked.connect(self.on_cancel_button_click) horizontal_layout.addWidget(self.cancel_button) vertical_layout.addLayout(horizontal_layout) self.setLayout(vertical_layout) # Interactions with the buttons. def on_button_click(self): if not self.complete_status: # Asks the user to provide a MODELLER licence key. modeller_key = get_modeller_license_key_dialog(pymod=self.pymod) if modeller_key is None: return None self.modeller_key = modeller_key # Starts the installation thread. self.mod_conda_thread.set_modeller_key(self.modeller_key) self.mod_conda_thread.start() self.start_button.setEnabled(False) self.mod_install_progressbar.setRange(0, 0) self.mod_install_progressbar.setValue(0) self.mod_install_progressbar.setTextVisible(True) self.mod_install_progressbar.setAlignment(QtCore.Qt.AlignCenter) self.mod_install_label.setText("Retrieving and installing the MODELLER conda package...") else: self.close() def on_cancel_button_click(self): self._terminate_threads() self.close() def closeEvent(self, evnt): self._terminate_threads() def _terminate_threads(self): if self.mod_conda_thread.isRunning(): self.mod_conda_thread.terminate() # Interactions with the installation thread. def on_complete_installation(self, mod_install_result): """ Launched when the MODELLER installation process is terminated successfully. """ if not mod_install_result["successful"]: self.mod_install_failure(mod_install_result) return None # Finds the MODELLER module to check if the licence key was correct. On the first installation # on Windows, this usually fails. It also fails when MODELLER is installed in the PyMod conda # environment. modeller_spec = importlib.util.find_spec("modeller") # Updates the GUI. if mod_install_result["successful"]: # Completes successfully. self.mod_install_progressbar.setRange(0, 100) self.mod_install_progressbar.setValue(100) self.mod_install_progressbar.setFormat("") installation_text = ("MODELLER Package installed. Please restart PyMOL" " to check if the installation was successful.") # if modeller_spec is not None: # installation_text = ("MODELLER Package installed successfully." # " Please restart PyMOL to use MODELLER.") self.mod_install_label.setText(installation_text) self.start_button.setText("Finish Installation") self.start_button.setEnabled(True) self.cancel_button.setEnabled(False) self.complete_status = True else: self.mod_install_failure(mod_install_result) def mod_install_failure(self, mod_install_result): """ Completes a failed MODELLER installation. """ self.mod_install_progressbar.setRange(0, 100) self.mod_install_progressbar.setValue(0) self.mod_install_progressbar.setFormat("") self.mod_install_label.setText("MODELLER Conda Package installation failed") message = 'MODELLER installation failed because of the following error: \n\n%s.' % str(mod_install_result["error"]) self.pymod.main_window.show_error_message("Installation Error", message) self.start_button.setText("Exit Installation") self.start_button.setEnabled(True) self.cancel_button.setEnabled(True) # False self.complete_status = True ########################### # Repair MODELLER dialog. # ########################### def get_modeller_license_key_dialog(pymod): # Asks the user to provide a MODELLER licence key. modeller_key, pressed_ok = QtWidgets.QInputDialog.getText(pymod.main_window, "Insert MODELLER Key", "Insert a valid MODELLER licence key:", QtWidgets.QLineEdit.Password, "") if not pressed_ok: return None modeller_key = re.sub("[^a-zA-Z0-9 _-]", "", modeller_key) if not modeller_key: message = "Please enter a valid MODELLER licence key." pymod.main_window.show_warning_message("Input Warning", message) return None return modeller_key def set_modeller_license_key(modeller_key): """ Edits the MODELLER configuration file to enter a licence key. """ # Attempts to find the MODELLER config file by importing MODELLER. Usually does not work on # Windows. modeller_spec = importlib.util.find_spec("modeller") if modeller_spec is not None: modeller_dirpath = os.path.dirname(modeller_spec.origin) modeller_config_filepath = os.path.join(modeller_dirpath, "config.py") else: modeller_config_filepath = None if modeller_config_filepath is None or not os.path.isfile(modeller_config_filepath): raise ValueError("MODELLER 'config.py' not found.") with open(modeller_config_filepath, "r") as c_fh: old_mod_config_file_lines = c_fh.readlines() new_mod_config_file_lines = [] licence_line_found = False for line in old_mod_config_file_lines: if line.startswith("license"): licence_line_found = True new_mod_config_file_lines.append("license = r'%s'" % modeller_key) else: new_mod_config_file_lines.append(line) if not licence_line_found: raise ValueError("'licence' line not found in %s" % modeller_config_filepath) with open(modeller_config_filepath, "w") as c_fh: c_fh.writelines(new_mod_config_file_lines) return modeller_config_filepath
Python
3D
pymodproject/pymod
pymod3/pymod_lib/pymod_main/__init__.py
.py
33,413
711
# Copyright 2020 by Giacomo Janson. All rights reserved. # This code is part of the PyMod package and governed by its license. Please # see the LICENSE file that should have been included as part of this package # or the main __init__.py file in the pymod3 folder. """ Module implementing a class to represent the PyMod plugin. """ # Python standard library. import os import sys import shutil import re import json import datetime # PyMOL. from pymol import cmd # PyMod modules. from pymod_lib import pymod_os_specific as pmos # Different OS compatibility-related code. from pymod_lib import pymod_vars as pmdt # PyMod data used throughout the plugin. from pymod_lib import pymod_tool as pm_tool # Classes to represent tools used within PyMod. from pymod_lib import pymod_element as pmel # Classes to represent sequences and alignments in PyMod. # Path names used shared in various parts of the plugin. from pymod_lib.pymod_vars import blast_databases_dirname, hmmer_databases_dirname, hmmscan_databases_dirname # Part of the graphical user interface of PyMod. from pymod_lib.pymod_gui.main_window.main_window_qt import PyMod_main_window_qt from pymod_lib.pymod_gui.shared_gui_components_qt import askyesno_qt from pymod_lib.pymod_gui.specific_gui_components_qt import PyMod_dir_selection_dialog # Import modules with classes used to extend the 'PyMod' base class. from ._development import PyMod_development from ._main_menu_commands import PyMod_main_menu_commands from ._workspaces import PyMod_workspaces from ._external import PyMod_external from ._files_managment import PyMod_files_managment from ._elements_interactions import PyMod_elements_interactions from ._elements_loading import PyMod_elements_loading from ._pymol_interactions import PyMod_pymol_interactions from ._installer import PyMod_installer # Function that launches PyMod from the plugin menu of PyMOL. def pymod_launcher(app, pymod_plugin_name, pymod_version, pymod_revision, parallel_modeller): pymod = PyMod(app, pymod_plugin_name, pymod_version, pymod_revision, parallel_modeller) ################################################################################################### # Class that creates the plugin structure. # ################################################################################################### class PyMod(PyMod_main_menu_commands, PyMod_workspaces, PyMod_external, PyMod_files_managment, PyMod_elements_interactions, PyMod_pymol_interactions, PyMod_elements_loading, PyMod_installer, PyMod_development): """ Class to represent the PyMod plugin. """ def __init__(self, app, pymod_plugin_name, pymod_version, pymod_revision, parallel_modeller): """ Startup of the plugin. """ #--------------------- # Initializes PyMod. - #--------------------- self.pymod_plugin_name = pymod_plugin_name self.pymod_version = pymod_version self.pymod_revision = pymod_revision # Set to 'True' when developing, useful for debugging. self.DEVELOP = False # Set to 'True' to perform some tests on sequences/structures from the GUI. self.TEST = False self.app = app # Initialize PyMod elements and information about the analyses performed by the user. self.initialize_pymod_elements_information() # -------------------------------------------------------------------------------------- # Prepare PyMod files and folders that will be created in the project main directory. - # -------------------------------------------------------------------------------------- # PyMod directory. The main folder where all PyMod files (with the exception of the # configuration file) will be stored. self.pymod_directory_name = "pymod" self.pymod_temp_directory_name = "pymod_temp_directory" self.projects_directory_name = "projects" self.new_project_default_name = "new_pymod_project" self.external_tools_dirname = "external_tools" self.data_dirname = "data" self.temp_directory_name = "temp_dir" self.active_session_filename = ".active_session.txt" self.inactive_session_filename = ".inactive_session.txt" # Structures. self.structures_dirname = "structures" # structures_dirpath # Alignments. self.alignments_dirname = "alignments" # alignments_directory self.alignments_files_names = "alignment" # Images directory self.images_dirname = "images" # images_directory # Models. self.models_dirname = "models" # models_directory self.models_subdirectory = "modeling_session" # PSIPRED. self.psipred_dirname = "psipred" # BLAST. self.similarity_searches_dirname = "similarity_searches" self.use_blast_v5_databases = True # Domain analysis. self.domain_analysis_dirname = 'domain_analysis' # File names used in order to store the information of PyMod sessions. self.session_temp_dirname = "pymod_project_temp_dir" self.session_filename = "pymod_session" # Initializes the main paths for the plugin. self.initializes_main_paths() # ----------------------- # Prepare PyMod tools. - # ----------------------- self.pymod_tools = [] # PyMod itself. self.pymod_plugin = pm_tool.Tool("pymod", self.pymod_plugin_name) self.pymod_plugin.initialize_parameters([pm_tool.Tool_directory("pymod_dir_path", "PyMod Directory", editable=False)]) self.pymod_tools.append(self.pymod_plugin) # ClustalW. self.clustalw = pm_tool.Executable_tool("clustalw", "Clustal W",) self.clustalw.initialize_parameters([pm_tool.Tool_exec_file("exe_file_path", "Executable File", auto_find=True)]) self.pymod_tools.append(self.clustalw) # Clustal Omega. self.clustalo = pm_tool.Executable_tool("clustalo", "Clustal Omega") self.clustalo.initialize_parameters([pm_tool.Tool_exec_file("exe_file_path", "Executable File", auto_find=True)]) self.pymod_tools.append(self.clustalo) # MUSCLE. self.muscle = pm_tool.Executable_tool("muscle", "MUSCLE") self.muscle.initialize_parameters([pm_tool.Tool_exec_file("exe_file_path", "Executable File", auto_find=True)]) self.pymod_tools.append(self.muscle) # BLAST+ suite. Used to run PSI-BLAST and store BLAST sequence databases retrieved from # ftp://ftp.ncbi.nlm.nih.gov/blast/db/ . self.blast_plus = pm_tool.Executable_tool("blast_plus", "BLAST+ suite") self.blast_plus.initialize_parameters([pm_tool.Tool_exec_directory("exe_dir_path", "Executables Directory", auto_find=True), # A default directory where the database folders available for the # PSI-BLAST database selection are going to be located. pm_tool.Tool_directory("database_dir_path", "Database Directory")]) self.pymod_tools.append(self.blast_plus) # HMMER suite. self.hmmer_tool = pm_tool.Executable_tool("hmmer", "HMMER suite") self.hmmer_tool.initialize_parameters([pm_tool.Tool_exec_directory("exe_dir_path", "Executables Directory", auto_find=True), pm_tool.Tool_directory("database_dir_path", "HMMER Database Directory"), pm_tool.Tool_directory("hmmscan_db_dir_path", "HMMSCAN Database Directory")]) self.pymod_tools.append(self.hmmer_tool) # PSIPRED. self.psipred = pm_tool.Executable_tool("psipred", "PSIPRED") self.psipred.initialize_parameters([pm_tool.Tool_directory("exe_dir_path", "Executables Directory"), pm_tool.Tool_directory("data_dir_path", "Data Files Directory"), pm_tool.Tool_directory("database_dir_path", "BLAST Database Directory")]) self.pymod_tools.append(self.psipred) # KSDSSP. self.ksdssp = pm_tool.Executable_tool("ksdssp", "KSDSSP") self.ksdssp.initialize_parameters([pm_tool.Tool_exec_file("exe_file_path", "Executable File")]) self.pymod_tools.append(self.ksdssp) # MODELLER. self.modeller = pm_tool.Modeller_tool("modeller", "MODELLER") self.modeller.initialize_parameters([pm_tool.Use_importable_modeller("use_importable_modeller", "Internal MODELLER"),]) self.pymod_tools.append(self.modeller) self.parallel_modeller = parallel_modeller # Initializes tools. for tool in self.pymod_tools: tool.pymod = self # If set to 'True' the most time consuming protocols of PyMod will be run in a thread so # that the GUI is not freezed. When developing the code, it is better to set it to 'False', # in order to better track exceptions. if self.DEVELOP: self.use_protocol_threads = False else: self.use_protocol_threads = True # Initializes colors for PyMod and PyMOL. self.initialize_colors() #---------------------------------------- # Builds the main window of the plugin. - #---------------------------------------- self.main_window = PyMod_main_window_qt(self) #----------------------- # Starts up a new job. - #----------------------- # If it is not found, then treat this session as the first one and asks the user to input # the 'PyMod Directory' path before beginning the first PyMod job. if not os.path.isfile(self.cfg_file_path): self.show_first_time_usage_message() self.show_pymod_directory_selection_window() # The configuration file is found. else: # Start an usual PyMod session. Get values options for each PyMod tool and start a # new PyMod job. try: self.get_parameters_from_configuration_file() # Checks if the PyMod directory exists. if not os.path.isdir(self.pymod_plugin["pymod_dir_path"].get_value()): message = ("The project directory specified in PyMod configuration" " file ('%s') is missing. Please specify a new" " one." % self.pymod_plugin["pymod_dir_path"].get_value()) raise Exception(message) self.new_job_state() except Exception as e: if self.DEVELOP: raise e self.show_configuration_file_error(e, "read") title = 'Configuration file repair' message = "Would you like to delete PyMod configuration file and build a new functional copy of it?" repair_choice = askyesno_qt(title, message, self.get_qt_parent()) if repair_choice: self.show_pymod_directory_selection_window() else: self.main_window.destroy() def show_first_time_usage_message(self): title = "PyMod first session" message = "This is the first time you run PyMod. Please specify a folder inside which to build the 'PyMod Directory'. " message += "All PyMod files (such as its external tools executables, sequence databases and its project files) will be stored in this 'PyMod Directory' on your system." self.main_window.show_info_message(title, message) def get_pymod_app(self): return self.app.root def get_qt_parent(self): return None ############################################################################################### # Configuration file and first time usage. # ############################################################################################### def get_parameters_from_configuration_file(self): """ Updates the values of the PyMod Tools parameters according to the information in the main configuration file. """ cfgfile = open(self.cfg_file_path, 'r') # Reads the json configuration file, where PyMod options are stored in a dictionary. pymod_config = json.loads(cfgfile.read()) for tool_object in self.pymod_tools: tool_dict = pymod_config[tool_object.name] for parameter_name in list(tool_dict.keys()): tool_object[parameter_name].value = tool_dict[parameter_name] cfgfile.close() def show_pymod_directory_selection_window(self): """ Allows to select the 'PyMod Directory' on PyMod first run. """ self.pymod_dir_window = PyMod_dir_selection_dialog(app=self.main_window, pymod=self) self.pymod_dir_window.exec_() def pymod_directory_selection_state(self): """ This is called when the SUBMIT button on the "PyMod project" window is pressed. """ try: # Check if the parent folder of the new PyMod directory exists. new_pymod_directory_parent = self.pymod_dir_window.main_entry.text() if not os.path.isdir(new_pymod_directory_parent): title = 'PyMod directory Error' message = "The directory inside which you would like to create your 'PyMod Directory' ('%s') does not exist on your system. Please select an existing path." % (new_pymod_directory_parent) self.main_window.show_error_message(title, message) return None # Check if a PyMod directory already exists in the parent folder. new_pymod_dirpath = os.path.join(new_pymod_directory_parent, self.pymod_directory_name) if os.path.exists(new_pymod_dirpath): title = 'PyMod directory Warning' message = "A folder named '%s' already exists on your system. Would you like to overwrite it and all its contents to build a new 'PyMod Directory'?" % (new_pymod_dirpath) overwrite = askyesno_qt(title, message, parent=self.get_qt_parent()) if overwrite: if os.path.isfile(new_pymod_dirpath): os.remove(new_pymod_dirpath) if os.path.isdir(new_pymod_dirpath): shutil.rmtree(new_pymod_dirpath) else: return None # Check if the configuration file directory exist. If it does not exist, build it. if not os.path.exists(self.cfg_directory_path): os.mkdir(self.cfg_directory_path) # Builds the new PyMod directory with its projects folder. os.mkdir(new_pymod_dirpath) os.mkdir(os.path.join(new_pymod_dirpath, self.projects_directory_name)) # Builds empty external tools and data directories. os.mkdir(os.path.join(new_pymod_dirpath, self.external_tools_dirname)) os.mkdir(os.path.join(new_pymod_dirpath, self.data_dirname)) # Writes the configuration file. cfgfile = open(self.cfg_file_path, 'w') pymod_config = {} # Initializes the parameters for each tool. for tool in self.pymod_tools: new_tool_parameters = {} for parameter in tool.parameters: # new_tool_parameters.update({parameter.name: parameter.get_starting_value()}) new_tool_parameters.update({parameter.name: ""}) pymod_config.update({tool.name: new_tool_parameters}) pymod_config["pymod"]["pymod_dir_path"] = new_pymod_dirpath pymod_config["modeller"]["use_importable_modeller"] = True # Define the default database paths for the BLAST and HMMER suites. Users may later change # these through the Options window. for tool_name, param_name, dirname in [("blast_plus", "database_dir_path", blast_databases_dirname), ("hmmer", "database_dir_path", hmmer_databases_dirname), ("hmmer", "hmmscan_db_dir_path", hmmscan_databases_dirname)]: database_dirpath = os.path.join(new_pymod_dirpath, self.data_dirname, dirname) pymod_config[tool_name][param_name] = database_dirpath if not os.path.isdir(database_dirpath): os.mkdir(database_dirpath) cfgfile.write(json.dumps(pymod_config)) cfgfile.close() except Exception as e: if self.DEVELOP: raise e title = "PyMod Directory Error" message = "Unable to write the PyMod configuration directory '%s' because of the following error: %s." % (self.cfg_directory_path, e) self.main_window.show_error_message(title, message) return None # Begin a new PyMod job. self.pymod_dir_window.close() self.get_parameters_from_configuration_file() # tkMessageBox.showinfo("PyMod first run", "You are about to begin your first PyMod session.", parent=self.get_qt_parent()) self.new_job_state() def show_configuration_file_error(self, error, mode): if mode == "read": action = "reading" elif mode == "write": action = "writing" else: action = None title = "Configuration file error" message = "There was an error while %s the PyMod configuration file (located at '%s'). The error is: '%s'." % (action, self.cfg_file_path, error) self.main_window.show_error_message(title, message) ############################################################################################### # Start a new job. # ############################################################################################### def initialize_pymod_elements_information(self): """ Initializes those attributes storing information on sequences and structures loaded in PyMod. Called when starting a new PyMod session. """ # This is the list where are going to be stored all the sequences displayed in the main # window represented as objects of the "PyMod_element" class. # self.pymod_elements_list = [] self.root_element = pmel.PyMod_root_element(header="PyMod root") # An index that increases by one every time an element is added to the above list by using # the .add_element_to_pymod() method. self.unique_index = 0 self.new_objects_index = 0 # A list of all PDB files loaded in PyMod by the user. self.pdb_list = [] # Count of the PDB files parsed in PyMod. self.pdb_counter = 0 # Alignments counters. self.alignment_count = 0 self.new_clusters_counter = 0 # Logo images counters. self.logo_image_counter = 0 # Attributes that will keep track of how many models the user builds in a PyMod session. self.performed_modeling_count = 0 # This will keep track of how many multiple chains models the user builds in a PyMod session. self.multiple_chain_models_count = 0 # This will contain ojects of the 'Modeling_session' class in order to build the 'Models' # submenu on the plugin's main menu. self.modeling_session_list = [] # BLAST analysis. self.blast_cluster_counter = 0 # Domain analysis. self.active_domain_analysis_count = 0 # This is an index that will bw used to color each structure loaded into PyMod with a # different color taken from the list above. It will be used in "color_struct()". self.color_index = 0 self.custom_colors_index = 0 # Each time a user adds a custom color, this will be increased. # Attributes to store the "compact headers" of elements loaded in PyMod. They allow to # automatically change the name of new elements if there are already some elements with the # same name. self.compact_header_root_dict = {} self.compact_header_set = set() # Similar set for full PDB files. self.original_pdb_files_set = set() def initializes_main_paths(self): home_dirpath, cfg_directory_path, pymod_envs_dirpath, pymod_env_dirpath, pymod_pkgs_dirpath = pmos.get_pymod_cfg_paths() # Gets the home directory of the user. self.home_directory = home_dirpath self.current_project_name = None self.current_project_dirpath = None # Creates the preferences file in an hidden directory in the home directory. self.cfg_directory_path = cfg_directory_path self.cfg_file_name = "preferences.txt" self.cfg_file_path = os.path.join(self.cfg_directory_path, self.cfg_file_name) # PyMod conda environment. These directories will only be used if the conda root of PyMOL # is located in some directory without writing permissions. In this case, new conda # packages will be downloaded and installed in this directory. self.pymod_envs_dirpath = pymod_envs_dirpath self.pymod_env_dirpath = pymod_env_dirpath self.pymod_pkgs_dirpath = pymod_pkgs_dirpath # def show_new_job_window(self): # """ # Builds a window that let users choose the name of the new projects direcotory at the # beginning of a PyMod session. # """ # # self.new_dir_window = New_project_window(self, self.main_window) # self.new_job_state() def new_job_state(self, overwrite=False): """ This is called when the SUBMIT button on the "New Job" window is pressed. """ # Checks if the name is valid. new_dir_name = self.new_project_default_name # self.new_dir_window.main_entry.get() if bool(re.search('[^A-z0-9-_]', new_dir_name)) or "\\" in new_dir_name: self.main_window.show_error_message('Name Error', 'Only a-z, 0-9, "-" and "_" are allowed in the project name.') return None # Writes the directory. try: # Composes the name of the new projects directory. pymod_projects_dir_path = os.path.join(self.pymod_plugin["pymod_dir_path"].get_value(), self.projects_directory_name) if not os.path.isdir(pymod_projects_dir_path): os.mkdir(pymod_projects_dir_path) new_project_dir_path = os.path.join(pymod_projects_dir_path, new_dir_name) # Decide whether to build a new directory or overwrite the content # of the previous one. if os.path.isdir(new_project_dir_path): if overwrite: # Just overwrite the previous directory. active_session = False else: # Look for a file signaling an active sessions in the project # directory. active_session = self.check_exisisting_session_tempfile(new_project_dir_path) if not active_session: # Remove the content of the previous folder. self.remove_previous_project_files(new_project_dir_path) else: # Let the user decide whether to remove the content of the # previous directory. title = "Overwrite an existing project?" message = ("An non-finished PyMod project was found in the" " 'projects' folder of your PyMod Directory. This" " either means that PyMod has shut down unexpectedly last" " time or that another PyMod instance is already running" " on your system.\nWould you like to overwrite the" " existing project folder? If another PyMod instance" " is running, its data will be lost (only one PyMod" " instance can be run at any time). If you are not" " running any other PyMod instances, you can safely" " overwrite the old project.") buttons_text = ("Overwrite and continue", "Skip and quit") if self.DEVELOP or self.TEST: overwrite_choice = True else: overwrite_choice = askyesno_qt(title, message, self.get_qt_parent(), buttons_text=buttons_text) if overwrite_choice: # Remove the content of the old directory. self.remove_previous_project_files(new_project_dir_path) else: # Quit PyMod. self.main_window.close() return None # Simply builds the new directory. else: os.mkdir(new_project_dir_path) # Start the new project. self.initialize_session(new_dir_name) except Exception as e: if self.DEVELOP: raise e message = "Unable to write directory '%s' because of the following error: %s." % (new_dir_name, e) self.main_window.show_error_message("Initialization error", message) try: # This raises an exception if the PyMod project has not been initialized. self.inactivate_session() except: pass self.main_window.close() return None def check_exisisting_session_tempfile(self, new_project_dir_path): return os.path.isfile(os.path.join(new_project_dir_path, self.active_session_filename)) def initialize_session(self, new_project_name, saved_session=False): """ Initializes a session and shows the main window, which was previously hidden. """ self.current_pymod_dirpath = self.pymod_plugin["pymod_dir_path"].get_value() self.current_project_name = new_project_name self.current_projects_dirpath = os.path.join(self.current_pymod_dirpath, self.projects_directory_name) self.current_project_dirpath = os.path.join(self.current_projects_dirpath, self.current_project_name) self.structures_dirpath = os.path.join(self.current_project_dirpath, self.structures_dirname) self.alignments_dirpath = os.path.join(self.current_project_dirpath, self.alignments_dirname) self.images_dirpath = os.path.join(self.current_project_dirpath, self.images_dirname) self.models_dirpath = os.path.join(self.current_project_dirpath, self.models_dirname) self.psipred_dirpath = os.path.join(self.current_project_dirpath, self.psipred_dirname) self.similarity_searches_dirpath = os.path.join(self.current_project_dirpath, self.similarity_searches_dirname) self.temp_directory_dirpath = os.path.join(self.current_project_dirpath, self.temp_directory_name) self.domain_analysis_dirpath = os.path.join(self.current_project_dirpath, self.domain_analysis_dirname) # Writes a temporary file to signal that the session is active. with open(os.path.join(self.current_project_dirpath, self.active_session_filename), "w") as t_fh: date_obj = datetime.datetime.now() t_fh.write("Session started: %s\n" % (date_obj.strftime("%d/%m/%Y at %H:%M:%S"))) # Creates the subdirectories. if not saved_session: self.create_project_subdirectories() self.launch_default() def launch_default(self): """ Actions performed when initializing a new PyMod session. """ self._launch_develop() def create_project_subdirectories(self): for single_dirpath in (self.alignments_dirpath, self.images_dirpath, self.images_dirpath, self.models_dirpath, self.structures_dirpath, self.psipred_dirpath, self.similarity_searches_dirpath, self.temp_directory_dirpath, self.domain_analysis_dirpath): try: os.mkdir(single_dirpath) except: pass def remove_previous_project_files(self, project_dirpath): """ Removes the previously used files and subdirectories of a project directory when users decide to overwrite an existing project's directory. """ # Safely remove all the files in the previously used directory. for the_file in os.listdir(project_dirpath): file_path = os.path.join(project_dirpath, the_file) if os.path.isfile(file_path): os.remove(file_path) # Remove the directories. for single_dir in (self.structures_dirname, self.alignments_dirname, self.models_dirname, self.psipred_dirname, self.similarity_searches_dirname, self.images_dirname, self.temp_directory_name, self.domain_analysis_dirname): dir_to_remove_path = os.path.join(project_dirpath, single_dir) if os.path.isdir(dir_to_remove_path): shutil.rmtree(dir_to_remove_path) def inactivate_session(self): active_session_filepath = os.path.join(self.current_project_dirpath, self.active_session_filename) if os.path.isfile(active_session_filepath): inactive_session_filepath = os.path.join(self.current_project_dirpath, self.inactive_session_filename) if os.path.isfile(inactive_session_filepath): os.remove(inactive_session_filepath) with open(active_session_filepath, "a") as t_fh: date_obj = datetime.datetime.now() t_fh.write("Session finished: %s\n" % (date_obj.strftime("%d/%m/%Y at %H:%M:%S"))) shutil.move(active_session_filepath, inactive_session_filepath) ############################################################################################### # Colors. # ############################################################################################### def initialize_colors(self): """ Prepares colors for PyMod and PyMOL. """ # Stores the color used for PyMod elements. self.all_colors_dict_tkinter = {} # Import in PyMod some PyMOL colors. self.update_pymod_color_dict_with_dict(pmdt.pymol_regular_colors_dict_rgb, update_in_pymol=False) # Light PyMOL colors. self.update_pymod_color_dict_with_dict(pmdt.pymol_light_colors_dict_rgb) # PyMod colors. # self.update_pymod_color_dict_with_list(pmdt.pymod_regular_colors_list, update_in_pymol=False) self.all_colors_dict_tkinter.update(pmdt.pymod_regular_colors_dict) # Prepares other colors for PyMOL and PyMod. self.update_pymod_color_dict_with_dict(pmdt.sec_str_color_dict) self.update_pymod_color_dict_with_dict(pmdt.psipred_color_dict) self.update_pymod_color_dict_with_dict(pmdt.campo_color_dict) self.update_pymod_color_dict_with_dict(pmdt.scr_color_dict) self.update_pymod_color_dict_with_dict(pmdt.entropy_color_dict) self.update_pymod_color_dict_with_dict(pmdt.pc_color_dict) self.update_pymod_color_dict_with_dict(pmdt.dope_color_dict) self.update_pymod_color_dict_with_dict(pmdt.polarity_color_dict) self.update_pymod_color_dict_with_dict(pmdt.residue_type_color_dict) self.update_pymod_color_dict_with_dict(pmdt.domain_colors_dict) def update_pymod_color_dict_with_dict(self, color_dict, update_in_pymol=True): for color_name in list(color_dict.keys()): if update_in_pymol: cmd.set_color(color_name, color_dict[color_name]) self.all_colors_dict_tkinter.update({color_name: pmdt.convert_rgb_to_hex(color_dict[color_name])}) def update_pymod_color_dict_with_list(self, color_list, update_in_pymol=False): for color_name in color_list: if update_in_pymol: cmd.set_color(color_name, color_name) self.all_colors_dict_tkinter.update({color_name: color_name}) def add_new_color(self, new_color_rgb, new_color_hex): """ Adds a new color to PyMod/PyMOL. """ new_color_name = "custom_color_%s" % self.custom_colors_index self.all_colors_dict_tkinter[new_color_name] = new_color_hex cmd.set_color(new_color_name, new_color_rgb) self.custom_colors_index += 1 return new_color_name
Python