text stringlengths 12 1.05M | repo_name stringlengths 5 86 | path stringlengths 4 191 | language stringclasses 1 value | license stringclasses 15 values | size int32 12 1.05M | keyword listlengths 1 23 | text_hash stringlengths 64 64 |
|---|---|---|---|---|---|---|---|
#!/usr/bin/env python
# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Authors: Qiming Sun <osirpt.sun@gmail.com>
# Susi Lehtola <susi.lehtola@gmail.com>
'''
XC functional, the interface to libxc
(http://www.tddft.org/programs/octopus/wiki/index.php/Libxc)
'''
import sys
import warnings
import copy
import ctypes
import math
import numpy
from pyscf import lib
from pyscf.dft.xc.utils import remove_dup, format_xc_code
_itrf = lib.load_library('libxc_itrf')
_itrf.LIBXC_is_lda.restype = ctypes.c_int
_itrf.LIBXC_is_gga.restype = ctypes.c_int
_itrf.LIBXC_is_meta_gga.restype = ctypes.c_int
_itrf.LIBXC_is_hybrid.restype = ctypes.c_int
_itrf.LIBXC_is_cam_rsh.restype = ctypes.c_int
_itrf.LIBXC_max_deriv_order.restype = ctypes.c_int
_itrf.LIBXC_number_of_functionals.restype = ctypes.c_int
_itrf.LIBXC_functional_numbers.argtypes = (numpy.ctypeslib.ndpointer(dtype=numpy.intc, ndim=1, flags=("W", "C", "A")), )
_itrf.LIBXC_functional_name.argtypes = [ctypes.c_int]
_itrf.LIBXC_functional_name.restype = ctypes.c_char_p
_itrf.LIBXC_hybrid_coeff.argtypes = [ctypes.c_int]
_itrf.LIBXC_hybrid_coeff.restype = ctypes.c_double
_itrf.LIBXC_nlc_coeff.argtypes = [ctypes.c_int,ctypes.POINTER(ctypes.c_double)]
_itrf.LIBXC_rsh_coeff.argtypes = [ctypes.c_int,ctypes.POINTER(ctypes.c_double)]
# XC dict is generated by
#for xcname in pylibxc.util.xc_available_functional_names():
# f = pylibxc.LibXCFunctional(xcname, 1)
# f_id = f.get_number()
# ref = f.get_references()
# key = f"'{xcname.upper()}'"
# print(f"{key:<31s}: {f_id:<3d}, # {ref[0]}")
XC = XC_CODES = {
'LDA_X' : 1 , # P. A. M. Dirac, Math. Proc. Cambridge Philos. Soc. 26, 376 (1930)
# F. Bloch, Z. Phys. 57, 545 (1929)
'LDA_C_WIGNER' : 2 , # E. Wigner, Trans. Faraday Soc. 34, 678 (1938)
# P. A. Stewart and P. M. W. Gill, J. Chem. Soc.{, Faraday Trans. 91, 4337 (1995)}
'LDA_C_RPA' : 3 , # M. Gell-Mann and K. A. Brueckner, Phys. Rev. 106, 364 (1957)
'LDA_C_HL' : 4 , # L. Hedin and B. I. Lundqvist, J. Phys. C: Solid State Phys. 4, 2064 (1971)
'LDA_C_GL' : 5 , # O. Gunnarsson and B. I. Lundqvist, Phys. Rev. B 13, 4274 (1976)
'LDA_C_XALPHA' : 6 , # J. C. Slater, Phys. Rev. 81, 385 (1951)
'LDA_C_VWN' : 7 , # S. H. Vosko, L. Wilk, and M. Nusair, Can. J. Phys. 58, 1200 (1980)
'LDA_C_VWN_RPA' : 8 , # S. H. Vosko, L. Wilk, and M. Nusair, Can. J. Phys. 58, 1200 (1980)
'LDA_C_PZ' : 9 , # J. P. Perdew and A. Zunger, Phys. Rev. B 23, 5048 (1981)
'LDA_C_PZ_MOD' : 10 , # J. P. Perdew and A. Zunger, Phys. Rev. B 23, 5048 (1981), modified to improve the matching between the low- and high-rs parts
'LDA_C_OB_PZ' : 11 , # G. Ortiz and P. Ballone, Phys. Rev. B 50, 1391 (1994)
# G. Ortiz and P. Ballone, Phys. Rev. B 56, 9970 (1997)
'LDA_C_PW' : 12 , # J. P. Perdew and Y. Wang, Phys. Rev. B 45, 13244 (1992)
'LDA_C_PW_MOD' : 13 , # J. P. Perdew and Y. Wang, Phys. Rev. B 45, 13244 (1992), added extra digits to some constants as in the PBE routine (http://dft.rutgers.edu/pubs/PBE.asc)
'LDA_C_OB_PW' : 14 , # G. Ortiz and P. Ballone, Phys. Rev. B 50, 1391 (1994)
# G. Ortiz and P. Ballone, Phys. Rev. B 56, 9970 (1997)
# J. P. Perdew and Y. Wang, Phys. Rev. B 45, 13244 (1992), added extra digits to some constants as in the PBE routine (http://dft.rutgers.edu/pubs/PBE.asc)
'LDA_C_2D_AMGB' : 15 , # C. Attaccalite, S. Moroni, P. Gori-Giorgi, and G. B. Bachelet, Phys. Rev. Lett. 88, 256601 (2002)
'LDA_C_2D_PRM' : 16 , # S. Pittalis, E. Rasanen, and M. A. L. Marques, Phys. Rev. B 78, 195322 (2008)
'LDA_C_VBH' : 17 , # U. von Barth and L. Hedin, J. Phys. C: Solid State Phys. 5, 1629 (1972)
'LDA_C_1D_CSC' : 18 , # M. Casula, S. Sorella, and G. Senatore, Phys. Rev. B 74, 245427 (2006)
'LDA_X_2D' : 19 , # P. A. M. Dirac, Math. Proc. Cambridge Philos. Soc. 26, 376 (1930)
# F. Bloch, Z. Phys. 57, 545 (1929)
'LDA_XC_TETER93' : 20 , # S. Goedecker, M. Teter, and J. Hutter, Phys. Rev. B 54, 1703 (1996)
'LDA_X_1D' : 21 , # N. Helbig, J. I. Fuks, M. Casula, M. J. Verstraete, M. A. L. Marques, I. V. Tokatly, and A. Rubio, Phys. Rev. A 83, 032503 (2011)
'LDA_C_ML1' : 22 , # E. I. Proynov and D. R. Salahub, Phys. Rev. B 49, 7874 (1994)
'LDA_C_ML2' : 23 , # E. I. Proynov and D. R. Salahub, Phys. Rev. B 49, 7874 (1994)
'LDA_C_GOMBAS' : 24 , # P. Gombas, Pseudopotentiale (Springer-Verlag, Wien, New York, 1967)
'LDA_C_PW_RPA' : 25 , # J. P. Perdew and Y. Wang, Phys. Rev. B 45, 13244 (1992)
'LDA_C_1D_LOOS' : 26 , # P.-F. Loos, J. Chem. Phys. 138, 064108 (2013)
'LDA_C_RC04' : 27 , # S. Ragot and P. Cortona, J. Chem. Phys. 121, 7671 (2004)
'LDA_C_VWN_1' : 28 , # S. H. Vosko, L. Wilk, and M. Nusair, Can. J. Phys. 58, 1200 (1980)
'LDA_C_VWN_2' : 29 , # S. H. Vosko, L. Wilk, and M. Nusair, Can. J. Phys. 58, 1200 (1980)
'LDA_C_VWN_3' : 30 , # S. H. Vosko, L. Wilk, and M. Nusair, Can. J. Phys. 58, 1200 (1980)
'LDA_C_VWN_4' : 31 , # S. H. Vosko, L. Wilk, and M. Nusair, Can. J. Phys. 58, 1200 (1980)
'LDA_XC_ZLP' : 43 , # Q. Zhao, M. Levy, and R. G. Parr, Phys. Rev. A 47, 918 (1993)
'LDA_K_TF' : 50 , # L. H. Thomas, Math. Proc. Cambridge Philos. Soc. 23, 542 (1927)
# E. Fermi, Rend. Accad. Naz. Lincei 6, 602 (1927)
'LDA_K_LP' : 51 , # C. Lee and R. G. Parr, Phys. Rev. A 35, 2377 (1987)
'LDA_XC_KSDT' : 259, # V. V. Karasiev, T. Sjostrom, J. Dufty, and S. B. Trickey, Phys. Rev. Lett. 112, 076403 (2014)
'LDA_C_CHACHIYO' : 287, # T. Chachiyo, J. Chem. Phys. 145, 021101 (2016)
'LDA_C_LP96' : 289, # S. Liu and R. G. Parr, Phys. Rev. A 53, 2211 (1996)
# S. Liu and R. Parr, Journal of Molecular Structure: \{THEOCHEM\ 501--502, 29 (2000)}
'LDA_X_REL' : 532, # A. K. Rajagopal, J. Phys. C: Solid State Phys. 11, L943 (1978)
# A. H. MacDonald and S. H. Vosko, J. Phys. C: Solid State Phys. 12, 2977 (1979)
# E. Engel, S. Keller, A. F. Bonetti, H. Muller, and R. M. Dreizler, Phys. Rev. A 52, 2750 (1995)
'LDA_XC_1D_EHWLRG_1' : 536, # M. T. Entwistle, M. J. P. Hodgson, J. Wetherell, B. Longstaff, J. D. Ramsden, and R. W. Godby, Phys. Rev. B 94, 205134 (2016)
'LDA_XC_1D_EHWLRG_2' : 537, # M. T. Entwistle, M. J. P. Hodgson, J. Wetherell, B. Longstaff, J. D. Ramsden, and R. W. Godby, Phys. Rev. B 94, 205134 (2016)
'LDA_XC_1D_EHWLRG_3' : 538, # M. T. Entwistle, M. J. P. Hodgson, J. Wetherell, B. Longstaff, J. D. Ramsden, and R. W. Godby, Phys. Rev. B 94, 205134 (2016)
'LDA_X_ERF' : 546, # J. Toulouse, A. Savin, and H.-J. Flad, Int. J. Quantum Chem. 100, 1047 (2004)
# Y. Tawada, T. Tsuneda, S. Yanagisawa, T. Yanai, and K. Hirao, J. Chem. Phys. 120, 8425 (2004)
'LDA_XC_LP_A' : 547, # C. Lee and R. G. Parr, Phys. Rev. A 42, 193 (1990)
'LDA_XC_LP_B' : 548, # C. Lee and R. G. Parr, Phys. Rev. A 42, 193 (1990)
'LDA_X_RAE' : 549, # A. Rae, Chem. Phys. Lett. 18, 574 (1973)
'LDA_K_ZLP' : 550, # P. Fuentealba and O. Reyes, Chem. Phys. Lett. 232, 31 (1995)
# Q. Zhao, M. Levy, and R. G. Parr, Phys. Rev. A 47, 918 (1993)
'LDA_C_MCWEENY' : 551, # R. McWeeny, in The New World of Quantum Chemistry, edited by \bibinfo {editor {B. Pullman} and R. Parr} (Reidel, Boston, 1976) pp. 3--31
# G. B. Jr. and S. M. Rothstein, J. Chem. Phys. 69, 1177 (1978)
'LDA_C_BR78' : 552, # G. B. Jr. and S. M. Rothstein, J. Chem. Phys. 69, 1177 (1978)
'LDA_C_PK09' : 554, # E. Proynov and J. Kong, Phys. Rev. A 79, 014103 (2009)
# E. Proynov and J. Kong, Phys. Rev. A 95, 059904 (2017)
'LDA_C_OW_LYP' : 573, # P. A. Stewart and P. M. W. Gill, J. Chem. Soc.{, Faraday Trans. 91, 4337 (1995)}
'LDA_C_OW' : 574, # P. A. Stewart and P. M. W. Gill, J. Chem. Soc.{, Faraday Trans. 91, 4337 (1995)}
'LDA_XC_GDSMFB' : 577, # S. {Groth, T. {Dornheim}, T. {Sjostrom}, F. D. {Malone}, W. M. C. {Foulkes}, and M. {Bonitz}, }ArXiv e-prints (2017), arXiv:1703.08074 [physics.plasm-ph]
'LDA_C_GK72' : 578, # R. G. Gordon and Y. S. Kim, J. Chem. Phys. 56, 3122 (1972), https://doi.org/10.1063/1.1677649
'LDA_C_KARASIEV' : 579, # V. V. Karasiev, J. Chem. Phys. 145, 157101 (2016), https://doi.org/10.1063/1.4964758
'LDA_K_LP96' : 580, # S. Liu and R. G. Parr, Phys. Rev. A 53, 2211 (1996)
# S. Liu and R. Parr, Journal of Molecular Structure: \{THEOCHEM\ 501--502, 29 (2000)}
'GGA_X_GAM' : 32 , # H. S. Yu, W. Zhang, P. Verma, X. He, and D. G. Truhlar, Phys. Chem. Chem. Phys. 17, 12146 (2015)
'GGA_C_GAM' : 33 , # H. S. Yu, W. Zhang, P. Verma, X. He, and D. G. Truhlar, Phys. Chem. Chem. Phys. 17, 12146 (2015)
'GGA_X_HCTH_A' : 34 , # F. A. Hamprecht, A. J. Cohen, D. J. Tozer, and N. C. Handy, J. Chem. Phys. 109, 6264 (1998)
'GGA_X_EV93' : 35 , # E. Engel and S. H. Vosko, Phys. Rev. B 47, 13164 (1993)
'GGA_X_BCGP' : 38 , # K. Burke, A. Cancio, T. Gould, and S. Pittalis, ArXiv e-prints (2014), arXiv:1409.4834 [cond-mat.mtrl-sci]
'GGA_C_BCGP' : 39 , # K. Burke, A. Cancio, T. Gould, and S. Pittalis, ArXiv e-prints (2014), arXiv:1409.4834 [cond-mat.mtrl-sci]
'GGA_X_LAMBDA_OC2_N' : 40 , # M. M. Odashima, K. Capelle, and S. B. Trickey, J. Chem. Theory Comput. 5, 798 (2009)
'GGA_X_B86_R' : 41 , # I. Hamada, Phys. Rev. B 89, 121103 (2014)
# A. D. Becke, J. Chem. Phys. 84, 4524 (1986)
# A. D. Becke, J. Chem. Phys. 85, 7184 (1986)
'GGA_X_LAMBDA_CH_N' : 44 , # M. M. Odashima, K. Capelle, and S. B. Trickey, J. Chem. Theory Comput. 5, 798 (2009)
'GGA_X_LAMBDA_LO_N' : 45 , # M. M. Odashima, K. Capelle, and S. B. Trickey, J. Chem. Theory Comput. 5, 798 (2009)
'GGA_X_HJS_B88_V2' : 46 , # E. Weintraub, T. M. Henderson, and G. E. Scuseria, J. Chem. Theory Comput. 5, 754 (2009)
'GGA_C_Q2D' : 47 , # L. Chiodo, L. A. Constantin, E. Fabiano, and F. Della Sala, Phys. Rev. Lett. 108, 126402 (2012)
'GGA_X_Q2D' : 48 , # L. Chiodo, L. A. Constantin, E. Fabiano, and F. Della Sala, Phys. Rev. Lett. 108, 126402 (2012)
'GGA_X_PBE_MOL' : 49 , # J. M. del Campo, J. L. G\'azquez, S. B. Trickey, and A. Vela, J. Chem. Phys. 136, 104108 (2012)
'GGA_K_TFVW' : 52 , # C. F. von Weizsacker, Z. Phys. 96, 431 (1935)
'GGA_K_REVAPBEINT' : 53 , # S. Laricchia, E. Fabiano, L. A. Constantin, and F. Della Sala, J. Chem. Theory Comput. 7, 2439 (2011)
'GGA_K_APBEINT' : 54 , # S. Laricchia, E. Fabiano, L. A. Constantin, and F. Della Sala, J. Chem. Theory Comput. 7, 2439 (2011)
'GGA_K_REVAPBE' : 55 , # L. A. Constantin, E. Fabiano, S. Laricchia, and F. Della Sala, Phys. Rev. Lett. 106, 186406 (2011)
'GGA_X_AK13' : 56 , # R. Armiento and S. Kummel, Phys. Rev. Lett. 111, 036402 (2013)
'GGA_K_MEYER' : 57 , # A. Meyer, G. C. Wang, and W. H. Young, Z. Naturforsch. A 31, 898 (1976)
'GGA_X_LV_RPW86' : 58 , # K. Berland and P. Hyldgaard, Phys. Rev. B 89, 035412 (2014)
'GGA_X_PBE_TCA' : 59 , # V. Tognetti, P. Cortona, and C. Adamo, Chem. Phys. Lett. 460, 536 (2008)
'GGA_X_PBEINT' : 60 , # E. Fabiano, L. A. Constantin, and F. Della Sala, Phys. Rev. B 82, 113104 (2010)
'GGA_C_ZPBEINT' : 61 , # L. A. Constantin, E. Fabiano, and F. Della Sala, Phys. Rev. B 84, 233103 (2011)
'GGA_C_PBEINT' : 62 , # E. Fabiano, L. A. Constantin, and F. Della Sala, Phys. Rev. B 82, 113104 (2010)
'GGA_C_ZPBESOL' : 63 , # L. A. Constantin, E. Fabiano, and F. Della Sala, Phys. Rev. B 84, 233103 (2011)
'GGA_XC_OPBE_D' : 65 , # L. Goerigk and S. Grimme, J. Chem. Theory Comput. 6, 107 (2010)
'GGA_XC_OPWLYP_D' : 66 , # L. Goerigk and S. Grimme, J. Chem. Theory Comput. 6, 107 (2010)
'GGA_XC_OBLYP_D' : 67 , # L. Goerigk and S. Grimme, J. Chem. Theory Comput. 6, 107 (2010)
'GGA_X_VMT84_GE' : 68 , # A. Vela, J. C. Pacheco-Kato, J. L. G\'azquez, J. M. del Campo, and S. B. Trickey, J. Chem. Phys. 136, 144115 (2012)
'GGA_X_VMT84_PBE' : 69 , # A. Vela, J. C. Pacheco-Kato, J. L. G\'azquez, J. M. del Campo, and S. B. Trickey, J. Chem. Phys. 136, 144115 (2012)
'GGA_X_VMT_GE' : 70 , # A. Vela, V. Medel, and S. B. Trickey, J. Chem. Phys. 130, 244103 (2009)
'GGA_X_VMT_PBE' : 71 , # A. Vela, V. Medel, and S. B. Trickey, J. Chem. Phys. 130, 244103 (2009)
'GGA_C_N12_SX' : 79 , # R. Peverati and D. G. Truhlar, Phys. Chem. Chem. Phys. 14, 16187 (2012)
'GGA_C_N12' : 80 , # R. Peverati and D. G. Truhlar, J. Chem. Theory Comput. 8, 2310 (2012)
'GGA_X_N12' : 82 , # R. Peverati and D. G. Truhlar, J. Chem. Theory Comput. 8, 2310 (2012)
'GGA_C_REGTPSS' : 83 , # J. P. Perdew, A. Ruzsinszky, G. I. Csonka, L. A. Constantin, and J. Sun, Phys. Rev. Lett. 103, 026403 (2009)
'GGA_C_OP_XALPHA' : 84 , # T. Tsuneda, T. Suzumura, and K. Hirao, J. Chem. Phys. 110, 10664 (1999)
# T. Tsuneda, T. Suzumura, and K. Hirao, J. Chem. Phys. 111, 5656 (1999)
'GGA_C_OP_G96' : 85 , # T. Tsuneda, T. Suzumura, and K. Hirao, J. Chem. Phys. 110, 10664 (1999)
# T. Tsuneda, T. Suzumura, and K. Hirao, J. Chem. Phys. 111, 5656 (1999)
'GGA_C_OP_PBE' : 86 , # T. Tsuneda, T. Suzumura, and K. Hirao, J. Chem. Phys. 110, 10664 (1999)
# T. Tsuneda, T. Suzumura, and K. Hirao, J. Chem. Phys. 111, 5656 (1999)
'GGA_C_OP_B88' : 87 , # T. Tsuneda, T. Suzumura, and K. Hirao, J. Chem. Phys. 110, 10664 (1999)
'GGA_C_FT97' : 88 , # M. Filatov and W. Thiel, Int. J. Quantum Chem. 62, 603 (1997)
# M. Filatov and W. Thiel, Mol. Phys. 91, 847 (1997)
'GGA_C_SPBE' : 89 , # M. Swart, M. Sol\'a, and F. M. Bickelhaupt, J. Chem. Phys. 131, 094103 (2009)
'GGA_X_SSB_SW' : 90 , # M. Swart, M. Sol\'a, and F. M. Bickelhaupt, J. Comput. Methods Sci. Eng. 9, 69 (2009)
'GGA_X_SSB' : 91 , # M. Swart, M. Sol\'a, and F. M. Bickelhaupt, J. Chem. Phys. 131, 094103 (2009)
'GGA_X_SSB_D' : 92 , # M. Swart, M. Sol\'a, and F. M. Bickelhaupt, J. Chem. Phys. 131, 094103 (2009)
'GGA_XC_HCTH_407P' : 93 , # A. D. Boese, A. Chandra, J. M. L. Martin, and D. Marx, J. Chem. Phys. 119, 5965 (2003)
'GGA_XC_HCTH_P76' : 94 , # G. Menconi, P. J. Wilson, and D. J. Tozer, J. Chem. Phys. 114, 3958 (2001)
'GGA_XC_HCTH_P14' : 95 , # G. Menconi, P. J. Wilson, and D. J. Tozer, J. Chem. Phys. 114, 3958 (2001)
'GGA_XC_B97_GGA1' : 96 , # A. J. Cohen and N. C. Handy, Chem. Phys. Lett. 316, 160 (2000)
'GGA_C_HCTH_A' : 97 , # F. A. Hamprecht, A. J. Cohen, D. J. Tozer, and N. C. Handy, J. Chem. Phys. 109, 6264 (1998)
'GGA_X_BPCCAC' : 98 , # E. Br\'emond, D. Pilard, I. Ciofini, H. Chermette, C. Adamo, and P. Cortona, Theor. Chem. Acc. 131, 1184 (2012)
'GGA_C_REVTCA' : 99 , # V. Tognetti, P. Cortona, and C. Adamo, Chem. Phys. Lett. 460, 536 (2008)
'GGA_C_TCA' : 100, # V. Tognetti, P. Cortona, and C. Adamo, J. Chem. Phys. 128, 034101 (2008)
'GGA_X_PBE' : 101, # J. P. Perdew, K. Burke, and M. Ernzerhof, Phys. Rev. Lett. 77, 3865 (1996)
# J. P. Perdew, K. Burke, and M. Ernzerhof, Phys. Rev. Lett. 78, 1396 (1997)
'GGA_X_PBE_R' : 102, # Y. Zhang and W. Yang, Phys. Rev. Lett. 80, 890 (1998)
'GGA_X_B86' : 103, # A. D. Becke, J. Chem. Phys. 84, 4524 (1986)
'GGA_X_HERMAN' : 104, # F. Herman, J. P. V. Dyke, and I. B. Ortenburger, Phys. Rev. Lett. 22, 807 (1969)
# F. Herman, I. B. Ortenburger, and J. P. V. Dyke, Int. J. Quantum Chem. 4, 827 (1969)
'GGA_X_B86_MGC' : 105, # A. D. Becke, J. Chem. Phys. 84, 4524 (1986)
# A. D. Becke, J. Chem. Phys. 85, 7184 (1986)
'GGA_X_B88' : 106, # A. D. Becke, Phys. Rev. A 38, 3098 (1988)
'GGA_X_G96' : 107, # P. M. W. Gill, Mol. Phys. 89, 433 (1996)
'GGA_X_PW86' : 108, # J. P. Perdew and W. Yue, Phys. Rev. B 33, 8800 (1986)
'GGA_X_PW91' : 109, # J. P. Perdew, in Proceedings of the 75. WE-Heraeus-Seminar and 21st Annual International Symposium on Electronic Structure of Solids, edited by P. Ziesche and H. Eschrig (Akademie Verlag, Berlin, 1991) p. 11
# J. P. Perdew, J. A. Chevary, S. H. Vosko, K. A. Jackson, M. R. Pederson, D. J. Singh, and C. Fiolhais, Phys. Rev. B 46, 6671 (1992)
# J. P. Perdew, J. A. Chevary, S. H. Vosko, K. A. Jackson, M. R. Pederson, D. J. Singh, and C. Fiolhais, Phys. Rev. B 48, 4978 (1993)
'GGA_X_OPTX' : 110, # N. C. Handy and A. J. Cohen, Mol. Phys. 99, 403 (2001)
'GGA_X_DK87_R1' : 111, # A. E. DePristo and J. D. Kress, J. Chem. Phys. 86, 1425 (1987)
'GGA_X_DK87_R2' : 112, # A. E. DePristo and J. D. Kress, J. Chem. Phys. 86, 1425 (1987)
'GGA_X_LG93' : 113, # D. J. Lacks and R. G. Gordon, Phys. Rev. A 47, 4681 (1993)
'GGA_X_FT97_A' : 114, # M. Filatov and W. Thiel, Mol. Phys. 91, 847 (1997)
'GGA_X_FT97_B' : 115, # M. Filatov and W. Thiel, Mol. Phys. 91, 847 (1997)
'GGA_X_PBE_SOL' : 116, # J. P. Perdew, A. Ruzsinszky, G. I. Csonka, O. A. Vydrov, G. E. Scuseria, L. A. Constantin, X. Zhou, and K. Burke, Phys. Rev. Lett. 100, 136406 (2008)
'GGA_X_RPBE' : 117, # B. Hammer, L. B. Hansen, and J. K. Norskov, Phys. Rev. B 59, 7413 (1999)
'GGA_X_WC' : 118, # Z. Wu and R. E. Cohen, Phys. Rev. B 73, 235116 (2006)
'GGA_X_MPW91' : 119, # C. Adamo and V. Barone, J. Chem. Phys. 108, 664 (1998)
'GGA_X_AM05' : 120, # R. Armiento and A. E. Mattsson, Phys. Rev. B 72, 085108 (2005)
# A. E. Mattsson, R. Armiento, J. Paier, G. Kresse, J. M. Wills, and T. R. Mattsson, J. Chem. Phys. 128, 084714 (2008)
'GGA_X_PBEA' : 121, # G. K. H. Madsen, Phys. Rev. B 75, 195108 (2007)
'GGA_X_MPBE' : 122, # C. Adamo and V. Barone, J. Chem. Phys. 116, 5933 (2002)
'GGA_X_XPBE' : 123, # X. Xu and W. A. Goddard, J. Chem. Phys. 121, 4068 (2004)
'GGA_X_2D_B86_MGC' : 124, # S. Pittalis, E. Rasanen, J. G. Vilhena, and M. A. L. Marques, Phys. Rev. A 79, 012503 (2009)
'GGA_X_BAYESIAN' : 125, # J. J. Mortensen, K. Kaasbjerg, S. L. Frederiksen, J. K. Norskov, J. P. Sethna, and K. W. Jacobsen, Phys. Rev. Lett. 95, 216401 (2005)
'GGA_X_PBE_JSJR' : 126, # L. S. Pedroza, A. J. R. da Silva, and K. Capelle, Phys. Rev. B 79, 201106 (2009)
'GGA_X_2D_B88' : 127, # J. G. Vilhena and M. A. L. Marques, unpublished (2014)
'GGA_X_2D_B86' : 128, # J. G. Vilhena and M. A. L. Marques, unpublished (2014)
'GGA_X_2D_PBE' : 129, # J. G. Vilhena and M. A. L. Marques, unpublished (2014)
'GGA_C_PBE' : 130, # J. P. Perdew, K. Burke, and M. Ernzerhof, Phys. Rev. Lett. 77, 3865 (1996)
# J. P. Perdew, K. Burke, and M. Ernzerhof, Phys. Rev. Lett. 78, 1396 (1997)
'GGA_C_LYP' : 131, # C. Lee, W. Yang, and R. G. Parr, Phys. Rev. B 37, 785 (1988)
# B. Miehlich, A. Savin, H. Stoll, and H. Preuss, Chem. Phys. Lett. 157, 200 (1989)
'GGA_C_P86' : 132, # J. P. Perdew, Phys. Rev. B 33, 8822 (1986)
'GGA_C_PBE_SOL' : 133, # J. P. Perdew, A. Ruzsinszky, G. I. Csonka, O. A. Vydrov, G. E. Scuseria, L. A. Constantin, X. Zhou, and K. Burke, Phys. Rev. Lett. 100, 136406 (2008)
'GGA_C_PW91' : 134, # J. P. Perdew, in Proceedings of the 75. WE-Heraeus-Seminar and 21st Annual International Symposium on Electronic Structure of Solids, edited by P. Ziesche and H. Eschrig (Akademie Verlag, Berlin, 1991) p. 11
# J. P. Perdew, J. A. Chevary, S. H. Vosko, K. A. Jackson, M. R. Pederson, D. J. Singh, and C. Fiolhais, Phys. Rev. B 46, 6671 (1992)
# J. P. Perdew, J. A. Chevary, S. H. Vosko, K. A. Jackson, M. R. Pederson, D. J. Singh, and C. Fiolhais, Phys. Rev. B 48, 4978 (1993)
'GGA_C_AM05' : 135, # R. Armiento and A. E. Mattsson, Phys. Rev. B 72, 085108 (2005)
# A. E. Mattsson, R. Armiento, J. Paier, G. Kresse, J. M. Wills, and T. R. Mattsson, J. Chem. Phys. 128, 084714 (2008)
'GGA_C_XPBE' : 136, # X. Xu and W. A. Goddard, J. Chem. Phys. 121, 4068 (2004)
'GGA_C_LM' : 137, # D. C. Langreth and M. J. Mehl, Phys. Rev. Lett. 47, 446 (1981)
# C. D. Hu and D. C. Langreth, Phys. Scr. 32, 391 (1985)
'GGA_C_PBE_JRGX' : 138, # L. S. Pedroza, A. J. R. da Silva, and K. Capelle, Phys. Rev. B 79, 201106 (2009)
'GGA_X_OPTB88_VDW' : 139, # J. Klime\v{s}, D. R. Bowler, and A. Michaelides, J. Phys.: Condens. Matter 22, 022201 (2010)
'GGA_X_PBEK1_VDW' : 140, # J. Klime\v{s}, D. R. Bowler, and A. Michaelides, J. Phys.: Condens. Matter 22, 022201 (2010)
'GGA_X_OPTPBE_VDW' : 141, # J. Klime\v{s}, D. R. Bowler, and A. Michaelides, J. Phys.: Condens. Matter 22, 022201 (2010)
'GGA_X_RGE2' : 142, # A. Ruzsinszky, G. I. Csonka, and G. E. Scuseria, J. Chem. Theory Comput. 5, 763 (2009)
'GGA_C_RGE2' : 143, # A. Ruzsinszky, G. I. Csonka, and G. E. Scuseria, J. Chem. Theory Comput. 5, 763 (2009)
'GGA_X_RPW86' : 144, # E. D. Murray, K. Lee, and D. C. Langreth, J. Chem. Theory Comput. 5, 2754 (2009)
'GGA_X_KT1' : 145, # T. W. Keal and D. J. Tozer, J. Chem. Phys. 119, 3015 (2003)
'GGA_XC_KT2' : 146, # T. W. Keal and D. J. Tozer, J. Chem. Phys. 119, 3015 (2003)
'GGA_C_WL' : 147, # L. C. Wilson and M. Levy, Phys. Rev. B 41, 12930 (1990)
'GGA_C_WI' : 148, # L. C. Wilson and S. Ivanov, Int. J. Quantum Chem. 69, 523 (1998)
'GGA_X_MB88' : 149, # V. Tognetti and C. Adamo, J. Phys. Chem. A 113, 14415 (2009)
'GGA_X_SOGGA' : 150, # Y. Zhao and D. G. Truhlar, J. Chem. Phys. 128, 184109 (2008)
'GGA_X_SOGGA11' : 151, # R. Peverati, Y. Zhao, and D. G. Truhlar, J. Phys. Chem. Lett. 2, 1991 (2011)
'GGA_C_SOGGA11' : 152, # R. Peverati, Y. Zhao, and D. G. Truhlar, J. Phys. Chem. Lett. 2, 1991 (2011)
'GGA_C_WI0' : 153, # L. C. Wilson and S. Ivanov, Int. J. Quantum Chem. 69, 523 (1998)
'GGA_XC_TH1' : 154, # D. J. Tozer and N. C. Handy, J. Chem. Phys. 108, 2545 (1998)
'GGA_XC_TH2' : 155, # D. J. Tozer and N. C. Handy, J. Phys. Chem. A 102, 3162 (1998)
'GGA_XC_TH3' : 156, # N. C. Handy and D. J. Tozer, Mol. Phys. 94, 707 (1998)
'GGA_XC_TH4' : 157, # N. C. Handy and D. J. Tozer, Mol. Phys. 94, 707 (1998)
'GGA_X_C09X' : 158, # V. R. Cooper, Phys. Rev. B 81, 161104 (2010)
'GGA_C_SOGGA11_X' : 159, # R. Peverati and D. G. Truhlar, J. Chem. Phys. 135, 191102 (2011)
'GGA_X_LB' : 160, # R. van Leeuwen and E. J. Baerends, Phys. Rev. A 49, 2421 (1994)
'GGA_XC_HCTH_93' : 161, # F. A. Hamprecht, A. J. Cohen, D. J. Tozer, and N. C. Handy, J. Chem. Phys. 109, 6264 (1998)
'GGA_XC_HCTH_120' : 162, # A. D. Boese, N. L. Doltsinis, N. C. Handy, and M. Sprik, J. Chem. Phys. 112, 1670 (2000)
'GGA_XC_HCTH_147' : 163, # A. D. Boese, N. L. Doltsinis, N. C. Handy, and M. Sprik, J. Chem. Phys. 112, 1670 (2000)
'GGA_XC_HCTH_407' : 164, # A. D. Boese and N. C. Handy, J. Chem. Phys. 114, 5497 (2001)
'GGA_XC_EDF1' : 165, # R. D. Adamson, P. M. W. Gill, and J. A. Pople, Chem. Phys. Lett. 284, 6 (1998)
'GGA_XC_XLYP' : 166, # X. Xu and W. A. Goddard, Proc. Natl. Acad. Sci. U. S. A. 101, 2673 (2004)
'GGA_XC_KT1' : 167, # T. W. Keal and D. J. Tozer, J. Chem. Phys. 119, 3015 (2003)
'GGA_XC_B97_D' : 170, # S. Grimme, J. Comput. Chem. 27, 1787 (2006)
'GGA_XC_PBE1W' : 173, # E. E. Dahlke and D. G. Truhlar, J. Phys. Chem. B 109, 15677 (2005)
'GGA_XC_MPWLYP1W' : 174, # E. E. Dahlke and D. G. Truhlar, J. Phys. Chem. B 109, 15677 (2005)
'GGA_XC_PBELYP1W' : 175, # E. E. Dahlke and D. G. Truhlar, J. Phys. Chem. B 109, 15677 (2005)
'GGA_X_LBM' : 182, # P. R. T. Schipper, O. V. Gritsenko, S. J. A. van Gisbergen, and E. J. Baerends, J. Chem. Phys. 112, 1344 (2000)
'GGA_X_OL2' : 183, # P. Fuentealba and O. Reyes, Chem. Phys. Lett. 232, 31 (1995)
# H. Ou-Yang and M. Levy, Int. J. Quantum Chem. 40, 379 (1991)
'GGA_X_APBE' : 184, # L. A. Constantin, E. Fabiano, S. Laricchia, and F. Della Sala, Phys. Rev. Lett. 106, 186406 (2011)
'GGA_K_APBE' : 185, # L. A. Constantin, E. Fabiano, S. Laricchia, and F. Della Sala, Phys. Rev. Lett. 106, 186406 (2011)
'GGA_C_APBE' : 186, # L. A. Constantin, E. Fabiano, S. Laricchia, and F. Della Sala, Phys. Rev. Lett. 106, 186406 (2011)
'GGA_K_TW1' : 187, # F. Tran and T. A. Wesolowski, Int. J. Quantum Chem. 89, 441 (2002)
'GGA_K_TW2' : 188, # F. Tran and T. A. Wesolowski, Int. J. Quantum Chem. 89, 441 (2002)
'GGA_K_TW3' : 189, # F. Tran and T. A. Wesolowski, Int. J. Quantum Chem. 89, 441 (2002)
'GGA_K_TW4' : 190, # F. Tran and T. A. Wesolowski, Int. J. Quantum Chem. 89, 441 (2002)
'GGA_X_HTBS' : 191, # P. Haas, F. Tran, P. Blaha, and K. Schwarz, Phys. Rev. B 83, 205117 (2011)
'GGA_X_AIRY' : 192, # L. A. Constantin, A. Ruzsinszky, and J. P. Perdew, Phys. Rev. B 80, 035125 (2009)
'GGA_X_LAG' : 193, # L. Vitos, B. Johansson, J. Koll\'ar, and H. L. Skriver, Phys. Rev. B 62, 10046 (2000)
'GGA_XC_MOHLYP' : 194, # N. E. Schultz, Y. Zhao, and D. G. Truhlar, J. Phys. Chem. A 109, 11127 (2005)
'GGA_XC_MOHLYP2' : 195, # J. Zheng, Y. Zhao, and D. G. Truhlar, J. Chem. Theory Comput. 5, 808 (2009)
'GGA_XC_TH_FL' : 196, # D. J. Tozer, N. C. Handy, and W. H. Green, Chem. Phys. Lett. 273, 183 (1997)
'GGA_XC_TH_FC' : 197, # D. J. Tozer, N. C. Handy, and W. H. Green, Chem. Phys. Lett. 273, 183 (1997)
'GGA_XC_TH_FCFO' : 198, # D. J. Tozer, N. C. Handy, and W. H. Green, Chem. Phys. Lett. 273, 183 (1997)
'GGA_XC_TH_FCO' : 199, # D. J. Tozer, N. C. Handy, and W. H. Green, Chem. Phys. Lett. 273, 183 (1997)
'GGA_C_OPTC' : 200, # A. J. Cohen and N. C. Handy, Mol. Phys. 99, 607 (2001)
'GGA_C_PBELOC' : 246, # L. A. Constantin, E. Fabiano, and F. Della Sala, Phys. Rev. B 86, 035130 (2012)
'GGA_XC_VV10' : 255, # O. A. Vydrov and T. Van Voorhis, J. Chem. Phys. 133, 244103 (2010)
'GGA_C_PBEFE' : 258, # R. Sarmiento-P\'erez, S. Botti, and M. A. L. Marques, J. Chem. Theory Comput. 11, 3844 (2015)
'GGA_C_OP_PW91' : 262, # T. Tsuneda, T. Suzumura, and K. Hirao, J. Chem. Phys. 110, 10664 (1999)
# T. Tsuneda, T. Suzumura, and K. Hirao, J. Chem. Phys. 111, 5656 (1999)
'GGA_X_PBEFE' : 265, # R. Sarmiento-P\'erez, S. Botti, and M. A. L. Marques, J. Chem. Theory Comput. 11, 3844 (2015)
'GGA_X_CAP' : 270, # J. Carmona-Esp\'indola, J. L. G\'azquez, A. Vela, and S. B. Trickey, J. Chem. Phys. 142, 054105 (2015), 10.1063/1.4906606
'GGA_X_EB88' : 271, # P. Elliott and K. Burke, Can. J. Chem. 87, 1485 (2009)
'GGA_C_PBE_MOL' : 272, # J. M. del Campo, J. L. G\'azquez, S. B. Trickey, and A. Vela, J. Chem. Phys. 136, 104108 (2012)
'GGA_K_ABSP3' : 277, # P. K. Acharya, L. J. Bartolotti, S. B. Sears, and R. G. Parr, Proc. Natl. Acad. Sci. U. S. A. 77, 6978 (1980)
'GGA_K_ABSP4' : 278, # P. K. Acharya, L. J. Bartolotti, S. B. Sears, and R. G. Parr, Proc. Natl. Acad. Sci. U. S. A. 77, 6978 (1980)
'GGA_C_BMK' : 280, # A. D. Boese and J. M. L. Martin, J. Chem. Phys. 121, 3405 (2004)
'GGA_C_TAU_HCTH' : 281, # A. D. Boese and N. C. Handy, J. Chem. Phys. 116, 9559 (2002)
'GGA_C_HYB_TAU_HCTH' : 283, # A. D. Boese and N. C. Handy, J. Chem. Phys. 116, 9559 (2002)
'GGA_X_BEEFVDW' : 285, # J. Wellendorff, K. T. Lundgaard, A. M\o{gelh\o{j}, V. Petzold, D. D. Landis, J. K. N\o{rskov}, T. Bligaard, and K. W. Jacobsen, }Phys. Rev. B 85, 235149 (2012)
'GGA_XC_BEEFVDW' : 286, # J. Wellendorff, K. T. Lundgaard, A. M\o{gelh\o{j}, V. Petzold, D. D. Landis, J. K. N\o{rskov}, T. Bligaard, and K. W. Jacobsen, }Phys. Rev. B 85, 235149 (2012)
'GGA_X_PBETRANS' : 291, # Eric Bremond, I. Ciofini, and C. Adamo, Mol. Phys. 114, 1059 (2016)
'GGA_X_CHACHIYO' : 298, # T. {Chachiyo and H. {Chachiyo}, }ArXiv e-prints (2017), arXiv:1706.01343 [cond-mat.mtrl-sci]
'GGA_K_VW' : 500, # C. F. von Weizsacker, Z. Phys. 96, 431 (1935)
'GGA_K_GE2' : 501, # A. S. Kompaneets and E. S. Pavlovskii, Zh. Eksp. Teor. Fiz. 31, 427 (1956), [J. Exp. Theor. Phys. 4, 328 (1957)]
# D. A. Kirznits, Zh. Eksp. Teor. Fiz. 32, 115 (1957), [J. Exp. Theor. Phys. 5, 64 (1957)]
'GGA_K_GOLDEN' : 502, # S. Golden, Phys. Rev. 105, 604 (1957)
'GGA_K_YT65' : 503, # K. Yonei and Y. Tomishima, J. Phys. Soc. Jpn. 20, 1051 (1965)
'GGA_K_BALTIN' : 504, # R. Baltin, Z. Naturforsch. A 27, 1176 (1972)
'GGA_K_LIEB' : 505, # E. H. Lieb, Rev. Mod. Phys. 53, 603 (1981)
'GGA_K_ABSP1' : 506, # P. K. Acharya, L. J. Bartolotti, S. B. Sears, and R. G. Parr, Proc. Natl. Acad. Sci. U. S. A. 77, 6978 (1980)
'GGA_K_ABSP2' : 507, # P. K. Acharya, L. J. Bartolotti, S. B. Sears, and R. G. Parr, Proc. Natl. Acad. Sci. U. S. A. 77, 6978 (1980)
'GGA_K_GR' : 508, # J. L. G\'azquez and J. Robles, J. Chem. Phys. 76, 1467 (1982)
'GGA_K_LUDENA' : 509, # E. V. Ludena, in Cond. Matt. Theor., Vol. 1, edited by F. B. Malik (Plenum, New York, 1986) p. 183
'GGA_K_GP85' : 510, # S. K. Ghosh and R. G. Parr, J. Chem. Phys. 82, 3307 (1985)
'GGA_K_PEARSON' : 511, # D. J. Lacks and R. G. Gordon, J. Chem. Phys. 100, 4446 (1994)
# E. W. Pearson and R. G. Gordon, J. Chem. Phys. 82, 881 (1985)
# E. W. Pearson, Theory and application of the electron gas model, Ph.D. thesis, Harvard University (1983)
'GGA_K_OL1' : 512, # H. Ou-Yang and M. Levy, Int. J. Quantum Chem. 40, 379 (1991)
'GGA_K_OL2' : 513, # H. Ou-Yang and M. Levy, Int. J. Quantum Chem. 40, 379 (1991)
'GGA_K_FR_B88' : 514, # P. Fuentealba and O. Reyes, Chem. Phys. Lett. 232, 31 (1995)
'GGA_K_FR_PW86' : 515, # P. Fuentealba and O. Reyes, Chem. Phys. Lett. 232, 31 (1995)
'GGA_K_DK' : 516, # A. E. DePristo and J. D. Kress, Phys. Rev. A 35, 438 (1987)
'GGA_K_PERDEW' : 517, # J. P. Perdew, Phys. Lett. A 165, 79 (1992)
'GGA_K_VSK' : 518, # L. Vitos, H. L. Skriver, and J. Koll\'ar, Phys. Rev. B 57, 12611 (1998)
'GGA_K_VJKS' : 519, # L. Vitos, B. Johansson, J. Koll\'ar, and H. L. Skriver, Phys. Rev. A 61, 052511 (2000)
'GGA_K_ERNZERHOF' : 520, # M. Ernzerhof, J. Mol. Struct.: THEOCHEM 501--502, 59 (2000)
'GGA_K_LC94' : 521, # A. Lembarki and H. Chermette, Phys. Rev. A 50, 5328 (1994)
'GGA_K_LLP' : 522, # H. Lee, C. Lee, and R. G. Parr, Phys. Rev. A 44, 768 (1991)
'GGA_K_THAKKAR' : 523, # A. J. Thakkar, Phys. Rev. A 46, 6920 (1992)
'GGA_X_WPBEH' : 524, # J. Heyd, G. E. Scuseria, and M. Ernzerhof, J. Chem. Phys. 118, 8207 (2003)
# J. Heyd, G. E. Scuseria, and M. Ernzerhof, J. Chem. Phys. 124, 219906 (2006)
# M. Ernzerhof and J. P. Perdew, J. Chem. Phys. 109, 3313 (1998)
# J. Heyd and G. E. Scuseria, J. Chem. Phys. 120, 7274 (2004)
# T. M. Henderson, A. F. Izmaylov, G. Scalmani, and G. E. Scuseria, J. Chem. Phys. 131, 044108 (2009)
'GGA_X_HJS_PBE' : 525, # T. M. Henderson, B. G. Janesko, and G. E. Scuseria, J. Chem. Phys. 128, 194105 (2008)
'GGA_X_HJS_PBE_SOL' : 526, # T. M. Henderson, B. G. Janesko, and G. E. Scuseria, J. Chem. Phys. 128, 194105 (2008)
'GGA_X_HJS_B88' : 527, # T. M. Henderson, B. G. Janesko, and G. E. Scuseria, J. Chem. Phys. 128, 194105 (2008)
'GGA_X_HJS_B97X' : 528, # T. M. Henderson, B. G. Janesko, and G. E. Scuseria, J. Chem. Phys. 128, 194105 (2008)
'GGA_X_ITYH' : 529, # H. Iikura, T. Tsuneda, T. Yanai, and K. Hirao, J. Chem. Phys. 115, 3540 (2001)
'GGA_X_SFAT' : 530, # A. Savin and H.-J. Flad, Int. J. Quantum Chem. 56, 327 (1995)
# Y. Akinaga and S. Ten-no, Chem. Phys. Lett. 462, 348 (2008)
'GGA_X_SG4' : 533, # L. A. Constantin, A. Terentjevs, F. Della Sala, P. Cortona, and E. Fabiano, Phys. Rev. B 93, 045126 (2016)
'GGA_C_SG4' : 534, # L. A. Constantin, A. Terentjevs, F. Della Sala, P. Cortona, and E. Fabiano, Phys. Rev. B 93, 045126 (2016)
'GGA_X_GG99' : 535, # A. T. Gilbert and P. M. Gill, Chem. Phys. Lett. 312, 511 (1999)
'GGA_X_PBEPOW' : 539, # Eric Bremond, J. Chem. Phys. 145, 244102 (2016)
'GGA_X_KGG99' : 544, # A. T. Gilbert and P. M. Gill, Chem. Phys. Lett. 312, 511 (1999)
'GGA_XC_HLE16' : 545, # P. Verma and D. G. Truhlar, J. Phys. Chem. Lett. 8, 380 (2017), pMID: 28033712
'GGA_C_SCAN_E0' : 553, # J. Sun, A. Ruzsinszky, and J. P. Perdew, Phys. Rev. Lett. 115, 036402 (2015)
'GGA_C_GAPC' : 555, # E. Fabiano, P. E. Trevisanutto, A. Terentjevs, and L. A. Constantin, J. Chem. Theory Comput. 10, 2016 (2014), pMID: 26580528
'GGA_C_GAPLOC' : 556, # E. Fabiano, P. E. Trevisanutto, A. Terentjevs, and L. A. Constantin, J. Chem. Theory Comput. 10, 2016 (2014), pMID: 26580528
'GGA_C_ZVPBEINT' : 557, # L. A. Constantin, E. Fabiano, and F. D. Sala, J. Chem. Phys. 137, 194105 (2012)
'GGA_C_ZVPBESOL' : 558, # L. A. Constantin, E. Fabiano, and F. D. Sala, J. Chem. Phys. 137, 194105 (2012)
'GGA_C_TM_LYP' : 559, # A. J. Thakkar and S. P. McCarthy, J. Chem. Phys. 131, 134109 (2009)
'GGA_C_TM_PBE' : 560, # A. J. Thakkar and S. P. McCarthy, J. Chem. Phys. 131, 134109 (2009)
'GGA_C_W94' : 561, # L. C. Wilson, Chemical Physics 181, 337 (1994)
'GGA_C_CS1' : 565, # N. C. Handy and A. J. Cohen, J. Chem. Phys. 116, 5411 (2002)
# E. I. Proynov and A. J. Thakkar, Int. J. Quantum Chem. 106, 436 (2006)
'GGA_X_B88M' : 570, # E. Proynov, H. Chermette, and D. R. Salahub, J. Chem. Phys. 113, 10013 (2000)
'GGA_K_PBE3' : 595, # V. V. Karasiev, S. B. Trickey, and F. E. Harris, Journal of Computer-Aided Materials Design 13, 111 (2006)
'GGA_K_PBE4' : 596, # V. V. Karasiev, S. B. Trickey, and F. E. Harris, Journal of Computer-Aided Materials Design 13, 111 (2006)
'GGA_K_EXP4' : 597, # V. V. Karasiev, S. B. Trickey, and F. E. Harris, Journal of Computer-Aided Materials Design 13, 111 (2006)
'HYB_GGA_X_N12_SX' : 81 , # R. Peverati and D. G. Truhlar, Phys. Chem. Chem. Phys. 14, 16187 (2012)
'HYB_GGA_XC_B97_1P' : 266, # A. J. Cohen and N. C. Handy, Chem. Phys. Lett. 316, 160 (2000)
'HYB_GGA_XC_PBE_MOL0' : 273, # J. M. del Campo, J. L. G\'azquez, S. B. Trickey, and A. Vela, J. Chem. Phys. 136, 104108 (2012)
'HYB_GGA_XC_PBE_SOL0' : 274, # J. M. del Campo, J. L. G\'azquez, S. B. Trickey, and A. Vela, J. Chem. Phys. 136, 104108 (2012)
'HYB_GGA_XC_PBEB0' : 275, # J. M. del Campo, J. L. G\'azquez, S. B. Trickey, and A. Vela, J. Chem. Phys. 136, 104108 (2012)
'HYB_GGA_XC_PBE_MOLB0' : 276, # J. M. del Campo, J. L. G\'azquez, S. B. Trickey, and A. Vela, J. Chem. Phys. 136, 104108 (2012)
'HYB_GGA_XC_PBE50' : 290, # Y. A. Bernard, Y. Shao, and A. I. Krylov, J. Chem. Phys. 136, 204103 (2012)
'HYB_GGA_XC_B3PW91' : 401, # A. D. Becke, J. Chem. Phys. 98, 5648 (1993)
'HYB_GGA_XC_B3LYP' : 402, # P. J. Stephens, F. J. Devlin, C. F. Chabalowski, and M. J. Frisch, J. Phys. Chem. 98, 11623 (1994)
'HYB_GGA_XC_B3P86' : 403, # Defined through Gaussian implementation
'HYB_GGA_XC_O3LYP' : 404, # A. J. Cohen and N. C. Handy, Mol. Phys. 99, 607 (2001)
'HYB_GGA_XC_MPW1K' : 405, # B. J. Lynch, P. L. Fast, M. Harris, and D. G. Truhlar, J. Phys. Chem. A 104, 4811 (2000)
'HYB_GGA_XC_PBEH' : 406, # C. Adamo and V. Barone, J. Chem. Phys. 110, 6158 (1999)
# M. Ernzerhof and G. E. Scuseria, J. Chem. Phys. 110, 5029 (1999)
'HYB_GGA_XC_B97' : 407, # A. D. Becke, J. Chem. Phys. 107, 8554 (1997)
'HYB_GGA_XC_B97_1' : 408, # F. A. Hamprecht, A. J. Cohen, D. J. Tozer, and N. C. Handy, J. Chem. Phys. 109, 6264 (1998)
'HYB_GGA_XC_B97_2' : 410, # P. J. Wilson, T. J. Bradley, and D. J. Tozer, J. Chem. Phys. 115, 9233 (2001)
'HYB_GGA_XC_X3LYP' : 411, # X. Xu and W. A. Goddard, Proc. Natl. Acad. Sci. U. S. A. 101, 2673 (2004)
'HYB_GGA_XC_B1WC' : 412, # D. I. Bilc, R. Orlando, R. Shaltaf, G.-M. Rignanese, J. Iniguez, and P. Ghosez, Phys. Rev. B 77, 165107 (2008)
'HYB_GGA_XC_B97_K' : 413, # A. D. Boese and J. M. L. Martin, J. Chem. Phys. 121, 3405 (2004)
'HYB_GGA_XC_B97_3' : 414, # T. W. Keal and D. J. Tozer, J. Chem. Phys. 123, 121103 (2005)
'HYB_GGA_XC_MPW3PW' : 415, # C. Adamo and V. Barone, J. Chem. Phys. 108, 664 (1998)
'HYB_GGA_XC_B1LYP' : 416, # C. Adamo and V. Barone, Chem. Phys. Lett. 274, 242 (1997)
'HYB_GGA_XC_B1PW91' : 417, # C. Adamo and V. Barone, Chem. Phys. Lett. 274, 242 (1997)
'HYB_GGA_XC_MPW1PW' : 418, # C. Adamo and V. Barone, J. Chem. Phys. 108, 664 (1998)
'HYB_GGA_XC_MPW3LYP' : 419, # Y. Zhao and D. G. Truhlar, J. Phys. Chem. A 108, 6908 (2004)
'HYB_GGA_XC_SB98_1A' : 420, # H. L. Schmider and A. D. Becke, J. Chem. Phys. 108, 9624 (1998)
'HYB_GGA_XC_SB98_1B' : 421, # H. L. Schmider and A. D. Becke, J. Chem. Phys. 108, 9624 (1998)
'HYB_GGA_XC_SB98_1C' : 422, # H. L. Schmider and A. D. Becke, J. Chem. Phys. 108, 9624 (1998)
'HYB_GGA_XC_SB98_2A' : 423, # H. L. Schmider and A. D. Becke, J. Chem. Phys. 108, 9624 (1998)
'HYB_GGA_XC_SB98_2B' : 424, # H. L. Schmider and A. D. Becke, J. Chem. Phys. 108, 9624 (1998)
'HYB_GGA_XC_SB98_2C' : 425, # H. L. Schmider and A. D. Becke, J. Chem. Phys. 108, 9624 (1998)
'HYB_GGA_X_SOGGA11_X' : 426, # R. Peverati and D. G. Truhlar, J. Chem. Phys. 135, 191102 (2011)
'HYB_GGA_XC_HSE03' : 427, # J. Heyd, G. E. Scuseria, and M. Ernzerhof, J. Chem. Phys. 118, 8207 (2003)
# J. Heyd, G. E. Scuseria, and M. Ernzerhof, J. Chem. Phys. 124, 219906 (2006)
'HYB_GGA_XC_HSE06' : 428, # J. Heyd, G. E. Scuseria, and M. Ernzerhof, J. Chem. Phys. 118, 8207 (2003)
# J. Heyd, G. E. Scuseria, and M. Ernzerhof, J. Chem. Phys. 124, 219906 (2006)
# A. V. Krukau, O. A. Vydrov, A. F. Izmaylov, and G. E. Scuseria, J. Chem. Phys. 125, 224106 (2006)
'HYB_GGA_XC_HJS_PBE' : 429, # T. M. Henderson, B. G. Janesko, and G. E. Scuseria, J. Chem. Phys. 128, 194105 (2008)
'HYB_GGA_XC_HJS_PBE_SOL' : 430, # T. M. Henderson, B. G. Janesko, and G. E. Scuseria, J. Chem. Phys. 128, 194105 (2008)
'HYB_GGA_XC_HJS_B88' : 431, # T. M. Henderson, B. G. Janesko, and G. E. Scuseria, J. Chem. Phys. 128, 194105 (2008)
'HYB_GGA_XC_HJS_B97X' : 432, # T. M. Henderson, B. G. Janesko, and G. E. Scuseria, J. Chem. Phys. 128, 194105 (2008)
'HYB_GGA_XC_CAM_B3LYP' : 433, # T. Yanai, D. P. Tew, and N. C. Handy, Chem. Phys. Lett. 393, 51 (2004)
'HYB_GGA_XC_TUNED_CAM_B3LYP' : 434, # K. Okuno, Y. Shigeta, R. Kishi, H. Miyasaka, and M. Nakano, J. Photochem. Photobiol., A 235, 29 (2012)
'HYB_GGA_XC_BHANDH' : 435, # A. D. Becke, J. Chem. Phys. 98, 1372 (1993)
# Defined through Gaussian implementation
'HYB_GGA_XC_BHANDHLYP' : 436, # A. D. Becke, J. Chem. Phys. 98, 1372 (1993)
# Defined through Gaussian implementation
'HYB_GGA_XC_MB3LYP_RC04' : 437, # V. Tognetti, P. Cortona, and C. Adamo, Chem. Phys. Lett. 439, 381 (2007)
'HYB_GGA_XC_MPWLYP1M' : 453, # N. E. Schultz, Y. Zhao, and D. G. Truhlar, J. Phys. Chem. A 109, 11127 (2005)
'HYB_GGA_XC_REVB3LYP' : 454, # L. Lu, H. Hu, H. Hou, and B. Wang, Comput. Theor. Chem. 1015, 64 (2013)
'HYB_GGA_XC_CAMY_BLYP' : 455, # Y. Akinaga and S. Ten-no, Chem. Phys. Lett. 462, 348 (2008)
'HYB_GGA_XC_PBE0_13' : 456, # P. Cortona, J. Chem. Phys. 136, 086101 (2012)
'HYB_GGA_XC_B3LYPS' : 459, # M. Reiher, O. Salomon, and B. A. Hess, Theor. Chem. Acc. 107, 48 (2001)
'HYB_GGA_XC_WB97' : 463, # J.-D. Chai and M. Head-Gordon, J. Chem. Phys. 128, 084106 (2008)
'HYB_GGA_XC_WB97X' : 464, # J.-D. Chai and M. Head-Gordon, J. Chem. Phys. 128, 084106 (2008)
'HYB_GGA_XC_LRC_WPBEH' : 465, # M. A. Rohrdanz, K. M. Martins, and J. M. Herbert, J. Chem. Phys. 130, 054112 (2009)
'HYB_GGA_XC_WB97X_V' : 466, # N. Mardirossian and M. Head-Gordon, Phys. Chem. Chem. Phys. 16, 9904 (2014)
'HYB_GGA_XC_LCY_PBE' : 467, # M. Seth and T. Ziegler, J. Chem. Theory Comput. 8, 901 (2012)
# M. Seth, T. Ziegler, M. Steinmetz, and S. Grimme, J. Chem. Theory Comput. 9, 2286 (2013)
'HYB_GGA_XC_LCY_BLYP' : 468, # Y. Akinaga and S. Ten-no, Chem. Phys. Lett. 462, 348 (2008)
# M. Seth, T. Ziegler, M. Steinmetz, and S. Grimme, J. Chem. Theory Comput. 9, 2286 (2013)
'HYB_GGA_XC_LC_VV10' : 469, # O. A. Vydrov and T. Van Voorhis, J. Chem. Phys. 133, 244103 (2010)
'HYB_GGA_XC_CAMY_B3LYP' : 470, # M. Seth and T. Ziegler, J. Chem. Theory Comput. 8, 901 (2012)
'HYB_GGA_XC_WB97X_D' : 471, # J.-D. Chai and M. Head-Gordon, Phys. Chem. Chem. Phys. 10, 6615 (2008)
'HYB_GGA_XC_HPBEINT' : 472, # E. Fabiano, L. A. Constantin, and F. Della Sala, Int. J. Quantum Chem. 113, 673 (2013)
'HYB_GGA_XC_LRC_WPBE' : 473, # M. A. Rohrdanz, K. M. Martins, and J. M. Herbert, J. Chem. Phys. 130, 054112 (2009)
'HYB_GGA_XC_B3LYP5' : 475, # P. J. Stephens, F. J. Devlin, C. F. Chabalowski, and M. J. Frisch, J. Phys. Chem. 98, 11623 (1994)
'HYB_GGA_XC_EDF2' : 476, # C. Y. Lin, M. W. George, and P. M. W. Gill, Australian Journal of Chemistry 57, 365 (2004)
'HYB_GGA_XC_CAP0' : 477, # J. Carmona-Esp\'indola, J. L. G\'azquez, A. Vela, and S. B. Trickey, Theor. Chem. Acc. 135, 120 (2016)
'HYB_GGA_XC_LC_WPBE' : 478, # O. A. Vydrov and G. E. Scuseria, J. Chem. Phys. 125, 234109 (2006), 10.1063/1.2409292
'HYB_GGA_XC_HSE12' : 479, # J. E. Moussa, P. A. Schultz, and J. R. Chelikowsky, J. Chem. Phys. 136, 204117 (2012)
'HYB_GGA_XC_HSE12S' : 480, # J. E. Moussa, P. A. Schultz, and J. R. Chelikowsky, J. Chem. Phys. 136, 204117 (2012)
'HYB_GGA_XC_HSE_SOL' : 481, # L. Schimka, J. Harl, and G. Kresse, J. Chem. Phys. 134, 024116 (2011)
'HYB_GGA_XC_CAM_QTP_01' : 482, # Y. Jin and R. J. Bartlett, J. Chem. Phys. 145, 034107 (2016), http://dx.doi.org/10.1063/1.4955497
'HYB_GGA_XC_MPW1LYP' : 483, # C. Adamo and V. Barone, J. Chem. Phys. 108, 664 (1998)
'HYB_GGA_XC_MPW1PBE' : 484, # C. Adamo and V. Barone, J. Chem. Phys. 108, 664 (1998)
'HYB_GGA_XC_KMLYP' : 485, # J. K. Kang and C. B. Musgrave, J. Chem. Phys. 115, 11040 (2001), http://dx.doi.org/10.1063/1.1415079
'HYB_GGA_XC_B5050LYP' : 572, # Y. Shao, M. Head-Gordon, and A. I. Krylov, J. Chem. Phys. 118, 4807 (2003)
'MGGA_C_DLDF' : 37 , # K. Pernal, R. Podeszwa, K. Patkowski, and K. Szalewicz, Phys. Rev. Lett. 103, 263201 (2009)
'MGGA_XC_ZLP' : 42 , # Q. Zhao, M. Levy, and R. G. Parr, Phys. Rev. A 47, 918 (1993)
'MGGA_XC_OTPSS_D' : 64 , # L. Goerigk and S. Grimme, J. Chem. Theory Comput. 6, 107 (2010)
'MGGA_C_CS' : 72 , # R. Colle and O. Salvetti, Theor. Chim. Acta 37, 329 (1975)
# C. Lee, W. Yang, and R. G. Parr, Phys. Rev. B 37, 785 (1988)
'MGGA_C_MN12_SX' : 73 , # R. Peverati and D. G. Truhlar, Phys. Chem. Chem. Phys. 14, 16187 (2012)
'MGGA_C_MN12_L' : 74 , # R. Peverati and D. G. Truhlar, Phys. Chem. Chem. Phys. 14, 13171 (2012)
'MGGA_C_M11_L' : 75 , # R. Peverati and D. G. Truhlar, J. Phys. Chem. Lett. 3, 117 (2012)
'MGGA_C_M11' : 76 , # R. Peverati and D. G. Truhlar, J. Phys. Chem. Lett. 2, 2810 (2011)
'MGGA_C_M08_SO' : 77 , # Y. Zhao and D. G. Truhlar, J. Chem. Theory Comput. 4, 1849 (2008)
'MGGA_C_M08_HX' : 78 , # Y. Zhao and D. G. Truhlar, J. Chem. Theory Comput. 4, 1849 (2008)
'MGGA_X_LTA' : 201, # M. Ernzerhof and G. E. Scuseria, J. Chem. Phys. 111, 911 (1999)
'MGGA_X_TPSS' : 202, # J. Tao, J. P. Perdew, V. N. Staroverov, and G. E. Scuseria, Phys. Rev. Lett. 91, 146401 (2003)
# J. P. Perdew, J. Tao, V. N. Staroverov, and G. E. Scuseria, J. Chem. Phys. 120, 6898 (2004)
'MGGA_X_M06_L' : 203, # Y. Zhao and D. G. Truhlar, J. Chem. Phys. 125, 194101 (2006)
# Y. Zhao and D. G. Truhlar, Theor. Chem. Acc. 120, 215 (2008)
'MGGA_X_GVT4' : 204, # T. V. Voorhis and G. E. Scuseria, J. Chem. Phys. 109, 400 (1998)
'MGGA_X_TAU_HCTH' : 205, # A. D. Boese and N. C. Handy, J. Chem. Phys. 116, 9559 (2002)
'MGGA_X_BR89' : 206, # A. D. Becke and M. R. Roussel, Phys. Rev. A 39, 3761 (1989)
'MGGA_X_BJ06' : 207, # A. D. Becke and E. R. Johnson, J. Chem. Phys. 124, 221101 (2006)
'MGGA_X_TB09' : 208, # F. Tran and P. Blaha, Phys. Rev. Lett. 102, 226401 (2009)
'MGGA_X_RPP09' : 209, # E. Rasanen, S. Pittalis, and C. R. Proetto, J. Chem. Phys. 132, 044112 (2010)
'MGGA_X_2D_PRHG07' : 210, # S. Pittalis, E. Rasanen, N. Helbig, and E. K. U. Gross, Phys. Rev. B 76, 235314 (2007)
'MGGA_X_2D_PRHG07_PRP10' : 211, # S. Pittalis, E. Rasanen, N. Helbig, and E. K. U. Gross, Phys. Rev. B 76, 235314 (2007)
# S. Pittalis, E. Rasanen, and C. R. Proetto, Phys. Rev. B 81, 115108 (2010)
'MGGA_X_REVTPSS' : 212, # J. P. Perdew, A. Ruzsinszky, G. I. Csonka, L. A. Constantin, and J. Sun, Phys. Rev. Lett. 103, 026403 (2009)
# J. P. Perdew, A. Ruzsinszky, G. I. Csonka, L. A. Constantin, and J. Sun, Phys. Rev. Lett. 106, 179902 (2011)
'MGGA_X_PKZB' : 213, # J. P. Perdew, S. Kurth, A. Zupan, and P. Blaha, Phys. Rev. Lett. 82, 2544 (1999)
'MGGA_X_MS0' : 221, # J. Sun, B. Xiao, and A. Ruzsinszky, J. Chem. Phys. 137, 051101 (2012)
'MGGA_X_MS1' : 222, # J. Sun, R. Haunschild, B. Xiao, I. W. Bulik, G. E. Scuseria, and J. P. Perdew, J. Chem. Phys. 138, 044113 (2013)
'MGGA_X_MS2' : 223, # J. Sun, R. Haunschild, B. Xiao, I. W. Bulik, G. E. Scuseria, and J. P. Perdew, J. Chem. Phys. 138, 044113 (2013)
'MGGA_X_M11_L' : 226, # R. Peverati and D. G. Truhlar, J. Phys. Chem. Lett. 3, 117 (2012)
'MGGA_X_MN12_L' : 227, # R. Peverati and D. G. Truhlar, Phys. Chem. Chem. Phys. 14, 13171 (2012)
'MGGA_XC_CC06' : 229, # A. C. Cancio and M. Y. Chou, Phys. Rev. B 74, 081202 (2006)
'MGGA_X_MK00' : 230, # F. R. Manby and P. J. Knowles, J. Chem. Phys. 112, 7002 (2000)
'MGGA_C_TPSS' : 231, # J. Tao, J. P. Perdew, V. N. Staroverov, and G. E. Scuseria, Phys. Rev. Lett. 91, 146401 (2003)
# J. P. Perdew, J. Tao, V. N. Staroverov, and G. E. Scuseria, J. Chem. Phys. 120, 6898 (2004)
'MGGA_C_VSXC' : 232, # T. V. Voorhis and G. E. Scuseria, J. Chem. Phys. 109, 400 (1998)
'MGGA_C_M06_L' : 233, # Y. Zhao and D. G. Truhlar, J. Chem. Phys. 125, 194101 (2006)
# Y. Zhao and D. G. Truhlar, Theor. Chem. Acc. 120, 215 (2008)
'MGGA_C_M06_HF' : 234, # Y. Zhao and D. G. Truhlar, J. Phys. Chem. A 110, 13126 (2006)
'MGGA_C_M06' : 235, # Y. Zhao and D. G. Truhlar, Theor. Chem. Acc. 120, 215 (2008)
'MGGA_C_M06_2X' : 236, # Y. Zhao and D. G. Truhlar, Theor. Chem. Acc. 120, 215 (2008)
'MGGA_C_M05' : 237, # Y. Zhao, N. E. Schultz, and D. G. Truhlar, J. Chem. Phys. 123, 161103 (2005)
'MGGA_C_M05_2X' : 238, # Y. Zhao, N. E. Schultz, and D. G. Truhlar, J. Chem. Theory Comput. 2, 364 (2006)
'MGGA_C_PKZB' : 239, # J. P. Perdew, S. Kurth, A. Zupan, and P. Blaha, Phys. Rev. Lett. 82, 2544 (1999)
'MGGA_C_BC95' : 240, # A. D. Becke, J. Chem. Phys. 104, 1040 (1996)
'MGGA_C_REVTPSS' : 241, # J. P. Perdew, A. Ruzsinszky, G. I. Csonka, L. A. Constantin, and J. Sun, Phys. Rev. Lett. 103, 026403 (2009)
# J. P. Perdew, A. Ruzsinszky, G. I. Csonka, L. A. Constantin, and J. Sun, Phys. Rev. Lett. 106, 179902 (2011)
'MGGA_XC_TPSSLYP1W' : 242, # E. E. Dahlke and D. G. Truhlar, J. Phys. Chem. B 109, 15677 (2005)
'MGGA_X_MK00B' : 243, # F. R. Manby and P. J. Knowles, J. Chem. Phys. 112, 7002 (2000)
'MGGA_X_BLOC' : 244, # L. A. Constantin, E. Fabiano, and F. Della Sala, J. Chem. Theory Comput. 9, 2256 (2013)
'MGGA_X_MODTPSS' : 245, # J. P. Perdew, A. Ruzsinszky, J. Tao, G. I. Csonka, and G. E. Scuseria, Phys. Rev. A 76, 042506 (2007)
'MGGA_C_TPSSLOC' : 247, # L. A. Constantin, E. Fabiano, and F. Della Sala, Phys. Rev. B 86, 035130 (2012)
'MGGA_X_MBEEF' : 249, # J. Wellendorff, K. T. Lundgaard, K. W. Jacobsen, and T. Bligaard, J. Chem. Phys. 140, 144107 (2014)
'MGGA_X_MBEEFVDW' : 250, # K. T. Lundgaard, J. Wellendorff, J. Voss, K. W. Jacobsen, and T. Bligaard, Phys. Rev. B 93, 235162 (2016)
'MGGA_XC_B97M_V' : 254, # N. Mardirossian and M. Head-Gordon, J. Chem. Phys. 142, 074111 (2015)
'MGGA_X_MVS' : 257, # J. Sun, J. P. Perdew, and A. Ruzsinszky, Proc. Natl. Acad. Sci. U. S. A. 112, 685 (2015)
'MGGA_X_MN15_L' : 260, # H. S. Yu, X. He, and D. G. Truhlar, J. Chem. Theory Comput. 12, 1280 (2016)
'MGGA_C_MN15_L' : 261, # H. S. Yu, X. He, and D. G. Truhlar, J. Chem. Theory Comput. 12, 1280 (2016)
'MGGA_X_SCAN' : 263, # J. Sun, A. Ruzsinszky, and J. P. Perdew, Phys. Rev. Lett. 115, 036402 (2015)
'MGGA_C_SCAN' : 267, # J. Sun, A. Ruzsinszky, and J. P. Perdew, Phys. Rev. Lett. 115, 036402 (2015)
'MGGA_C_MN15' : 269, # H. S. Yu, X. He, S. L. Li, and D. G. Truhlar, Chem. Sci. 7, 5032 (2016)
'MGGA_X_B00' : 284, # A. D. Becke, J. Chem. Phys. 112, 4020 (2000)
'MGGA_XC_HLE17' : 288, # P. Verma and D. G. Truhlar, J. Phys. Chem C 121, 7144 (2017)
'MGGA_C_SCAN_RVV10' : 292, # H. Peng, Z.-H. Yang, J. P. Perdew, and J. Sun, Phys. Rev. X 6, 041005 (2016)
'MGGA_X_REVM06_L' : 293, # Y. Wang, X. Jin, H. S. Yu, D. G. Truhlar, and X. He, Proceedings of the National Academy of Sciences 114, 8487 (2017)
'MGGA_C_REVM06_L' : 294, # Y. Wang, X. Jin, H. S. Yu, D. G. Truhlar, and X. He, Proceedings of the National Academy of Sciences 114, 8487 (2017)
'MGGA_X_TM' : 540, # J. Tao and Y. Mo, Phys. Rev. Lett. 117, 073001 (2016)
'MGGA_X_VT84' : 541, # J. M. del Campo, J. L. Gazquez, S. Trickey, and A. Vela, Chem. Phys. Lett. 543, 179 (2012)
'MGGA_X_SA_TPSS' : 542, # L. A. Constantin, E. Fabiano, J. M. Pitarke, and F. Della Sala, Phys. Rev. B 93, 115127 (2016)
'MGGA_K_PC07' : 543, # J. P. Perdew and L. A. Constantin, Phys. Rev. B 75, 155109 (2007)
'MGGA_C_KCIS' : 562, # J. Rey and A. Savin, Int. J. Quantum Chem. 69, 581 (1998)
# J. B. Krieger, J. Chen, G. J. Iafrate, and A. Savin, \enquote {Construction of an accurate self-interaction-corrected correlation energy functional based on an electron gas with a gap,} in Electron Correlations and Materials Properties, edited by A. Gonis, N. Kioussis, and M. Ciftan (Springer US, Boston, MA, 1999) pp. 463--477
# J. B. Krieger, J. Chen, and S. Kurth, AIP Conference Proceedings 577, 48 (2001)
# J. Toulouse, A. Savin, and C. Adamo, J. Chem. Phys. 117, 10465 (2002)
'MGGA_XC_LP90' : 564, # C. Lee and R. G. Parr, Phys. Rev. A 42, 193 (1990)
'MGGA_C_B88' : 571, # A. D. Becke, J. Chem. Phys. 88, 1053 (1988)
'MGGA_X_GX' : 575, # P.-F. Loos, J. Chem. Phys. 146, 114108 (2017)
'MGGA_X_PBE_GX' : 576, # P.-F. Loos, J. Chem. Phys. 146, 114108 (2017)
'MGGA_X_REVSCAN' : 581, # P. D. Mezei, G. I. Csonka, and M. Kallay, J. Chem. Theory Comput. 0, null (0)
'MGGA_C_REVSCAN' : 582, # P. D. Mezei, G. I. Csonka, and M. Kallay, J. Chem. Theory Comput. 0, null (0)
'MGGA_C_SCAN_VV10' : 584, # J. G. Brandenburg, J. E. Bates, J. Sun, and J. P. Perdew, Phys. Rev. B 94, 115144 (2016)
'MGGA_C_REVSCAN_VV10' : 585, # P. D. Mezei, G. I. Csonka, and M. Kallay, J. Chem. Theory Comput. 0, null (0)
'MGGA_X_BR89_EXPLICIT' : 586, # A. D. Becke and M. R. Roussel, Phys. Rev. A 39, 3761 (1989)
# E. Proynov, Z. Gan, and J. Kong, Chem. Phys. Lett. 455, 103 (2008)
'HYB_MGGA_X_DLDF' : 36 , # K. Pernal, R. Podeszwa, K. Patkowski, and K. Szalewicz, Phys. Rev. Lett. 103, 263201 (2009)
'HYB_MGGA_X_MS2H' : 224, # J. Sun, R. Haunschild, B. Xiao, I. W. Bulik, G. E. Scuseria, and J. P. Perdew, J. Chem. Phys. 138, 044113 (2013)
'HYB_MGGA_X_MN12_SX' : 248, # R. Peverati and D. G. Truhlar, Phys. Chem. Chem. Phys. 14, 16187 (2012)
'HYB_MGGA_X_SCAN0' : 264, # K. Hui and J.-D. Chai, J. Chem. Phys. 144, 044114 (2016), 10.1063/1.4940734
'HYB_MGGA_X_MN15' : 268, # H. S. Yu, X. He, S. L. Li, and D. G. Truhlar, Chem. Sci. 7, 5032 (2016)
'HYB_MGGA_X_BMK' : 279, # A. D. Boese and J. M. L. Martin, J. Chem. Phys. 121, 3405 (2004)
'HYB_MGGA_X_TAU_HCTH' : 282, # A. D. Boese and N. C. Handy, J. Chem. Phys. 116, 9559 (2002)
'HYB_MGGA_X_M08_HX' : 295, # Y. Zhao and D. G. Truhlar, J. Chem. Theory Comput. 4, 1849 (2008)
'HYB_MGGA_X_M08_SO' : 296, # Y. Zhao and D. G. Truhlar, J. Chem. Theory Comput. 4, 1849 (2008)
'HYB_MGGA_X_M11' : 297, # R. Peverati and D. G. Truhlar, J. Phys. Chem. Lett. 2, 2810 (2011)
'HYB_MGGA_X_M05' : 438, # Y. Zhao, N. E. Schultz, and D. G. Truhlar, J. Chem. Phys. 123, 161103 (2005)
'HYB_MGGA_X_M05_2X' : 439, # Y. Zhao, N. E. Schultz, and D. G. Truhlar, J. Chem. Theory Comput. 2, 364 (2006)
'HYB_MGGA_XC_B88B95' : 440, # A. D. Becke, J. Chem. Phys. 104, 1040 (1996)
'HYB_MGGA_XC_B86B95' : 441, # A. D. Becke, J. Chem. Phys. 104, 1040 (1996)
'HYB_MGGA_XC_PW86B95' : 442, # A. D. Becke, J. Chem. Phys. 104, 1040 (1996)
'HYB_MGGA_XC_BB1K' : 443, # Y. Zhao, B. J. Lynch, and D. G. Truhlar, J. Phys. Chem. A 108, 2715 (2004)
'HYB_MGGA_X_M06_HF' : 444, # Y. Zhao and D. G. Truhlar, J. Phys. Chem. A 110, 13126 (2006)
'HYB_MGGA_XC_MPW1B95' : 445, # Y. Zhao and D. G. Truhlar, J. Phys. Chem. A 108, 6908 (2004)
'HYB_MGGA_XC_MPWB1K' : 446, # Y. Zhao and D. G. Truhlar, J. Phys. Chem. A 108, 6908 (2004)
'HYB_MGGA_XC_X1B95' : 447, # Y. Zhao and D. G. Truhlar, J. Phys. Chem. A 108, 6908 (2004)
'HYB_MGGA_XC_XB1K' : 448, # Y. Zhao and D. G. Truhlar, J. Phys. Chem. A 108, 6908 (2004)
'HYB_MGGA_X_M06' : 449, # Y. Zhao and D. G. Truhlar, Theor. Chem. Acc. 120, 215 (2008)
'HYB_MGGA_X_M06_2X' : 450, # Y. Zhao and D. G. Truhlar, Theor. Chem. Acc. 120, 215 (2008)
'HYB_MGGA_XC_PW6B95' : 451, # Y. Zhao and D. G. Truhlar, J. Phys. Chem. A 109, 5656 (2005)
'HYB_MGGA_XC_PWB6K' : 452, # Y. Zhao and D. G. Truhlar, J. Phys. Chem. A 109, 5656 (2005)
'HYB_MGGA_XC_TPSSH' : 457, # V. N. Staroverov, G. E. Scuseria, J. Tao, and J. P. Perdew, J. Chem. Phys. 119, 12129 (2003)
'HYB_MGGA_XC_REVTPSSH' : 458, # G. I. Csonka, J. P. Perdew, and A. Ruzsinszky, J. Chem. Theory Comput. 6, 3688 (2010)
'HYB_MGGA_X_MVSH' : 474, # J. Sun, J. P. Perdew, and A. Ruzsinszky, Proc. Natl. Acad. Sci. U. S. A. 112, 685 (2015)
'HYB_MGGA_XC_WB97M_V' : 531, # N. Mardirossian and M. Head-Gordon, J. Chem. Phys. 144, 214110 (2016)
'HYB_MGGA_XC_B0KCIS' : 563, # J. Toulouse, A. Savin, and C. Adamo, J. Chem. Phys. 117, 10465 (2002)
'HYB_MGGA_XC_MPW1KCIS' : 566, # Y. Zhao, N. Gonzalez-Garcia, and D. G. Truhlar, J. Phys. Chem A 109, 2012 (2005), pMID: 16833536
'HYB_MGGA_XC_MPWKCIS1K' : 567, # Y. Zhao, N. Gonzalez-Garcia, and D. G. Truhlar, J. Phys. Chem A 109, 2012 (2005), pMID: 16833536
'HYB_MGGA_XC_PBE1KCIS' : 568, # Y. Zhao and D. G. Truhlar, J. Chem. Theory Comput. 1, 415 (2005), pMID: 26641508
'HYB_MGGA_XC_TPSS1KCIS' : 569, # Y. Zhao, B. J. Lynch, and D. G. Truhlar, Phys. Chem. Chem. Phys. 7, 43 (2005)
'HYB_MGGA_X_REVSCAN0' : 583, # P. D. Mezei, G. I. Csonka, and M. Kallay, J. Chem. Theory Comput. 0, null (0)
'HYB_MGGA_XC_B98' : 598, # A. D. Becke, J. Chem. Phys. 109, 2092 (1998)
}
def _xc_key_without_underscore(xc_keys):
new_xc = []
for key, xc_id in xc_keys.items():
for delimeter in ('_XC_', '_X_', '_C_', '_K_'):
if delimeter in key:
key0, key1 = key.split(delimeter)
new_key1 = key1.replace('_', '').replace('-', '')
if key1 != new_key1:
new_xc.append((key0+delimeter+new_key1, xc_id))
break
return new_xc
XC_CODES.update(_xc_key_without_underscore(XC_CODES))
del(_xc_key_without_underscore)
#
# alias
#
XC_CODES.update({
'LDA' : 1 ,
'SLATER' : 1 ,
'VWN3' : 8,
'VWNRPA' : 8,
'VWN5' : 7,
'B88' : 106,
'PBE0' : 406,
'PBE1PBE' : 406,
'OPTXCORR' : '0.7344536875999693*SLATER - 0.6984752285760186*OPTX,',
'B3LYP' : 'B3LYP5', # VWN5 version
'B3LYP5' : '.2*HF + .08*SLATER + .72*B88, .81*LYP + .19*VWN',
'B3LYPG' : 402, # VWN3, used by Gaussian
'B3P86' : 'B3P865', # VWN5 version
'B3P865' : '.2*HF + .08*SLATER + .72*B88, .81*P86 + .19*VWN',
#?'B3P86G' : 403, # VWN3, used by Gaussian
'B3P86G' : '.2*HF + .08*SLATER + .72*B88, .81*P86 + .19*VWN3',
'B3PW91' : 'B3PW915',
'B3PW915' : '.2*HF + .08*SLATER + .72*B88, .81*PW91 + .19*VWN',
#'B3PW91G' : '.2*HF + .08*SLATER + .72*B88, .81*PW91 + .19*VWN3',
'B3PW91G' : 401,
#'O3LYP5' : '.1161*HF + .9262*SLATER + .8133*OPTXCORR, .81*LYP + .19*VWN5',
#'O3LYPG' : '.1161*HF + .9262*SLATER + .8133*OPTXCORR, .81*LYP + .19*VWN3',
'O3LYP' : 404, # in libxc == '.1161*HF + 0.071006917*SLATER + .8133*OPTX, .81*LYP + .19*VWN5', may be erroreous
'MPW3PW' : 'MPW3PW5', # VWN5 version
'MPW3PW5' : '.2*HF + .08*SLATER + .72*MPW91, .81*PW91 + .19*VWN',
'MPW3PWG' : 415, # VWN3, used by Gaussian
'MPW3LYP' : 'MPW3LYP5', # VWN5 version
'MPW3LYP5' : '.218*HF + .073*SLATER + .709*MPW91, .871*LYP + .129*VWN',
'MPW3LYPG' : 419, # VWN3, used by Gaussian
'REVB3LYP' : 'REVB3LYP5', # VWN5 version
'REVB3LYP5' : '.2*HF + .13*SLATER + .67*B88, .84*LYP + .16*VWN',
'REVB3LYPG' : 454, # VWN3, used by Gaussian
'X3LYP' : 'X3LYP5', # VWN5 version
'X3LYP5' : '.218*HF + .073*SLATER + .542385*B88 + .166615*PW91, .871*LYP + .129*VWN',
'X3LYPG' : 411, # VWN3, used by Gaussian
'CAMB3LYP' : 'HYB_GGA_XC_CAM_B3LYP',
'CAMYBLYP' : 'HYB_GGA_XC_CAMY_BLYP',
'CAMYB3LYP' : 'HYB_GGA_XC_CAMY_B3LYP',
'B5050LYP' : '.5*HF + .08*SLATER + .42*B88, .81*LYP + .19*VWN',
'MPW1LYP' : '.25*HF + .75*MPW91, LYP',
'MPW1PBE' : '.25*HF + .75*MPW91, PBE',
'PBE50' : '.5*HF + .5*PBE, PBE',
'REVPBE0' : '.25*HF + .75*PBE_R, PBE',
'B1B95' : 440,
'TPSS0' : '.25*HF + .75*TPSS, TPSS',
})
XC_KEYS = set(XC_CODES.keys())
# Some XC functionals have conventional name, like M06-L means M06-L for X
# functional and M06-L for C functional, PBE mean PBE-X plus PBE-C. If the
# conventional name was placed in the XC_CODES, it may lead to recursive
# reference when parsing the xc description. These names (as exceptions of
# XC_CODES) are listed in XC_ALIAS below and they should be treated as a
# shortcut for XC functional.
XC_ALIAS = {
# Conventional name : name in XC_CODES
'BLYP' : 'B88,LYP',
'BP86' : 'B88,P86',
'PW91' : 'PW91,PW91',
'PBE' : 'PBE,PBE',
'REVPBE' : 'PBE_R,PBE',
'PBESOL' : 'PBE_SOL,PBE_SOL',
'PKZB' : 'PKZB,PKZB',
'TPSS' : 'TPSS,TPSS',
'REVTPSS' : 'REVTPSS,REVTPSS',
'SCAN' : 'SCAN,SCAN',
'SOGGA' : 'SOGGA,PBE',
'BLOC' : 'BLOC,TPSSLOC',
'OLYP' : 'OPTX,LYP',
'OPBE' : 'OPTX,PBE',
'RPBE' : 'RPBE,PBE',
'BPBE' : 'B88,PBE',
'MPW91' : 'MPW91,PW91',
'HFLYP' : 'HF,LYP',
'HFPW92' : 'HF,PW_MOD',
'SPW92' : 'SLATER,PW_MOD',
'SVWN' : 'SLATER,VWN',
'MS0' : 'MS0,REGTPSS',
'MS1' : 'MS1,REGTPSS',
'MS2' : 'MS2,REGTPSS',
'MS2H' : 'MS2H,REGTPSS',
'MVS' : 'MVS,REGTPSS',
'MVSH' : 'MVSH,REGTPSS',
'SOGGA11' : 'SOGGA11,SOGGA11',
'SOGGA11_X' : 'SOGGA11_X,SOGGA11_X',
'KT1' : 'KT1,VWN',
'DLDF' : 'DLDF,DLDF',
'GAM' : 'GAM,GAM',
'M06_L' : 'M06_L,M06_L',
'M11_L' : 'M11_L,M11_L',
'MN12_L' : 'MN12_L,MN12_L',
'MN15_L' : 'MN15_L,MN15_L',
'N12' : 'N12,N12',
'N12_SX' : 'N12_SX,N12_SX',
'MN12_SX' : 'MN12_SX,MN12_SX',
'MN15' : 'MN15,MN15',
'MBEEF' : 'MBEEF,PBE_SOL',
'SCAN0' : 'SCAN0,SCAN',
'PBEOP' : 'PBE,OP_PBE',
'BOP' : 'B88,OP_B88',
# new in libxc-4.2.3
'REVSCAN' : 'MGGA_X_REVSCAN,XC_MGGA_C_REVSCAN',
'REVSCAN_VV10' : 'MGGA_X_REVSCAN,XC_MGGA_C_REVSCAN_VV10',
'SCAN_VV10' : 'MGGA_X_SCAN,XC_MGGA_C_SCAN_VV10',
'SCAN_RVV10' : 'MGGA_X_SCAN,XC_MGGA_C_SCAN_RVV10',
'M05' : 'HYB_MGGA_X_M05,MGGA_C_M05',
'M06' : 'HYB_MGGA_X_M06,MGGA_C_M06',
'M05_2X' : 'HYB_MGGA_X_M05_2X,MGGA_C_M05_2X',
'M06_2X' : 'HYB_MGGA_X_M06_2X,MGGA_C_M06_2X',
# extra aliases
'SOGGA11X' : 'SOGGA11_X',
'M06L' : 'M06_L',
'M11L' : 'M11_L',
'MN12L' : 'MN12_L',
'MN15L' : 'MN15_L',
'N12SX' : 'N12_SX',
'MN12SX' : 'MN12_SX',
'M052X' : 'M05_2X',
'M062X' : 'M06_2X',
}
XC_ALIAS.update([(key.replace('-',''), XC_ALIAS[key])
for key in XC_ALIAS if '-' in key])
VV10_XC = set(('B97M_V', 'WB97M_V', 'WB97X_V', 'VV10', 'LC_VV10',
'REVSCAN_VV10', 'SCAN_VV10', 'SCAN_RVV10'))
PROBLEMATIC_XC = dict([(XC_CODES[x], x) for x in
('GGA_C_SPBE', 'MGGA_X_REVTPSS')])
def xc_type(xc_code):
if xc_code is None:
return None
elif isinstance(xc_code, str):
if is_nlc(xc_code):
return 'NLC'
hyb, fn_facs = parse_xc(xc_code)
else:
fn_facs = [(xc_code, 1)] # mimic fn_facs
if not fn_facs:
return 'HF'
elif all(_itrf.LIBXC_is_lda(ctypes.c_int(xid)) for xid, fac in fn_facs):
return 'LDA'
elif any(_itrf.LIBXC_is_meta_gga(ctypes.c_int(xid)) for xid, fac in fn_facs):
return 'MGGA'
else:
# any(_itrf.LIBXC_is_gga(ctypes.c_int(xid)) for xid, fac in fn_facs)
# include hybrid_xc
return 'GGA'
def is_lda(xc_code):
return xc_type(xc_code) == 'LDA'
def is_hybrid_xc(xc_code):
if xc_code is None:
return False
elif isinstance(xc_code, str):
if xc_code.isdigit():
return _itrf.LIBXC_is_hybrid(ctypes.c_int(int(xc_code)))
else:
return ('HF' in xc_code or hybrid_coeff(xc_code) != 0)
elif isinstance(xc_code, int):
return _itrf.LIBXC_is_hybrid(ctypes.c_int(xc_code))
else:
return any((is_hybrid_xc(x) for x in xc_code))
def is_meta_gga(xc_code):
return xc_type(xc_code) == 'MGGA'
def is_gga(xc_code):
return xc_type(xc_code) == 'GGA'
def is_nlc(xc_code):
return '__VV10' in xc_code.upper()
def max_deriv_order(xc_code):
hyb, fn_facs = parse_xc(xc_code)
if fn_facs:
return min(_itrf.LIBXC_max_deriv_order(ctypes.c_int(xid)) for xid, fac in fn_facs)
else:
return 3
def test_deriv_order(xc_code, deriv, raise_error=False):
support = deriv <= max_deriv_order(xc_code)
if not support and raise_error:
from pyscf.dft import xcfun
msg = ('libxc library does not support derivative order %d for %s' %
(deriv, xc_code))
try:
if xcfun.test_deriv_order(xc_code, deriv, raise_error=False):
msg += ('''
This functional derivative is supported in the xcfun library.
The following code can be used to change the libxc library to xcfun library:
from pyscf.dft import xcfun
mf._numint.libxc = xcfun
''')
raise NotImplementedError(msg)
except KeyError as e:
sys.stderr.write('\n'+msg+'\n')
sys.stderr.write('%s not found in xcfun library\n\n' % xc_code)
raise e
return support
def hybrid_coeff(xc_code, spin=0):
'''Support recursively defining hybrid functional
'''
hyb, fn_facs = parse_xc(xc_code)
for xid, fac in fn_facs:
hyb[0] += fac * _itrf.LIBXC_hybrid_coeff(ctypes.c_int(xid))
return hyb[0]
def nlc_coeff(xc_code):
'''Get NLC coefficients
'''
hyb, fn_facs = parse_xc(xc_code)
nlc_pars = [0, 0]
nlc_tmp = (ctypes.c_double*2)()
for xid, fac in fn_facs:
_itrf.LIBXC_nlc_coeff(xid, nlc_tmp)
nlc_pars[0] += nlc_tmp[0]
nlc_pars[1] += nlc_tmp[1]
return nlc_pars
def rsh_coeff(xc_code):
'''Range-separated parameter and HF exchange components: omega, alpha, beta
Exc_RSH = c_LR * LR_HFX + c_SR * SR_HFX + (1-c_SR) * Ex_SR + (1-c_LR) * Ex_LR + Ec
= alpha * HFX + beta * SR_HFX + (1-c_SR) * Ex_SR + (1-c_LR) * Ex_LR + Ec
= alpha * LR_HFX + hyb * SR_HFX + (1-c_SR) * Ex_SR + (1-c_LR) * Ex_LR + Ec
SR_HFX = < pi | e^{-omega r_{12}}/r_{12} | iq >
LR_HFX = < pi | (1-e^{-omega r_{12}})/r_{12} | iq >
alpha = c_LR
beta = c_SR - c_LR = hyb - alpha
'''
if xc_code is None:
return 0, 0, 0
check_omega = True
if isinstance(xc_code, str) and ',' in xc_code:
# Parse only X part for the RSH coefficients. This is to handle
# exceptions for C functionals such as M11.
xc_code = format_xc_code(xc_code)
xc_code = xc_code.split(',')[0] + ','
if 'SR_HF' in xc_code or 'LR_HF' in xc_code or 'RSH(' in xc_code:
check_omega = False
hyb, fn_facs = parse_xc(xc_code)
hyb, alpha, omega = hyb
beta = hyb - alpha
rsh_pars = [omega, alpha, beta]
rsh_tmp = (ctypes.c_double*3)()
_itrf.LIBXC_rsh_coeff(433, rsh_tmp)
for xid, fac in fn_facs:
_itrf.LIBXC_rsh_coeff(xid, rsh_tmp)
if rsh_pars[0] == 0:
rsh_pars[0] = rsh_tmp[0]
elif check_omega:
# Check functional is actually a CAM functional
if rsh_tmp[0] != 0 and not _itrf.LIBXC_is_cam_rsh(ctypes.c_int(xid)):
raise KeyError('Libxc functional %i employs a range separation kernel that is not supported in PySCF' % xid)
# Check omega
if (rsh_tmp[0] != 0 and rsh_pars[0] != rsh_tmp[0]):
raise ValueError('Different values of omega found for RSH functionals')
rsh_pars[1] += rsh_tmp[1] * fac
rsh_pars[2] += rsh_tmp[2] * fac
return rsh_pars
def parse_xc_name(xc_name='LDA,VWN'):
'''Convert the XC functional name to libxc library internal ID.
'''
fn_facs = parse_xc(xc_name)[1]
return fn_facs[0][0], fn_facs[1][0]
def parse_xc(description):
r'''Rules to input functional description:
* The given functional description must be a one-line string.
* The functional description is case-insensitive.
* The functional description string has two parts, separated by ",". The
first part describes the exchange functional, the second is the correlation
functional.
- If "," was not in string, the entire string is considered as a
compound XC functional (including both X and C functionals, such as b3lyp).
- To input only X functional (without C functional), leave the second
part blank. E.g. description='slater,' means pure LDA functional.
- To neglect X functional (just apply C functional), leave the first
part blank. E.g. description=',vwn' means pure VWN functional.
- If compound XC functional is specified, no matter whehter it is in the
X part (the string in front of comma) or the C part (the string behind
comma), both X and C functionals of the compound XC functional will be
used.
* The functional name can be placed in arbitrary order. Two name needs to
be separated by operators "+" or "-". Blank spaces are ignored.
NOTE the parser only reads operators "+" "-" "*". / is not in support.
* A functional name can have at most one factor. If the factor is not
given, it is set to 1. Compound functional can be scaled as a unit. For
example '0.5*b3lyp' is equivalent to
'HF*0.1 + .04*LDA + .36*B88, .405*LYP + .095*VWN'
* String "HF" stands for exact exchange (HF K matrix). Putting "HF" in
correlation functional part is the same to putting "HF" in exchange
part.
* String "RSH" means range-separated operator. Its format is
RSH(omega, alpha, beta). Another way to input RSH is to use keywords
SR_HF and LR_HF: "SR_HF(0.1) * alpha_plus_beta" and "LR_HF(0.1) *
alpha" where the number in parenthesis is the value of omega.
* Be careful with the libxc convention on GGA functional, in which the LDA
contribution has been included.
Args:
xc_code : str
A string to describe the linear combination of different XC functionals.
The X and C functional are separated by comma like '.8*LDA+.2*B86,VWN'.
If "HF" was appeared in the string, it stands for the exact exchange.
rho : ndarray
Shape of ((*,N)) for electron density (and derivatives) if spin = 0;
Shape of ((*,N),(*,N)) for alpha/beta electron density (and derivatives) if spin > 0;
where N is number of grids.
rho (*,N) are ordered as (den,grad_x,grad_y,grad_z,laplacian,tau)
where grad_x = d/dx den, laplacian = \nabla^2 den, tau = 1/2(\nabla f)^2
In spin unrestricted case,
rho is ((den_u,grad_xu,grad_yu,grad_zu,laplacian_u,tau_u)
(den_d,grad_xd,grad_yd,grad_zd,laplacian_d,tau_d))
Kwargs:
spin : int
spin polarized if spin > 0
relativity : int
No effects.
verbose : int or object of :class:`Logger`
No effects.
Returns:
ex, vxc, fxc, kxc
where
* vxc = (vrho, vsigma, vlapl, vtau) for restricted case
* vxc for unrestricted case
| vrho[:,2] = (u, d)
| vsigma[:,3] = (uu, ud, dd)
| vlapl[:,2] = (u, d)
| vtau[:,2] = (u, d)
* fxc for restricted case:
(v2rho2, v2rhosigma, v2sigma2, v2lapl2, vtau2, v2rholapl, v2rhotau, v2lapltau, v2sigmalapl, v2sigmatau)
* fxc for unrestricted case:
| v2rho2[:,3] = (u_u, u_d, d_d)
| v2rhosigma[:,6] = (u_uu, u_ud, u_dd, d_uu, d_ud, d_dd)
| v2sigma2[:,6] = (uu_uu, uu_ud, uu_dd, ud_ud, ud_dd, dd_dd)
| v2lapl2[:,3]
| vtau2[:,3]
| v2rholapl[:,4]
| v2rhotau[:,4]
| v2lapltau[:,4]
| v2sigmalapl[:,6]
| v2sigmatau[:,6]
* kxc for restricted case:
v3rho3, v3rho2sigma, v3rhosigma2, v3sigma3,
v3rho2tau, v3rhosigmatau, v3rhotau2, v3sigma2tau, v3sigmatau2, v3tau3
* kxc for unrestricted case:
| v3rho3[:,4] = (u_u_u, u_u_d, u_d_d, d_d_d)
| v3rho2sigma[:,9] = (u_u_uu, u_u_ud, u_u_dd, u_d_uu, u_d_ud, u_d_dd, d_d_uu, d_d_ud, d_d_dd)
| v3rhosigma2[:,12] = (u_uu_uu, u_uu_ud, u_uu_dd, u_ud_ud, u_ud_dd, u_dd_dd, d_uu_uu, d_uu_ud, d_uu_dd, d_ud_ud, d_ud_dd, d_dd_dd)
| v3sigma3[:,10] = (uu_uu_uu, uu_uu_ud, uu_uu_dd, uu_ud_ud, uu_ud_dd, uu_dd_dd, ud_ud_ud, ud_ud_dd, ud_dd_dd, dd_dd_dd)
| v3rho2tau
| v3rhosigmatau
| v3rhotau2
| v3sigma2tau
| v3sigmatau2
| v3tau3
see also libxc_itrf.c
'''
hyb = [0, 0, 0] # hybrid, alpha, omega (== SR_HF, LR_HF, omega)
if description is None:
return hyb, []
elif isinstance(description, int):
return hyb, [(description, 1.)]
elif not isinstance(description, str): #isinstance(description, (tuple,list)):
return parse_xc('%s,%s' % tuple(description))
def assign_omega(omega, hyb_or_sr, lr=0):
if hyb[2] == omega or omega == 0:
hyb[0] += hyb_or_sr
hyb[1] += lr
elif hyb[2] == 0:
hyb[0] += hyb_or_sr
hyb[1] += lr
hyb[2] = omega
else:
raise ValueError('Different values of omega found for RSH functionals')
fn_facs = []
def parse_token(token, ftype, search_xc_alias=False):
if token:
if token[0] == '-':
sign = -1
token = token[1:]
else:
sign = 1
if '*' in token:
fac, key = token.split('*')
if fac[0].isalpha():
fac, key = key, fac
fac = sign * float(fac)
else:
fac, key = sign, token
if key[:3] == 'RSH':
# RSH(alpha; beta; omega): Range-separated-hybrid functional
alpha, beta, omega = [float(x) for x in key[4:-1].split(';')]
assign_omega(omega, fac*(alpha+beta), fac*alpha)
elif key == 'HF':
hyb[0] += fac
hyb[1] += fac # also add to LR_HF
elif 'SR_HF' in key:
if '(' in key:
omega = float(key.split('(')[1].split(')')[0])
assign_omega(omega, fac, 0)
else: # Assuming this omega the same to the existing omega
hyb[0] += fac
elif 'LR_HF' in key:
if '(' in key:
omega = float(key.split('(')[1].split(')')[0])
assign_omega(omega, 0, fac)
else:
hyb[1] += fac # == alpha
elif key.isdigit():
fn_facs.append((int(key), fac))
else:
if search_xc_alias and key in XC_ALIAS:
x_id = XC_ALIAS[key]
elif key in XC_CODES:
x_id = XC_CODES[key]
else:
possible_xc_for = fpossible_dic[ftype]
possible_xc = XC_KEYS.intersection(possible_xc_for(key))
if possible_xc:
if len(possible_xc) > 1:
sys.stderr.write('Possible xc_code %s matches %s. '
% (list(possible_xc), key))
for x_id in possible_xc: # Prefer X functional
if '_X_' in x_id:
break
else:
x_id = possible_xc.pop()
sys.stderr.write('XC parser takes %s\n' % x_id)
sys.stderr.write('You can add prefix to %s for a '
'specific functional (e.g. X_%s, '
'HYB_MGGA_X_%s)\n'
% (key, key, key))
else:
x_id = possible_xc.pop()
x_id = XC_CODES[x_id]
else:
raise KeyError('Unknown %s functional %s' % (ftype, key))
if isinstance(x_id, str):
hyb1, fn_facs1 = parse_xc(x_id)
# Recursively scale the composed functional, to support e.g. '0.5*b3lyp'
if hyb1[0] != 0 or hyb1[1] != 0:
assign_omega(hyb1[2], hyb1[0]*fac, hyb1[1]*fac)
fn_facs.extend([(xid, c*fac) for xid, c in fn_facs1])
elif x_id is None:
raise NotImplementedError('%s functional %s' % (ftype, key))
else:
fn_facs.append((x_id, fac))
def possible_x_for(key):
return set((key,
'LDA_X_'+key, 'GGA_X_'+key, 'MGGA_X_'+key,
'HYB_GGA_X_'+key, 'HYB_MGGA_X_'+key))
def possible_xc_for(key):
return set((key, 'LDA_XC_'+key, 'GGA_XC_'+key, 'MGGA_XC_'+key,
'HYB_GGA_XC_'+key, 'HYB_MGGA_XC_'+key))
def possible_k_for(key):
return set((key,
'LDA_K_'+key, 'GGA_K_'+key,))
def possible_x_k_for(key):
return possible_x_for(key).union(possible_k_for(key))
def possible_c_for(key):
return set((key,
'LDA_C_'+key, 'GGA_C_'+key, 'MGGA_C_'+key))
fpossible_dic = {'X': possible_x_for,
'C': possible_c_for,
'compound XC': possible_xc_for,
'K': possible_k_for,
'X or K': possible_x_k_for}
description = format_xc_code(description)
if '-' in description: # To handle e.g. M06-L
for key in _NAME_WITH_DASH:
if key in description:
description = description.replace(key, _NAME_WITH_DASH[key])
if ',' in description:
x_code, c_code = description.split(',')
for token in x_code.replace('-', '+-').replace(';+', ';').split('+'):
parse_token(token, 'X or K')
for token in c_code.replace('-', '+-').replace(';+', ';').split('+'):
parse_token(token, 'C')
else:
for token in description.replace('-', '+-').replace(';+', ';').split('+'):
parse_token(token, 'compound XC', search_xc_alias=True)
if hyb[2] == 0: # No omega is assigned. LR_HF is 0 for normal Coulomb operator
hyb[1] = 0
return hyb, remove_dup(fn_facs)
_NAME_WITH_DASH = {'SR-HF' : 'SR_HF',
'LR-HF' : 'LR_HF',
'OTPSS-D' : 'OTPSS_D',
'B97-1' : 'B97_1',
'B97-2' : 'B97_2',
'B97-3' : 'B97_3',
'B97-K' : 'B97_K',
'B97-D' : 'B97_D',
'HCTH-93' : 'HCTH_93',
'HCTH-120' : 'HCTH_120',
'HCTH-147' : 'HCTH_147',
'HCTH-407' : 'HCTH_407',
'WB97X-D' : 'WB97X_D',
'WB97X-V' : 'WB97X_V',
'WB97M-V' : 'WB97M_V',
'B97M-V' : 'B97M_V',
'M05-2X' : 'M05_2X',
'M06-L' : 'M06_L',
'M06-HF' : 'M06_HF',
'M06-2X' : 'M06_2X',
'M08-HX' : 'M08_HX',
'M08-SO' : 'M08_SO',
'M11-L' : 'M11_L',
'MN12-L' : 'MN12_L',
'MN15-L' : 'MN15_L',
'MN12-SX' : 'MN12_SX',
'N12-SX' : 'N12_SX',
'LRC-WPBE' : 'LRC_WPBE',
'LRC-WPBEH': 'LRC_WPBEH',
'LC-VV10' : 'LC_VV10',
'CAM-B3LYP': 'CAM_B3LYP'}
def eval_xc(xc_code, rho, spin=0, relativity=0, deriv=1, omega=None, verbose=None):
r'''Interface to call libxc library to evaluate XC functional, potential
and functional derivatives.
* The given functional xc_code must be a one-line string.
* The functional xc_code is case-insensitive.
* The functional xc_code string has two parts, separated by ",". The
first part describes the exchange functional, the second part sets the
correlation functional.
- If "," not appeared in string, the entire string is treated as the
name of a compound functional (containing both the exchange and
the correlation functional) which was declared in the functional
aliases list. The full list of functional aliases can be obtained by
calling the function pyscf.dft.xcfun.XC_ALIAS.keys() .
If the string was not found in the aliased functional list, it is
treated as X functional.
- To input only X functional (without C functional), leave the second
part blank. E.g. description='slater,' means a functional with LDA
contribution only.
- To neglect the contribution of X functional (just apply C functional),
leave blank in the first part, e.g. description=',vwn' means a
functional with VWN only.
- If compound XC functional is specified, no matter whether it is in the
X part (the string in front of comma) or the C part (the string behind
comma), both X and C functionals of the compound XC functional will be
used.
* The functional name can be placed in arbitrary order. Two names need to
be separated by operators "+" or "-". Blank spaces are ignored.
NOTE the parser only reads operators "+" "-" "*". / is not supported.
* A functional name can have at most one factor. If the factor is not
given, it is set to 1. Compound functional can be scaled as a unit. For
example '0.5*b3lyp' is equivalent to
'HF*0.1 + .04*LDA + .36*B88, .405*LYP + .095*VWN'
* String "HF" stands for exact exchange (HF K matrix). "HF" can be put in
the correlation functional part (after comma). Putting "HF" in the
correlation part is the same to putting "HF" in the exchange part.
* String "RSH" means range-separated operator. Its format is
RSH(alpha; beta; omega). Another way to input RSH is to use keywords
SR_HF and LR_HF: "SR_HF(0.1) * alpha_plus_beta" and "LR_HF(0.1) *
alpha" where the number in parenthesis is the value of omega.
* Be careful with the libxc convention of GGA functional, in which the LDA
contribution is included.
Args:
xc_code : str
A string to describe the linear combination of different XC functionals.
The X and C functional are separated by comma like '.8*LDA+.2*B86,VWN'.
If "HF" (exact exchange) is appeared in the string, the HF part will
be skipped. If an empty string "" is given, the returns exc, vxc,...
will be vectors of zeros.
rho : ndarray
Shape of ((*,N)) for electron density (and derivatives) if spin = 0;
Shape of ((*,N),(*,N)) for alpha/beta electron density (and derivatives) if spin > 0;
where N is number of grids.
rho (*,N) are ordered as (den,grad_x,grad_y,grad_z,laplacian,tau)
where grad_x = d/dx den, laplacian = \nabla^2 den, tau = 1/2(\nabla f)^2
In spin unrestricted case,
rho is ((den_u,grad_xu,grad_yu,grad_zu,laplacian_u,tau_u)
(den_d,grad_xd,grad_yd,grad_zd,laplacian_d,tau_d))
Kwargs:
spin : int
spin polarized if spin > 0
relativity : int
No effects.
verbose : int or object of :class:`Logger`
No effects.
Returns:
ex, vxc, fxc, kxc
where
* vxc = (vrho, vsigma, vlapl, vtau) for restricted case
* vxc for unrestricted case
| vrho[:,2] = (u, d)
| vsigma[:,3] = (uu, ud, dd)
| vlapl[:,2] = (u, d)
| vtau[:,2] = (u, d)
* fxc for restricted case:
(v2rho2, v2rhosigma, v2sigma2, v2lapl2, vtau2, v2rholapl, v2rhotau, v2lapltau, v2sigmalapl, v2sigmatau)
* fxc for unrestricted case:
| v2rho2[:,3] = (u_u, u_d, d_d)
| v2rhosigma[:,6] = (u_uu, u_ud, u_dd, d_uu, d_ud, d_dd)
| v2sigma2[:,6] = (uu_uu, uu_ud, uu_dd, ud_ud, ud_dd, dd_dd)
| v2lapl2[:,3]
| vtau2[:,3]
| v2rholapl[:,4]
| v2rhotau[:,4]
| v2lapltau[:,4]
| v2sigmalapl[:,6]
| v2sigmatau[:,6]
* kxc for restricted case:
(v3rho3, v3rho2sigma, v3rhosigma2, v3sigma3)
* kxc for unrestricted case:
| v3rho3[:,4] = (u_u_u, u_u_d, u_d_d, d_d_d)
| v3rho2sigma[:,9] = (u_u_uu, u_u_ud, u_u_dd, u_d_uu, u_d_ud, u_d_dd, d_d_uu, d_d_ud, d_d_dd)
| v3rhosigma2[:,12] = (u_uu_uu, u_uu_ud, u_uu_dd, u_ud_ud, u_ud_dd, u_dd_dd, d_uu_uu, d_uu_ud, d_uu_dd, d_ud_ud, d_ud_dd, d_dd_dd)
| v3sigma3[:,10] = (uu_uu_uu, uu_uu_ud, uu_uu_dd, uu_ud_ud, uu_ud_dd, uu_dd_dd, ud_ud_ud, ud_ud_dd, ud_dd_dd, dd_dd_dd)
see also libxc_itrf.c
'''
hyb, fn_facs = parse_xc(xc_code)
if omega is not None:
hyb[2] = float(omega)
return _eval_xc(hyb, fn_facs, rho, spin, relativity, deriv, verbose)
SINGULAR_IDS = set((131, # LYP functions
402, 404, 411, 416, 419, # hybrid LYP functions
74 , 75 , 226, 227)) # M11L and MN12L functional
def _eval_xc(hyb, fn_facs, rho, spin=0, relativity=0, deriv=1, verbose=None):
assert(deriv <= 3)
if spin == 0:
nspin = 1
rho_u = rho_d = numpy.asarray(rho, order='C')
else:
nspin = 2
rho_u = numpy.asarray(rho[0], order='C')
rho_d = numpy.asarray(rho[1], order='C')
assert(rho_u.dtype == numpy.double)
assert(rho_d.dtype == numpy.double)
if rho_u.ndim == 1:
rho_u = rho_u.reshape(1,-1)
rho_d = rho_d.reshape(1,-1)
ngrids = rho_u.shape[1]
fn_ids = [x[0] for x in fn_facs]
facs = [x[1] for x in fn_facs]
if hyb[2] != 0:
# Current implementation does not support different omegas for
# different RSH functionals if there are multiple RSHs
omega = [hyb[2]] * len(facs)
else:
omega = [0] * len(facs)
fn_ids_set = set(fn_ids)
if fn_ids_set.intersection(PROBLEMATIC_XC):
problem_xc = [PROBLEMATIC_XC[k]
for k in fn_ids_set.intersection(PROBLEMATIC_XC)]
warnings.warn('Libxc functionals %s may have discrepancy to xcfun '
'library.\n' % problem_xc)
n = len(fn_ids)
if (n == 0 or # xc_code = '' or xc_code = 'HF', an empty functional
all((is_lda(x) for x in fn_ids))):
if spin == 0:
nvar = 1
else:
nvar = 2
elif any((is_meta_gga(x) for x in fn_ids)):
if spin == 0:
nvar = 4
else:
nvar = 9
else: # GGA
if spin == 0:
nvar = 2
else:
nvar = 5
outlen = (math.factorial(nvar+deriv) //
(math.factorial(nvar) * math.factorial(deriv)))
if SINGULAR_IDS.intersection(fn_ids_set) and deriv > 1:
non0idx = (rho_u[0] > 1e-10) & (rho_d[0] > 1e-10)
rho_u = numpy.asarray(rho_u[:,non0idx], order='C')
rho_d = numpy.asarray(rho_d[:,non0idx], order='C')
outbuf = numpy.zeros((outlen,non0idx.sum()))
else:
outbuf = numpy.zeros((outlen,ngrids))
_itrf.LIBXC_eval_xc(ctypes.c_int(n),
(ctypes.c_int*n)(*fn_ids),
(ctypes.c_double*n)(*facs),
(ctypes.c_double*n)(*omega),
ctypes.c_int(nspin),
ctypes.c_int(deriv), ctypes.c_int(rho_u.shape[1]),
rho_u.ctypes.data_as(ctypes.c_void_p),
rho_d.ctypes.data_as(ctypes.c_void_p),
outbuf.ctypes.data_as(ctypes.c_void_p))
if outbuf.shape[1] != ngrids:
out = numpy.zeros((outlen,ngrids))
out[:,non0idx] = outbuf
outbuf = out
exc = outbuf[0]
vxc = fxc = kxc = None
if nvar == 1: # LDA
if deriv > 0:
vxc = (outbuf[1], None, None, None)
if deriv > 1:
fxc = (outbuf[2],) + (None,)*9
if deriv > 2:
kxc = (outbuf[3], None, None, None)
elif nvar == 2:
if spin == 0: # GGA
if deriv > 0:
vxc = (outbuf[1], outbuf[2], None, None)
if deriv > 1:
fxc = (outbuf[3], outbuf[4], outbuf[5],) + (None,)*7
if deriv > 2:
kxc = outbuf[6:10]
else: # LDA
if deriv > 0:
vxc = (outbuf[1:3].T, None, None, None)
if deriv > 1:
fxc = (outbuf[3:6].T,) + (None,)*9
if deriv > 2:
kxc = (outbuf[6:10].T, None, None, None)
elif nvar == 5: # GGA
if deriv > 0:
vxc = (outbuf[1:3].T, outbuf[3:6].T, None, None)
if deriv > 1:
fxc = (outbuf[6:9].T, outbuf[9:15].T, outbuf[15:21].T) + (None,)*7
if deriv > 2:
kxc = (outbuf[21:25].T, outbuf[25:34].T, outbuf[34:46].T, outbuf[46:56].T)
elif nvar == 4: # MGGA
if deriv > 0:
vxc = outbuf[1:5]
if deriv > 1:
fxc = outbuf[5:15]
if deriv > 2:
kxc = outbuf[15:19]
elif nvar == 9: # MGGA
if deriv > 0:
vxc = (outbuf[1:3].T, outbuf[3:6].T, outbuf[6:8].T, outbuf[8:10].T)
if deriv > 1:
fxc = (outbuf[10:13].T, outbuf[13:19].T, outbuf[19:25].T,
outbuf[25:28].T, outbuf[28:31].T, outbuf[31:35].T,
outbuf[35:39].T, outbuf[39:43].T, outbuf[43:49].T,
outbuf[49:55].T)
return exc, vxc, fxc, kxc
def define_xc_(ni, description, xctype='LDA', hyb=0, rsh=(0,0,0)):
'''Define XC functional. See also :func:`eval_xc` for the rules of input description.
Args:
ni : an instance of :class:`NumInt`
description : str
A string to describe the linear combination of different XC functionals.
The X and C functional are separated by comma like '.8*LDA+.2*B86,VWN'.
If "HF" was appeared in the string, it stands for the exact exchange.
Kwargs:
xctype : str
'LDA' or 'GGA' or 'MGGA'
hyb : float
hybrid functional coefficient
rsh : a list of three floats
coefficients (omega, alpha, beta) for range-separated hybrid functional.
omega is the exponent factor in attenuated Coulomb operator e^{-omega r_{12}}/r_{12}
alpha is the coefficient for long-range part, hybrid coefficient
can be obtained by alpha + beta
Examples:
>>> mol = gto.M(atom='O 0 0 0; H 0 0 1; H 0 1 0', basis='ccpvdz')
>>> mf = dft.RKS(mol)
>>> define_xc_(mf._numint, '.2*HF + .08*LDA + .72*B88, .81*LYP + .19*VWN')
>>> mf.kernel()
-76.3783361189611
>>> define_xc_(mf._numint, 'LDA*.08 + .72*B88 + .2*HF, .81*LYP + .19*VWN')
>>> mf.kernel()
-76.3783361189611
>>> def eval_xc(xc_code, rho, *args, **kwargs):
... exc = 0.01 * rho**2
... vrho = 0.01 * 2 * rho
... vxc = (vrho, None, None, None)
... fxc = None # 2nd order functional derivative
... kxc = None # 3rd order functional derivative
... return exc, vxc, fxc, kxc
>>> define_xc_(mf._numint, eval_xc, xctype='LDA')
>>> mf.kernel()
48.8525211046668
'''
if isinstance(description, str):
ni.eval_xc = lambda xc_code, rho, *args, **kwargs: \
eval_xc(description, rho, *args, **kwargs)
ni.hybrid_coeff = lambda *args, **kwargs: hybrid_coeff(description)
ni.rsh_coeff = lambda *args: rsh_coeff(description)
ni._xc_type = lambda *args: xc_type(description)
elif callable(description):
ni.eval_xc = description
ni.hybrid_coeff = lambda *args, **kwargs: hyb
ni.rsh_coeff = lambda *args, **kwargs: rsh
ni._xc_type = lambda *args: xctype
else:
raise ValueError('Unknown description %s' % description)
return ni
def define_xc(ni, description, xctype='LDA', hyb=0, rsh=(0,0,0)):
return define_xc_(copy.copy(ni), description, xctype, hyb, rsh)
define_xc.__doc__ = define_xc_.__doc__
if __name__ == '__main__':
from pyscf import gto, dft
mol = gto.M(
atom = [
["O" , (0. , 0. , 0.)],
[1 , (0. , -0.757 , 0.587)],
[1 , (0. , 0.757 , 0.587)] ],
)
mf = dft.RKS(mol)
#mf._numint.libxc = dft.xcfun
mf.xc = 'camb3lyp'
mf.kernel()
mf.xc = 'b88,lyp'
eref = mf.kernel()
mf = dft.RKS(mol)
mf._numint = define_xc(mf._numint, 'BLYP')
e1 = mf.kernel()
print(e1 - eref)
mf = dft.RKS(mol)
mf._numint = define_xc(mf._numint, 'B3LYP5')
e1 = mf.kernel()
print(e1 - -75.2753037898599)
| gkc1000/pyscf | pyscf/dft/libxc.py | Python | apache-2.0 | 98,072 | [
"DIRAC",
"Gaussian",
"Octopus",
"PySCF"
] | cb31d54ebb92db7f3539895ba0b9abb47f7d36aed16ecb7b9b74120e5a831a0d |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = '''
---
module: acl
version_added: "1.4"
short_description: Sets and retrieves file ACL information.
description:
- Sets and retrieves file ACL information.
options:
path:
required: true
default: null
description:
- The full path of the file or object.
aliases: ['name']
state:
required: false
default: query
choices: [ 'query', 'present', 'absent' ]
description:
- defines whether the ACL should be present or not. The C(query) state gets the current acl without changing it, for use in 'register' operations.
follow:
required: false
default: yes
choices: [ 'yes', 'no' ]
description:
- whether to follow symlinks on the path if a symlink is encountered.
default:
version_added: "1.5"
required: false
default: no
choices: [ 'yes', 'no' ]
description:
- if the target is a directory, setting this to yes will make it the default acl for entities created inside the directory. It causes an error if path is a file.
entity:
version_added: "1.5"
required: false
description:
- actual user or group that the ACL applies to when matching entity types user or group are selected.
etype:
version_added: "1.5"
required: false
default: null
choices: [ 'user', 'group', 'mask', 'other' ]
description:
- the entity type of the ACL to apply, see setfacl documentation for more info.
permissions:
version_added: "1.5"
required: false
default: null
description:
- Permissions to apply/remove can be any combination of r, w and x (read, write and execute respectively)
entry:
required: false
default: null
description:
- DEPRECATED. The acl to set or remove. This must always be quoted in the form of '<etype>:<qualifier>:<perms>'. The qualifier may be empty for some types, but the type and perms are always required. '-' can be used as placeholder when you do not care about permissions. This is now superseded by entity, type and permissions fields.
recursive:
version_added: "2.0"
required: false
default: no
choices: [ 'yes', 'no' ]
description:
- Recursively sets the specified ACL (added in Ansible 2.0). Incompatible with C(state=query).
author:
- "Brian Coca (@bcoca)"
- "Jérémie Astori (@astorije)"
notes:
- The "acl" module requires that acls are enabled on the target filesystem and that the setfacl and getfacl binaries are installed.
- As of Ansible 2.0, this module only supports Linux distributions.
- As of Ansible 2.3, the I(name) option has been changed to I(path) as default, but I(name) still works as well.
'''
EXAMPLES = '''
# Grant user Joe read access to a file
- acl:
path: /etc/foo.conf
entity: joe
etype: user
permissions: r
state: present
# Removes the acl for Joe on a specific file
- acl:
path: /etc/foo.conf
entity: joe
etype: user
state: absent
# Sets default acl for joe on foo.d
- acl:
path: /etc/foo.d
entity: joe
etype: user
permissions: rw
default: yes
state: present
# Same as previous but using entry shorthand
- acl:
path: /etc/foo.d
entry: "default:user:joe:rw-"
state: present
# Obtain the acl for a specific file
- acl:
path: /etc/foo.conf
register: acl_info
'''
RETURN = '''
acl:
description: Current acl on provided path (after changes, if any)
returned: success
type: list
sample: [ "user::rwx", "group::rwx", "other::rwx" ]
'''
import os
# import module snippets
from ansible.module_utils.basic import AnsibleModule, get_platform
def split_entry(entry):
''' splits entry and ensures normalized return'''
a = entry.split(':')
d = None
if entry.lower().startswith("d"):
d = True
a.pop(0)
if len(a) == 2:
a.append(None)
t, e, p = a
t = t.lower()
if t.startswith("u"):
t = "user"
elif t.startswith("g"):
t = "group"
elif t.startswith("m"):
t = "mask"
elif t.startswith("o"):
t = "other"
else:
t = None
return [d, t, e, p]
def build_entry(etype, entity, permissions=None, use_nfsv4_acls=False):
'''Builds and returns an entry string. Does not include the permissions bit if they are not provided.'''
if use_nfsv4_acls:
return ':'.join([etype, entity, permissions, 'allow'])
if permissions:
return etype + ':' + entity + ':' + permissions
else:
return etype + ':' + entity
def build_command(module, mode, path, follow, default, recursive, entry=''):
'''Builds and returns a getfacl/setfacl command.'''
if mode == 'set':
cmd = [module.get_bin_path('setfacl', True)]
cmd.append('-m "%s"' % entry)
elif mode == 'rm':
cmd = [module.get_bin_path('setfacl', True)]
cmd.append('-x "%s"' % entry)
else: # mode == 'get'
cmd = [module.get_bin_path('getfacl', True)]
# prevents absolute path warnings and removes headers
if get_platform().lower() == 'linux':
cmd.append('--omit-header')
cmd.append('--absolute-names')
if recursive:
cmd.append('--recursive')
if not follow:
if get_platform().lower() == 'linux':
cmd.append('--physical')
elif get_platform().lower() == 'freebsd':
cmd.append('-h')
if default:
if(mode == 'rm'):
cmd.insert(1, '-k')
else: # mode == 'set' or mode == 'get'
cmd.insert(1, '-d')
cmd.append(path)
return cmd
def acl_changed(module, cmd):
'''Returns true if the provided command affects the existing ACLs, false otherwise.'''
# FreeBSD do not have a --test flag, so by default, it is safer to always say "true"
if get_platform().lower() == 'freebsd':
return True
cmd = cmd[:] # lists are mutables so cmd would be overwritten without this
cmd.insert(1, '--test')
lines = run_acl(module, cmd)
for line in lines:
if not line.endswith('*,*'):
return True
return False
def run_acl(module, cmd, check_rc=True):
try:
(rc, out, err) = module.run_command(' '.join(cmd), check_rc=check_rc)
except Exception:
e = get_exception()
module.fail_json(msg=e.strerror)
lines = []
for l in out.splitlines():
if not l.startswith('#'):
lines.append(l.strip())
if lines and not lines[-1].split():
# trim last line only when it is empty
return lines[:-1]
else:
return lines
def main():
module = AnsibleModule(
argument_spec=dict(
path=dict(required=True, aliases=['name'], type='path'),
entry=dict(required=False, type='str'),
entity=dict(required=False, type='str', default=''),
etype=dict(
required=False,
choices=['other', 'user', 'group', 'mask'],
type='str'
),
permissions=dict(required=False, type='str'),
state=dict(
required=False,
default='query',
choices=['query', 'present', 'absent'],
type='str'
),
follow=dict(required=False, type='bool', default=True),
default=dict(required=False, type='bool', default=False),
recursive=dict(required=False, type='bool', default=False),
use_nfsv4_acls=dict(required=False, type='bool', default=False)
),
supports_check_mode=True,
)
if get_platform().lower() not in ['linux', 'freebsd']:
module.fail_json(msg="The acl module is not available on this system.")
path = module.params.get('path')
entry = module.params.get('entry')
entity = module.params.get('entity')
etype = module.params.get('etype')
permissions = module.params.get('permissions')
state = module.params.get('state')
follow = module.params.get('follow')
default = module.params.get('default')
recursive = module.params.get('recursive')
use_nfsv4_acls = module.params.get('use_nfsv4_acls')
if not os.path.exists(path):
module.fail_json(msg="Path not found or not accessible.")
if state == 'query' and recursive:
module.fail_json(msg="'recursive' MUST NOT be set when 'state=query'.")
if not entry:
if state == 'absent' and permissions:
module.fail_json(msg="'permissions' MUST NOT be set when 'state=absent'.")
if state == 'absent' and not entity:
module.fail_json(msg="'entity' MUST be set when 'state=absent'.")
if state in ['present', 'absent'] and not etype:
module.fail_json(msg="'etype' MUST be set when 'state=%s'." % state)
if entry:
if etype or entity or permissions:
module.fail_json(msg="'entry' MUST NOT be set when 'entity', 'etype' or 'permissions' are set.")
if state == 'present' and not entry.count(":") in [2, 3]:
module.fail_json(msg="'entry' MUST have 3 or 4 sections divided by ':' when 'state=present'.")
if state == 'absent' and not entry.count(":") in [1, 2]:
module.fail_json(msg="'entry' MUST have 2 or 3 sections divided by ':' when 'state=absent'.")
if state == 'query':
module.fail_json(msg="'entry' MUST NOT be set when 'state=query'.")
default_flag, etype, entity, permissions = split_entry(entry)
if default_flag is not None:
default = default_flag
if get_platform().lower() == 'freebsd':
if recursive:
module.fail_json(msg="recursive is not supported on that platform.")
changed = False
msg = ""
if state == 'present':
entry = build_entry(etype, entity, permissions, use_nfsv4_acls)
command = build_command(
module, 'set', path, follow,
default, recursive, entry
)
changed = acl_changed(module, command)
if changed and not module.check_mode:
run_acl(module, command)
msg = "%s is present" % entry
elif state == 'absent':
entry = build_entry(etype, entity, use_nfsv4_acls)
command = build_command(
module, 'rm', path, follow,
default, recursive, entry
)
changed = acl_changed(module, command)
if changed and not module.check_mode:
run_acl(module, command, False)
msg = "%s is absent" % entry
elif state == 'query':
msg = "current acl"
acl = run_acl(
module,
build_command(module, 'get', path, follow, default, recursive)
)
module.exit_json(changed=changed, msg=msg, acl=acl)
if __name__ == '__main__':
main()
| cmelange/ansible | lib/ansible/modules/files/acl.py | Python | gpl-3.0 | 11,638 | [
"Brian"
] | 35d271dc1ccea7e65230a2db957f276be020058e253edd4a587e8df982ff45b0 |
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
import numpy as np
from skbio.diversity._util import _validate_counts_vector
from skbio.util._decorator import experimental
@experimental(as_of="0.4.0")
def ace(counts, rare_threshold=10):
r"""Calculate the ACE metric (Abundance-based Coverage Estimator).
The ACE metric is defined as:
.. math::
S_{ace}=S_{abund}+\frac{S_{rare}}{C_{ace}}+
\frac{F_1}{C_{ace}}\gamma^2_{ace}
where :math:`S_{abund}` is the number of abundant OTUs (with more than
`rare_threshold` individuals) when all samples are pooled,
:math:`S_{rare}` is the number of rare OTUs (with less than or equal to
`rare_threshold` individuals) when all samples are pooled, :math:`C_{ace}`
is the sample abundance coverage estimator, :math:`F_1` is the frequency of
singletons, and :math:`\gamma^2_{ace}` is the estimated coefficient of
variation for rare OTUs.
The estimated coefficient of variation is defined as (assuming
`rare_threshold` is 10, the default):
.. math::
\gamma^2_{ace}=max\left[\frac{S_{rare}}{C_{ace}}
\frac{\sum^{10}_{i=1}{{i\left(i-1\right)}}F_i}
{\left(N_{rare}\right)\left(N_{rare}-1\right)} -1,0\right]
Parameters
----------
counts : 1-D array_like, int
Vector of counts.
rare_threshold : int, optional
Threshold at which an OTU containing as many or fewer individuals will
be considered rare.
Returns
-------
double
Computed ACE metric.
Raises
------
ValueError
If every rare OTU is a singleton.
Notes
-----
ACE was first introduced in [1]_ and [2]_. The implementation here is based
on the description given in the EstimateS manual [3]_.
If no rare OTUs exist, returns the number of abundant OTUs. The default
value of 10 for `rare_threshold` is based on [4]_.
If `counts` contains zeros, indicating OTUs which are known to exist in the
environment but did not appear in the sample, they will be ignored for the
purpose of calculating the number of rare OTUs.
References
----------
.. [1] Chao, A. & S.-M Lee. 1992 Estimating the number of classes via
sample coverage. Journal of the American Statistical Association 87,
210-217.
.. [2] Chao, A., M.-C. Ma, & M. C. K. Yang. 1993. Stopping rules and
estimation for recapture debugging with unequal failure rates.
Biometrika 80, 193-201.
.. [3] http://viceroy.eeb.uconn.edu/estimates/
.. [4] Chao, A., W.-H. Hwang, Y.-C. Chen, and C.-Y. Kuo. 2000. Estimating
the number of shared species in two communities. Statistica Sinica
10:227-246.
"""
counts = _validate_counts_vector(counts)
freq_counts = np.bincount(counts)
s_rare = _otus_rare(freq_counts, rare_threshold)
singles = freq_counts[1]
if singles > 0 and singles == s_rare:
raise ValueError("The only rare OTUs are singletons, so the ACE "
"metric is undefined. EstimateS suggests using "
"bias-corrected Chao1 instead.")
s_abun = _otus_abundant(freq_counts, rare_threshold)
if s_rare == 0:
return s_abun
n_rare = _number_rare(freq_counts, rare_threshold)
c_ace = 1 - singles / n_rare
top = s_rare * _number_rare(freq_counts, rare_threshold, gamma=True)
bottom = c_ace * n_rare * (n_rare - 1)
gamma_ace = (top / bottom) - 1
if gamma_ace < 0:
gamma_ace = 0
return s_abun + (s_rare / c_ace) + ((singles / c_ace) * gamma_ace)
def _otus_rare(freq_counts, rare_threshold):
"""Count number of rare OTUs."""
return freq_counts[1:rare_threshold + 1].sum()
def _otus_abundant(freq_counts, rare_threshold):
"""Count number of abundant OTUs."""
return freq_counts[rare_threshold + 1:].sum()
def _number_rare(freq_counts, rare_threshold, gamma=False):
"""Return number of individuals in rare OTUs.
``gamma=True`` generates the ``n_rare`` used for the variation coefficient.
"""
n_rare = 0
if gamma:
for i, j in enumerate(freq_counts[:rare_threshold + 1]):
n_rare = n_rare + (i * j) * (i - 1)
else:
for i, j in enumerate(freq_counts[:rare_threshold + 1]):
n_rare = n_rare + (i * j)
return n_rare
| anderspitman/scikit-bio | skbio/diversity/alpha/_ace.py | Python | bsd-3-clause | 4,650 | [
"scikit-bio"
] | 67c42b97398082dbb16cb624ee229b6f4e9299efac87be6b4d375df6794dd878 |
#!python
"""\
Easy Install
------------
A tool for doing automatic download/extract/build of distutils-based Python
packages. For detailed documentation, see the accompanying EasyInstall.txt
file, or visit the `EasyInstall home page`__.
__ http://packages.python.org/distribute/easy_install.html
"""
import sys, os.path, zipimport, shutil, tempfile, zipfile, re, stat, random
from glob import glob
from setuptools import Command, _dont_write_bytecode
from setuptools.sandbox import run_setup
from distutils import log, dir_util
from distutils.util import convert_path, subst_vars
from distutils.sysconfig import get_python_lib, get_config_vars
from distutils.errors import DistutilsArgError, DistutilsOptionError, \
DistutilsError, DistutilsPlatformError
from distutils.command.install import INSTALL_SCHEMES, SCHEME_KEYS
from setuptools.archive_util import unpack_archive
from setuptools.package_index import PackageIndex
from setuptools.package_index import URL_SCHEME
from setuptools.command import bdist_egg, egg_info
from pkg_resources import yield_lines, normalize_path, resource_string, \
ensure_directory, get_distribution, find_distributions, \
Environment, Requirement, Distribution, \
PathMetadata, EggMetadata, WorkingSet, \
DistributionNotFound, VersionConflict, \
DEVELOP_DIST
sys_executable = os.path.normpath(sys.executable)
__all__ = [
'samefile', 'easy_install', 'PthDistributions', 'extract_wininst_cfg',
'main', 'get_exe_prefixes',
]
import site
HAS_USER_SITE = not sys.version < "2.6" and site.ENABLE_USER_SITE
def samefile(p1,p2):
if hasattr(os.path,'samefile') and (
os.path.exists(p1) and os.path.exists(p2)
):
return os.path.samefile(p1,p2)
return (
os.path.normpath(os.path.normcase(p1)) ==
os.path.normpath(os.path.normcase(p2))
)
if sys.version_info <= (3,):
def _to_ascii(s):
return s
def isascii(s):
try:
unicode(s, 'ascii')
return True
except UnicodeError:
return False
else:
def _to_ascii(s):
return s.encode('ascii')
def isascii(s):
try:
s.encode('ascii')
return True
except UnicodeError:
return False
class easy_install(Command):
"""Manage a download/build/install process"""
description = "Find/get/install Python packages"
command_consumes_arguments = True
user_options = [
('prefix=', None, "installation prefix"),
("zip-ok", "z", "install package as a zipfile"),
("multi-version", "m", "make apps have to require() a version"),
("upgrade", "U", "force upgrade (searches PyPI for latest versions)"),
("install-dir=", "d", "install package to DIR"),
("script-dir=", "s", "install scripts to DIR"),
("exclude-scripts", "x", "Don't install scripts"),
("always-copy", "a", "Copy all needed packages to install dir"),
("index-url=", "i", "base URL of Python Package Index"),
("find-links=", "f", "additional URL(s) to search for packages"),
("delete-conflicting", "D", "no longer needed; don't use this"),
("ignore-conflicts-at-my-risk", None,
"no longer needed; don't use this"),
("build-directory=", "b",
"download/extract/build in DIR; keep the results"),
('optimize=', 'O',
"also compile with optimization: -O1 for \"python -O\", "
"-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
('record=', None,
"filename in which to record list of installed files"),
('always-unzip', 'Z', "don't install as a zipfile, no matter what"),
('site-dirs=','S',"list of directories where .pth files work"),
('editable', 'e', "Install specified packages in editable form"),
('no-deps', 'N', "don't install dependencies"),
('allow-hosts=', 'H', "pattern(s) that hostnames must match"),
('local-snapshots-ok', 'l', "allow building eggs from local checkouts"),
('version', None, "print version information and exit"),
('no-find-links', None,
"Don't load find-links defined in packages being installed")
]
boolean_options = [
'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy',
'delete-conflicting', 'ignore-conflicts-at-my-risk', 'editable',
'no-deps', 'local-snapshots-ok', 'version'
]
if HAS_USER_SITE:
user_options.append(('user', None,
"install in user site-package '%s'" % site.USER_SITE))
boolean_options.append('user')
negative_opt = {'always-unzip': 'zip-ok'}
create_index = PackageIndex
def initialize_options(self):
if HAS_USER_SITE:
whereami = os.path.abspath(__file__)
self.user = whereami.startswith(site.USER_SITE)
else:
self.user = 0
self.zip_ok = self.local_snapshots_ok = None
self.install_dir = self.script_dir = self.exclude_scripts = None
self.index_url = None
self.find_links = None
self.build_directory = None
self.args = None
self.optimize = self.record = None
self.upgrade = self.always_copy = self.multi_version = None
self.editable = self.no_deps = self.allow_hosts = None
self.root = self.prefix = self.no_report = None
self.version = None
self.install_purelib = None # for pure module distributions
self.install_platlib = None # non-pure (dists w/ extensions)
self.install_headers = None # for C/C++ headers
self.install_lib = None # set to either purelib or platlib
self.install_scripts = None
self.install_data = None
self.install_base = None
self.install_platbase = None
if HAS_USER_SITE:
self.install_userbase = site.USER_BASE
self.install_usersite = site.USER_SITE
else:
self.install_userbase = None
self.install_usersite = None
self.no_find_links = None
# Options not specifiable via command line
self.package_index = None
self.pth_file = self.always_copy_from = None
self.delete_conflicting = None
self.ignore_conflicts_at_my_risk = None
self.site_dirs = None
self.installed_projects = {}
self.sitepy_installed = False
# Always read easy_install options, even if we are subclassed, or have
# an independent instance created. This ensures that defaults will
# always come from the standard configuration file(s)' "easy_install"
# section, even if this is a "develop" or "install" command, or some
# other embedding.
self._dry_run = None
self.verbose = self.distribution.verbose
self.distribution._set_command_options(
self, self.distribution.get_option_dict('easy_install')
)
def delete_blockers(self, blockers):
for filename in blockers:
if os.path.exists(filename) or os.path.islink(filename):
log.info("Deleting %s", filename)
if not self.dry_run:
if os.path.isdir(filename) and not os.path.islink(filename):
rmtree(filename)
else:
os.unlink(filename)
def finalize_options(self):
if self.version:
print 'distribute %s' % get_distribution('distribute').version
sys.exit()
py_version = sys.version.split()[0]
prefix, exec_prefix = get_config_vars('prefix', 'exec_prefix')
self.config_vars = {'dist_name': self.distribution.get_name(),
'dist_version': self.distribution.get_version(),
'dist_fullname': self.distribution.get_fullname(),
'py_version': py_version,
'py_version_short': py_version[0:3],
'py_version_nodot': py_version[0] + py_version[2],
'sys_prefix': prefix,
'prefix': prefix,
'sys_exec_prefix': exec_prefix,
'exec_prefix': exec_prefix,
}
if HAS_USER_SITE:
self.config_vars['userbase'] = self.install_userbase
self.config_vars['usersite'] = self.install_usersite
# fix the install_dir if "--user" was used
#XXX: duplicate of the code in the setup command
if self.user and HAS_USER_SITE:
self.create_home_path()
if self.install_userbase is None:
raise DistutilsPlatformError(
"User base directory is not specified")
self.install_base = self.install_platbase = self.install_userbase
if os.name == 'posix':
self.select_scheme("unix_user")
else:
self.select_scheme(os.name + "_user")
self.expand_basedirs()
self.expand_dirs()
self._expand('install_dir','script_dir','build_directory','site_dirs')
# If a non-default installation directory was specified, default the
# script directory to match it.
if self.script_dir is None:
self.script_dir = self.install_dir
if self.no_find_links is None:
self.no_find_links = False
# Let install_dir get set by install_lib command, which in turn
# gets its info from the install command, and takes into account
# --prefix and --home and all that other crud.
self.set_undefined_options('install_lib',
('install_dir','install_dir')
)
# Likewise, set default script_dir from 'install_scripts.install_dir'
self.set_undefined_options('install_scripts',
('install_dir', 'script_dir')
)
if self.user and self.install_purelib:
self.install_dir = self.install_purelib
self.script_dir = self.install_scripts
# default --record from the install command
self.set_undefined_options('install', ('record', 'record'))
normpath = map(normalize_path, sys.path)
self.all_site_dirs = get_site_dirs()
if self.site_dirs is not None:
site_dirs = [
os.path.expanduser(s.strip()) for s in self.site_dirs.split(',')
]
for d in site_dirs:
if not os.path.isdir(d):
log.warn("%s (in --site-dirs) does not exist", d)
elif normalize_path(d) not in normpath:
raise DistutilsOptionError(
d+" (in --site-dirs) is not on sys.path"
)
else:
self.all_site_dirs.append(normalize_path(d))
if not self.editable: self.check_site_dir()
self.index_url = self.index_url or "http://pypi.python.org/simple"
self.shadow_path = self.all_site_dirs[:]
for path_item in self.install_dir, normalize_path(self.script_dir):
if path_item not in self.shadow_path:
self.shadow_path.insert(0, path_item)
if self.allow_hosts is not None:
hosts = [s.strip() for s in self.allow_hosts.split(',')]
else:
hosts = ['*']
if self.package_index is None:
self.package_index = self.create_index(
self.index_url, search_path = self.shadow_path, hosts=hosts,
)
self.local_index = Environment(self.shadow_path+sys.path)
if self.find_links is not None:
if isinstance(self.find_links, basestring):
self.find_links = self.find_links.split()
else:
self.find_links = []
if self.local_snapshots_ok:
self.package_index.scan_egg_links(self.shadow_path+sys.path)
if not self.no_find_links:
self.package_index.add_find_links(self.find_links)
self.set_undefined_options('install_lib', ('optimize','optimize'))
if not isinstance(self.optimize,int):
try:
self.optimize = int(self.optimize)
if not (0 <= self.optimize <= 2): raise ValueError
except ValueError:
raise DistutilsOptionError("--optimize must be 0, 1, or 2")
if self.delete_conflicting and self.ignore_conflicts_at_my_risk:
raise DistutilsOptionError(
"Can't use both --delete-conflicting and "
"--ignore-conflicts-at-my-risk at the same time"
)
if self.editable and not self.build_directory:
raise DistutilsArgError(
"Must specify a build directory (-b) when using --editable"
)
if not self.args:
raise DistutilsArgError(
"No urls, filenames, or requirements specified (see --help)")
self.outputs = []
def _expand_attrs(self, attrs):
for attr in attrs:
val = getattr(self, attr)
if val is not None:
if os.name == 'posix' or os.name == 'nt':
val = os.path.expanduser(val)
val = subst_vars(val, self.config_vars)
setattr(self, attr, val)
def expand_basedirs(self):
"""Calls `os.path.expanduser` on install_base, install_platbase and
root."""
self._expand_attrs(['install_base', 'install_platbase', 'root'])
def expand_dirs(self):
"""Calls `os.path.expanduser` on install dirs."""
self._expand_attrs(['install_purelib', 'install_platlib',
'install_lib', 'install_headers',
'install_scripts', 'install_data',])
def run(self):
if self.verbose != self.distribution.verbose:
log.set_verbosity(self.verbose)
try:
for spec in self.args:
self.easy_install(spec, not self.no_deps)
if self.record:
outputs = self.outputs
if self.root: # strip any package prefix
root_len = len(self.root)
for counter in xrange(len(outputs)):
outputs[counter] = outputs[counter][root_len:]
from distutils import file_util
self.execute(
file_util.write_file, (self.record, outputs),
"writing list of installed files to '%s'" %
self.record
)
self.warn_deprecated_options()
finally:
log.set_verbosity(self.distribution.verbose)
def pseudo_tempname(self):
"""Return a pseudo-tempname base in the install directory.
This code is intentionally naive; if a malicious party can write to
the target directory you're already in deep doodoo.
"""
try:
pid = os.getpid()
except:
pid = random.randint(0,sys.maxint)
return os.path.join(self.install_dir, "test-easy-install-%s" % pid)
def warn_deprecated_options(self):
if self.delete_conflicting or self.ignore_conflicts_at_my_risk:
log.warn(
"Note: The -D, --delete-conflicting and"
" --ignore-conflicts-at-my-risk no longer have any purpose"
" and should not be used."
)
def check_site_dir(self):
"""Verify that self.install_dir is .pth-capable dir, if needed"""
print 'install_dir', self.install_dir
instdir = normalize_path(self.install_dir)
pth_file = os.path.join(instdir,'easy-install.pth')
# Is it a configured, PYTHONPATH, implicit, or explicit site dir?
is_site_dir = instdir in self.all_site_dirs
if not is_site_dir:
# No? Then directly test whether it does .pth file processing
is_site_dir = self.check_pth_processing()
else:
# make sure we can write to target dir
testfile = self.pseudo_tempname()+'.write-test'
test_exists = os.path.exists(testfile)
try:
if test_exists: os.unlink(testfile)
open(testfile,'w').close()
os.unlink(testfile)
except (OSError,IOError):
self.cant_write_to_target()
if not is_site_dir and not self.multi_version:
# Can't install non-multi to non-site dir
raise DistutilsError(self.no_default_version_msg())
if is_site_dir:
if self.pth_file is None:
self.pth_file = PthDistributions(pth_file, self.all_site_dirs)
else:
self.pth_file = None
PYTHONPATH = os.environ.get('PYTHONPATH','').split(os.pathsep)
if instdir not in map(normalize_path, filter(None,PYTHONPATH)):
# only PYTHONPATH dirs need a site.py, so pretend it's there
self.sitepy_installed = True
elif self.multi_version and not os.path.exists(pth_file):
self.sitepy_installed = True # don't need site.py in this case
self.pth_file = None # and don't create a .pth file
self.install_dir = instdir
def cant_write_to_target(self):
msg = """can't create or remove files in install directory
The following error occurred while trying to add or remove files in the
installation directory:
%s
The installation directory you specified (via --install-dir, --prefix, or
the distutils default setting) was:
%s
""" % (sys.exc_info()[1], self.install_dir,)
if not os.path.exists(self.install_dir):
msg += """
This directory does not currently exist. Please create it and try again, or
choose a different installation directory (using the -d or --install-dir
option).
"""
else:
msg += """
Perhaps your account does not have write access to this directory? If the
installation directory is a system-owned directory, you may need to sign in
as the administrator or "root" account. If you do not have administrative
access to this machine, you may wish to choose a different installation
directory, preferably one that is listed in your PYTHONPATH environment
variable.
For information on other options, you may wish to consult the
documentation at:
http://packages.python.org/distribute/easy_install.html
Please make the appropriate changes for your system and try again.
"""
raise DistutilsError(msg)
def check_pth_processing(self):
"""Empirically verify whether .pth files are supported in inst. dir"""
instdir = self.install_dir
log.info("Checking .pth file support in %s", instdir)
pth_file = self.pseudo_tempname()+".pth"
ok_file = pth_file+'.ok'
ok_exists = os.path.exists(ok_file)
try:
if ok_exists: os.unlink(ok_file)
dirname = os.path.dirname(ok_file)
if not os.path.exists(dirname):
os.makedirs(dirname)
f = open(pth_file,'w')
except (OSError,IOError):
self.cant_write_to_target()
else:
try:
f.write("import os;open(%r,'w').write('OK')\n" % (ok_file,))
f.close(); f=None
executable = sys.executable
if os.name=='nt':
dirname,basename = os.path.split(executable)
alt = os.path.join(dirname,'pythonw.exe')
if basename.lower()=='python.exe' and os.path.exists(alt):
# use pythonw.exe to avoid opening a console window
executable = alt
from distutils.spawn import spawn
spawn([executable,'-E','-c','pass'],0)
if os.path.exists(ok_file):
log.info(
"TEST PASSED: %s appears to support .pth files",
instdir
)
return True
finally:
if f: f.close()
if os.path.exists(ok_file): os.unlink(ok_file)
if os.path.exists(pth_file): os.unlink(pth_file)
if not self.multi_version:
log.warn("TEST FAILED: %s does NOT support .pth files", instdir)
return False
def install_egg_scripts(self, dist):
"""Write all the scripts for `dist`, unless scripts are excluded"""
if not self.exclude_scripts and dist.metadata_isdir('scripts'):
for script_name in dist.metadata_listdir('scripts'):
self.install_script(
dist, script_name,
dist.get_metadata('scripts/'+script_name)
)
self.install_wrapper_scripts(dist)
def add_output(self, path):
if os.path.isdir(path):
for base, dirs, files in os.walk(path):
for filename in files:
self.outputs.append(os.path.join(base,filename))
else:
self.outputs.append(path)
def not_editable(self, spec):
if self.editable:
raise DistutilsArgError(
"Invalid argument %r: you can't use filenames or URLs "
"with --editable (except via the --find-links option)."
% (spec,)
)
def check_editable(self,spec):
if not self.editable:
return
if os.path.exists(os.path.join(self.build_directory, spec.key)):
raise DistutilsArgError(
"%r already exists in %s; can't do a checkout there" %
(spec.key, self.build_directory)
)
def easy_install(self, spec, deps=False):
tmpdir = tempfile.mkdtemp(prefix="easy_install-")
download = None
if not self.editable: self.install_site_py()
try:
if not isinstance(spec,Requirement):
if URL_SCHEME(spec):
# It's a url, download it to tmpdir and process
self.not_editable(spec)
download = self.package_index.download(spec, tmpdir)
return self.install_item(None, download, tmpdir, deps, True)
elif os.path.exists(spec):
# Existing file or directory, just process it directly
self.not_editable(spec)
return self.install_item(None, spec, tmpdir, deps, True)
else:
spec = parse_requirement_arg(spec)
self.check_editable(spec)
dist = self.package_index.fetch_distribution(
spec, tmpdir, self.upgrade, self.editable, not self.always_copy,
self.local_index
)
if dist is None:
msg = "Could not find suitable distribution for %r" % spec
if self.always_copy:
msg+=" (--always-copy skips system and development eggs)"
raise DistutilsError(msg)
elif dist.precedence==DEVELOP_DIST:
# .egg-info dists don't need installing, just process deps
self.process_distribution(spec, dist, deps, "Using")
return dist
else:
return self.install_item(spec, dist.location, tmpdir, deps)
finally:
if os.path.exists(tmpdir):
rmtree(tmpdir)
def install_item(self, spec, download, tmpdir, deps, install_needed=False):
# Installation is also needed if file in tmpdir or is not an egg
install_needed = install_needed or self.always_copy
install_needed = install_needed or os.path.dirname(download) == tmpdir
install_needed = install_needed or not download.endswith('.egg')
install_needed = install_needed or (
self.always_copy_from is not None and
os.path.dirname(normalize_path(download)) ==
normalize_path(self.always_copy_from)
)
if spec and not install_needed:
# at this point, we know it's a local .egg, we just don't know if
# it's already installed.
for dist in self.local_index[spec.project_name]:
if dist.location==download:
break
else:
install_needed = True # it's not in the local index
log.info("Processing %s", os.path.basename(download))
if install_needed:
dists = self.install_eggs(spec, download, tmpdir)
for dist in dists:
self.process_distribution(spec, dist, deps)
else:
dists = [self.check_conflicts(self.egg_distribution(download))]
self.process_distribution(spec, dists[0], deps, "Using")
if spec is not None:
for dist in dists:
if dist in spec:
return dist
def select_scheme(self, name):
"""Sets the install directories by applying the install schemes."""
# it's the caller's problem if they supply a bad name!
scheme = INSTALL_SCHEMES[name]
for key in SCHEME_KEYS:
attrname = 'install_' + key
if getattr(self, attrname) is None:
setattr(self, attrname, scheme[key])
def process_distribution(self, requirement, dist, deps=True, *info):
self.update_pth(dist)
self.package_index.add(dist)
self.local_index.add(dist)
if not self.editable:
self.install_egg_scripts(dist)
self.installed_projects[dist.key] = dist
log.info(self.installation_report(requirement, dist, *info))
if (dist.has_metadata('dependency_links.txt') and
not self.no_find_links):
self.package_index.add_find_links(
dist.get_metadata_lines('dependency_links.txt')
)
if not deps and not self.always_copy:
return
elif requirement is not None and dist.key != requirement.key:
log.warn("Skipping dependencies for %s", dist)
return # XXX this is not the distribution we were looking for
elif requirement is None or dist not in requirement:
# if we wound up with a different version, resolve what we've got
distreq = dist.as_requirement()
requirement = requirement or distreq
requirement = Requirement(
distreq.project_name, distreq.specs, requirement.extras
)
log.info("Processing dependencies for %s", requirement)
try:
distros = WorkingSet([]).resolve(
[requirement], self.local_index, self.easy_install
)
except DistributionNotFound, e:
raise DistutilsError(
"Could not find required distribution %s" % e.args
)
except VersionConflict, e:
raise DistutilsError(
"Installed distribution %s conflicts with requirement %s"
% e.args
)
if self.always_copy or self.always_copy_from:
# Force all the relevant distros to be copied or activated
for dist in distros:
if dist.key not in self.installed_projects:
self.easy_install(dist.as_requirement())
log.info("Finished processing dependencies for %s", requirement)
def should_unzip(self, dist):
if self.zip_ok is not None:
return not self.zip_ok
if dist.has_metadata('not-zip-safe'):
return True
if not dist.has_metadata('zip-safe'):
return True
return True
def maybe_move(self, spec, dist_filename, setup_base):
dst = os.path.join(self.build_directory, spec.key)
if os.path.exists(dst):
log.warn(
"%r already exists in %s; build directory %s will not be kept",
spec.key, self.build_directory, setup_base
)
return setup_base
if os.path.isdir(dist_filename):
setup_base = dist_filename
else:
if os.path.dirname(dist_filename)==setup_base:
os.unlink(dist_filename) # get it out of the tmp dir
contents = os.listdir(setup_base)
if len(contents)==1:
dist_filename = os.path.join(setup_base,contents[0])
if os.path.isdir(dist_filename):
# if the only thing there is a directory, move it instead
setup_base = dist_filename
ensure_directory(dst); shutil.move(setup_base, dst)
return dst
def install_wrapper_scripts(self, dist):
if not self.exclude_scripts:
for args in get_script_args(dist):
self.write_script(*args)
def install_script(self, dist, script_name, script_text, dev_path=None):
"""Generate a legacy script wrapper and install it"""
spec = str(dist.as_requirement())
is_script = is_python_script(script_text, script_name)
if is_script and dev_path:
script_text = get_script_header(script_text) + (
"# EASY-INSTALL-DEV-SCRIPT: %(spec)r,%(script_name)r\n"
"__requires__ = %(spec)r\n"
"from pkg_resources import require; require(%(spec)r)\n"
"del require\n"
"__file__ = %(dev_path)r\n"
"execfile(__file__)\n"
) % locals()
elif is_script:
script_text = get_script_header(script_text) + (
"# EASY-INSTALL-SCRIPT: %(spec)r,%(script_name)r\n"
"__requires__ = %(spec)r\n"
"import pkg_resources\n"
"pkg_resources.run_script(%(spec)r, %(script_name)r)\n"
) % locals()
self.write_script(script_name, _to_ascii(script_text), 'b')
def write_script(self, script_name, contents, mode="t", blockers=()):
"""Write an executable file to the scripts directory"""
self.delete_blockers( # clean up old .py/.pyw w/o a script
[os.path.join(self.script_dir,x) for x in blockers])
log.info("Installing %s script to %s", script_name, self.script_dir)
target = os.path.join(self.script_dir, script_name)
self.add_output(target)
if not self.dry_run:
ensure_directory(target)
f = open(target,"w"+mode)
f.write(contents)
f.close()
chmod(target,0755)
def install_eggs(self, spec, dist_filename, tmpdir):
# .egg dirs or files are already built, so just return them
if dist_filename.lower().endswith('.egg'):
return [self.install_egg(dist_filename, tmpdir)]
elif dist_filename.lower().endswith('.exe'):
return [self.install_exe(dist_filename, tmpdir)]
# Anything else, try to extract and build
setup_base = tmpdir
if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'):
unpack_archive(dist_filename, tmpdir, self.unpack_progress)
elif os.path.isdir(dist_filename):
setup_base = os.path.abspath(dist_filename)
if (setup_base.startswith(tmpdir) # something we downloaded
and self.build_directory and spec is not None
):
setup_base = self.maybe_move(spec, dist_filename, setup_base)
# Find the setup.py file
setup_script = os.path.join(setup_base, 'setup.py')
if not os.path.exists(setup_script):
setups = glob(os.path.join(setup_base, '*', 'setup.py'))
if not setups:
raise DistutilsError(
"Couldn't find a setup script in %s" % os.path.abspath(dist_filename)
)
if len(setups)>1:
raise DistutilsError(
"Multiple setup scripts in %s" % os.path.abspath(dist_filename)
)
setup_script = setups[0]
# Now run it, and return the result
if self.editable:
log.info(self.report_editable(spec, setup_script))
return []
else:
return self.build_and_install(setup_script, setup_base)
def egg_distribution(self, egg_path):
if os.path.isdir(egg_path):
metadata = PathMetadata(egg_path,os.path.join(egg_path,'EGG-INFO'))
else:
metadata = EggMetadata(zipimport.zipimporter(egg_path))
return Distribution.from_filename(egg_path,metadata=metadata)
def install_egg(self, egg_path, tmpdir):
destination = os.path.join(self.install_dir,os.path.basename(egg_path))
destination = os.path.abspath(destination)
if not self.dry_run:
ensure_directory(destination)
dist = self.egg_distribution(egg_path)
self.check_conflicts(dist)
if not samefile(egg_path, destination):
if os.path.isdir(destination) and not os.path.islink(destination):
dir_util.remove_tree(destination, dry_run=self.dry_run)
elif os.path.exists(destination):
self.execute(os.unlink,(destination,),"Removing "+destination)
uncache_zipdir(destination)
if os.path.isdir(egg_path):
if egg_path.startswith(tmpdir):
f,m = shutil.move, "Moving"
else:
f,m = shutil.copytree, "Copying"
elif self.should_unzip(dist):
self.mkpath(destination)
f,m = self.unpack_and_compile, "Extracting"
elif egg_path.startswith(tmpdir):
f,m = shutil.move, "Moving"
else:
f,m = shutil.copy2, "Copying"
self.execute(f, (egg_path, destination),
(m+" %s to %s") %
(os.path.basename(egg_path),os.path.dirname(destination)))
self.add_output(destination)
return self.egg_distribution(destination)
def install_exe(self, dist_filename, tmpdir):
# See if it's valid, get data
cfg = extract_wininst_cfg(dist_filename)
if cfg is None:
raise DistutilsError(
"%s is not a valid distutils Windows .exe" % dist_filename
)
# Create a dummy distribution object until we build the real distro
dist = Distribution(None,
project_name=cfg.get('metadata','name'),
version=cfg.get('metadata','version'), platform="win32"
)
# Convert the .exe to an unpacked egg
egg_path = dist.location = os.path.join(tmpdir, dist.egg_name()+'.egg')
egg_tmp = egg_path+'.tmp'
egg_info = os.path.join(egg_tmp, 'EGG-INFO')
pkg_inf = os.path.join(egg_info, 'PKG-INFO')
ensure_directory(pkg_inf) # make sure EGG-INFO dir exists
dist._provider = PathMetadata(egg_tmp, egg_info) # XXX
self.exe_to_egg(dist_filename, egg_tmp)
# Write EGG-INFO/PKG-INFO
if not os.path.exists(pkg_inf):
f = open(pkg_inf,'w')
f.write('Metadata-Version: 1.0\n')
for k,v in cfg.items('metadata'):
if k<>'target_version':
f.write('%s: %s\n' % (k.replace('_','-').title(), v))
f.close()
script_dir = os.path.join(egg_info,'scripts')
self.delete_blockers( # delete entry-point scripts to avoid duping
[os.path.join(script_dir,args[0]) for args in get_script_args(dist)]
)
# Build .egg file from tmpdir
bdist_egg.make_zipfile(
egg_path, egg_tmp, verbose=self.verbose, dry_run=self.dry_run
)
# install the .egg
return self.install_egg(egg_path, tmpdir)
def exe_to_egg(self, dist_filename, egg_tmp):
"""Extract a bdist_wininst to the directories an egg would use"""
# Check for .pth file and set up prefix translations
prefixes = get_exe_prefixes(dist_filename)
to_compile = []
native_libs = []
top_level = {}
def process(src,dst):
s = src.lower()
for old,new in prefixes:
if s.startswith(old):
src = new+src[len(old):]
parts = src.split('/')
dst = os.path.join(egg_tmp, *parts)
dl = dst.lower()
if dl.endswith('.pyd') or dl.endswith('.dll'):
parts[-1] = bdist_egg.strip_module(parts[-1])
top_level[os.path.splitext(parts[0])[0]] = 1
native_libs.append(src)
elif dl.endswith('.py') and old!='SCRIPTS/':
top_level[os.path.splitext(parts[0])[0]] = 1
to_compile.append(dst)
return dst
if not src.endswith('.pth'):
log.warn("WARNING: can't process %s", src)
return None
# extract, tracking .pyd/.dll->native_libs and .py -> to_compile
unpack_archive(dist_filename, egg_tmp, process)
stubs = []
for res in native_libs:
if res.lower().endswith('.pyd'): # create stubs for .pyd's
parts = res.split('/')
resource = parts[-1]
parts[-1] = bdist_egg.strip_module(parts[-1])+'.py'
pyfile = os.path.join(egg_tmp, *parts)
to_compile.append(pyfile); stubs.append(pyfile)
bdist_egg.write_stub(resource, pyfile)
self.byte_compile(to_compile) # compile .py's
bdist_egg.write_safety_flag(os.path.join(egg_tmp,'EGG-INFO'),
bdist_egg.analyze_egg(egg_tmp, stubs)) # write zip-safety flag
for name in 'top_level','native_libs':
if locals()[name]:
txt = os.path.join(egg_tmp, 'EGG-INFO', name+'.txt')
if not os.path.exists(txt):
f = open(txt,'w')
f.write('\n'.join(locals()[name])+'\n')
f.close()
def check_conflicts(self, dist):
"""Verify that there are no conflicting "old-style" packages"""
return dist # XXX temporarily disable until new strategy is stable
from imp import find_module, get_suffixes
from glob import glob
blockers = []
names = dict.fromkeys(dist._get_metadata('top_level.txt')) # XXX private attr
exts = {'.pyc':1, '.pyo':1} # get_suffixes() might leave one out
for ext,mode,typ in get_suffixes():
exts[ext] = 1
for path,files in expand_paths([self.install_dir]+self.all_site_dirs):
for filename in files:
base,ext = os.path.splitext(filename)
if base in names:
if not ext:
# no extension, check for package
try:
f, filename, descr = find_module(base, [path])
except ImportError:
continue
else:
if f: f.close()
if filename not in blockers:
blockers.append(filename)
elif ext in exts and base!='site': # XXX ugh
blockers.append(os.path.join(path,filename))
if blockers:
self.found_conflicts(dist, blockers)
return dist
def found_conflicts(self, dist, blockers):
if self.delete_conflicting:
log.warn("Attempting to delete conflicting packages:")
return self.delete_blockers(blockers)
msg = """\
-------------------------------------------------------------------------
CONFLICT WARNING:
The following modules or packages have the same names as modules or
packages being installed, and will be *before* the installed packages in
Python's search path. You MUST remove all of the relevant files and
directories before you will be able to use the package(s) you are
installing:
%s
""" % '\n '.join(blockers)
if self.ignore_conflicts_at_my_risk:
msg += """\
(Note: you can run EasyInstall on '%s' with the
--delete-conflicting option to attempt deletion of the above files
and/or directories.)
""" % dist.project_name
else:
msg += """\
Note: you can attempt this installation again with EasyInstall, and use
either the --delete-conflicting (-D) option or the
--ignore-conflicts-at-my-risk option, to either delete the above files
and directories, or to ignore the conflicts, respectively. Note that if
you ignore the conflicts, the installed package(s) may not work.
"""
msg += """\
-------------------------------------------------------------------------
"""
sys.stderr.write(msg)
sys.stderr.flush()
if not self.ignore_conflicts_at_my_risk:
raise DistutilsError("Installation aborted due to conflicts")
def installation_report(self, req, dist, what="Installed"):
"""Helpful installation message for display to package users"""
msg = "\n%(what)s %(eggloc)s%(extras)s"
if self.multi_version and not self.no_report:
msg += """
Because this distribution was installed --multi-version, before you can
import modules from this package in an application, you will need to
'import pkg_resources' and then use a 'require()' call similar to one of
these examples, in order to select the desired version:
pkg_resources.require("%(name)s") # latest installed version
pkg_resources.require("%(name)s==%(version)s") # this exact version
pkg_resources.require("%(name)s>=%(version)s") # this version or higher
"""
if self.install_dir not in map(normalize_path,sys.path):
msg += """
Note also that the installation directory must be on sys.path at runtime for
this to work. (e.g. by being the application's script directory, by being on
PYTHONPATH, or by being added to sys.path by your code.)
"""
eggloc = dist.location
name = dist.project_name
version = dist.version
extras = '' # TODO: self.report_extras(req, dist)
return msg % locals()
def report_editable(self, spec, setup_script):
dirname = os.path.dirname(setup_script)
python = sys.executable
return """\nExtracted editable version of %(spec)s to %(dirname)s
If it uses setuptools in its setup script, you can activate it in
"development" mode by going to that directory and running::
%(python)s setup.py develop
See the setuptools documentation for the "develop" command for more info.
""" % locals()
def run_setup(self, setup_script, setup_base, args):
sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg)
sys.modules.setdefault('distutils.command.egg_info', egg_info)
args = list(args)
if self.verbose>2:
v = 'v' * (self.verbose - 1)
args.insert(0,'-'+v)
elif self.verbose<2:
args.insert(0,'-q')
if self.dry_run:
args.insert(0,'-n')
log.info(
"Running %s %s", setup_script[len(setup_base)+1:], ' '.join(args)
)
try:
run_setup(setup_script, args)
except SystemExit, v:
raise DistutilsError("Setup script exited with %s" % (v.args[0],))
def build_and_install(self, setup_script, setup_base):
args = ['bdist_egg', '--dist-dir']
dist_dir = tempfile.mkdtemp(
prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script)
)
try:
args.append(dist_dir)
self.run_setup(setup_script, setup_base, args)
all_eggs = Environment([dist_dir])
eggs = []
for key in all_eggs:
for dist in all_eggs[key]:
eggs.append(self.install_egg(dist.location, setup_base))
if not eggs and not self.dry_run:
log.warn("No eggs found in %s (setup script problem?)",
dist_dir)
return eggs
finally:
rmtree(dist_dir)
log.set_verbosity(self.verbose) # restore our log verbosity
def update_pth(self,dist):
if self.pth_file is None:
return
for d in self.pth_file[dist.key]: # drop old entries
if self.multi_version or d.location != dist.location:
log.info("Removing %s from easy-install.pth file", d)
self.pth_file.remove(d)
if d.location in self.shadow_path:
self.shadow_path.remove(d.location)
if not self.multi_version:
if dist.location in self.pth_file.paths:
log.info(
"%s is already the active version in easy-install.pth",
dist
)
else:
log.info("Adding %s to easy-install.pth file", dist)
self.pth_file.add(dist) # add new entry
if dist.location not in self.shadow_path:
self.shadow_path.append(dist.location)
if not self.dry_run:
self.pth_file.save()
if dist.key=='distribute':
# Ensure that setuptools itself never becomes unavailable!
# XXX should this check for latest version?
filename = os.path.join(self.install_dir,'setuptools.pth')
if os.path.islink(filename): os.unlink(filename)
f = open(filename, 'wt')
f.write(self.pth_file.make_relative(dist.location)+'\n')
f.close()
def unpack_progress(self, src, dst):
# Progress filter for unpacking
log.debug("Unpacking %s to %s", src, dst)
return dst # only unpack-and-compile skips files for dry run
def unpack_and_compile(self, egg_path, destination):
to_compile = []; to_chmod = []
def pf(src,dst):
if dst.endswith('.py') and not src.startswith('EGG-INFO/'):
to_compile.append(dst)
to_chmod.append(dst)
elif dst.endswith('.dll') or dst.endswith('.so'):
to_chmod.append(dst)
self.unpack_progress(src,dst)
return not self.dry_run and dst or None
unpack_archive(egg_path, destination, pf)
self.byte_compile(to_compile)
if not self.dry_run:
for f in to_chmod:
mode = ((os.stat(f)[stat.ST_MODE]) | 0555) & 07755
chmod(f, mode)
def byte_compile(self, to_compile):
if _dont_write_bytecode:
self.warn('byte-compiling is disabled, skipping.')
return
from distutils.util import byte_compile
try:
# try to make the byte compile messages quieter
log.set_verbosity(self.verbose - 1)
byte_compile(to_compile, optimize=0, force=1, dry_run=self.dry_run)
if self.optimize:
byte_compile(
to_compile, optimize=self.optimize, force=1,
dry_run=self.dry_run
)
finally:
log.set_verbosity(self.verbose) # restore original verbosity
def no_default_version_msg(self):
return """bad install directory or PYTHONPATH
You are attempting to install a package to a directory that is not
on PYTHONPATH and which Python does not read ".pth" files from. The
installation directory you specified (via --install-dir, --prefix, or
the distutils default setting) was:
%s
and your PYTHONPATH environment variable currently contains:
%r
Here are some of your options for correcting the problem:
* You can choose a different installation directory, i.e., one that is
on PYTHONPATH or supports .pth files
* You can add the installation directory to the PYTHONPATH environment
variable. (It must then also be on PYTHONPATH whenever you run
Python and want to use the package(s) you are installing.)
* You can set up the installation directory to support ".pth" files by
using one of the approaches described here:
http://packages.python.org/distribute/easy_install.html#custom-installation-locations
Please make the appropriate changes for your system and try again.""" % (
self.install_dir, os.environ.get('PYTHONPATH','')
)
def install_site_py(self):
"""Make sure there's a site.py in the target dir, if needed"""
if self.sitepy_installed:
return # already did it, or don't need to
sitepy = os.path.join(self.install_dir, "site.py")
source = resource_string(Requirement.parse("distribute"), "site.py")
current = ""
if os.path.exists(sitepy):
log.debug("Checking existing site.py in %s", self.install_dir)
f = open(sitepy,'rb')
current = f.read()
# we want str, not bytes
if sys.version_info >= (3,):
current = current.decode()
f.close()
if not current.startswith('def __boot():'):
raise DistutilsError(
"%s is not a setuptools-generated site.py; please"
" remove it." % sitepy
)
if current != source:
log.info("Creating %s", sitepy)
if not self.dry_run:
ensure_directory(sitepy)
f = open(sitepy,'wb')
f.write(source)
f.close()
self.byte_compile([sitepy])
self.sitepy_installed = True
def create_home_path(self):
"""Create directories under ~."""
if not self.user:
return
home = convert_path(os.path.expanduser("~"))
for name, path in self.config_vars.iteritems():
if path.startswith(home) and not os.path.isdir(path):
self.debug_print("os.makedirs('%s', 0700)" % path)
os.makedirs(path, 0700)
INSTALL_SCHEMES = dict(
posix = dict(
install_dir = '$base/lib/python$py_version_short/site-packages',
script_dir = '$base/bin',
),
)
DEFAULT_SCHEME = dict(
install_dir = '$base/Lib/site-packages',
script_dir = '$base/Scripts',
)
def _expand(self, *attrs):
config_vars = self.get_finalized_command('install').config_vars
if self.prefix:
# Set default install_dir/scripts from --prefix
config_vars = config_vars.copy()
config_vars['base'] = self.prefix
scheme = self.INSTALL_SCHEMES.get(os.name,self.DEFAULT_SCHEME)
for attr,val in scheme.items():
if getattr(self,attr,None) is None:
setattr(self,attr,val)
from distutils.util import subst_vars
for attr in attrs:
val = getattr(self, attr)
if val is not None:
val = subst_vars(val, config_vars)
if os.name == 'posix':
val = os.path.expanduser(val)
setattr(self, attr, val)
def get_site_dirs():
# return a list of 'site' dirs
sitedirs = filter(None,os.environ.get('PYTHONPATH','').split(os.pathsep))
prefixes = [sys.prefix]
if sys.exec_prefix != sys.prefix:
prefixes.append(sys.exec_prefix)
for prefix in prefixes:
if prefix:
if sys.platform in ('os2emx', 'riscos'):
sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
elif os.sep == '/':
sitedirs.extend([os.path.join(prefix,
"lib",
"python" + sys.version[:3],
"site-packages"),
os.path.join(prefix, "lib", "site-python")])
else:
sitedirs.extend(
[prefix, os.path.join(prefix, "lib", "site-packages")]
)
if sys.platform == 'darwin':
# for framework builds *only* we add the standard Apple
# locations. Currently only per-user, but /Library and
# /Network/Library could be added too
if 'Python.framework' in prefix:
home = os.environ.get('HOME')
if home:
sitedirs.append(
os.path.join(home,
'Library',
'Python',
sys.version[:3],
'site-packages'))
for plat_specific in (0,1):
site_lib = get_python_lib(plat_specific)
if site_lib not in sitedirs: sitedirs.append(site_lib)
if HAS_USER_SITE:
sitedirs.append(site.USER_SITE)
sitedirs = map(normalize_path, sitedirs)
return sitedirs
def expand_paths(inputs):
"""Yield sys.path directories that might contain "old-style" packages"""
seen = {}
for dirname in inputs:
dirname = normalize_path(dirname)
if dirname in seen:
continue
seen[dirname] = 1
if not os.path.isdir(dirname):
continue
files = os.listdir(dirname)
yield dirname, files
for name in files:
if not name.endswith('.pth'):
# We only care about the .pth files
continue
if name in ('easy-install.pth','setuptools.pth'):
# Ignore .pth files that we control
continue
# Read the .pth file
f = open(os.path.join(dirname,name))
lines = list(yield_lines(f))
f.close()
# Yield existing non-dupe, non-import directory lines from it
for line in lines:
if not line.startswith("import"):
line = normalize_path(line.rstrip())
if line not in seen:
seen[line] = 1
if not os.path.isdir(line):
continue
yield line, os.listdir(line)
def extract_wininst_cfg(dist_filename):
"""Extract configuration data from a bdist_wininst .exe
Returns a ConfigParser.RawConfigParser, or None
"""
f = open(dist_filename,'rb')
try:
endrec = zipfile._EndRecData(f)
if endrec is None:
return None
prepended = (endrec[9] - endrec[5]) - endrec[6]
if prepended < 12: # no wininst data here
return None
f.seek(prepended-12)
import struct, StringIO, ConfigParser
tag, cfglen, bmlen = struct.unpack("<iii",f.read(12))
if tag not in (0x1234567A, 0x1234567B):
return None # not a valid tag
f.seek(prepended-(12+cfglen))
cfg = ConfigParser.RawConfigParser({'version':'','target_version':''})
try:
cfg.readfp(StringIO.StringIO(f.read(cfglen).split(chr(0),1)[0]))
except ConfigParser.Error:
return None
if not cfg.has_section('metadata') or not cfg.has_section('Setup'):
return None
return cfg
finally:
f.close()
def get_exe_prefixes(exe_filename):
"""Get exe->egg path translations for a given .exe file"""
prefixes = [
('PURELIB/', ''), ('PLATLIB/pywin32_system32', ''),
('PLATLIB/', ''),
('SCRIPTS/', 'EGG-INFO/scripts/')
]
z = zipfile.ZipFile(exe_filename)
try:
for info in z.infolist():
name = info.filename
parts = name.split('/')
if len(parts)==3 and parts[2]=='PKG-INFO':
if parts[1].endswith('.egg-info'):
prefixes.insert(0,('/'.join(parts[:2]), 'EGG-INFO/'))
break
if len(parts)<>2 or not name.endswith('.pth'):
continue
if name.endswith('-nspkg.pth'):
continue
if parts[0].upper() in ('PURELIB','PLATLIB'):
for pth in yield_lines(z.read(name)):
pth = pth.strip().replace('\\','/')
if not pth.startswith('import'):
prefixes.append((('%s/%s/' % (parts[0],pth)), ''))
finally:
z.close()
prefixes = [(x.lower(),y) for x, y in prefixes]
prefixes.sort(); prefixes.reverse()
return prefixes
def parse_requirement_arg(spec):
try:
return Requirement.parse(spec)
except ValueError:
raise DistutilsError(
"Not a URL, existing file, or requirement spec: %r" % (spec,)
)
class PthDistributions(Environment):
"""A .pth file with Distribution paths in it"""
dirty = False
def __init__(self, filename, sitedirs=()):
self.filename = filename; self.sitedirs=map(normalize_path, sitedirs)
self.basedir = normalize_path(os.path.dirname(self.filename))
self._load(); Environment.__init__(self, [], None, None)
for path in yield_lines(self.paths):
map(self.add, find_distributions(path, True))
def _load(self):
self.paths = []
saw_import = False
seen = dict.fromkeys(self.sitedirs)
if os.path.isfile(self.filename):
f = open(self.filename,'rt')
for line in f:
if line.startswith('import'):
saw_import = True
continue
path = line.rstrip()
self.paths.append(path)
if not path.strip() or path.strip().startswith('#'):
continue
# skip non-existent paths, in case somebody deleted a package
# manually, and duplicate paths as well
path = self.paths[-1] = normalize_path(
os.path.join(self.basedir,path)
)
if not os.path.exists(path) or path in seen:
self.paths.pop() # skip it
self.dirty = True # we cleaned up, so we're dirty now :)
continue
seen[path] = 1
f.close()
if self.paths and not saw_import:
self.dirty = True # ensure anything we touch has import wrappers
while self.paths and not self.paths[-1].strip():
self.paths.pop()
def save(self):
"""Write changed .pth file back to disk"""
if not self.dirty:
return
data = '\n'.join(map(self.make_relative,self.paths))
if data:
log.debug("Saving %s", self.filename)
data = (
"import sys; sys.__plen = len(sys.path)\n"
"%s\n"
"import sys; new=sys.path[sys.__plen:];"
" del sys.path[sys.__plen:];"
" p=getattr(sys,'__egginsert',0); sys.path[p:p]=new;"
" sys.__egginsert = p+len(new)\n"
) % data
if os.path.islink(self.filename):
os.unlink(self.filename)
f = open(self.filename,'wt')
f.write(data); f.close()
elif os.path.exists(self.filename):
log.debug("Deleting empty %s", self.filename)
os.unlink(self.filename)
self.dirty = False
def add(self,dist):
"""Add `dist` to the distribution map"""
if (dist.location not in self.paths and (
dist.location not in self.sitedirs or
dist.location == os.getcwd() #account for '.' being in PYTHONPATH
)):
self.paths.append(dist.location)
self.dirty = True
Environment.add(self,dist)
def remove(self,dist):
"""Remove `dist` from the distribution map"""
while dist.location in self.paths:
self.paths.remove(dist.location); self.dirty = True
Environment.remove(self,dist)
def make_relative(self,path):
npath, last = os.path.split(normalize_path(path))
baselen = len(self.basedir)
parts = [last]
sep = os.altsep=='/' and '/' or os.sep
while len(npath)>=baselen:
if npath==self.basedir:
parts.append(os.curdir)
parts.reverse()
return sep.join(parts)
npath, last = os.path.split(npath)
parts.append(last)
else:
return path
def get_script_header(script_text, executable=sys_executable, wininst=False):
"""Create a #! line, getting options (if any) from script_text"""
from distutils.command.build_scripts import first_line_re
first = (script_text+'\n').splitlines()[0]
match = first_line_re.match(first)
options = ''
if match:
options = match.group(1) or ''
if options: options = ' '+options
if wininst:
executable = "python.exe"
else:
executable = nt_quote_arg(executable)
hdr = "#!%(executable)s%(options)s\n" % locals()
if not isascii(hdr):
# Non-ascii path to sys.executable, use -x to prevent warnings
if options:
if options.strip().startswith('-'):
options = ' -x'+options.strip()[1:]
# else: punt, we can't do it, let the warning happen anyway
else:
options = ' -x'
executable = fix_jython_executable(executable, options)
hdr = "#!%(executable)s%(options)s\n" % locals()
return hdr
def auto_chmod(func, arg, exc):
if func is os.remove and os.name=='nt':
chmod(arg, stat.S_IWRITE)
return func(arg)
exc = sys.exc_info()
raise exc[0], (exc[1][0], exc[1][1] + (" %s %s" % (func,arg)))
def uncache_zipdir(path):
"""Ensure that the importer caches dont have stale info for `path`"""
from zipimport import _zip_directory_cache as zdc
_uncache(path, zdc)
_uncache(path, sys.path_importer_cache)
def _uncache(path, cache):
if path in cache:
del cache[path]
else:
path = normalize_path(path)
for p in cache:
if normalize_path(p)==path:
del cache[p]
return
def is_python(text, filename='<string>'):
"Is this string a valid Python script?"
try:
compile(text, filename, 'exec')
except (SyntaxError, TypeError):
return False
else:
return True
def is_sh(executable):
"""Determine if the specified executable is a .sh (contains a #! line)"""
try:
fp = open(executable)
magic = fp.read(2)
fp.close()
except (OSError,IOError): return executable
return magic == '#!'
def nt_quote_arg(arg):
"""Quote a command line argument according to Windows parsing rules"""
result = []
needquote = False
nb = 0
needquote = (" " in arg) or ("\t" in arg)
if needquote:
result.append('"')
for c in arg:
if c == '\\':
nb += 1
elif c == '"':
# double preceding backslashes, then add a \"
result.append('\\' * (nb*2) + '\\"')
nb = 0
else:
if nb:
result.append('\\' * nb)
nb = 0
result.append(c)
if nb:
result.append('\\' * nb)
if needquote:
result.append('\\' * nb) # double the trailing backslashes
result.append('"')
return ''.join(result)
def is_python_script(script_text, filename):
"""Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.
"""
if filename.endswith('.py') or filename.endswith('.pyw'):
return True # extension says it's Python
if is_python(script_text, filename):
return True # it's syntactically valid Python
if script_text.startswith('#!'):
# It begins with a '#!' line, so check if 'python' is in it somewhere
return 'python' in script_text.splitlines()[0].lower()
return False # Not any Python I can recognize
try:
from os import chmod as _chmod
except ImportError:
# Jython compatibility
def _chmod(*args): pass
def chmod(path, mode):
log.debug("changing mode of %s to %o", path, mode)
try:
_chmod(path, mode)
except os.error, e:
log.debug("chmod failed: %s", e)
def fix_jython_executable(executable, options):
if sys.platform.startswith('java') and is_sh(executable):
# Workaround Jython's sys.executable being a .sh (an invalid
# shebang line interpreter)
if options:
# Can't apply the workaround, leave it broken
log.warn("WARNING: Unable to adapt shebang line for Jython,"
" the following script is NOT executable\n"
" see http://bugs.jython.org/issue1112 for"
" more information.")
else:
return '/usr/bin/env %s' % executable
return executable
def get_script_args(dist, executable=sys_executable, wininst=False):
"""Yield write_script() argument tuples for a distribution's entrypoints"""
spec = str(dist.as_requirement())
header = get_script_header("", executable, wininst)
for group in 'console_scripts', 'gui_scripts':
for name, ep in dist.get_entry_map(group).items():
script_text = (
"# EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r\n"
"__requires__ = %(spec)r\n"
"import sys\n"
"from pkg_resources import load_entry_point\n"
"\n"
"if __name__ == '__main__':"
"\n"
" sys.exit(\n"
" load_entry_point(%(spec)r, %(group)r, %(name)r)()\n"
" )\n"
) % locals()
if sys.platform=='win32' or wininst:
# On Windows/wininst, add a .py extension and an .exe launcher
if group=='gui_scripts':
ext, launcher = '-script.pyw', 'gui.exe'
old = ['.pyw']
new_header = re.sub('(?i)python.exe','pythonw.exe',header)
else:
ext, launcher = '-script.py', 'cli.exe'
old = ['.py','.pyc','.pyo']
new_header = re.sub('(?i)pythonw.exe','python.exe',header)
if os.path.exists(new_header[2:-1]) or sys.platform!='win32':
hdr = new_header
else:
hdr = header
yield (name+ext, hdr+script_text, 't', [name+x for x in old])
yield (
name+'.exe', resource_string('setuptools', launcher),
'b' # write in binary mode
)
else:
# On other platforms, we assume the right thing to do is to
# just write the stub with no extension.
yield (name, header+script_text)
def rmtree(path, ignore_errors=False, onerror=auto_chmod):
"""Recursively delete a directory tree.
This code is taken from the Python 2.4 version of 'shutil', because
the 2.3 version doesn't really work right.
"""
if ignore_errors:
def onerror(*args):
pass
elif onerror is None:
def onerror(*args):
raise
names = []
try:
names = os.listdir(path)
except os.error, err:
onerror(os.listdir, path, sys.exc_info())
for name in names:
fullname = os.path.join(path, name)
try:
mode = os.lstat(fullname).st_mode
except os.error:
mode = 0
if stat.S_ISDIR(mode):
rmtree(fullname, ignore_errors, onerror)
else:
try:
os.remove(fullname)
except os.error, err:
onerror(os.remove, fullname, sys.exc_info())
try:
os.rmdir(path)
except os.error:
onerror(os.rmdir, path, sys.exc_info())
def bootstrap():
# This function is called when setuptools*.egg is run using /bin/sh
import setuptools; argv0 = os.path.dirname(setuptools.__path__[0])
sys.argv[0] = argv0; sys.argv.append(argv0); main()
def main(argv=None, **kw):
from setuptools import setup
from setuptools.dist import Distribution
import distutils.core
USAGE = """\
usage: %(script)s [options] requirement_or_url ...
or: %(script)s --help
"""
def gen_usage (script_name):
script = os.path.basename(script_name)
return USAGE % vars()
def with_ei_usage(f):
old_gen_usage = distutils.core.gen_usage
try:
distutils.core.gen_usage = gen_usage
return f()
finally:
distutils.core.gen_usage = old_gen_usage
class DistributionWithoutHelpCommands(Distribution):
common_usage = ""
def _show_help(self,*args,**kw):
with_ei_usage(lambda: Distribution._show_help(self,*args,**kw))
def find_config_files(self):
files = Distribution.find_config_files(self)
if 'setup.cfg' in files:
files.remove('setup.cfg')
return files
if argv is None:
argv = sys.argv[1:]
with_ei_usage(lambda:
setup(
script_args = ['-q','easy_install', '-v']+argv,
script_name = sys.argv[0] or 'easy_install',
distclass=DistributionWithoutHelpCommands, **kw
)
)
| jokajak/itweb | data/env/lib/python2.6/site-packages/distribute-0.6.14-py2.6.egg/setuptools/command/easy_install.py | Python | gpl-3.0 | 69,824 | [
"VisIt"
] | 465069e79035401fbf894699002540f7cc2ed2251896bb4dc828b8b5cfb8235d |
import pysam
class fasta(object):
def __init__(self, fasta):
self.fasta = pysam.FastaFile(fasta)
self.lengths = dict([(x,y) for x,y in zip(
self.fasta.references, self.fasta.lengths)])
def extract(self, chrom, start, end, upper=False):
''' Function to extract sequence of specified region.
Args:
chrom (str)- Name of chromosome.
start (int)- Start of regions.
end (int)- End of sequence.
Returns:
seq (str)- String of sequence.
'''
# Check arguments
if end > self.lengths[chrom]:
raise ValueError('End is greater than chromosome length')
# Extract and return sequence
seq = self.fasta.fetch(chrom, start, end)
return(seq)
def extract_fasta(self, outfasta, regions, upper=False):
''' Function to create FASTA file of extracted regions
Args:
outfasta (str)- Name of output FASTA file.
regions - Iterable returning chrom, start and end values.
upper (bool)- Convert sequences to upper case.
'''
# Open and create output file
with open(outfasta, 'w') as outfile:
for chrom, start, end in regions:
name = '>{}:{}-{}\n'.format(chrom, start + 1, end)
outfile.write(name)
seq = self.extract(chrom, start, end)
outfile.write(seq)
outfile.write('\n')
def extract_fastq(self, outfastq, regions, quality=30):
''' Function to create FASTQ file of extracted regions
Args:
outfasta (str)- Name of output FASTA file.
regions - Iterable returning chrom, start and end values.
upper (bool)- Convert sequences to upper case.
'''
# Open and create output file
with open(outfastq, 'w') as outfile:
for chrom, start, end in regions:
name = '@{}:{}-{}'.format(chrom, start + 1, end)
seq = self.extract(chrom, start, end)
quality = chr(quality + 33) * (end - start)
fastqEntry = '{}\n{}\n+\n{}\n'.format(
name, seq, quality)
outfile.write(qualityString + '\n')
def tile_region(
self, chrom, start, end, size, overlap=0, complete=True
):
''' Function to create list of inervals tiling a region
Args:
chrom (str)- Name of chromosome.
start (int)- Start of interval to tile.
end (int)- End of interval to tile.
size (int)- Size of each interval.
overlap (int)- Overlap between intervals.
Returns:
regions (list)- A list of tuples of the region.
'''
# Check arguments
if not all([isinstance(x, int) for x in (start, end, size, overlap)]):
raise TypeError('start, end, size and overlap must be integers')
if not all([x > -1 for x in start, end, size]):
raise ValueError('start, end and size must be non-negative')
if start >= end:
raise ValueError('Start must be less than end')
if end > self.lengths[chrom]:
raise ValueError('End is greater than chromosome length')
# Create intervals
startList = range(start, end - overlap, size - overlap)
if (startList[-1] + size) != end and complete:
raise ValueError('Supplied parameters do not span region')
# Create and return output
outList = [(chrom, x, x + size) for x in startList]
return(outList)
| adam-rabinowitz/ngs_analysis | fasta/pysam_extract.py | Python | gpl-2.0 | 3,734 | [
"pysam"
] | efcea8abe40633a162288d8bf413fdd60a9a0bebaae7e7b5b849ba48960b476a |
# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Free University
# Berlin, 14195 Berlin, Germany.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation and/or
# other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
'''
Created on 23.01.2015
@author: marscher
'''
from __future__ import absolute_import
import mdtraj
import os
import tempfile
import unittest
from pyemma.coordinates import api
from pyemma.coordinates.data.feature_reader import FeatureReader
from pyemma.util.log import getLogger
import pkg_resources
import numpy as np
from pyemma.coordinates.api import discretizer, tica, source
from six.moves import range
log = getLogger('TestFeatureReader')
def create_traj(top):
trajfile = tempfile.mktemp('.xtc')
n_frames = np.random.randint(500, 1500)
log.debug("create traj with %i frames" % n_frames)
xyz = np.arange(n_frames * 3 * 3).reshape((n_frames, 3, 3))
t = mdtraj.load(top)
t.xyz = xyz
t.time = np.arange(n_frames)
t.save(trajfile)
return trajfile, xyz, n_frames
class TestFeatureReader(unittest.TestCase):
@classmethod
def setUpClass(cls):
c = super(TestFeatureReader, cls).setUpClass()
# create a fake trajectory which has 3 atoms and coordinates are just a range
# over all frames.
cls.topfile = pkg_resources.resource_filename(__name__, 'data/test.pdb')
cls.trajfile, cls.xyz, cls.n_frames = create_traj(cls.topfile)
cls.trajfile2, cls.xyz2, cls.n_frames2 = create_traj(cls.topfile)
return c
@classmethod
def tearDownClass(cls):
try:
os.unlink(cls.trajfile)
except EnvironmentError:
pass
def testIteratorAccess(self):
reader = api.source(self.trajfile, top=self.topfile)
assert isinstance(reader, FeatureReader)
frames = 0
data = []
for i, X in reader:
assert isinstance(X, np.ndarray)
frames += X.shape[0]
data.append(X)
self.assertEqual(frames, reader.trajectory_lengths()[0])
data = np.vstack(data)
# restore shape of input
data.reshape(self.xyz.shape)
self.assertTrue(np.allclose(data, self.xyz.reshape(-1, 9)))
def testIteratorAccess2(self):
reader = FeatureReader([self.trajfile, self.trajfile2], self.topfile)
reader.chunksize = 100
data = {itraj: [] for itraj in range(reader.number_of_trajectories())}
for i, X in reader:
data[i].append(X)
# restore shape of input
data[0] = np.vstack(data[0]).reshape(-1, 9)
data[1] = np.vstack(data[1]).reshape(-1, 9)
np.testing.assert_equal(data[0], self.xyz.reshape(-1, 9))
np.testing.assert_equal(data[1], self.xyz2.reshape(-1, 9))
def testTimeLaggedIterator(self):
lag = 10
reader = FeatureReader(self.trajfile, self.topfile)
frames = 0
data = []
lagged = []
for _, X, Y in reader.iterator(lag=lag):
frames += X.shape[0]
data.append(X)
lagged.append(Y)
assert len(data) == len(lagged)
# .reshape(self.xyz.shape)
merged_lagged = np.concatenate(lagged, axis=0)
# reproduce outcome
xyz_s = self.xyz.shape
fake_lagged = self.xyz.reshape((xyz_s[0], -1))[lag:]
self.assertTrue(np.allclose(merged_lagged, fake_lagged))
# restore shape of input
data = np.vstack(data).reshape(self.xyz.shape)
self.assertEqual(frames, reader.trajectory_lengths()[0])
self.assertTrue(np.allclose(data, self.xyz))
def test_with_pipeline_time_lagged(self):
reader = api.source(self.trajfile, top=self.topfile)
assert isinstance(reader, FeatureReader)
t = tica(dim=2, lag=1)
d = discretizer(reader, t)
d.parametrize()
def test_in_memory(self):
reader = api.source(self.trajfile, top=self.topfile)
out1 = reader.get_output()
# now map stuff to memory
reader.in_memory = True
reader2 = api.source(self.trajfile, top=self.topfile)
out = reader2.get_output()
assert len(out) == len(reader._Y) == 1
np.testing.assert_equal(out1, out)
np.testing.assert_equal(reader._Y[0], out[0])
np.testing.assert_equal(reader.get_output(), out)
# reset in_memory and check output gets deleted
reader.in_memory = False
assert reader._Y is None
def test_in_memory_with_stride(self):
# map "results" to memory
reader = api.source(self.trajfile, top=self.topfile)
reader.in_memory = True
assert reader._parametrized
reader.parametrize(stride=2)
reader2 = api.source(self.trajfile, top=self.topfile)
out = reader2.get_output(stride=2)
np.testing.assert_equal(reader._Y[0], out[0])
def test_in_memory_switch_stride_dim(self):
reader = api.source(self.trajfile, top=self.topfile)
reader.chunksize = 100
reader.in_memory = True
# now get output with different strides
strides = [1, 2, 3, 4, 5]
for s in strides:
out = reader.get_output(stride=s)
shape = (reader.trajectory_length(0, stride=s), reader.dimension())
self.assertEqual(out[0].shape, shape, "not equal for stride=%i" % s)
def test_lagged_stridden_access(self):
reader = api.source([self.trajfile, self.trajfile2], top=self.topfile)
reader.chunksize = 210
strides = [2, 3, 5, 7, 15]
lags = [1, 3, 7, 10, 30]
err_msg = "not equal for stride=%i, lag=%i"
for stride in strides:
for lag in lags:
chunks = {itraj: []
for itraj in range(reader.number_of_trajectories())}
for itraj, _, Y in reader.iterator(stride, lag):
chunks[itraj].append(Y)
chunks[0] = np.vstack(chunks[0])
np.testing.assert_almost_equal(
chunks[0], self.xyz.reshape(-1, 9)[lag::stride], err_msg=err_msg % (stride, lag))
chunks[1] = np.vstack(chunks[1])
np.testing.assert_almost_equal(
chunks[1], self.xyz2.reshape(-1, 9)[lag::stride], err_msg=err_msg % (stride, lag))
if __name__ == "__main__":
unittest.main()
| trendelkampschroer/PyEMMA | pyemma/coordinates/tests/test_featurereader.py | Python | bsd-2-clause | 7,578 | [
"MDTraj"
] | b3e5711da2b7aed64a0a413d26ca69919f4cabb20019777d55a9653fe96ff849 |
#!/usr/bin/env python
"""
Generate plots for synthetic three-state force spectroscopy model.
"""
import bhmm
from bhmm.util.analysis import generate_latex_table
# dynamically import plotting tools
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
import plots
def run(nstates, nsamples):
# Load force data.
from netCDF4 import Dataset
ncfile = Dataset('fiber3-trace011.nc', 'r')
tau = 0.001 # 1 kHz
obs_label = 'force / pN'
time_units = 's' # seconds
o_t = ncfile.variables['force'] # load trace
# force to make a copy because netCDF appears to cause problems
nsubsample = 50 # subsampling rate
o_t = o_t[::nsubsample]
tau *= nsubsample
# -------------------
O = [o_t] # form list of traces
# Initialize MLHMM.
print "Initializing MLHMM with "+str(nstates)+" states."
estimator = bhmm.MLHMM(O, nstates)
# Plot initial guess.
plots.plot_state_assignments(estimator.hmm, None, O[0], time_units=time_units, obs_label=obs_label, tau=tau,
pdf_filename='fiber3-trace11-guess-stateassignments-nstate'+str(nstates)+'.pdf')
# Fit MLHMM
mle = estimator.fit()
# Plot.
plots.plot_state_assignments(mle, mle.hidden_state_trajectories[0], o_t, time_units=time_units,
obs_label=obs_label, tau=tau,
pdf_filename='fiber3-trace11-mlhmm-stateassignments-nstate'+str(nstates)+'.pdf')
# Initialize BHMM, using MLHMM model as initial model.
print "Initializing BHMM and running with "+str(nsamples)+" samples."
sampler = bhmm.BHMM(O, nstates, initial_model=mle)
# Sample models.
bhmm_models = sampler.sample(nsamples=nsamples, save_hidden_state_trajectory=False)
# Generate a sample saving a hidden state trajectory.
final_models = sampler.sample(nsamples=1, save_hidden_state_trajectory=True)
# Plot.
model = final_models[0]
s_t = model.hidden_state_trajectories[0]
o_t = O[0]
plots.plot_state_assignments(model, s_t, o_t, time_units=time_units, obs_label=obs_label, tau=tau,
pdf_filename='fiber3-trace11-bhmm-stateassignments-nstate'+str(nstates)+'.pdf')
# write latex table with sample statistics
conf = 0.95
sampled_hmm = bhmm.BHMM(mle, bhmm_models)
generate_latex_table(sampled_hmm, conf=conf, dt=tau, time_unit='s',
caption='BHMM model estimates for RNA hairpin data.',
outfile='p5ab-bhmm-statistics-table-nstate'+str(nstates)+'.tex')
if __name__ == "__main__":
# Be verbose.
bhmm.config.verbose = True
# Fit MLHMM and BHMM
nstates = 2
nsamples = 1000
run(nstates, nsamples)
| jchodera/bhmm-force-spectroscopy-manuscript | examples/p5ab-hairpin/generate-figure.py | Python | lgpl-3.0 | 2,862 | [
"NetCDF"
] | ab6db090cf2f041f4521663cdd67018ee0125797695da30edfb96587da9bd3c4 |
#!/bin/env python
#
#
# This file is part Protein Engineering Analysis Tool (PEAT)
# (C) Copyright Jens Erik Nielsen, University College Dublin 2003-
# All rights reserved
#
#
# Rewritten by D Farrell, Jan 2009
#
import cgi
import sys,os, string, types
os.environ['MPLCONFIGDIR']='/tmp'
from PEATDB.Base import PDatabase
from PEATDB.Record import PEATRecord
from PEATDB.PEATTables import PEATTableModel, PEATTable
class PEATWeb:
"""Class providing a web interface for PEAT projects"""
def __init__(self, server='localhost', project='test', port=8080,
user=None, passwd=None,
bindir='', fullpath=''):
"""bindir : path to cgi script in server address
fullpath : file system path to script """
import socket
self.host = socket.getfqdn(socket.gethostname())
self.sessionkey=None
self.form=cgi.FieldStorage()
self.server = server
self.project = project
self.user = user
self.password = passwd
self.port = port
self.bindir = bindir
dirname = os.path.basename(fullpath)
self.imgdir = '/' + dirname + '/images'
self.plotsdir = '/'+ dirname + '/plots'
self.imagepath = fullpath + '/plots'
action = self.form.getfirst('action')
self.action = action
if not self.form.getfirst('action'):
self.show_intro()
return
elif action == 'show_intro':
self.show_intro()
elif action == 'show_help':
self.show_help()
elif action == 'show_all':
self.show_all()
elif action=='show_specific':
self.show_specific()
elif action == 'show_datasets':
self.show_datasets()
elif action == 'search':
self.show_search_results()
return
def show_intro(self):
'''Show intro page'''
self.showHeader(menu=1)
print '<div align=left>'
print '<big><big><a>PEAT DB Web Interface, %s </big></a>' %self.project
print '<br>'
print '<UL>\
<LI>Browse contents of the DB in one table\
<LI>Visualise and overly any combination of curves (and our fits)\
<LI>Download the raw data as csv/text files and refit/analyse\
</UL>'
print '</div>'
self.footer()
return
def show_help(self):
'''Show help page, override this '''
self.showHeader(menu=1)
self.footer()
return
def showHeader(self,title=None,menu=None):
"""show headings and column names for DB"""
imgdir = self.imgdir
html_header = 'Content-Type: text/html; charset=utf-8\n'
html_header += '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/loose.dtd">\n\n'
print html_header
print '<html>'
print '<head>'
if title==None:
print '<title>PEAT Web Interface</title>'
else:
print '<title>%s</title>' % title
print '<link href="%s/styles.css" rel="stylesheet" type="text/css" />' %self.bindir
print '<link rel="shortcut icon" href="%s/favicon.ico" type="image/x-icon" />' %self.bindir
print '<script type="text/javascript" src="/scripts/checkbox.js"></script>'
print '</head>'
print '<body>'
print '<div class="header">'
print '<p id="title">PEAT Web Interface: %s</p>' %self.project
print '</div>'
print '<script type="text/javascript" src="/scripts/boxover.js"></script>'
print '<hr>'
print '<div>'
if menu==1:
self.menu()
return
def write_sessionkey(self, action=None, project=None, manage=None):
"""Write the session key"""
if self.user:
print '<input type=hidden name=login value=%s>' %self.user
print '<input type=hidden name=sessionkey value=%s>' %self.sessionkey
if action:
print '<input type=hidden name=action value=%s>' %action
if project:
print '<input type=hidden name=project value=%s>' %project
if manage:
print '<input type=hidden name=manage value=yes>'
return
def footer(self):
"""Print page footer"""
print '<br>'
print '<p><center>Provided by <a href="http://enzyme.ucd.ie">Nielsen Research Group at UCD</a></center></p>'
print '</div>'
print '</div>'
print '</body>'
return
def menu(self):
"""Print the menu"""
bindir = self.bindir
print '<div class="menu">'
print '<table id="menu" valign=top align=left>'
print '<th><b>Menu</b></th>'
print '<form action="%s/main.cgi" METHOD="POST" ENCTYPE="multipart/form-data">' %bindir
self.write_sessionkey('show_intro')
print '<tr><td class="menu">\
<input type=submit value="Home" name=submit size=20 class="btn"></td></tr>'
print '</form>'
print
print '<form action="%s/main.cgi" METHOD="POST" ENCTYPE="multipart/form-data">' %bindir
self.write_sessionkey('show_all')
print '<tr><td class="menu">'
print '<input type=submit value="Show All Records" name=submit class="btn"'
print """title="header=[Show all] body=[Show all records in the DB]"></td></tr>"""
print '</form>'
print
print '<form action="%s/main.cgi" METHOD="POST" ENCTYPE="multipart/form-data">' %bindir
self.write_sessionkey('summary')
print '<tr><td class="menu">\
<input type=submit value="Summary" name=submit class="btn"></td></tr>'
print '</form>'
print '<form action="%s/main.cgi" METHOD="POST" ENCTYPE="multipart/form-data">' %bindir
self.write_sessionkey('show_help')
print '<tr><td class="menu">\
<input type=submit value="Help" name=submit class="btn"></td></tr>'
print '</form>'
print
searchmessage = 'Enter your search here'
print '<tr><td class="menu"><a><b>SEARCH</a></td></tr>'
print '<form action="%s/main.cgi" METHOD="POST" ENCTYPE="multipart/form-data">' %bindir
self.write_sessionkey('search')
#protein search box
print '<tr><td class="menu">'
print 'Protein: '
print '<select name="proteinmatchmethod" class="btn">'
print '<option value="or">Any words'
print '<option value="and">All words'
print '</select>'
print '</td></tr>'
print '<td class="menu">'
print """<input type="text" name="words" size=22 maxlength=50 value="" \
title="header=[Protein search] body=[Enter multiple names seperated by a space.\
This search is not case sensitive]"></td></tr>"""
#dataset search box
print '<tr><td class="menu">'
print 'Dataset: '
print '<tr><td class="menu">'
print """<input type="text" name="dataset" size=22 maxlength=40 value="" class="btn"\
title="header=[Name of data item] body=[Use any strings]"></td></tr>"""
#drop list for whether to match any or all of the searches from each box
print '<tr><td class="menu">'
print """Match: <select name="matchmethod" class="btn" title="header=[Global match method] \
body=[Match records with ALL of the search criteria or only those with ANY those\
attributes]">"""
print '<option value="and">All'
print '<option value="or">Any'
print '</select> <p>'
print '</td></tr>'
print '</td></tr>'
print '<tr><td class="menu"><input type="submit" value="Search Now" class="btn"></td></tr>'
print '</form>'
print '</table>'
print '</div>'
print '<div id="content">'
return
def show_all(self):
'''Show all records in DB
From the locally saved project if present, otherwise checkout'''
self.DB = self.connect()
self.showHeader(menu=1)
sys.stdout.flush()
self.show_DB()
return
def connect(self):
"""Connect to the peat db"""
saveout = sys.stdout
logpath = os.path.abspath('out.log')
fsock = open(logpath, 'w')
sys.stdout = fsock
sys.stdout.flush()
print self.server
DB = PDatabase(server=self.server, port=self.port,
username=self.user,
password=self.password,
project=self.project)
sys.stdout.flush()
sys.stdout = saveout
fsock.close()
return DB
def show_DB(self, selected=None):
"""
Show all the records in the PEAT database in a html table.
"""
DB = self.DB
ptmodel = PEATTableModel(DB)
colnames = ptmodel.columnNames
exclude = ['pdb Info','Mutations']
ekincols = ptmodel.ekintypes
print '<table id="mytable" cellspacing=0>'
print '<tr>'
#do column names at top first
for c in colnames:
if c in exclude:
continue
print '<th>'+c+'</th>'
print '</tr>'
y_count=1
r=0
#used for summarising titration curve
tit1H=0
tit15N=0
tit13C=0
#get sort order by name field
if selected == None:
selected = DB.getRecs()
names = []
for p in selected:
names.append((DB[p].name, p))
names.sort()
for name in names:
protein = name[1]
if r % 2 == 0:
cls = 'alt'
else:
cls = ''
print '<tr>'
for column in colnames:
if column in exclude:
continue
#get field type here
fieldtype=None
if DB['userfields'].has_key(column):
fieldtype=DB['userfields'][column]['field_type']
elif column == 'Structure':
fieldtype='structure'
if fieldtype==None:
fieldtype = 'text'
display_text = DB[protein].getDisplayAttribute(column)
if display_text == '':
display_text = '-'
if fieldtype == 'Text' or fieldtype == 'text' or fieldtype == 'structure':
if column == 'Name':
print '<th class="spec"> %s </th>' % display_text
else:
print '<td class=%s> %s </td>' % (cls,display_text)
#links
elif fieldtype == 'Link':
display_text = '-'
if DB[protein].has_key(column) and isinstance(DB[protein][column], dict):
if DB[protein][column].has_key('text'):
display_text = DB[protein][column]['text']
link_text = DB[protein][column]['link']
if link_text != None and link_text != '':
if column == 'PDB_link':
viewlink = 'http://firstglance.jmol.org/fg.htm?mol='+display_text
#print '<td class=%s> <a href=%s target="_blank">%s</a> <a href=%s target="_blank"><img class="thumb" \
# src="%s/fg.png"></a></td>' % (cls,link_text,display_text,viewlink, self.imgdir)
print '<td class=%s> <a href=%s target="_blank">%s</a> <a href=%s target="_blank"> view\
</a></td>' % (cls,link_text,display_text,viewlink)
elif column == 'PMID_link':
authors=''
try:
auth, title = DB[protein][column]['authors'], DB[protein][column]['title']
for a in auth:
authors+=a.encode("utf-8")+' '
except:
auth, title = ('NA', 'NA')
print '<td class=%s> <a href=%s target="_blank" title="header=[%s] \
body=[%s]">%s</a></td>' % (cls,link_text,authors,title,display_text)
else:
print '<td class=%s> <a href=%s target="_blank">%s</a></td>' % (cls,link_text,display_text)
else:
print '<td class=%s> %s </td>' % (cls,display_text)
else:
print '<td class=%s> %s </td>' % (cls,display_text)
#ekin data fields
elif fieldtype in ekincols:
if display_text.startswith(' 0 recs') or fieldtype == 'Text':
print '<td class=%s> %s </td>' % (cls, display_text)
else:
import urllib
urlfields = urllib.urlencode({'login':self.user,'project':self.project,
'sessionkey':self.sessionkey,
'protein':protein,'column':column,
'fieldtype':fieldtype,'action':'show_specific'})
print '<td class=%s> <a href="%s/main.cgi?%s" target="_blank">%s</a></td>' % (cls,self.bindir,urlfields,display_text)
#get no. of curves in that record
try:
numcurves = int(display_text.split('recs')[0])
except:
numcurves = 1
if '1H' in column:
tit1H=tit1H+1*numcurves
elif '15N' in column:
tit15N=tit15N+1*numcurves
elif '13C' in column:
tit13C=tit13C+1*numcurves
print '</tr>'
r=r+1
# Update the row count
y_count=y_count+1
print '<tr><td valign=top colspan=3> summary: %s proteins 1H=%s 15N=%s 13C=%s</tr>' %(r, tit1H, tit15N, tit13C)
print '</table>'
self.footer()
return
def show_specific(self):
"""Show datasets for an individual cell, depends on fieldtype"""
protein = self.form.getfirst('protein')
rectype = self.form.getfirst('rectype')
col = self.form.getfirst('column')
sys.stdout.flush()
DB = self.DB = self.connect()
ptmodel = PEATTableModel(DB)
ekincols = ptmodel.ekintypes
fieldtype = DB['userfields'][col]['field_type']
protname = DB[protein]['name']
self.showHeader(title=str(protname+': '+col), menu=1)
print '<div><a>Protein: %s </a><br>' %protname
print 'Column data: %s </div>' %col
from PEATDB.Ekin.Web import EkinWeb
if fieldtype in ekincols:
fieldtype = 'ekindata'
#plot ekin data curves, if fieldtype is ekindata
if fieldtype == 'ekindata':
E = DB[protein][col]
EW = EkinWeb()
EW.showEkinPlots(project=E, datasets='ALL', path=self.plotsdir,
imgpath=self.imagepath)
print '</table>'
#save the pdb structure to a file and provide url link to it
elif fieldtype == 'structure':
recdata = DB[protein][col]
for k in recdata:
print '<br><a> %s</a>' %str(k)
elif fieldtype == 'Notes':
recdata = DB[protein][col]
print '<br><a> %s</a>' %recdata['text']
elif fieldtype == 'File':
recdata = DB[protein][col]
print '<p> This record contains a data file. Click link to open.'
print '<a href="http://peat.ucd.ie/titration_db/%s">Open link</a>' %recdata['location']
else:
print '<br>Sorry, no handler for this data right now..</br>'
self.footer()
return
def show_datasets(self):
"""Show single or multiple dataset plot from search results"""
plotoption = self.form.getfirst('plotoption')
norm = bool(self.form.getfirst('normalise'))
logx = bool(self.form.getfirst('logx'))
logy = bool(self.form.getfirst('logy'))
legend = bool(self.form.getfirst('legend'))
DB = self.DB = self.connect()
from PEATDB.Ekin.Web import EkinWeb
ekincols = DB.ekintypes
self.showHeader(menu=1)
self.menu()
sys.stdout.flush()
#get dataset name(s) from form
residuefield = self.form.getvalue('residue')
if not isinstance(residuefield, list):
residuefield = [residuefield]
#prepare data, if more than one dataset from seperate proteins,
print '</div>'
print '<table id="mytable" cellspacing=0>'
print '<tr><th>'
print 'plotoption:', plotoption
print 'norm:', str(norm)
print 'log-x', logx
print 'log-y', logy
print 'legend', legend
print '</table>'
ekindata={}
ekindata['__datatabs_fits__']={}
ekindata['__meta_data__']={}
#extracting seperate datasets and put them in ekindata
for r in residuefield:
fields = r.split('$')
protein = fields[0]
col = fields[1]
d = fields[2]
E = DB[protein][col]
fits = E.__datatabs_fits__
meta = E.__meta_data__
protname = DB[protein]['name']
ekindata['__datatabs_fits__'][d+'_'+col+'_'+protname] = fits[d]
ekindata['__meta_data__'][d+'_'+col+'_'+protname] = meta[d]
ekindata[d+'_'+col+'_'+protname] = E.getDataset(d)
if plotoption == None:
plotoption = 1
else:
plotoption = 3
EW = EkinWeb()
EW.showEkinPlots(ekindata, 'ALL', path=self.plotsdir,
imgpath=self.imagepath,
plotoption=plotoption, normalise=norm, legend=legend,
logx=logx, logy=logy)
return
def do_search(self, globalop, proteinop, proteins, datasets):
"""Do searches for the various parameters, name, pka etc"""
import re, urllib
from PEATDB.PEATTables import PEATTableModel
from PEATDB.Ekin.Fitting import Fitting
from PEATDB.Ekin.Web import EkinWeb
DB = self.DB
EW = EkinWeb()
ekincols = DB.ekintypes
found=[]
protlist = proteins.split(' ')
residuelist = residues.split(' ')
def createPhrase(items, op):
if op == 'or':
logicsymbol = '|'
else:
logicsymbol = '+'
itemlist = items.split(' ')
phrase =''
c=1
for i in itemlist:
if c == len(itemlist):
phrase = phrase + i
else:
phrase = phrase + i + logicsymbol
c=c+1
return re.compile(phrase, re.IGNORECASE)
#if there is a protein name entered, get the list of proteins/records to use
#otherwise use all records to search for the other keys
names = []
keywords = {}
for p in DB.getRecs():
name = DB[p].name
names.append((name,p))
if hasattr(DB[p], 'keywords'):
keywords[name] = DB[p].keywords
else:
keywords[name] = ''
names.sort()
#create search expressions
s_protein = createPhrase(proteins, proteinop)
s_residue = createPhrase(residues, 'or')
pkarange = pka.split('-')
#do search
for name in names:
proteinname = name[0]
protein = name[1]
if s_protein.search(proteinname) or s_protein.search(keywords[proteinname]):
found.append(protein)
if len(found)==0:
print '<h2>Sorry, no proteins found that match this name. <h2>'
return
elif residues == '' and pka == '':
self.show_DB(selected=found)
return found
#now search for the other keys inside selected proteins if needed
ekinfound={}; foundfits={}
ignore =['__fit_matches__', '__Exp_Meta_Dat__', '__datatabs_fits__']
kys = list(DB.getRecs())
kys.sort()
if len(found) == 0 or globalop == 'or':
found = DB.getRecs()
print '<table id="mytable" cellspacing=0 align=center>'
'''search recs for residue and pkarange
and add dataset names to new ekinfound dict'''
for protein in found:
for col in DB[protein].keys():
if nucleus != 'any':
if nucleus not in col:
continue
E = DB[protein][col]
if DB['userfields'].has_key(col):
fieldtype=DB['userfields'][col]['field_type']
else:
fieldtype=None
if fieldtype in ekincols:
dk = E.datasets
fits = E.__datatabs_fits__
for k in dk:
meta = E.getMetaData(k)
try:
thisres = meta['residue']
except:
thisres = k
if thisres == None:
thisres = k
if residues != '':
if s_residue.search(thisres) and not k in ignore:
if not ekinfound.has_key(protein+'$'+col):
ekinfound[protein+'$'+col]=[]
ekinfound[protein+'$'+col].append(k)
if pka != '':
foundpka = 0
if k in fits.keys():
if fits[k] == None:
continue
if fits[k].has_key('model'):
model = fits[k]['model']
else:
continue
if not foundfits.has_key(protein+'$'+col):
foundfits[protein+'$'+col]={}
X = Fitting.getFitter(model)
pnames = X.names
i=0
#check if first num is larger, then swap
try:
pk1=float(pkarange[0])
pk2=float(pkarange[1])
except:
print '<h2> Error: pka values are not valid </h2>'
return
if pk1 > pk2:
tmp = pk1
pk1 = pk2
pk2 = tmp
#iterate thru parameter names and match any pK fields
#this code is not that efficient!
for p in pnames:
if 'pK' in p:
pka = fits[k][i]
if pka >= pk1 and pka <= pk2:
foundpka=1
i=i+1
#if match is 'ANY', just append dataset if not there already
#also for case if no residue value entered
if globalop == 'or' or residues == '':
if foundpka == 1:
if not ekinfound.has_key(protein+'$'+col):
ekinfound[protein+'$'+col]=[]
if not k in ekinfound[protein+'$'+col]:
ekinfound[protein+'$'+col].append(k)
#if match is 'ALL', need to check dataset already found
#and if no pka found, remove it. if both are true keep it
elif globalop == 'and':
if foundpka == 0:
if ekinfound.has_key(protein+'$'+col) and k in ekinfound[protein+'$'+col]:
#print 'removing', protein, col
ekinfound[protein+'$'+col].remove(k)
foundfits[protein+'$'+col][k]=fits[k]
#check for empty fields in ekinfound dict and delete them..
for d in ekinfound.keys():
if len(ekinfound[d])==0:
del(ekinfound[d])
#if no results, just say that and return
if len(ekinfound)==0:
print '<h2> Sorry, no records found that match these parameters. </h2>'
return
#top display button and options
print '<form name="resultsform" action="%s/main.cgi" METHOD="POST" ENCTYPE="multipart/form-data">' %self.bindir
self.write_sessionkey('show_datasets')
print '<td valign=top align=right colspan=3> <input type=submit value="display selected" name=submit>'
print '<label><input type=checkbox name="plotoption" value=3>single graph</label>'
print '<label><input type=checkbox name="normalise" value=1>normalise</label>'
print '<label><input type=checkbox name="logx" value=1>log-x</label>'
print '<label><input type=checkbox name="logy" value=1>log-y</label>'
print '<label><input type=checkbox name="legend" value=1>legend</label>'
print '<input type=button value="Check All" onClick="checkAll(document.resultsform.residue)">'
print '<input type=button value="Uncheck All" onClick="uncheckAll(document.resultsform.residue)"></td>'
print '</tr>'
#header
cols=['protein','column','residues']
for c in cols:
print '<th>'+c+'</th>'
print '</tr>'
ekys = ekinfound.keys()
ekys.sort()
r=1
for k in ekys:
if r % 2 == 0:
cls = "spec"
else:
cls = ""
fields = k.split('$')
protein = fields[0]
column = fields[1]
proteinname = DB[protein]['name']
print '<tr>'
print '<th class="spec">%s</th> <td> %s </td>' %(proteinname, column)
print '<td>'
for residue in ekinfound[k]:
residuefield = k+"$"+residue
fithtml = ''
try:
print '<input type=checkbox id="residue" name="residue" value=%s>' %("'"+residuefield+"'")
except:
print 'UnicodeEncodeError'
continue
urlfields = urllib.urlencode({'login':self.user,'project':self.project,
'residue': residuefield,'action': 'show_datasets'})
print '<a href="/cgi-bin/titration_db/main.cgi?%s" target="_blank">%s</a>'\
% (urlfields, residue)
print '</tr>'
r=r+1
print '</form>'
print '</table>'
self.footer()
return
def show_search_results(self):
"""Display search results"""
self.showHeader(menu=1)
sys.stdout.flush()
self.DB = self.connect()
key=self.form.getfirst('key')
matchmethod=self.form.getfirst('matchmethod')
proteinmatchmethod=self.form.getfirst('proteinmatchmethod')
words=self.form.getfirst('words')
residue=self.form.getfirst('residue')
nucleus=self.form.getfirst('nucleus')
pka=self.form.getfirst('pka')
print '<table bgcolor=#CD9B9B border="1" bordercolor=black cellspacing=0 cellpadding=4 valign=top \
align=center width=80%><tr><td>'
print '<div align=left>'
print '<big><a>Search results for protein=%s %s residue=%s %s nucleus=%s pka=%s</big></a>'\
%(words,matchmethod,residue,matchmethod,nucleus,pka)
print '<br>'
print '</div>'
print '</table>'
self.do_search(matchmethod, proteinmatchmethod, words, residue, nucleus, pka)
return
if __name__ == '__main__':
#test
PEATWeb(project='titration_db',
user='guest',
passwd='123',
bindir='/cgi-bin/newtitdb',
fullpath='/var/www/html/newtitdb')
| dmnfarrell/peat | PEATDB/web.py | Python | mit | 29,143 | [
"Jmol"
] | 6775e8fbc56050463fc6512f386685b6111e03e34407ac631131d8c7541cc9fe |
# ----------------------------------------------------------------------------
# Copyright 2015 Nervana Systems Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------
"""
Convolution layer tests
"""
import numpy as np
from neon import NervanaObject
from neon.backends import gen_backend
from neon.layers import Sequential, Conv, Pooling, BranchNode, Affine, Tree
from neon.initializers.initializer import Gaussian, Constant
from neon.transforms import Rectlin
init1 = Gaussian(scale=0.01)
relu = Rectlin()
bias = Constant(0)
common = dict(activation=relu, init=init1, bias=bias)
commonp1 = dict(activation=relu, init=init1, bias=bias, padding=1)
commonp3s2 = dict(activation=relu, init=init1, bias=bias, padding=3, strides=2)
pool2s1p1 = dict(fshape=2, padding=1, strides=1)
batch_size = 64
def make_tree(trunk, branch1, branch2, alphas):
# Make one copy that is the Tree version
_trunk = [l['layer'](**l['config']) for l in trunk]
bnode = [BranchNode(name='bnode')]
_branch1 = [l['layer'](**l['config']) for l in branch1]
_branch2 = [l['layer'](**l['config']) for l in branch2]
v1 = Tree([_trunk + bnode + _branch1, bnode + _branch2], alphas)
# Now a second copy with no sharing as the reference version
_trunkb = [l['layer'](**l['config']) for l in trunk]
_branch1b = [l['layer'](**l['config']) for l in branch1]
_branch2b = [l['layer'](**l['config']) for l in branch2]
return (v1, _trunkb, _branch1b, _branch2b)
def test_branch_model():
NervanaObject.be = gen_backend("gpu", batch_size=64)
be = NervanaObject.be
trunk = [{'layer': Conv, 'config': dict(fshape=(5, 5, 16), **common)},
{'layer': Pooling, 'config': dict(op='max', **pool2s1p1)}]
branch1 = [{'layer': Conv, 'config': dict(fshape=(5, 5, 32), **common)},
{'layer': Pooling, 'config': dict(op='max', **pool2s1p1)},
{'layer': Affine, 'config': dict(nout=200, **common)},
{'layer': Affine, 'config': dict(nout=10, init=init1, activation=relu)}]
branch2 = [{'layer': Conv, 'config': dict(fshape=(3, 3, 32), **common)},
{'layer': Pooling, 'config': dict(op='max', **pool2s1p1)},
{'layer': Affine, 'config': dict(nout=256, **common)},
{'layer': Affine, 'config': dict(nout=10, init=init1, activation=relu)}]
alphas = [1, 1]
neon_layer, t, b1, b2 = make_tree(trunk, branch1, branch2, alphas)
inshape = (16, 32, 32)
insize = np.prod(inshape)
# Let's force bprop deltas computation for
inpa = np.random.random((insize, batch_size))
inp = be.array(inpa)
neon_layer.configure(inshape)
neon_layer.allocate()
neon_layer.allocate_deltas()
neon_out = [i.get() for i in neon_layer.fprop(inp)]
ref_layers = [Sequential(t), Sequential(b1), Sequential(b2)]
ref_layers[0].configure(inshape)
ref_layers[1].configure(ref_layers[0].out_shape)
ref_layers[2].configure(ref_layers[0].out_shape)
[r.allocate() for r in ref_layers]
[r.allocate_deltas() for r in ref_layers]
# Now copy the weights
ref_all_layers = ref_layers[0].layers + ref_layers[1].layers + ref_layers[2].layers
ref_weight_layers = [l for l in ref_all_layers if l.has_params]
neon_weight_layers = neon_layer.layers_to_optimize
for rl, nl in zip(ref_weight_layers, neon_weight_layers):
rl.set_params({'params': {'W': nl.W.get()}})
# Forward prop
inp_middle = ref_layers[0].fprop(inp)
ref_out = [r.fprop(inp_middle).get() for r in ref_layers[1:]]
for h, r in zip(neon_out, ref_out):
difference = np.max(np.abs(h-r))
assert(difference < 1e-9)
# Back prop
erra = [np.random.random(ll.shape) for ll in neon_out]
err = [be.array(e) for e in erra]
input_layer = neon_layer.layers[0].layers[0] # reference the trunk, then the root
input_layer.prev_layer = True
input_layer.set_deltas([be.iobuf(inshape)])
neon_layer.bprop(err)
errp = input_layer.deltas.get()
for i, r in enumerate(ref_layers):
r.layers[0].prev_layer = True
_inshape = inshape if i == 0 else ref_layers[0].out_shape
r.layers[0].set_deltas([be.iobuf(_inshape)])
joined_err = be.iobuf(ref_layers[0].out_shape)
branch_errs = [r.bprop(e, a) for r, e, a in reversed(zip(ref_layers[1:], err, alphas))]
joined_err[:] = branch_errs[0] + branch_errs[1]
err_ref = ref_layers[0].bprop(joined_err).get()
difference = np.max(np.abs(err_ref - errp))
print difference
assert(difference < 1e-9)
if __name__ == '__main__':
test_branch_model()
| dongjoon-hyun/neon | tests/test_branch_layer.py | Python | apache-2.0 | 5,174 | [
"Gaussian"
] | f931d5d1747c64abe5680c20841941d00c30d69efe70372fc66e4ff63c181750 |
# coding=utf-8
# Copyright 2022 The Uncertainty Baselines Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""ResNet50 model with SNGP."""
import functools
import string
import edward2 as ed
import tensorflow as tf
# Use batch normalization defaults from Pytorch.
BATCH_NORM_DECAY = 0.9
BATCH_NORM_EPSILON = 1e-5
def MonteCarloDropout( # pylint:disable=invalid-name
inputs,
dropout_rate,
use_mc_dropout,
filterwise_dropout):
"""Defines the Monte Carlo dropout layer."""
training = None
noise_shape = None
if use_mc_dropout:
training = True
if filterwise_dropout:
noise_shape = [inputs.shape[0], 1, 1, inputs.shape[3]]
return tf.keras.layers.Dropout(
dropout_rate, noise_shape=noise_shape)(
inputs, training=training)
def make_random_feature_initializer(random_feature_type):
# Use stddev=0.05 to replicate the default behavior of
# tf.keras.initializer.RandomNormal.
if random_feature_type == 'orf':
return ed.initializers.OrthogonalRandomFeatures(stddev=0.05)
elif random_feature_type == 'rff':
return tf.keras.initializers.RandomNormal(stddev=0.05)
else:
return random_feature_type
def make_conv2d_layer(use_spec_norm,
spec_norm_iteration,
spec_norm_bound):
"""Defines type of Conv2D layer to use based on spectral normalization."""
Conv2DBase = functools.partial(tf.keras.layers.Conv2D, padding='same') # pylint: disable=invalid-name
def Conv2DNormed(*conv_args, **conv_kwargs): # pylint: disable=invalid-name
return ed.layers.SpectralNormalizationConv2D(
Conv2DBase(*conv_args, **conv_kwargs),
iteration=spec_norm_iteration,
norm_multiplier=spec_norm_bound)
return Conv2DNormed if use_spec_norm else Conv2DBase
def bottleneck_block(inputs, filters, stage, block, strides, conv_layer,
dropout_layer):
"""Residual block with 1x1 -> 3x3 -> 1x1 convs in main path.
Note that strides appear in the second conv (3x3) rather than the first (1x1).
This is also known as "ResNet v1.5" as it differs from He et al. (2015)
(http://torch.ch/blog/2016/02/04/resnets.html).
Args:
inputs: tf.Tensor.
filters: list of integers, the filters of 3 conv layer at main path
stage: integer, current stage label, used for generating layer names
block: 'a','b'..., current block label, used for generating layer names
strides: Strides for the second conv layer in the block.
conv_layer: tf.keras.layers.Layer.
dropout_layer: Callable for dropout layer.
Returns:
tf.Tensor.
"""
filters1, filters2, filters3 = filters
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
x = conv_layer(
filters1,
kernel_size=1,
use_bias=False,
kernel_initializer='he_normal',
name=conv_name_base + '2a')(
inputs)
x = tf.keras.layers.BatchNormalization(
momentum=BATCH_NORM_DECAY,
epsilon=BATCH_NORM_EPSILON,
name=bn_name_base + '2a')(x)
x = tf.keras.layers.Activation('relu')(x)
x = dropout_layer(x)
x = conv_layer(
filters2,
kernel_size=3,
strides=strides,
padding='same',
use_bias=False,
kernel_initializer='he_normal',
name=conv_name_base + '2b')(
x)
x = tf.keras.layers.BatchNormalization(
momentum=BATCH_NORM_DECAY,
epsilon=BATCH_NORM_EPSILON,
name=bn_name_base + '2b')(x)
x = tf.keras.layers.Activation('relu')(x)
x = dropout_layer(x)
x = conv_layer(
filters3,
kernel_size=1,
use_bias=False,
kernel_initializer='he_normal',
name=conv_name_base + '2c')(
x)
x = tf.keras.layers.BatchNormalization(
momentum=BATCH_NORM_DECAY,
epsilon=BATCH_NORM_EPSILON,
name=bn_name_base + '2c')(x)
shortcut = inputs
if not x.shape.is_compatible_with(shortcut.shape):
shortcut = conv_layer(
filters3,
kernel_size=1,
use_bias=False,
strides=strides,
kernel_initializer='he_normal',
name=conv_name_base + '1')(
shortcut)
shortcut = tf.keras.layers.BatchNormalization(
momentum=BATCH_NORM_DECAY,
epsilon=BATCH_NORM_EPSILON,
name=bn_name_base + '1')(shortcut)
shortcut = dropout_layer(shortcut)
x = tf.keras.layers.add([x, shortcut])
x = tf.keras.layers.Activation('relu')(x)
return x
def group(inputs, filters, num_blocks, stage, strides, conv_layer,
dropout_layer):
"""Group of residual blocks."""
blocks = string.ascii_lowercase
x = bottleneck_block(
inputs,
filters,
stage,
block=blocks[0],
strides=strides,
conv_layer=conv_layer,
dropout_layer=dropout_layer)
for i in range(num_blocks - 1):
x = bottleneck_block(
x,
filters,
stage,
block=blocks[i + 1],
strides=1,
conv_layer=conv_layer,
dropout_layer=dropout_layer)
return x
def resnet50_sngp_add_last_layer(inputs, x, num_classes, use_gp_layer,
gp_hidden_dim, gp_scale, gp_bias,
gp_input_normalization, gp_random_feature_type,
gp_cov_discount_factor, gp_cov_ridge_penalty,
gp_output_imagenet_initializer):
"""Builds ResNet50.
Using strided conv, pooling, four groups of residual blocks, and pooling, the
network maps spatial features of size 224x224 -> 112x112 -> 56x56 -> 28x28 ->
14x14 -> 7x7 (Table 1 of He et al. (2015)).
Args:
inputs: inputs
x: x
num_classes: Number of output classes.
use_gp_layer: Whether to use Gaussian process layer as the output layer.
gp_hidden_dim: The hidden dimension of the GP layer, which corresponds to
the number of random features used for the approximation.
gp_scale: The length-scale parameter for the RBF kernel of the GP layer.
gp_bias: The bias term for GP layer.
gp_input_normalization: Whether to normalize the input using LayerNorm for
GP layer. This is similar to automatic relevance determination (ARD) in
the classic GP learning.
gp_random_feature_type: The type of random feature to use for
`RandomFeatureGaussianProcess`.
gp_cov_discount_factor: The discount factor to compute the moving average of
precision matrix.
gp_cov_ridge_penalty: Ridge penalty parameter for GP posterior covariance.
gp_output_imagenet_initializer: Whether to initialize GP output layer using
Gaussian with small standard deviation (sd=0.01).
Returns:
tf.keras.Model.
"""
x = tf.keras.layers.GlobalAveragePooling2D(name='avg_pool')(x)
if use_gp_layer:
gp_output_initializer = None
if gp_output_imagenet_initializer:
# Use the same initializer as dense
gp_output_initializer = tf.keras.initializers.RandomNormal(stddev=0.01)
output_layer = functools.partial(
ed.layers.RandomFeatureGaussianProcess,
num_inducing=gp_hidden_dim,
gp_kernel_scale=gp_scale,
gp_output_bias=gp_bias,
normalize_input=gp_input_normalization,
gp_cov_momentum=gp_cov_discount_factor,
gp_cov_ridge_penalty=gp_cov_ridge_penalty,
scale_random_features=False,
use_custom_random_features=True,
custom_random_features_initializer=make_random_feature_initializer(
gp_random_feature_type),
kernel_initializer=gp_output_initializer)
else:
output_layer = functools.partial(
tf.keras.layers.Dense,
activation=None,
kernel_initializer=tf.keras.initializers.RandomNormal(stddev=0.01),
name='fc1000')
outputs = output_layer(num_classes)(x)
return tf.keras.Model(inputs=inputs, outputs=outputs, name='resnet50')
def resnet50_sngp(input_shape,
batch_size,
num_classes,
use_mc_dropout,
dropout_rate,
filterwise_dropout,
use_gp_layer,
gp_hidden_dim,
gp_scale,
gp_bias,
gp_input_normalization,
gp_random_feature_type,
gp_cov_discount_factor,
gp_cov_ridge_penalty,
gp_output_imagenet_initializer,
use_spec_norm,
spec_norm_iteration,
spec_norm_bound,
omit_last_layer=False):
"""Builds ResNet50.
Using strided conv, pooling, four groups of residual blocks, and pooling, the
network maps spatial features of size 224x224 -> 112x112 -> 56x56 -> 28x28 ->
14x14 -> 7x7 (Table 1 of He et al. (2015)).
Args:
input_shape: Shape tuple of input excluding batch dimension.
batch_size: The batch size of the input layer. Required by the spectral
normalization.
num_classes: Number of output classes.
use_mc_dropout: Whether to apply Monte Carlo dropout.
dropout_rate: Dropout rate.
filterwise_dropout: Dropout whole convolutional filters instead of
individual values in the feature map.
use_gp_layer: Whether to use Gaussian process layer as the output layer.
gp_hidden_dim: The hidden dimension of the GP layer, which corresponds to
the number of random features used for the approximation.
gp_scale: The length-scale parameter for the RBF kernel of the GP layer.
gp_bias: The bias term for GP layer.
gp_input_normalization: Whether to normalize the input using LayerNorm for
GP layer. This is similar to automatic relevance determination (ARD) in
the classic GP learning.
gp_random_feature_type: The type of random feature to use for
`RandomFeatureGaussianProcess`.
gp_cov_discount_factor: The discount factor to compute the moving average of
precision matrix.
gp_cov_ridge_penalty: Ridge penalty parameter for GP posterior covariance.
gp_output_imagenet_initializer: Whether to initialize GP output layer using
Gaussian with small standard deviation (sd=0.01).
use_spec_norm: Whether to apply spectral normalization.
spec_norm_iteration: Number of power iterations to perform for estimating
the spectral norm of weight matrices.
spec_norm_bound: Upper bound to spectral norm of weight matrices.
omit_last_layer: Optional. Omits the last pooling layer if it is set to
True.
Returns:
tf.keras.Model.
"""
dropout_layer = functools.partial(
MonteCarloDropout,
dropout_rate=dropout_rate,
use_mc_dropout=use_mc_dropout,
filterwise_dropout=filterwise_dropout)
conv_layer = make_conv2d_layer(use_spec_norm=use_spec_norm,
spec_norm_iteration=spec_norm_iteration,
spec_norm_bound=spec_norm_bound)
inputs = tf.keras.layers.Input(shape=input_shape, batch_size=batch_size)
x = tf.keras.layers.ZeroPadding2D(padding=3, name='conv1_pad')(inputs)
# TODO(jereliu): apply SpectralNormalization to input layer as well.
x = tf.keras.layers.Conv2D(
64,
kernel_size=7,
strides=2,
padding='valid',
use_bias=False,
kernel_initializer='he_normal',
name='conv1')(x)
x = tf.keras.layers.BatchNormalization(
momentum=BATCH_NORM_DECAY,
epsilon=BATCH_NORM_EPSILON,
name='bn_conv1')(x)
x = tf.keras.layers.Activation('relu')(x)
x = dropout_layer(x)
x = tf.keras.layers.MaxPooling2D(3, strides=2, padding='same')(x)
x = group(
x, [64, 64, 256],
stage=2,
num_blocks=3,
strides=1,
conv_layer=conv_layer,
dropout_layer=dropout_layer)
x = group(
x, [128, 128, 512],
stage=3,
num_blocks=4,
strides=2,
conv_layer=conv_layer,
dropout_layer=dropout_layer)
x = group(
x, [256, 256, 1024],
stage=4,
num_blocks=6,
strides=2,
conv_layer=conv_layer,
dropout_layer=dropout_layer)
x = group(
x, [512, 512, 2048],
stage=5,
num_blocks=3,
strides=2,
conv_layer=conv_layer,
dropout_layer=dropout_layer)
if omit_last_layer:
return tf.keras.Model(inputs=inputs, outputs=x, name='resnet50')
return resnet50_sngp_add_last_layer(
inputs, x, num_classes, use_gp_layer, gp_hidden_dim, gp_scale, gp_bias,
gp_input_normalization, gp_random_feature_type, gp_cov_discount_factor,
gp_cov_ridge_penalty, gp_output_imagenet_initializer)
| google/uncertainty-baselines | uncertainty_baselines/models/resnet50_sngp.py | Python | apache-2.0 | 13,039 | [
"Gaussian"
] | 966dc5c35846a4e1504cc29598d2fce094648152b2d694231742a401b3791560 |
import numpy
def kurt2(*args):
''' Sample kurtosis (fourth moment divided by squared variance)
of a matrix. Kurtosis of a Gaussian distribution is 3.
MEAN (optional) and VAR (optional) make the computation faster. '''
if len(args) == 0:
print('Error: input matrix is required')
if len(args) < 2:
mn = args[0].mean()
else:
mn = args[1]
if len(args) < 3:
v = var2(args[0])
else:
v = args[2]
if numpy.isreal(args[0]).all():
res = (numpy.abs(args[0] - mn)**4).mean() / v**2
else:
res = ((((args[0] - mn).real**4).mean() / v.real**2) +
((numpy.i * (args[0] - mn).imag**4).mean() / v.imag**2))
return res
| tochikuji/pyPyrTools | pyrtools/kurt2.py | Python | mit | 732 | [
"Gaussian"
] | ff241ed5851b6d3008a418f3d7ddf3354704858baf067acb2c0205d9d9b7134e |
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2007 Donald N. Allingham
# Copyright (C) 2007-2012 Brian G. Matherly
# Copyright (C) 2010 Jakim Friant
# Copyright (C) 2014 Paul Franklin
# Copyright (C) 2010-2015 Craig J. Anderson
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""Reports/Graphical Reports/Ancestor Tree"""
#------------------------------------------------------------------------
#
# Python modules
#
#------------------------------------------------------------------------
#------------------------------------------------------------------------
#
# Gramps modules
#
#------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.sgettext
from gramps.gen.errors import ReportError
from gramps.gen.plug.menu import (TextOption, NumberOption, BooleanOption,
EnumeratedListOption, StringOption,
PersonOption)
from gramps.gen.plug.report import Report, MenuReportOptions, stdoptions
from gramps.gen.plug.docgen import (FontStyle, ParagraphStyle, GraphicsStyle,
FONT_SANS_SERIF, PARA_ALIGN_CENTER)
from gramps.plugins.lib.libtreebase import *
from gramps.plugins.lib.librecurse import AscendPerson
from gramps.gen.proxy import CacheProxyDb
from gramps.gen.display.name import displayer as _nd
PT2CM = utils.pt2cm
#cm2pt = utils.cm2pt
#------------------------------------------------------------------------
#
# Constants
#
#------------------------------------------------------------------------
_BORN = _("b.", "birth abbreviation"),
_DIED = _("d.", "death abbreviation"),
_MARR = _("m.", "marriage abbreviation"),
LVL_GEN, LVL_INDX, LVL_Y = range(3)
#------------------------------------------------------------------------
#
# Box classes
#
#------------------------------------------------------------------------
class PersonBox(BoxBase):
"""
Calculates information about the box that will print on a page
"""
def __init__(self, level):
BoxBase.__init__(self)
self.boxstr = "AC2-box"
#self.level = (level[0]-1, level[1])
self.level = level
def __lt__(self, other):
return self.level[LVL_Y] < other.level[LVL_Y]
class FamilyBox(BoxBase):
"""
Calculates information about the box that will print on a page
"""
def __init__(self, level):
BoxBase.__init__(self)
self.boxstr = "AC2-fam-box"
#self.level = (level[0]-1, level[1])
self.level = level
def __lt__(self, other):
return self.level[LVL_Y] < other.level[LVL_Y]
#------------------------------------------------------------------------
#
# Titles Class(es)
#
#------------------------------------------------------------------------
class TitleN(TitleNoDisplay):
"""No Title class for the report """
def __init__(self, doc, locale):
TitleNoDisplay.__init__(self, doc, "AC2-Title-box")
self._ = locale.translation.sgettext
def calc_title(self, center):
"""Calculate the title of the report"""
#we want no text, but need a text for the TOC in a book!
self.mark_text = self._("Ancestor Graph")
self.text = ''
class TitleA(TitleBox):
"""Title class for the report """
def __init__(self, doc, locale, name_displayer):
self._nd = name_displayer
TitleBox.__init__(self, doc, "AC2-Title-box")
self._ = locale.translation.sgettext
def calc_title(self, center):
"""Calculate the title of the report"""
name = ""
if center is not None:
name = self._nd.display(center)
# feature request 2356: avoid genitive form
self.text = self._("Ancestor Graph for %s") % name
self.set_box_height_width()
#------------------------------------------------------------------------
#
# CalcItems (helper class to calculate text)
# make_ancestor_tree (main recursive functions)
#
#------------------------------------------------------------------------
class CalcItems:
""" A helper class to calculate the default box text
and text for each person / marriage
"""
def __init__(self, dbase):
_gui = GUIConnect()
self._gui = _gui
#calculate the printed lines for each box
#str = ""
#if self.get_val('miss_val'):
# str = "_____"
display_repl = _gui.get_val("replace_list")
self.__calc_l = CalcLines(dbase, display_repl, _gui.locale, _gui.n_d)
self.__blank_father = None
self.__blank_mother = None
self.__blank_father = \
self.__calc_l.calc_lines(None, None, _gui.get_val("father_disp"))
self.__blank_mother = \
self.__calc_l.calc_lines(None, None, _gui.get_val("mother_disp"))
self.center_use = _gui.get_val("center_uses")
self.disp_father = _gui.get_val("father_disp")
self.disp_mother = _gui.get_val("mother_disp")
self.disp_marr = [_gui.get_val("marr_disp")]
self.__blank_marriage = \
self.__calc_l.calc_lines(None, None, self.disp_marr)
def calc_person(self, index, indi_handle, fams_handle):
working_lines = ""
if index[1] % 2 == 0 or (index[1] == 1 and self.center_use == 0):
if indi_handle == fams_handle is None:
working_lines = self.__calc_l.calc_lines(
None, None, self._gui.get_val("father_disp"))
else:
working_lines = self.disp_father
else:
if indi_handle == fams_handle is None:
working_lines = self.__calc_l.calc_lines(
None, None, self._gui.get_val("mother_disp"))
else:
working_lines = self.disp_mother
if indi_handle == fams_handle is None:
return working_lines
else:
return self.__calc_l.calc_lines(indi_handle, fams_handle,
working_lines)
def calc_marriage(self, indi_handle, fams_handle):
if indi_handle == fams_handle is None:
return self.__blank_marriage
else:
return self.__calc_l.calc_lines(indi_handle, fams_handle,
self.disp_marr)
class MakeAncestorTree(AscendPerson):
"""
The main procedure to use recursion to make the tree based off of a person.
order of people inserted into Persons is important.
makes sure that order is done correctly.
"""
def __init__(self, dbase, canvas):
_gui = GUIConnect()
AscendPerson.__init__(self, dbase, _gui.maxgen(), _gui.fill_out())
self.database = dbase
self.canvas = canvas
self.inlc_marr = _gui.inc_marr()
self.inc_sib = _gui.inc_sib()
self.compress_tree = _gui.compress_tree()
self.center_family = None
self.lines = [None] * (_gui.maxgen() + 1)
self.max_generation = 0
self.calc_items = CalcItems(self.database)
def add_person(self, index, indi_handle, fams_handle):
""" Makes a person box and add that person into the Canvas. """
#print str(index) + " add_person " + str(indi_handle)
myself = PersonBox((index[0] - 1,) + index[1:])
if index[LVL_GEN] == 1: # Center Person
self.center_family = fams_handle
if index[LVL_GEN] > self.max_generation:
self.max_generation = index[LVL_GEN]
myself.text = self.calc_items.calc_person(index,
indi_handle, fams_handle)
# myself.text[0] = myself.text[0] + ' ' + repr(index) # for debugging
if indi_handle is not None: # None is legal for an empty box
myself.add_mark(self.database,
self.database.get_person_from_handle(indi_handle))
self.canvas.add_box(myself)
#make the lines
indx = index[LVL_GEN]
self.lines[indx] = myself
if indx > 1:
if self.lines[indx - 1].line_to is None:
line = LineBase(self.lines[indx - 1])
self.lines[indx - 1].line_to = line
self.canvas.add_line(line)
else:
line = self.lines[indx - 1].line_to
line.add_to(myself)
return myself
def add_person_again(self, index, indi_handle, fams_handle):
self.add_person(index, indi_handle, fams_handle)
def add_marriage(self, index, indi_handle, fams_handle):
""" Makes a marriage box and add that person into the Canvas. """
if not self.inlc_marr:
return
myself = FamilyBox((index[0] - 1,) + index[1:])
#calculate the text.
myself.text = self.calc_items.calc_marriage(indi_handle, fams_handle)
self.canvas.add_box(myself)
def y_index(self, x_level, index):
""" Calculate the column or generation that this person is in.
x_level -> 0 to max_gen-1
index -> 1 to (self.max_generation**2)-1
"""
#Calculate which row in the column of people.
tmp_y = index - (2**x_level)
#Calculate which row in the table (yes table) of people.
delta = (2**self.max_generation) // (2**(x_level))
return int((delta / 2) + (tmp_y * delta)) - 1
def do_y_indx(self):
''' Make the y_index for all boxes
first off of a forumula, then remove blank areas around the edges,
then compress the tree if desired
'''
min_y = self.y_index(self.canvas.boxes[0].level[LVL_GEN],
self.canvas.boxes[0].level[LVL_INDX])
for box in self.canvas.boxes:
if "fam" in box.boxstr:
box.level = box.level + \
(self.y_index(box.level[LVL_GEN] - 1,
int(box.level[LVL_INDX] / 2)),)
else:
box.level = box.level + \
(self.y_index(box.level[LVL_GEN], box.level[LVL_INDX]),)
min_y = min(min_y, box.level[LVL_Y])
#print (str(box.level))
#if a last father (of fathers) does not have a father/parents
#Then there could be a gap. Remove this gap
if min_y > 0:
for box in self.canvas.boxes:
box.level = box.level[:LVL_Y] + (box.level[LVL_Y] - min_y,)
#Now that we have y_index, lets see if we need to squish the tree
self.canvas.boxes.sort() # Sort them on the y_index
if not self.compress_tree:
return
#boxes are already in top down [LVL_Y] form so lets
#set the box in the correct y level depending on compress_tree
y_level = 0
current_y = self.canvas.boxes[0].level[LVL_Y]
for box in self.canvas.boxes:
y_index = box.level[LVL_Y]
if y_index > current_y:
current_y = y_index
y_level += 1
box.level = box.level[:LVL_Y] + (y_level,)
def do_sibs(self):
if not self.inc_sib or self.center_family is None:
return
family = self.database.get_family_from_handle(self.center_family)
mykids = [kid.ref for kid in family.get_child_ref_list()]
if len(mykids) == 1: # No other siblings. Don't do anything.
return
# The first person is the center person had he/she has our information
center = self.canvas.boxes.pop(self.canvas.boxes.index(self.lines[1]))
line = center.line_to
level = center.level[LVL_Y]
move = level - (len(mykids) // 2) + ((len(mykids) + 1) % 2)
if move < 0:
# more kids than parents. ran off the page. Move them all down
for box in self.canvas.boxes:
box.level = (box.level[0], box.level[1], box.level[2] - move)
move = 0
line.start = []
rrr = -1 # if len(mykids)%2 == 1 else 0
for kid in mykids:
rrr += 1
mee = self.add_person((1, 1, move + rrr), kid, self.center_family)
line.add_from(mee)
#mee.level = (0, 1, level - (len(mykids)//2)+rrr)
mee.line_to = line
def start(self, person_id):
""" go ahead and make it happen """
center = self.database.get_person_from_gramps_id(person_id)
if center is None:
raise ReportError(
_("Person %s is not in the Database") % person_id)
center_h = center.get_handle()
#Step 1. Get the people
self.recurse(center_h)
#Step 2. Calculate the y_index for everyone
self.do_y_indx()
#Step 3. Siblings of the center person
self.do_sibs()
#------------------------------------------------------------------------
#
# Transform Classes
#
#------------------------------------------------------------------------
#------------------------------------------------------------------------
# Class lr_Transform
#------------------------------------------------------------------------
class LRTransform:
"""
setup all of the boxes on the canvas in for a left/right report
"""
def __init__(self, canvas, max_generations):
self.canvas = canvas
self.rept_opts = canvas.report_opts
self.y_offset = (self.rept_opts.littleoffset * 2 +
self.canvas.title.height)
def _place(self, box):
""" put the box in it's correct spot """
#1. cm_x
box.x_cm = self.rept_opts.littleoffset
box.x_cm += (box.level[LVL_GEN] *
(self.rept_opts.col_width + self.rept_opts.max_box_width))
#2. cm_y
box.y_cm = self.rept_opts.max_box_height + self.rept_opts.box_pgap
box.y_cm *= box.level[LVL_Y]
box.y_cm += self.y_offset
#if box.height < self.rept_opts.max_box_height:
# box.y_cm += ((self.rept_opts.max_box_height - box.height) /2)
def place(self):
""" Step through boxes so they can be put in the right spot """
#prime the pump
self.__last_y_level = self.canvas.boxes[0].level[LVL_Y]
#go
for box in self.canvas.boxes:
self._place(box)
#------------------------------------------------------------------------
#
# class make_report
#
#------------------------------------------------------------------------
class MakeReport:
def __init__(self, dbase, doc, canvas, font_normal):
self.database = dbase
self.doc = doc
self.canvas = canvas
self.font_normal = font_normal
_gui = GUIConnect()
self.inlc_marr = _gui.inc_marr()
self.compress_tree = _gui.compress_tree()
self.mother_ht = self.father_ht = 0
self.max_generations = 0
def get_height_width(self, box):
"""
obtain width information for each level (x)
obtain height information for each item
"""
self.canvas.set_box_height_width(box)
if box.width > self.canvas.report_opts.max_box_width:
self.canvas.report_opts.max_box_width = box.width # + box.shadow
if box.level[LVL_Y] > 0:
if box.level[LVL_INDX] % 2 == 0 and box.height > self.father_ht:
self.father_ht = box.height
elif box.level[LVL_INDX] % 2 == 1 and box.height > self.mother_ht:
self.mother_ht = box.height
if box.level[LVL_GEN] > self.max_generations:
self.max_generations = box.level[LVL_GEN]
def get_generations(self):
return self.max_generations
def start(self):
# __gui = GUIConnect()
# 1.
#set the sizes for each box and get the max_generations.
self.father_ht = 0.0
self.mother_ht = 0.0
for box in self.canvas.boxes:
self.get_height_width(box)
if self.compress_tree and not self.inlc_marr:
self.canvas.report_opts.max_box_height = \
min(self.father_ht, self.mother_ht)
else:
self.canvas.report_opts.max_box_height = \
max(self.father_ht, self.mother_ht)
#At this point we know everything we need to make the report.
#Size of each column of people - self.rept_opt.box_width
#size of each column (or row) of lines - self.rept_opt.col_width
#size of each row - self.rept_opt.box_height
#go ahead and set it now.
for box in self.canvas.boxes:
box.width = self.canvas.report_opts.max_box_width
# 2.
#setup the transform class to move around the boxes on the canvas
transform = LRTransform(self.canvas, self.max_generations)
transform.place()
class GUIConnect:
""" This is a BORG object. There is ONLY one.
This give some common routines that EVERYONE can use like
get the value from a GUI variable
"""
__shared_state = {}
def __init__(self): # We are BORG!
self.__dict__ = self.__shared_state
def set__opts(self, options, locale, name_displayer):
""" Set only once as we are BORG. """
self.__opts = options
self.locale = locale
self.n_d = name_displayer
def get_val(self, val):
""" Get a GUI value. """
value = self.__opts.get_option_by_name(val)
if value:
return value.get_value()
else:
False
def title_class(self, doc):
""" Return a class that holds the proper title based off of the
GUI options """
title_type = self.get_val('report_title')
if title_type:
return TitleA(doc, self.locale, self.n_d)
else:
return TitleN(doc, self.locale)
def inc_marr(self):
return self.get_val("inc_marr")
def inc_sib(self):
return self.get_val("inc_siblings")
def maxgen(self):
return self.get_val("maxgen")
def fill_out(self):
return self.get_val("fill_out")
def compress_tree(self):
return self.get_val("compress_tree")
#------------------------------------------------------------------------
#
# AncestorTree
#
#------------------------------------------------------------------------
class AncestorTree(Report):
""" AncestorTree Report """
def __init__(self, database, options, user):
"""
Create AncestorTree object that produces the report.
The arguments are:
database - the Gramps database instance
options - instance of the Options class for this report
user - a gen.user.User() instance
"""
Report.__init__(self, database, options, user)
self.options = options
self._user = user
self.set_locale(options.menu.get_option_by_name('trans').get_value())
stdoptions.run_date_format_option(self, options.menu)
stdoptions.run_private_data_option(self, options.menu)
stdoptions.run_living_people_option(self, options.menu, self._locale)
self.database = CacheProxyDb(self.database)
stdoptions.run_name_format_option(self, options.menu)
self._nd = self._name_display
def begin_report(self):
"""
This report needs the following parameters (class variables)
that come in the options class.
max_generations - Maximum number of generations to include.
pagebbg - Whether to include page breaks between generations.
dispf - Display format for the output box.
scale_report - Whether to scale the report to fit the width or all.
indblank - Whether to include blank pages.
compress - Whether to compress chart.
incl_private - Whether to include private data
living_people - How to handle living people
years_past_death - Consider as living this many years after death
We will
1. a canvas in its full one-page size
2. a page that we wish to print on
scale up/down either or both of the above as needed/desired.
almost all of this should be moved into Canvas!
"""
database = self.database
self.connect = GUIConnect()
self.connect.set__opts(self.options.menu, self._locale, self._nd)
#Set up the canvas that we will print on.
style_sheet = self.doc.get_style_sheet()
font_normal = style_sheet.get_paragraph_style("AC2-Normal").get_font()
#The canvas that we will put our report on and print off of
self.canvas = Canvas(self.doc,
ReportOptions(self.doc, font_normal, 'AC2-line'))
self.canvas.report_opts.box_shadow *= \
self.connect.get_val('shadowscale')
self.canvas.report_opts.box_pgap *= self.connect.get_val('box_Yscale')
self.canvas.report_opts.box_mgap *= self.connect.get_val('box_Yscale')
with self._user.progress(_('Ancestor Tree'),
_('Making the Tree...'), 4) as step:
#make the tree onto the canvas
# inlc_marr = self.connect.get_val("inc_marr")
self.max_generations = self.connect.get_val('maxgen')
tree = MakeAncestorTree(database, self.canvas)
tree.start(self.connect.get_val('pid'))
tree = None
step()
#Title
title = self.connect.title_class(self.doc)
center = self.database.get_person_from_gramps_id(
self.connect.get_val('pid'))
title.calc_title(center)
self.canvas.add_title(title)
#make the report as big as it wants to be.
report = MakeReport(database, self.doc, self.canvas, font_normal)
report.start()
self.max_generations = report.get_generations() # already know
report = None
step()
#Note?
if self.connect.get_val("inc_note"):
note_box = NoteBox(self.doc, "AC2-note-box",
self.connect.get_val("note_place"))
subst = SubstKeywords(self.database, self._locale, self._nd,
None, None)
note_box.text = subst.replace_and_clean(
self.connect.get_val('note_disp'))
self.canvas.add_note(note_box)
#Now we have the report in its full size.
#Do we want to scale the report?
one_page = self.connect.get_val("resize_page")
scale_report = self.connect.get_val("scale_tree")
scale = self.canvas.scale_report(one_page,
scale_report != 0,
scale_report == 2)
step()
if scale != 1 or self.connect.get_val('shadowscale') != 1.0:
self.scale_styles(scale)
def write_report(self):
one_page = self.connect.get_val("resize_page")
#scale_report = self.connect.get_val("scale_tree")
#inlc_marr = self.connect.get_val("inc_marr")
inc_border = self.connect.get_val('inc_border')
incblank = self.connect.get_val("inc_blank")
prnnum = self.connect.get_val("inc_pagenum")
#####################
#Setup page information
colsperpage = self.doc.get_usable_width()
colsperpage += self.canvas.report_opts.col_width
colsperpage = int(
colsperpage / (self.canvas.report_opts.max_box_width +
self.canvas.report_opts.col_width))
colsperpage = colsperpage or 1
#####################
#Vars
if prnnum:
page_num_box = PageNumberBox(self.doc, 'AC2-box', self._locale)
#TODO - Here
#####################
#ok, everyone is now ready to print on the canvas. Paginate?
self.canvas.paginate(colsperpage, one_page)
#####################
#Yeah!!!
#lets finally make some pages!!!
#####################
pages = self.canvas.page_count(incblank)
with self._user.progress(_('Ancestor Tree'),
_('Printing the Tree...'), pages) as step:
for page in self.canvas.page_iter_gen(incblank):
self.doc.start_page()
#do we need to print a border?
if inc_border:
page.draw_border('AC2-line')
#Do we need to print the page number?
if prnnum:
page_num_box.display(page)
#Print the individual people and lines
page.display()
step()
self.doc.end_page()
def scale_styles(self, scale):
"""
Scale the styles for this report.
"""
style_sheet = self.doc.get_style_sheet()
graph_style = style_sheet.get_draw_style("AC2-box")
graph_style.set_shadow(graph_style.get_shadow(),
self.canvas.report_opts.box_shadow * scale)
graph_style.set_line_width(graph_style.get_line_width() * scale)
style_sheet.add_draw_style("AC2-box", graph_style)
graph_style = style_sheet.get_draw_style("AC2-fam-box")
graph_style.set_shadow(graph_style.get_shadow(),
self.canvas.report_opts.box_shadow * scale)
graph_style.set_line_width(graph_style.get_line_width() * scale)
style_sheet.add_draw_style("AC2-fam-box", graph_style)
graph_style = style_sheet.get_draw_style("AC2-note-box")
#graph_style.set_shadow(graph_style.get_shadow(),
# self.canvas.report_opts.box_shadow * scale)
graph_style.set_line_width(graph_style.get_line_width() * scale)
style_sheet.add_draw_style("AC2-note-box", graph_style)
para_style = style_sheet.get_paragraph_style("AC2-Normal")
font = para_style.get_font()
font.set_size(font.get_size() * scale)
para_style.set_font(font)
style_sheet.add_paragraph_style("AC2-Normal", para_style)
para_style = style_sheet.get_paragraph_style("AC2-Note")
font = para_style.get_font()
font.set_size(font.get_size() * scale)
para_style.set_font(font)
style_sheet.add_paragraph_style("AC2-Note", para_style)
para_style = style_sheet.get_paragraph_style("AC2-Title")
font = para_style.get_font()
font.set_size(font.get_size() * scale)
para_style.set_font(font)
style_sheet.add_paragraph_style("AC2-Title", para_style)
graph_style = GraphicsStyle()
width = graph_style.get_line_width()
width = width * scale
graph_style.set_line_width(width)
style_sheet.add_draw_style("AC2-line", graph_style)
self.doc.set_style_sheet(style_sheet)
#------------------------------------------------------------------------
#
# AncestorTreeOptions
#
#------------------------------------------------------------------------
class AncestorTreeOptions(MenuReportOptions):
"""
Defines options and provides handling interface.
"""
def __init__(self, name, dbase):
self.__db = dbase
self.__pid = None
self.box_Y_sf = None
self.box_shadow_sf = None
MenuReportOptions.__init__(self, name, dbase)
def get_subject(self):
""" Return a string that describes the subject of the report. """
gid = self.__pid.get_value()
person = self.__db.get_person_from_gramps_id(gid)
return _nd.display(person)
def add_menu_options(self, menu):
##################
category_name = _("Tree Options")
self.__pid = PersonOption(_("Center Person"))
self.__pid.set_help(_("The center person for the tree"))
menu.add_option(category_name, "pid", self.__pid)
siblings = BooleanOption(
_('Include siblings of the center person'), False)
siblings.set_help(
_("Whether to only display the center person or all "
"of his/her siblings too"))
menu.add_option(category_name, "inc_siblings", siblings)
self.max_gen = NumberOption(_("Generations"), 10, 1, 50)
self.max_gen.set_help(_("The number of generations to include "
"in the tree"))
menu.add_option(category_name, "maxgen", self.max_gen)
self.fillout = EnumeratedListOption(_("Display unknown\ngenerations"),
0)
self.fillout.set_help(_("The number of generations of empty "
"boxes that will be displayed"))
menu.add_option(category_name, "fill_out", self.fillout)
self.max_gen.connect('value-changed', self.__fillout_vals)
self.__fillout_vals()
compress = BooleanOption(_('Compress tree'), True)
compress.set_help(
_("Whether to remove any extra blank spaces set "
"aside for people that are unknown"))
menu.add_option(category_name, "compress_tree", compress)
#better to 'Show siblings of\nthe center person
#Spouse_disp = EnumeratedListOption(_("Show spouses of\nthe center "
# "person"), 0)
#Spouse_disp.add_item(0, _("No. Do not show Spouses"))
#Spouse_disp.add_item(1, _("Yes, and use the Main Display Format"))
#Spouse_disp.add_item(2, _("Yes, and use the Secondary "
# "Display Format"))
#Spouse_disp.set_help(_("Show spouses of the center person?"))
#menu.add_option(category_name, "Spouse_disp", Spouse_disp)
##################
category_name = _("Report Options")
self.title = EnumeratedListOption(_("Report Title"), 0)
self.title.add_item(0, _("Do not include a title"))
self.title.add_item(1, _("Include Report Title"))
self.title.set_help(_("Choose a title for the report"))
menu.add_option(category_name, "report_title", self.title)
border = BooleanOption(_('Include a border'), False)
border.set_help(_("Whether to make a border around the report."))
menu.add_option(category_name, "inc_border", border)
prnnum = BooleanOption(_('Include Page Numbers'), False)
prnnum.set_help(_("Whether to print page numbers on each page."))
menu.add_option(category_name, "inc_pagenum", prnnum)
self.scale = EnumeratedListOption(_("Scale tree to fit"), 0)
self.scale.add_item(0, _("Do not scale tree"))
self.scale.add_item(1, _("Scale tree to fit page width only"))
self.scale.add_item(2, _("Scale tree to fit the size of the page"))
self.scale.set_help(
_("Whether to scale the tree to fit a specific paper size"))
menu.add_option(category_name, "scale_tree", self.scale)
self.scale.connect('value-changed', self.__check_blank)
if "BKI" not in self.name.split(","):
self.__onepage = BooleanOption(
_("Resize Page to Fit Tree size\n"
"\n"
"Note: Overrides options in the 'Paper Option' tab"
),
False)
self.__onepage.set_help(
_("Whether to resize the page to fit the size \n"
"of the tree. Note: the page will have a \n"
"non standard size.\n"
"\n"
"With this option selected, the following will happen:\n"
"\n"
"With the 'Do not scale tree' option the page\n"
" is resized to the height/width of the tree\n"
"\n"
"With 'Scale tree to fit page width only' the height of\n"
" the page is resized to the height of the tree\n"
"\n"
"With 'Scale tree to fit the size of the page' the page\n"
" is resized to remove any gap in either height or width"
))
menu.add_option(category_name, "resize_page", self.__onepage)
self.__onepage.connect('value-changed', self.__check_blank)
else:
self.__onepage = None
self.__blank = BooleanOption(_('Include Blank Pages'), True)
self.__blank.set_help(_("Whether to include pages that are blank."))
menu.add_option(category_name, "inc_blank", self.__blank)
self.__check_blank()
##################
category_name = _("Report Options (2)")
stdoptions.add_name_format_option(menu, category_name)
stdoptions.add_living_people_option(menu, category_name)
stdoptions.add_private_data_option(menu, category_name)
locale_opt = stdoptions.add_localization_option(menu, category_name)
stdoptions.add_date_format_option(menu, category_name, locale_opt)
##################
category_name = _("Display")
disp = TextOption(_("Father\nDisplay Format"),
["$n",
"%s $b" % _BORN,
"-{%s $d}" % _DIED])
disp.set_help(_("Display format for the fathers box."))
menu.add_option(category_name, "father_disp", disp)
#Will add when libsubstkeyword supports it.
#missing = EnumeratedListOption(_("Replace missing\nplaces\\dates \
# with"), 0)
#missing.add_item(0, _("Does not display anything"))
#missing.add_item(1, _("Displays '_____'"))
#missing.set_help(_("What will print when information is not known"))
#menu.add_option(category_name, "miss_val", missing)
disp_mom = TextOption(_("Mother\nDisplay Format"),
["$n",
"%s $b" % _BORN,
"%s $m" % _MARR,
"-{%s $d}" % _DIED])
disp_mom.set_help(_("Display format for the mothers box."))
menu.add_option(category_name, "mother_disp", disp_mom)
center_disp = EnumeratedListOption(_("Center person uses\n"
"which format"), 0)
center_disp.add_item(0, _("Use Fathers Display format"))
center_disp.add_item(1, _("Use Mothers display format"))
center_disp.set_help(_("The display format for the center person"))
menu.add_option(category_name, "center_uses", center_disp)
self.incmarr = BooleanOption(_('Include Marriage box'), False)
self.incmarr.set_help(
_("Whether to include a separate marital box in the report"))
menu.add_option(category_name, "inc_marr", self.incmarr)
self.incmarr.connect('value-changed', self._incmarr_changed)
self.marrdisp = StringOption(_("Marriage\nDisplay Format"),
"%s $m" % _MARR)
self.marrdisp.set_help(_("Display format for the marital box."))
menu.add_option(category_name, "marr_disp", self.marrdisp)
self._incmarr_changed()
##################
category_name = _("Advanced")
repldisp = TextOption(
_("Replace Display Format:\n'Replace this'/' with this'"),
[])
repldisp.set_help(_("i.e.\nUnited States of America/U.S.A"))
menu.add_option(category_name, "replace_list", repldisp)
# TODO this code is never used and so I conclude it is for future use
# self.__include_images = BooleanOption(
# _('Include thumbnail images of people'), False)
# self.__include_images.set_help(
# _("Whether to include thumbnails of people."))
# menu.add_option(category_name, "includeImages",
# self.__include_images)
self.usenote = BooleanOption(_('Include a note'), False)
self.usenote.set_help(_("Whether to include a note on the report."))
menu.add_option(category_name, "inc_note", self.usenote)
self.usenote.connect('value-changed', self._usenote_changed)
self.notedisp = TextOption(_("Note"), [])
self.notedisp.set_help(_("Add a note\n\n"
"$T inserts today's date"))
menu.add_option(category_name, "note_disp", self.notedisp)
locales = NoteType(0, 1)
self.notelocal = EnumeratedListOption(_("Note Location"), 0)
for num, text in locales.note_locals():
self.notelocal.add_item(num, text)
self.notelocal.set_help(_("Where to place the note."))
menu.add_option(category_name, "note_place", self.notelocal)
self._usenote_changed()
self.box_Y_sf = NumberOption(_("inter-box scale factor"),
1.00, 0.10, 2.00, 0.01)
self.box_Y_sf.set_help(
_("Make the inter-box spacing bigger or smaller"))
menu.add_option(category_name, "box_Yscale", self.box_Y_sf)
self.box_shadow_sf = NumberOption(_("box shadow scale factor"),
1.00, 0.00, 2.00, 0.01) # down to 0
self.box_shadow_sf.set_help(_("Make the box shadow bigger or smaller"))
menu.add_option(category_name, "shadowscale", self.box_shadow_sf)
def _incmarr_changed(self):
"""
If Marriage box is not enabled, disable Marriage Display Format box
"""
value = self.incmarr.get_value()
self.marrdisp.set_available(value)
def _usenote_changed(self):
"""
If Note box is not enabled, disable Note Location box
"""
value = self.usenote.get_value()
self.notelocal.set_available(value)
def __check_blank(self):
if self.__onepage:
value = not self.__onepage.get_value()
else:
value = True
off = value and (self.scale.get_value() != 2)
self.__blank.set_available(off)
def __fillout_vals(self):
max_gen = self.max_gen.get_value()
old_val = self.fillout.get_value()
item_list = []
item_list.append([0, _("No generations of empty boxes "
"for unknown ancestors")])
if max_gen > 1:
item_list.append([1, _("One Generation of empty boxes "
"for unknown ancestors")])
item_list.extend(
[itr, str(itr) +
_(" Generations of empty boxes for unknown ancestors")]
for itr in range(2, max_gen))
self.fillout.set_items(item_list)
if old_val + 2 > len(item_list):
self.fillout.set_value(len(item_list) - 2)
def make_default_style(self, default_style):
"""Make the default output style for the Ancestor Tree."""
# Paragraph Styles:
font = FontStyle()
font.set_size(9)
font.set_type_face(FONT_SANS_SERIF)
para_style = ParagraphStyle()
para_style.set_font(font)
para_style.set_description(
_('The basic style used for the text display.'))
default_style.add_paragraph_style("AC2-Normal", para_style)
box_shadow = PT2CM(font.get_size()) * .6
font = FontStyle()
font.set_size(9)
font.set_type_face(FONT_SANS_SERIF)
para_style = ParagraphStyle()
para_style.set_font(font)
para_style.set_description(
_('The basic style used for the note display.'))
default_style.add_paragraph_style("AC2-Note", para_style)
font = FontStyle()
font.set_size(16)
font.set_type_face(FONT_SANS_SERIF)
para_style = ParagraphStyle()
para_style.set_font(font)
para_style.set_alignment(PARA_ALIGN_CENTER)
para_style.set_description(_('The style used for the title.'))
default_style.add_paragraph_style("AC2-Title", para_style)
# Draw styles
graph_style = GraphicsStyle()
graph_style.set_paragraph_style("AC2-Normal")
graph_style.set_shadow(1, box_shadow) # shadow set by text size
graph_style.set_fill_color((255, 255, 255))
default_style.add_draw_style("AC2-box", graph_style)
graph_style = GraphicsStyle()
graph_style.set_paragraph_style("AC2-Normal")
#graph_style.set_shadow(0, PT2CM(9)) # shadow set by text size
graph_style.set_fill_color((255, 255, 255))
default_style.add_draw_style("AC2-fam-box", graph_style)
graph_style = GraphicsStyle()
graph_style.set_paragraph_style("AC2-Note")
graph_style.set_fill_color((255, 255, 255))
default_style.add_draw_style("AC2-note-box", graph_style)
# TODO this seems meaningless, as only the text is displayed
graph_style = GraphicsStyle()
graph_style.set_paragraph_style("AC2-Title")
graph_style.set_color((0, 0, 0))
graph_style.set_fill_color((255, 255, 255))
graph_style.set_line_width(0)
graph_style.set_description(_("Cannot edit this reference"))
default_style.add_draw_style("AC2-Title-box", graph_style)
graph_style = GraphicsStyle()
default_style.add_draw_style("AC2-line", graph_style)
#=====================================
#But even if you should suffer for what is right, you are blessed.
#"Do not fear what they fear ; do not be frightened."
#Take Courage
#1 Peter 3:14
| Fedik/gramps | gramps/plugins/drawreport/ancestortree.py | Python | gpl-2.0 | 42,346 | [
"Brian"
] | a3497c25def2d869a89b91c02b9a9406b76f86b4eb927279b33121163a76ef22 |
#!/usr/bin/env python
''' script for filtering insertions vs. the human reference GRCh37/hg19 '''
''' may be useful as a template for extension to other species '''
import pysam
import sys
import os
import logging
import argparse
import align
import numpy as np
import subprocess
from uuid import uuid4
verbose=False
FORMAT = '%(asctime)s %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger(__name__)
if verbose:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
tebreak_dir = os.path.dirname(os.path.realpath(__file__))
def load_falib(infa):
seqdict = {}
with open(infa, 'r') as fa:
seqid = ''
seq = ''
for line in fa:
if line.startswith('>'):
if seq != '':
seqdict[seqid] = seq
seqid = line.lstrip('>').strip().split()[0]
seq = ''
else:
assert seqid != ''
seq = seq + line.strip()
if seqid not in seqdict and seq != '':
seqdict[seqid] = seq
return seqdict
def ref_filter(chrom, start, end, superfams, tbx, extend=0):
start = int(start)
end = int(end)
if extend > 0:
start -= extend
end += extend
if start < 0: start = 0
for sf in superfams.split(','):
if sf == 'L1':
if chrom not in tbx[sf].contigs: return True
for ins in tbx[sf].fetch(chrom, start, end): return True
if sf in ('ALU', 'SVA'):
if chrom not in tbx[sf].contigs: return True
for ins in tbx[sf].fetch(chrom, start, end): return True
if sf == 'SVA':
if chrom not in tbx[sf].contigs: return True
for ins in tbx[sf].fetch(chrom, start, end): return True
return False
def len_filter(rec):
telen = int(rec['TE_Align_End']) - int(rec['TE_Align_Start'])
if 'ALU' in rec['Superfamily'] and telen < 250: return True
if 'SVA' in rec['Superfamily'] and telen < 1000: return True
if 'L1' in rec['Superfamily'] and int(rec['TE_Align_End']) < 5950: return True
return False
def avgmap(maptabix, chrom, start, end):
''' return average mappability across chrom:start-end region; maptabix = pysam.Tabixfile'''
scores = []
if None in (start, end): return None
if chrom in maptabix.contigs:
for rec in maptabix.fetch(chrom, int(start), int(end)):
mchrom, mstart, mend, mscore = rec.strip().split()
mstart, mend = int(mstart), int(mend)
mscore = float(mscore)
while mstart < mend and mstart:
mstart += 1
if mstart >= int(start) and mstart <= int(end):
scores.append(mscore)
if len(scores) > 0:
return sum(scores) / float(len(scores))
else:
return 0.0
else:
return 0.0
def rc(dna):
''' reverse complement '''
complements = maketrans('acgtrymkbdhvACGTRYMKBDHV', 'tgcayrkmvhdbTGCAYRKMVHDB')
return dna.translate(complements)[::-1]
def realign_filter(rec, inslib):
seqn = rec['Superfamily'] + ':' + rec['Subfamily']
if seqn not in inslib:
return False
seq_headers = ['Genomic_Consensus_5p', 'Genomic_Consensus_3p', 'Insert_Consensus_5p', 'Insert_Consensus_3p']
matches = []
for seqtype in seq_headers:
if rec[seqtype] == 'NA':
continue
#print seqtype, rec[seqtype]
alignment = align(rec[seqtype], inslib[seqn], rec['Subfamily'])
if alignment:
matches.append([seqtype] + alignment)
return matches
def align(qryseq, refseq, elt):
rnd = str(uuid4())
tgtfa = 'tmp.' + rnd + '.tgt.fa'
qryfa = 'tmp.' + rnd + '.qry.fa'
tgt = open(tgtfa, 'w')
qry = open(qryfa, 'w')
tgt.write('>ref' + '\n' + refseq + '\n')
qry.write('>qry' + '\n' + qryseq + '\n')
tgt.close()
qry.close()
cmd = ['exonerate', '--bestn', '1', '-m', 'ungapped', '--showalignment','0', '--ryo', elt + '\t%s\t%qab\t%qae\t%tab\t%tae\t%pi\n', qryfa, tgtfa]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
best = []
topscore = 0
for pline in p.stdout.readlines():
if pline.startswith(elt):
c = pline.strip().split()
if int(c[1]) > topscore:
topscore = int(c[1])
best = c
os.remove(tgtfa)
os.remove(qryfa)
return best
def overlap(iv1, iv2):
if min(iv1[1], iv2[1]) - max(iv1[0], iv2[0]) > 0: # is there overlap?
return [max(iv1[0], iv2[0]), min(iv1[1], iv2[1])]
return None
def main(args):
l1_ref = tebreak_dir + '/../lib/mask.L1.hg19.bed.gz'
alu_ref = tebreak_dir + '/../lib/mask.Alu.hg19.bed.gz'
sva_ref = tebreak_dir + '/../lib/mask.SVA.hg19.bed.gz'
map_ref = tebreak_dir + '/../lib/wgEncodeCrgMapabilityAlign100mer.bed.gz'
inslib = None
if args.insref:
inslib = load_falib(args.insref)
for fn in (l1_ref, alu_ref, sva_ref):
if not os.path.exists(fn): sys.exit('reference %s not found' % fn)
if not os.path.exists(fn + '.tbi'): sys.exit('index for reference %s not found' %fn)
tbx = {}
tbx['L1'] = pysam.Tabixfile(l1_ref)
tbx['ALU'] = pysam.Tabixfile(alu_ref)
tbx['SVA'] = pysam.Tabixfile(sva_ref)
map_tbx = pysam.Tabixfile(map_ref)
header = []
with open(args.tabfile, 'r') as tab:
for i, line in enumerate(tab):
if i == 0: # header
header = line.strip().split('\t')
if args.realign and args.insref:
header += ['ExonerateRealign']
if args.chimera:
header += ['ChimeraBaseCount', 'ChimeraMatchIns', 'ChimeraMatchRef', 'InsSiteHomology', 'PossibleRefEltChimera']
print '\t'.join(header)
else:
rec = {}
out = True
for n, field in enumerate(line.strip().split('\t')):
rec[header[n]] = field
#logger.debug(rec['UUID'])
if int(rec['3p_Cons_Len']) < 120 and int(rec['5p_Cons_Len']) < 120:
logger.debug('Filtered %s: consensus length < %d' % (rec['UUID'], 120))
out = False
if 'NA' in (rec['TE_Align_Start'], rec['TE_Align_End']):
logger.debug('Filtered %s: TE_Align_Start or TE_Align_End is "NA"' % rec['UUID'])
out = False
ref_present = False
if args.wideref:
ref_present = ref_filter(rec['Chromosome'], rec['Left_Extreme'], rec['Right_Extreme'], rec['Superfamily'], tbx, extend=10000)
else:
ref_present = ref_filter(rec['Chromosome'], rec['Left_Extreme'], rec['Right_Extreme'], rec['Superfamily'], tbx)
if ref_present and not args.ignore_ref_filter:
logger.debug('Filtered %s: proximity to reference TE of same superfamily' % rec['UUID'])
out = False
if max(float(rec['5p_Elt_Match']), float(rec['3p_Elt_Match'])) < 0.95:
logger.debug('Filtered %s: max(5p_Elt_Match, 3p_Elt_Match) < 0.95' % rec['UUID'])
out = False
if max(float(rec['5p_Genome_Match']), float(rec['3p_Genome_Match'])) < 0.98:
logger.debug('Filtered %s: max(5p_Genome_Match, 3p_Genome_Match) < 0.98' % rec['UUID'])
out = False
mapscore = avgmap(map_tbx, rec['Chromosome'], rec['Left_Extreme'], rec['Right_Extreme'])# * (max(int(rec['3p_Cons_Len']), int(rec['5p_Cons_Len']))/100.)
if mapscore < 0.1:
logger.debug('Filtered %s: mappability of %f < 0.1' % (rec['UUID'], mapscore))
out = False
if float(rec['Remapped_Discordant']) < 4:
logger.debug('Filtered %s: low discordant evidence (< 4 reads)' % rec['UUID'])
out = False
if float(rec['Remap_Disc_Fraction']) < 0.5:
logger.debug('Filtered %s: low discordant evidence (< 50pct supporting)' % rec['UUID'])
out = False
if rec['Insert_Consensus_5p'] == rec['Insert_Consensus_3p'] == 'NA':
logger.debug('Filtered %s: no insertion consensus mapped to insertion reference' % rec['UUID'])
out = False
if args.lenfilter and out and len_filter(rec):
logger.debug('Filtered %s: TE length filter' % rec['UUID'])
out = False
align_info = 'NA'
if out and args.realign and args.insref:
align_info = realign_filter(rec, inslib)
if len(align_info) == 0:
out = False
well_aligned = False
for alignment in align_info:
seqtype, _, score, qstart, qend, tstart, tend, pi = alignment
tstart = int(tstart)
tend = int(tend)
pi = float(pi)
if pi >= 95.0 and abs(tend-tstart) >= 100:
well_aligned = True
if not well_aligned: out = False
ins_site_homlen = 0 # insertion site homology length
ins_site_homseq = 'NA' # sequence of overlapped region
ch_ref_present = False
ins_pct_match = 0.0
ref_pct_match = 0.0
if out and args.chimera:
if not args.refgenome:
sys.exit('--refgenome required in conjunction with --chimera')
if not args.insref:
sys.exit('--insref required in conjunction with --chimera')
ref = pysam.Fastafile(args.refgenome)
left = int(rec['Left_Extreme']) - 1000
right = int(rec['Right_Extreme']) + 1000
if left < 0: left = 0
ref_seq = ref.fetch(rec['Chromosome'], left, right)
seqn = rec['Superfamily'] + ':' + rec['Subfamily']
ins_seq = inslib[seqn]
alignside = ''
ins_align = []
gen_align = []
if rec['Genomic_Consensus_3p'] != 'NA':
ins_align = align(rec['Genomic_Consensus_3p'], ins_seq, rec['Subfamily'])
gen_align = align(rec['Genomic_Consensus_3p'], ref_seq, 'Genomic')
alignside = 'Genomic_Consensus_3p'
else:
ins_align = align(rec['Genomic_Consensus_5p'], ins_seq, rec['Subfamily'])
gen_align = align(rec['Genomic_Consensus_5p'], ref_seq, 'Genomic')
alignside = 'Genomic_Consensus_5p'
ins_subcoords = None
if ins_align:
ins_subcoords = map(int, ins_align[2:4])
gen_subcoords = None
if gen_align:
gen_subcoords = map(int, gen_align[2:4])
else:
out = False
ol = None
if gen_subcoords is not None and ins_subcoords is not None:
ol = overlap(ins_subcoords, gen_subcoords)
if ol is not None:
ins_site_homlen = ol[1]-ol[0]
ins_site_homseq = rec[alignside][ol[0]:ol[1]]
ch_align_ins = align(ins_site_homseq, ins_seq, 'Ins')
ch_align_ref = align(ins_site_homseq, ref_seq, 'Ref')
if ch_align_ins:
ins_pct_match = ch_align_ins[-1]
if ch_align_ref:
ref_pct_match = ch_align_ref[-1]
# chimera with adjacent ref element check
ch_ref_present = ref_filter(rec['Chromosome'], rec['Left_Extreme'], rec['Right_Extreme'], rec['Superfamily'], tbx, extend=10000)
if out:
fields = line.strip().split()
if args.insref and args.realign:
fields.append(','.join([';'.join(alignment) for alignment in align_info]))
if args.chimera:
fields.append(str(ins_site_homlen))
fields.append(str(ins_pct_match))
fields.append(str(ref_pct_match))
fields.append(ins_site_homseq)
fields.append(str(ch_ref_present))
print '\t'.join(fields)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='filter script for TEs on hg19')
parser.add_argument('--tabfile', required=True, help='tabular output from resolve.py, requires header to be present')
parser.add_argument('--insref', default=None, help='req. alignment to insertion sequence reference')
parser.add_argument('--ignore_ref_filter', default=False, action='store_true', help='turn of filtering vs. reference elements')
parser.add_argument('--lenfilter', default=False, action='store_true', help='turn on filter by insertion length')
parser.add_argument('--refgenome', default=None)
parser.add_argument('--realign', default=False, action='store_true')
parser.add_argument('--chimera', default=False, action='store_true')
parser.add_argument('--wideref', default=False, action='store_true')
args = parser.parse_args()
main(args)
| adamewing/tebreak | scripts/misc/filter_hg19.py | Python | mit | 13,875 | [
"pysam"
] | 0934f09531139324a115fc11862583ebf0c5138a3a5be58e05d611926507d312 |
#!/usr/bin/python
# flake8: noqa
import unittest
from sznqalibs import hoover
import copy
import json
import unittest
class DictPathTest(unittest.TestCase):
def setUp(self):
super(DictPathTest, self).setUp()
class PathyDict(dict, hoover.DictPath):
pass
testDict = {
's': 11,
'x': {
'a': 55,
'hello': {
'world': 1, 'sun': 3, 'blackhole': None
},
'b': 59
},
}
self.pdict = PathyDict(testDict)
def testDelSun(self):
oracle = copy.deepcopy(self.pdict)
result = copy.deepcopy(self.pdict)
del oracle['x']['hello']['sun']
result.delpath("/x/hello/sun")
self.assertEqual(oracle, result)
def testGetHello(self):
oracle = copy.deepcopy(self.pdict['x']['hello'])
result = self.pdict.getpath("/x/hello")
self.assertEqual(oracle, result)
def testSetHello(self):
oracle = copy.deepcopy(self.pdict)
result = copy.deepcopy(self.pdict)
oracle['x']['hello']['sun'] = 'moon'
result.setpath("/x/hello/sun", 'moon')
self.assertEqual(oracle, result)
def testSetNewItem(self):
oracle = copy.deepcopy(self.pdict)
result = copy.deepcopy(self.pdict)
oracle['x']['hullo'] = 'NEW'
result.setpath("/x/hullo", 'NEW')
self.assertEqual(oracle, result)
def testHelloExists(self):
self.assertTrue(self.pdict.ispath('/x/hello'))
def testWorldNotExists(self):
self.assertFalse(self.pdict.ispath('/x/world'))
def testDelBadPath(self):
fn = lambda: self.pdict.delpath('/x/hullo')
self.assertRaises(KeyError, fn)
def testGetBadPath(self):
fn = lambda: self.pdict.getpath('/x/hullo')
self.assertRaises(KeyError, fn)
def testSetBadPath(self):
fn = lambda: self.pdict.setpath('/x/hullo/newthing', 1)
self.assertRaises(KeyError, fn)
# the scary None
def testDelNone(self):
oracle = copy.deepcopy(self.pdict)
result = copy.deepcopy(self.pdict)
del oracle['x']['hello']['blackhole']
result.delpath("/x/hello/blackhole")
self.assertEqual(oracle, result)
def testSetNone(self):
oracle = copy.deepcopy(self.pdict)
result = copy.deepcopy(self.pdict)
oracle['x']['hello']['sun'] = None
result.setpath("/x/hello/sun", None)
self.assertEqual(oracle, result)
def testSetNewNone(self):
oracle = copy.deepcopy(self.pdict)
result = copy.deepcopy(self.pdict)
oracle['x']['hullo'] = None
result.setpath("/x/hullo", None)
self.assertEqual(oracle, result)
def testGetNone(self):
oracle = copy.deepcopy(self.pdict['x']['hello']['blackhole'])
result = self.pdict.getpath("/x/hello/blackhole")
self.assertEqual(oracle, result)
def testNoneExists(self):
result = self.pdict.ispath('/x/hello/blackhole')
self.assertTrue(result)
class CartmanTest(unittest.TestCase):
def sdiff(self, a, b):
sa = [json.dumps(i) for i in a]
sb = [json.dumps(i) for i in b]
diff = set(sa) - set(sb)
return [json.loads(i) for i in diff]
def chkoracle(self, o):
def dups(self):
so = [json.dumps(i) for i in o]
return len(o) != len(set(so))
if dups(o):
self.logger.warn("duplicates in oracle!")
def setUp(self):
super(CartmanTest, self).setUp()
def compare(self, source, scheme, oracle):
self.chkoracle(oracle)
def fmtdiff(diff, word):
strn = ""
if diff:
strn = ("\n----------------------"
"\n %s elements (%s):\n%s"
% (word, len(diff), pretty(diff)))
return strn
pretty = hoover.jsDump
cm = hoover.Cartman(source, scheme)
result = [i for i in cm]
xtra = self.sdiff(result, oracle)
miss = self.sdiff(oracle, result)
err = ""
err += fmtdiff(miss, 'missing')
err += fmtdiff(xtra, 'extra')
return err
def test_Flat_2of3(self):
scheme = {
'a': hoover.Cartman.Iterable,
'b': hoover.Cartman.Iterable,
}
source = {
'a': [1, 2, 3],
'b': ['i', 'ii', 'iii'],
'c': ['I', 'II', 'III'],
}
oracle = [
{'a': 1, 'b': 'i'},
{'a': 1, 'b': 'ii'},
{'a': 1, 'b': 'iii'},
{'a': 2, 'b': 'i'},
{'a': 2, 'b': 'ii'},
{'a': 2, 'b': 'iii'},
{'a': 3, 'b': 'i'},
{'a': 3, 'b': 'ii'},
{'a': 3, 'b': 'iii'},
]
err = self.compare(source, scheme, oracle)
self.assertFalse(err, "errors found: %s\n" % err)
def test_Deep1(self):
scheme = {
'a': hoover.Cartman.Iterable,
'b': hoover.Cartman.Iterable,
'x': {
'h1': hoover.Cartman.Iterable,
'h2': hoover.Cartman.Iterable,
}
}
source = {
'a': [1, 2, 3],
'b': ['i', 'ii', 'iii'],
'x': {'h1': [101, 102], 'h2': [201, 202]}
}
oracle = [
{'a': 1, 'b': 'i', 'x': {'h1': 101, 'h2': 201}},
{'a': 1, 'b': 'i', 'x': {'h1': 101, 'h2': 202}},
{'a': 1, 'b': 'i', 'x': {'h1': 102, 'h2': 201}},
{'a': 1, 'b': 'i', 'x': {'h1': 102, 'h2': 202}},
{'a': 1, 'b': 'ii', 'x': {'h1': 101, 'h2': 201}},
{'a': 1, 'b': 'ii', 'x': {'h1': 101, 'h2': 202}},
{'a': 1, 'b': 'ii', 'x': {'h1': 102, 'h2': 201}},
{'a': 1, 'b': 'ii', 'x': {'h1': 102, 'h2': 202}},
{'a': 1, 'b': 'iii', 'x': {'h1': 101, 'h2': 201}},
{'a': 1, 'b': 'iii', 'x': {'h1': 101, 'h2': 202}},
{'a': 1, 'b': 'iii', 'x': {'h1': 102, 'h2': 201}},
{'a': 1, 'b': 'iii', 'x': {'h1': 102, 'h2': 202}},
{'a': 2, 'b': 'i', 'x': {'h1': 101, 'h2': 201}},
{'a': 2, 'b': 'i', 'x': {'h1': 101, 'h2': 202}},
{'a': 2, 'b': 'i', 'x': {'h1': 102, 'h2': 201}},
{'a': 2, 'b': 'i', 'x': {'h1': 102, 'h2': 202}},
{'a': 2, 'b': 'ii', 'x': {'h1': 101, 'h2': 201}},
{'a': 2, 'b': 'ii', 'x': {'h1': 101, 'h2': 202}},
{'a': 2, 'b': 'ii', 'x': {'h1': 102, 'h2': 201}},
{'a': 2, 'b': 'ii', 'x': {'h1': 102, 'h2': 202}},
{'a': 2, 'b': 'iii', 'x': {'h1': 101, 'h2': 201}},
{'a': 2, 'b': 'iii', 'x': {'h1': 101, 'h2': 202}},
{'a': 2, 'b': 'iii', 'x': {'h1': 102, 'h2': 201}},
{'a': 2, 'b': 'iii', 'x': {'h1': 102, 'h2': 202}},
{'a': 3, 'b': 'i', 'x': {'h1': 101, 'h2': 201}},
{'a': 3, 'b': 'i', 'x': {'h1': 101, 'h2': 202}},
{'a': 3, 'b': 'i', 'x': {'h1': 102, 'h2': 201}},
{'a': 3, 'b': 'i', 'x': {'h1': 102, 'h2': 202}},
{'a': 3, 'b': 'ii', 'x': {'h1': 101, 'h2': 201}},
{'a': 3, 'b': 'ii', 'x': {'h1': 101, 'h2': 202}},
{'a': 3, 'b': 'ii', 'x': {'h1': 102, 'h2': 201}},
{'a': 3, 'b': 'ii', 'x': {'h1': 102, 'h2': 202}},
{'a': 3, 'b': 'iii', 'x': {'h1': 101, 'h2': 201}},
{'a': 3, 'b': 'iii', 'x': {'h1': 101, 'h2': 202}},
{'a': 3, 'b': 'iii', 'x': {'h1': 102, 'h2': 201}},
{'a': 3, 'b': 'iii', 'x': {'h1': 102, 'h2': 202}},
]
err = self.compare(source, scheme, oracle)
self.assertFalse(err, "errors found: %s\n" % err)
def test_Scalar(self):
scheme = {
'a': hoover.Cartman.Iterable,
'b': hoover.Cartman.Iterable,
'il': hoover.Cartman.Scalar,
'id': hoover.Cartman.Scalar,
'ii': hoover.Cartman.Scalar,
}
source = {
'a': [1, 2, 3],
'b': ['i', 'ii', 'iii'],
'il': [2, 7],
'id': {'a': 1},
'ii': 42
}
invars = {
'il': [2, 7], 'id': {'a': 1}, 'ii': 42
}
oracle = [
{'a': 1, 'b': 'i'},
{'a': 1, 'b': 'ii'},
{'a': 1, 'b': 'iii'},
{'a': 2, 'b': 'i'},
{'a': 2, 'b': 'ii'},
{'a': 2, 'b': 'iii'},
{'a': 3, 'b': 'i'},
{'a': 3, 'b': 'ii'},
{'a': 3, 'b': 'iii'},
]
for o in oracle:
o.update(invars)
err = self.compare(source, scheme, oracle)
self.assertFalse(err, "errors found: %s\n" % err)
def test_dataDangling(self):
scheme = {
'a': hoover.Cartman.Iterable,
'b': hoover.Cartman.Iterable,
}
source = {
'a': [1, 2, 3],
'b': ['i', 'ii', 'iii'],
'dangling_str': "tr",
'dangling_dict': {'a': 1},
'dangling_list': []
}
oracle = [
{'a': 1, 'b': 'i'},
{'a': 1, 'b': 'ii'},
{'a': 1, 'b': 'iii'},
{'a': 2, 'b': 'i'},
{'a': 2, 'b': 'ii'},
{'a': 2, 'b': 'iii'},
{'a': 3, 'b': 'i'},
{'a': 3, 'b': 'ii'},
{'a': 3, 'b': 'iii'},
]
err = self.compare(source, scheme, oracle)
self.assertFalse(err, "errors found: %s\n" % err)
def test_dataMissing(self):
scheme = {
'a': hoover.Cartman.Iterable,
'b': hoover.Cartman.Iterable,
'MIA': hoover.Cartman.Iterable,
}
source = {
'a': [1, 2, 3],
'b': ['i', 'ii', 'iii'],
}
oracle = [
{'a': 1, 'b': 'i'},
{'a': 1, 'b': 'ii'},
{'a': 1, 'b': 'iii'},
{'a': 2, 'b': 'i'},
{'a': 2, 'b': 'ii'},
{'a': 2, 'b': 'iii'},
{'a': 3, 'b': 'i'},
{'a': 3, 'b': 'ii'},
{'a': 3, 'b': 'iii'},
]
err = self.compare(source, scheme, oracle)
self.assertFalse(err, "errors found: %s\n" % err)
def test_withListIterator(self):
scheme = {
'a': hoover.Cartman.Iterable,
'b': hoover.Cartman.Iterable,
'ITER': hoover.Cartman.Iterable,
}
source = {
'a': [1, 2, 3],
'b': ['i', 'ii', 'iii'],
'ITER': iter(['iterate', 'over', 'me'])
}
oracle = [
{'a': 1, 'b': 'i', 'ITER': 'iterate'},
{'a': 1, 'b': 'ii', 'ITER': 'iterate'},
{'a': 1, 'b': 'iii', 'ITER': 'iterate'},
{'a': 2, 'b': 'i', 'ITER': 'iterate'},
{'a': 2, 'b': 'ii', 'ITER': 'iterate'},
{'a': 2, 'b': 'iii', 'ITER': 'iterate'},
{'a': 3, 'b': 'i', 'ITER': 'iterate'},
{'a': 3, 'b': 'ii', 'ITER': 'iterate'},
{'a': 3, 'b': 'iii', 'ITER': 'iterate'},
{'a': 1, 'b': 'i', 'ITER': 'over'},
{'a': 1, 'b': 'ii', 'ITER': 'over'},
{'a': 1, 'b': 'iii', 'ITER': 'over'},
{'a': 2, 'b': 'i', 'ITER': 'over'},
{'a': 2, 'b': 'ii', 'ITER': 'over'},
{'a': 2, 'b': 'iii', 'ITER': 'over'},
{'a': 3, 'b': 'i', 'ITER': 'over'},
{'a': 3, 'b': 'ii', 'ITER': 'over'},
{'a': 3, 'b': 'iii', 'ITER': 'over'},
{'a': 1, 'b': 'i', 'ITER': 'me'},
{'a': 1, 'b': 'ii', 'ITER': 'me'},
{'a': 1, 'b': 'iii', 'ITER': 'me'},
{'a': 2, 'b': 'i', 'ITER': 'me'},
{'a': 2, 'b': 'ii', 'ITER': 'me'},
{'a': 2, 'b': 'iii', 'ITER': 'me'},
{'a': 3, 'b': 'i', 'ITER': 'me'},
{'a': 3, 'b': 'ii', 'ITER': 'me'},
{'a': 3, 'b': 'iii', 'ITER': 'me'},
]
err = self.compare(source, scheme, oracle)
self.assertFalse(err, "errors found: %s\n" % err)
def test_withCustomIterator_TypeA(self):
class ITER_A(object):
def __init__(self, items):
self.items = items
self.n = 0
def __iter__(self):
return self
def next(self):
try:
item = self.items[self.n]
except IndexError:
raise StopIteration
else:
self.n += 1
return item
scheme = {
'd': {
'a': hoover.Cartman.Iterable,
'b': hoover.Cartman.Iterable,
'ITER_A': hoover.Cartman.Iterable
}
}
source = {
'd': {
'a': [1, 2, 3],
'b': ['i', 'ii', 'iii'],
'ITER_A': ITER_A(['iterate', 'over', 'him'])
}
}
oracle = [
{'d': {'a': 1, 'b': 'i', 'ITER_A': 'iterate'}},
{'d': {'a': 1, 'b': 'ii', 'ITER_A': 'iterate'}},
{'d': {'a': 1, 'b': 'iii', 'ITER_A': 'iterate'}},
{'d': {'a': 2, 'b': 'i', 'ITER_A': 'iterate'}},
{'d': {'a': 2, 'b': 'ii', 'ITER_A': 'iterate'}},
{'d': {'a': 2, 'b': 'iii', 'ITER_A': 'iterate'}},
{'d': {'a': 3, 'b': 'i', 'ITER_A': 'iterate'}},
{'d': {'a': 3, 'b': 'ii', 'ITER_A': 'iterate'}},
{'d': {'a': 3, 'b': 'iii', 'ITER_A': 'iterate'}},
{'d': {'a': 1, 'b': 'i', 'ITER_A': 'over'}},
{'d': {'a': 1, 'b': 'ii', 'ITER_A': 'over'}},
{'d': {'a': 1, 'b': 'iii', 'ITER_A': 'over'}},
{'d': {'a': 2, 'b': 'i', 'ITER_A': 'over'}},
{'d': {'a': 2, 'b': 'ii', 'ITER_A': 'over'}},
{'d': {'a': 2, 'b': 'iii', 'ITER_A': 'over'}},
{'d': {'a': 3, 'b': 'i', 'ITER_A': 'over'}},
{'d': {'a': 3, 'b': 'ii', 'ITER_A': 'over'}},
{'d': {'a': 3, 'b': 'iii', 'ITER_A': 'over'}},
{'d': {'a': 1, 'b': 'i', 'ITER_A': 'him'}},
{'d': {'a': 1, 'b': 'ii', 'ITER_A': 'him'}},
{'d': {'a': 1, 'b': 'iii', 'ITER_A': 'him'}},
{'d': {'a': 2, 'b': 'i', 'ITER_A': 'him'}},
{'d': {'a': 2, 'b': 'ii', 'ITER_A': 'him'}},
{'d': {'a': 2, 'b': 'iii', 'ITER_A': 'him'}},
{'d': {'a': 3, 'b': 'i', 'ITER_A': 'him'}},
{'d': {'a': 3, 'b': 'ii', 'ITER_A': 'him'}},
{'d': {'a': 3, 'b': 'iii', 'ITER_A': 'him'}},
]
err = self.compare(source, scheme, oracle)
self.assertFalse(err, "errors found: %s\n" % err)
def test_withCustomIterator_TypeB(self):
class ITER_B(object):
def __init__(self, items):
self.items = items
def __getitem__(self, n):
return self.items[n]
scheme = {
'd': {
'a': hoover.Cartman.Iterable,
'b': hoover.Cartman.Iterable,
'ITER_B': hoover.Cartman.Iterable
}
}
source = {
'd': {
'a': [1, 2, 3],
'b': ['i', 'ii', 'iii'],
'ITER_B': ITER_B(['iterate', 'by', 'him'])
}
}
oracle = [
{'d': {'a': 1, 'b': 'i', 'ITER_B': 'iterate'}},
{'d': {'a': 1, 'b': 'ii', 'ITER_B': 'iterate'}},
{'d': {'a': 1, 'b': 'iii', 'ITER_B': 'iterate'}},
{'d': {'a': 2, 'b': 'i', 'ITER_B': 'iterate'}},
{'d': {'a': 2, 'b': 'ii', 'ITER_B': 'iterate'}},
{'d': {'a': 2, 'b': 'iii', 'ITER_B': 'iterate'}},
{'d': {'a': 3, 'b': 'i', 'ITER_B': 'iterate'}},
{'d': {'a': 3, 'b': 'ii', 'ITER_B': 'iterate'}},
{'d': {'a': 3, 'b': 'iii', 'ITER_B': 'iterate'}},
{'d': {'a': 1, 'b': 'i', 'ITER_B': 'by'}},
{'d': {'a': 1, 'b': 'ii', 'ITER_B': 'by'}},
{'d': {'a': 1, 'b': 'iii', 'ITER_B': 'by'}},
{'d': {'a': 2, 'b': 'i', 'ITER_B': 'by'}},
{'d': {'a': 2, 'b': 'ii', 'ITER_B': 'by'}},
{'d': {'a': 2, 'b': 'iii', 'ITER_B': 'by'}},
{'d': {'a': 3, 'b': 'i', 'ITER_B': 'by'}},
{'d': {'a': 3, 'b': 'ii', 'ITER_B': 'by'}},
{'d': {'a': 3, 'b': 'iii', 'ITER_B': 'by'}},
{'d': {'a': 1, 'b': 'i', 'ITER_B': 'him'}},
{'d': {'a': 1, 'b': 'ii', 'ITER_B': 'him'}},
{'d': {'a': 1, 'b': 'iii', 'ITER_B': 'him'}},
{'d': {'a': 2, 'b': 'i', 'ITER_B': 'him'}},
{'d': {'a': 2, 'b': 'ii', 'ITER_B': 'him'}},
{'d': {'a': 2, 'b': 'iii', 'ITER_B': 'him'}},
{'d': {'a': 3, 'b': 'i', 'ITER_B': 'him'}},
{'d': {'a': 3, 'b': 'ii', 'ITER_B': 'him'}},
{'d': {'a': 3, 'b': 'iii', 'ITER_B': 'him'}},
]
err = self.compare(source, scheme, oracle)
self.assertFalse(err, "errors found: %s\n" % err)
def test_BadSchemeBelow(self):
def fn():
scheme = {
'h': 1,
'p': hoover.Cartman.Iterable,
'd': hoover.Cartman.Iterable
}
source = {
'h': {
'ua': ['ua1', 'ua2']
},
'p': ['a', 'b'],
'd': [False, True]
}
iter(hoover.Cartman(source, scheme)).next()
self.assertRaises(ValueError, fn)
def test_BadSourceBelow(self):
def fn():
scheme = {
'h': {
'ua': hoover.Cartman.Iterable,
},
'p': hoover.Cartman.Iterable,
'd': hoover.Cartman.Iterable
}
source = {
'h': 'NOT A CORRESPONDING OBJECT',
'p': ['a', 'b'],
'd': [False, True]
}
iter(hoover.Cartman(source, scheme)).next()
self.assertRaises(ValueError, fn)
def test_BadMark(self):
def fn():
class a_mark(hoover.Cartman._BaseMark):
pass
scheme = {
'a': hoover.Cartman.Iterable,
'b': hoover.Cartman.Iterable,
'c': a_mark
}
source = dict.fromkeys(scheme.keys(), [])
iter(hoover.Cartman(source, scheme)).next()
self.assertRaises(ValueError, fn)
class RuleOpTest(unittest.TestCase):
# basic cases
def testAllEmpty(self):
oracle = True
result = hoover.RuleOp.Match((hoover.RuleOp.ALL, []), bool)
self.assertEqual(oracle, result)
def testAllTrue(self):
oracle = True
result = hoover.RuleOp.Match((hoover.RuleOp.ALL, [1, 1, 1]), bool)
self.assertEqual(oracle, result)
def testAllMixed(self):
oracle = False
result = hoover.RuleOp.Match((hoover.RuleOp.ALL, [1, 0, 1]), bool)
self.assertEqual(oracle, result)
def testAllFalse(self):
oracle = False
result = hoover.RuleOp.Match((hoover.RuleOp.ALL, [0, 0, 0]), bool)
self.assertEqual(oracle, result)
def testAnyEmpty(self):
oracle = False
result = hoover.RuleOp.Match((hoover.RuleOp.ANY, []), bool)
self.assertEqual(oracle, result)
def testAnyTrue(self):
oracle = True
result = hoover.RuleOp.Match((hoover.RuleOp.ANY, [1, 1, 1]), bool)
self.assertEqual(oracle, result)
def testAnyMixed(self):
oracle = True
result = hoover.RuleOp.Match((hoover.RuleOp.ANY, [1, 0, 1]), bool)
self.assertEqual(oracle, result)
def testAnyFalse(self):
oracle = False
result = hoover.RuleOp.Match((hoover.RuleOp.ANY, [0, 0, 0]), bool)
self.assertEqual(oracle, result)
# nesting
def testAnyAllTrue(self):
patt = (hoover.RuleOp.ANY, [(hoover.RuleOp.ALL, [1, 1]), 0, 0])
oracle = True
result = hoover.RuleOp.Match(patt, bool)
self.assertEqual(oracle, result)
def testAllAnyFalse(self):
patt = (hoover.RuleOp.ALL, [1, (hoover.RuleOp.ANY, [0, 0]), 1, 1])
oracle = False
result = hoover.RuleOp.Match(patt, bool)
self.assertEqual(oracle, result)
# error handling
def testBadOpClass(self):
class bad_op(object):
def _match(self):
return True
fn = lambda: hoover.RuleOp.Match(((bad_op, [])), bool)
self.assertRaises(ValueError, fn)
def testBadOpNonClass(self):
fn = lambda: hoover.RuleOp.Match((("bad_op", [])), bool)
self.assertRaises(ValueError, fn)
def testBadPatternScalar(self):
fn = lambda: hoover.RuleOp.Match(43, bool)
self.assertRaises(ValueError, fn)
def testBadPatternShort(self):
fn = lambda: hoover.RuleOp.Match((43,), bool)
self.assertRaises(ValueError, fn)
def testBadPatternLong(self):
fn = lambda: hoover.RuleOp.Match((43, 41, 42), bool)
self.assertRaises(ValueError, fn)
def testBadItems(self):
fn = lambda: hoover.RuleOp.Match(((hoover.RuleOp.ALL, 1)), bool)
self.assertRaises(ValueError, fn)
# own operator
def testOwnOp(self):
class MYOP(hoover._BaseRuleOp):
def _match(self):
return True
oracle = True
result = hoover.RuleOp.Match((MYOP, [0, 1, 2]), bool)
self.assertEqual(oracle, result)
class JsDiff(unittest.TestCase):
def setUp(self):
self.a = {
'joe': 31,
'johnny': 55,
'twins': {
'al': 1,
'bo': 1,
'ww': 1
},
'annie': 1,
'todo': [
'buy milk',
'visit aunt Emma',
{'buy presents': [
'for daddy',
'for mommy',
'for sister',
'for brother'
]},
'stop smoking',
'make less promises'
],
'stones': [
'red stone',
'stone',
'get stoned'
]
}
self.b = {
'joe': 31,
'johnny': 55,
'twins': {
'al': 1,
'bo': 1,
'ww': 1
},
'annie': 3,
'todo': [
'buy milk',
{'buy presents': [
'for sister',
'for brother'
]},
'stop smoking',
'take over the world',
'make less promises'
],
'tamara': 110,
'stones': [
'red stone',
'moonstone',
'stone',
'get stoned'
]
}
def testDense(self):
oracle = (
'aaa ~/A\n'
' {\n'
'a "annie": 1,\n'
' "stones": [\n'
' "todo": [\n'
'a "visit aunt Emma",\n'
' "buy presents": [\n'
'a "for daddy",\n'
'a "for mommy",\n'
'bbb ~/B\n'
' {\n'
'b "annie": 3,\n'
' "stones": [\n'
'b "moonstone",\n'
'b "tamara": 110,\n'
' "todo": [\n'
' "buy presents": [\n'
'b "take over the world",'
)
result = hoover.jsDiff(self.a, self.b)
self.assertEqual(oracle, result)
class DataMatch(unittest.TestCase):
class sdict(dict):
pass
class slist(list):
pass
def setUp(self):
super(DataMatch, self).setUp()
# dict
def test_Dict_Ok(self):
p = { 1: 2 }
r = { 1: 2, 3: 4 }
self.assertTrue(hoover.dataMatch(p, r))
def test_Dict_Nok(self):
p = { 1: 2 }
r = { 1: 3, 3: 4 }
self.assertFalse(hoover.dataMatch(p, r))
def test_DictDict_Ok(self):
p = { 'a': { 'A': 'B' } }
r = { 1: 2, 'a': { 'A': 'B' } }
self.assertTrue(hoover.dataMatch(p, r))
def test_DictDict_Nok(self):
p = { 'a': { 'A': 'B' } }
r = { 1: 2, 'a': { 'C': 'D' } }
self.assertFalse(hoover.dataMatch(p, r))
def test_DictList_Ok(self):
p = { 3: [ 11, 12 ] }
r = { 1: 2, 3: [ 10, 11, 12, 13 ] }
self.assertTrue(hoover.dataMatch(p, r))
def test_DictList_Nok(self):
p = { 3: [ 11, 12 ] }
r = { 1: 2, 3: [ 10, 11, 13 ] }
self.assertFalse(hoover.dataMatch(p, r))
# list
def test_List_Ok(self):
p = [ 101, 102 ]
r = [ 101, 103, 102 ]
self.assertTrue(hoover.dataMatch(p, r))
def test_List_Nok(self):
p = [ 101, 102 ]
r = [ 101, 103 ]
self.assertFalse(hoover.dataMatch(p, r))
def test_ListList_Ok(self):
p = [ 101, ['a', 'b'], 102 ]
r = [ 101, [1, 'a', 2, 'b'], 103, 102 ]
self.assertTrue(hoover.dataMatch(p, r))
def test_ListDict_Ok(self):
p = [ 101, {'a': 'A'}, 102 ]
r = [ 101, {'a': 'A', 'b': 'B'}, 103, 102 ]
self.assertTrue(hoover.dataMatch(p, r))
def test_ListDict_Nok(self):
p = [ 101, {'a': 'A'}, 102 ]
r = [ 101, {'a': 'X', 'b': 'B'}, 103, 102 ]
self.assertFalse(hoover.dataMatch(p, r))
# dict/list subclass
def test_DictPSub_Ok(self):
p = self.sdict({ 1: 2 })
r = { 1: 2, 3: 4 }
self.assertTrue(hoover.dataMatch(p, r))
def test_DictPSub_Nok(self):
p = self.sdict({ 1: 2 })
r = { 1: 3, 3: 4 }
self.assertFalse(hoover.dataMatch(p, r))
def test_DictRSub_Ok(self):
p = { 1: 2 }
r = self.sdict({ 1: 2, 3: 4 })
self.assertTrue(hoover.dataMatch(p, r))
def test_DictRSub_Nok(self):
p = { 1: 2 }
r = self.sdict({ 1: 3, 3: 4 })
self.assertFalse(hoover.dataMatch(p, r))
def test_DictPRSub_Ok(self):
p = self.sdict({ 1: 2 })
r = self.sdict({ 1: 2, 3: 4 })
self.assertTrue(hoover.dataMatch(p, r))
def test_DictPRSub_Nok(self):
p = self.sdict({ 1: 2 })
r = self.sdict({ 1: 3, 3: 4 })
self.assertFalse(hoover.dataMatch(p, r))
def test_ListPSub_Ok(self):
p = self.slist([ 101, 102 ])
r = [ 101, 103, 102 ]
self.assertTrue(hoover.dataMatch(p, r))
def test_ListPSub_Nok(self):
p = self.slist([ 101, 102 ])
r = [ 101, 103 ]
self.assertFalse(hoover.dataMatch(p, r))
def test_ListRSub_Ok(self):
p = [ 101, 102 ]
r = self.slist([ 101, 103, 102 ])
self.assertTrue(hoover.dataMatch(p, r))
def test_ListRSub_Nok(self):
p = [ 101, 102 ]
r = self.slist([ 101, 103 ])
self.assertFalse(hoover.dataMatch(p, r))
def test_ListPRSub_Ok(self):
p = self.slist([ 101, 102 ])
r = self.slist([ 101, 103, 102 ])
self.assertTrue(hoover.dataMatch(p, r))
def test_ListPRSub_Nok(self):
p = self.slist([ 101, 102 ])
r = self.slist([ 101, 103 ])
self.assertFalse(hoover.dataMatch(p, r))
if __name__ == "__main__":
unittest.main()
| seznam/sznqalibs | tests/test_hoover.py | Python | mit | 27,441 | [
"VisIt"
] | 11d64da14a0820d78ca78b0270d9356d66edfda43b3e8a69e0015e59d8e5aea1 |
#!/usr/bin/env python
"""
Given a BLAST or DIAMOND JSON output files, the corresponding FASTA (or FASTQ)
sequence files, and filtering criteria, produce a summary of matched titles
and (optionally) an alignment panel.
Run with --help for help.
"""
from __future__ import print_function
import os
import sys
import argparse
from collections import defaultdict
from itertools import chain
# It's not clear that the PDF backend is the right choice here, but it
# works (i.e., the generation of PNG images works fine).
import matplotlib
matplotlib.use('PDF')
# These imports are here because dark.graphics imports matplotlib.pyplot
# and we need to set the matplotlib backend (see above) before that import
# happens. So please don't move these imports higher in this file.
from dark.titles import TitlesAlignments
from dark.fasta import FastaReads
from dark.fastq import FastqReads
from dark.graphics import DEFAULT_LOG_LINEAR_X_AXIS_BASE, alignmentPanelHTML
from dark.utils import numericallySortFilenames
def parseColors(colors, args):
"""
Parse read id color specification.
@param colors: A C{list} of C{str}s. Each item is of the form, e.g.,
'green X Y Z...', where each of X, Y, Z, ... etc. is either a read
id or the name of a FASTA or FASTQ file containing reads whose ids
should be displayed with the corresponding color. Note that if read
ids contain spaces you will need to use the latter (i.e. FASTA/Q file
name) approach because C{args.colors} is split on whitespace.
@param args: The argparse C{Namespace} instance holding the other parsed
command line arguments.
@return: A C{dict} whose keys are colors and whose values are sets of
read ids.
"""
result = defaultdict(set)
for colorInfo in colors:
readIds = colorInfo.split()
color = readIds.pop(0)
for readId in readIds:
if os.path.isfile(readId):
filename = readId
if args.fasta:
reads = FastaReads(filename)
else:
reads = FastqReads(filename)
for read in reads:
result[color].add(read.id)
else:
result[color].add(readId)
return result
if __name__ == '__main__':
# We do not use the addFASTACommandLineOptions and
# parseFASTACommandLineOptions utility functions below because we allow
# multiple FASTA or FASTQ files on the command line, which we specify
# by --fasta and --fastq. And those names clash with the option names
# used by those utility functions.
parser = argparse.ArgumentParser(
description='Non-interactively generate an alignment panel',
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
epilog=('Given BLAST or DIAMOND JSON output files, the '
'corresponding FASTA (or FASTQ) sequence files, and '
'filtering criteria, produce an alignment panel.'))
parser.add_argument(
'--earlyExit', default=False, action='store_true',
help=('If True, just print the number of interesting matches, but do '
'not create the alignment panel.'))
parser.add_argument(
'--matcher', default='blast', choices=('blast', 'diamond'),
help='The matching algorithm that was used to produce the JSON.')
parser.add_argument(
'--json', metavar='JSON-file', nargs='+', action='append',
required=True, help='the JSON file(s) of BLAST or DIAMOND output.')
# A mutually exclusive group for either FASTA or FASTQ files.
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
'--fasta', metavar='FASTA-file', nargs='+', action='append',
help=('the FASTA file(s) of sequences that were given to BLAST '
'or DIAMOND.'))
group.add_argument(
'--fastq', metavar='FASTQ-file', nargs='+', action='append',
help=('the FASTQ file(s) of sequences that were given to BLAST '
'or DIAMOND.'))
parser.add_argument(
'--databaseFastaFilename',
help=('Only used when --showOrfs is also given. '
'The filename of the FASTA file used to make the BLAST or '
'DIAMOND database. If --matcher diamond is used, either this '
'argument or --sqliteDatabaseFilename must be specified. If '
'--matcher blast is used these options can be omitted, in '
'which case the code will fall back to using blastdbcmd, '
'which can be unreliable. See also --sqliteDatabaseFilename '
'for a way to enable fast subject lookup for either matcher.'))
parser.add_argument(
'--sqliteDatabaseFilename',
help=('Only used when --showOrfs is also given. '
'The filename of the sqlite3 database file of FASTA metadata, '
'made from the FASTA that was used to make the BLAST or DIAMOND '
'database. If --matcher diamond is used, either this argument '
'or --databaseFilename must be specified.'))
parser.add_argument(
'--databaseFastaDirectory',
help=('Only used when --showOrfs is also given. '
'The directory where the FASTA file used to make the BLAST or '
'DIAMOND database can be found. This argument is only useful '
'when --sqliteDatabaseFilename is specified.'))
# Args for filtering on ReadsAlignments.
parser.add_argument(
'--minStart', type=int, default=None,
help='Reads that start before this subject offset should not be '
'shown.')
parser.add_argument(
'--maxStop', type=int, default=None,
help='Reads that end after this subject offset should not be shown.')
parser.add_argument(
'--oneAlignmentPerRead', default=False, action='store_true',
help='If True, only keep the best alignment for each read.')
parser.add_argument(
'--maxAlignmentsPerRead', type=int, default=None,
help=('Reads with more than this many alignments will be elided. Pass '
'zero to only keep reads with no matches (alignments).'))
parser.add_argument(
'--scoreCutoff', type=float, default=None,
help=('A float score. Matches with scores worse than this will be '
'ignored.'))
parser.add_argument(
'--maxHspsPerHit', type=int, default=None,
help='A numeric max number of HSPs to show for each hit on hitId.')
parser.add_argument(
'--whitelist', nargs='+', default=None, action='append',
help='sequence titles that should be whitelisted')
parser.add_argument(
'--blacklist', nargs='+', default=None, action='append',
help='sequence titles that should be blacklisted')
parser.add_argument(
'--titleRegex', default=None,
help='a regex that sequence titles must match.')
parser.add_argument(
'--negativeTitleRegex', default=None,
help='a regex that sequence titles must not match.')
parser.add_argument(
'--truncateTitlesAfter', default=None,
help=('a string that titles will be truncated beyond. If the '
'truncated version of a title has already been seen, '
'that title will be skipped.'))
parser.add_argument(
'--minSequenceLen', type=int, default=None,
help='sequences of lesser length will be elided.')
parser.add_argument(
'--maxSequenceLen', type=int, default=None,
help='sequences of greater length will be elided.')
parser.add_argument(
'--taxonomy', default=None,
help=('a string of the taxonomic group on which should be '
'filtered. eg "Vira" will filter on viruses.'))
# Args for filtering on TitlesAlignments.
parser.add_argument(
'--minMatchingReads', type=int, default=None,
help='sequences that are matched by fewer reads will be elided.')
parser.add_argument(
'--minMedianScore', type=float, default=None,
help=('sequences that are matched with a median score that is '
'worse will be elided.'))
parser.add_argument(
'--withScoreBetterThan', type=float, default=None,
help=('sequences that are matched without at least one score '
'at least this good will be elided.'))
parser.add_argument(
'--minNewReads', type=float, default=None,
help=('The fraction of its reads by which a new read set must differ '
'from all previously seen read sets in order to be considered '
'acceptably different.'))
parser.add_argument(
'--maxTitles', type=int, default=None,
help=('The maximum number of titles to keep. If more titles than '
'this result from the filtering, titles will be sorted '
'(according to the --sortOn value) and only the best will be '
'retained.'))
parser.add_argument(
'--minCoverage', type=float, default=None,
help=('The (0.0 to 1.0) minimum fraction of a subject sequence that '
'must be matched by at least one read.'))
# Args for the alignment panel
parser.add_argument(
'--sortOn', default='maxScore',
choices=('maxScore', 'medianScore', 'readCount', 'length', 'title'),
help='The attribute to sort subplots on.')
parser.add_argument(
'--rankValues', type=bool, default=False,
help=('If True, display reads with a Y axis coord that is the rank of '
'the score.'))
parser.add_argument(
'--outputDir', default=None,
help='Specifies a directory to write the HTML summary to.')
parser.add_argument(
'--color', action='append',
help=('a string which has a color as the first element and read ids '
'and/or FASTA file names as the following element(s), separated '
'by spaces.'))
parser.add_argument(
'--equalizeXAxes', default=False, action='store_true',
help=('If True, all alignment graphs will have their X axes drawn '
'with the same range.'))
parser.add_argument(
'--xRange', default='subject',
choices=('reads', 'subject'),
help=('Set the X axis range to show either the subject or the extent '
'of the reads that hit the subject.'))
parser.add_argument(
'--logLinearXAxis', default=False, action='store_true',
help=('If True, convert read offsets so that empty regions in the '
'alignment panel plots will only be as wide as their logged '
'actual values'))
parser.add_argument(
'--logBase', type=float, default=DEFAULT_LOG_LINEAR_X_AXIS_BASE,
help='The base of the logarithm to use if logLinearXAxis is True')
parser.add_argument(
'--showFeatures', default=False, action='store_true',
help=('If specified, look up features for the individual images in '
'the alignment panel.'))
parser.add_argument(
'--showOrfs', default=False, action='store_true',
help=('If specified, show subject ORFs in the individual panel plots. '
'Use of this option requires that you also provide information '
'about the subject database, e.g., via --databaseFastaFilename.')
parser.add_argument(
'--sortFilenames', default=False, action='store_true',
help=('If specified, the JSON and FASTA/Q file names will be '
'processed in sorted order. The sorting is based on finding '
'a numerical prefix in the filename. This can be useful when '
'processing output files produced by systems like HTCondor, '
'which makes files with names like 1.out, 10.out, etc. that do '
'not sort properly and so cannot conveniently be given to this '
'program along with a single FASTA/Q file (because the order of '
'the results in the files from HTCondor does not match the '
'order of sequences in the FASTA/Q file.'))
args = parser.parse_args()
# Flatten lists of lists that we get from using both nargs='+' and
# action='append'. We use both because it allows people to use (e.g.)
# --json on the command line either via "--json file1 --json file2" or
# "--json file1 file2", or a combination of these. That way it's not
# necessary to remember which way you're supposed to use it and you also
# can't be hit by the subtle problem encountered in
# https://github.com/acorg/dark-matter/issues/453
jsonFiles = list(chain.from_iterable(args.json))
whitelist = (
set(chain.from_iterable(args.whitelist)) if args.whitelist else None)
blacklist = (
set(chain.from_iterable(args.blacklist)) if args.blacklist else None)
# TODO: Add a --readClass command-line option in case we want to
# process FASTA containing AA sequences.
if args.fasta:
if args.sortFilenames:
files = numericallySortFilenames(chain.from_iterable(args.fasta))
else:
files = list(chain.from_iterable(args.fasta))
reads = FastaReads(files)
else:
if args.sortFilenames:
files = numericallySortFilenames(chain.from_iterable(args.fastq))
else:
files = list(chain.from_iterable(args.fastq))
reads = FastqReads(files)
if args.matcher == 'blast':
from dark.blast.alignments import BlastReadsAlignments
readsAlignments = BlastReadsAlignments(
reads, jsonFiles, databaseFilename=args.databaseFastaFilename,
databaseDirectory=args.databaseFastaDirectory,
sqliteDatabaseFilename=args.sqliteDatabaseFilename,
sortBlastFilenames=args.sortFilenames)
else:
# Must be 'diamond' (due to parser.add_argument 'choices' argument).
if args.showOrfs:
if (args.databaseFastaFilename is None and
args.sqliteDatabaseFilename is None):
print('Either --databaseFastaFilename or '
'--sqliteDatabaseFilename must be used with --matcher '
'diamond.', file=sys.stderr)
sys.exit(1)
elif not (args.databaseFastaFilename is None or
args.sqliteDatabaseFilename is None):
print('--databaseFastaFilename and --sqliteDatabaseFilename '
'cannot both be used with --matcher diamond.',
file=sys.stderr)
sys.exit(1)
else:
if (args.databaseFastaFilename or args.sqliteDatabaseFilename or
args.databaseFastaDirectory):
print('The --databaseFastaFilename, --sqliteDatabaseFilename, '
'and --databaseFastaDirectory options can only be used '
'if --showOrfs is also used.',
file=sys.stderr)
sys.exit(1)
from dark.diamond.alignments import DiamondReadsAlignments
readsAlignments = DiamondReadsAlignments(
reads, jsonFiles, sortFilenames=args.sortFilenames,
databaseFilename=args.databaseFastaFilename,
databaseDirectory=args.databaseFastaDirectory,
sqliteDatabaseFilename=args.sqliteDatabaseFilename)
readsAlignments.filter(
maxAlignmentsPerRead=args.maxAlignmentsPerRead,
minSequenceLen=args.minSequenceLen,
maxSequenceLen=args.maxSequenceLen,
minStart=args.minStart, maxStop=args.maxStop,
oneAlignmentPerRead=args.oneAlignmentPerRead,
maxHspsPerHit=args.maxHspsPerHit,
scoreCutoff=args.scoreCutoff,
whitelist=whitelist, blacklist=blacklist,
titleRegex=args.titleRegex, negativeTitleRegex=args.negativeTitleRegex,
truncateTitlesAfter=args.truncateTitlesAfter, taxonomy=args.taxonomy)
titlesAlignments = TitlesAlignments(readsAlignments).filter(
minMatchingReads=args.minMatchingReads,
minMedianScore=args.minMedianScore,
withScoreBetterThan=args.withScoreBetterThan,
minNewReads=args.minNewReads, maxTitles=args.maxTitles,
sortOn=args.sortOn, minCoverage=args.minCoverage)
nTitles = len(titlesAlignments)
print('Found %d interesting title%s.' %
(nTitles, '' if nTitles == 1 else 's'), file=sys.stderr)
if nTitles:
print(titlesAlignments.tabSeparatedSummary(sortOn=args.sortOn))
if args.earlyExit:
sys.exit(0)
if nTitles == 0:
print('No alignment panel generated due to no matching titles.',
file=sys.stderr)
sys.exit(0)
idList = parseColors(args.color, args) if args.color else None
alignmentPanelHTML(
titlesAlignments, sortOn=args.sortOn, outputDir=args.outputDir,
idList=idList, equalizeXAxes=args.equalizeXAxes, xRange=args.xRange,
logLinearXAxis=args.logLinearXAxis, logBase=args.logBase,
showFeatures=args.showFeatures, showOrfs=args.showOrfs)
| bamueh/dark-matter | bin/noninteractive-alignment-panel.py | Python | mit | 17,220 | [
"BLAST"
] | 6b0e7364188ee9bcf72648f986eb71efcfe26c0b19895f085a67f4d13e144c39 |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'DataDomain.weight'
db.add_column('profiles_datadomain', 'weight', self.gf('django.db.models.fields.PositiveIntegerField')(default=1), keep_default=False)
def backwards(self, orm):
# Deleting field 'DataDomain.weight'
db.delete_column('profiles_datadomain', 'weight')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'profiles.datadisplay': {
'Meta': {'object_name': 'DataDisplay'},
'html': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100'}),
'indicator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Indicator']", 'null': 'True', 'blank': 'True'}),
'record': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.GeoRecord']", 'null': 'True', 'blank': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}),
'subsubtitle': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}),
'subtitle': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}),
'template': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.DataDisplayTemplate']"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '300'})
},
'profiles.datadisplaytemplate': {
'Meta': {'object_name': 'DataDisplayTemplate'},
'display_type': ('django.db.models.fields.CharField', [], {'default': "'STANDARD'", 'max_length': '11'}),
'domains': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['profiles.DataDomain']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'indicators': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['profiles.Indicator']", 'symmetrical': 'False', 'blank': 'True'}),
'levels': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['profiles.GeoLevel']", 'symmetrical': 'False', 'blank': 'True'}),
'records': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['profiles.GeoRecord']", 'symmetrical': 'False', 'blank': 'True'}),
'source': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'subsubtitle': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}),
'subtitle': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '300'})
},
'profiles.datadomain': {
'Meta': {'object_name': 'DataDomain'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'indicators': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['profiles.Indicator']", 'through': "orm['profiles.IndicatorDomain']", 'symmetrical': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '20'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '20', 'db_index': 'True'}),
'weight': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'})
},
'profiles.datasource': {
'Meta': {'object_name': 'DataSource'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'implementation': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'})
},
'profiles.geolevel': {
'Meta': {'object_name': 'GeoLevel'},
'data_sources': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['profiles.DataSource']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '200'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.GeoLevel']", 'null': 'True', 'blank': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '200', 'db_index': 'True'})
},
'profiles.georecord': {
'Meta': {'unique_together': "(('slug', 'level'), ('level', 'geo_id', 'custom_name', 'owner'))", 'object_name': 'GeoRecord'},
'components': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'components_rel_+'", 'blank': 'True', 'to': "orm['profiles.GeoRecord']"}),
'custom_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'geo_id': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'geom': ('django.contrib.gis.db.models.fields.GeometryField', [], {'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'level': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.GeoLevel']"}),
'mappings': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'mappings_rel_+'", 'blank': 'True', 'to': "orm['profiles.GeoRecord']"}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.GeoRecord']", 'null': 'True', 'blank': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'db_index': 'True', 'max_length': '100', 'blank': 'True'})
},
'profiles.indicator': {
'Meta': {'object_name': 'Indicator'},
'data_domains': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['profiles.DataDomain']", 'through': "orm['profiles.IndicatorDomain']", 'symmetrical': 'False'}),
'data_type': ('django.db.models.fields.CharField', [], {'default': "'COUNT'", 'max_length': '10'}),
'display_change': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'display_name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'display_percent': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'levels': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['profiles.GeoLevel']", 'symmetrical': 'False'}),
'limitations': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'long_definition': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'notes': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'purpose': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'routine_use': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'short_definition': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'}),
'universe': ('django.db.models.fields.CharField', [], {'max_length': '300', 'blank': 'True'})
},
'profiles.indicatordata': {
'Meta': {'unique_together': "(('indicator', 'record', 'time'),)", 'object_name': 'IndicatorData'},
'change_from_time': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'data_as_change_from'", 'null': 'True', 'to': "orm['profiles.Time']"}),
'change_to_time': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'data_as_change_to'", 'null': 'True', 'to': "orm['profiles.Time']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'image': ('sorl.thumbnail.fields.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'indicator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Indicator']"}),
'moe': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'number': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'percent': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),
'record': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.GeoRecord']"}),
'time': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Time']", 'null': 'True'})
},
'profiles.indicatordomain': {
'Meta': {'object_name': 'IndicatorDomain'},
'default': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.DataDomain']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'indicator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Indicator']"})
},
'profiles.indicatorpart': {
'Meta': {'object_name': 'IndicatorPart'},
'data': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'data_source': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.DataSource']"}),
'formula': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'indicator': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Indicator']"}),
'time': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['profiles.Time']"})
},
'profiles.time': {
'Meta': {'object_name': 'Time'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '20'}),
'sort': ('django.db.models.fields.DecimalField', [], {'max_digits': '5', 'decimal_places': '1'})
}
}
complete_apps = ['profiles']
| ProvidencePlan/Profiles | communityprofiles/profiles/oldmigrations/0032_auto__add_field_datadomain_weight.py | Python | mit | 14,381 | [
"MOE"
] | e2bc884ac1917cfc20b448a025125d56b48df0a599a314a66ec1db2339c04aaa |
"""
Create a profile from arbitrary ASCII text files
================================================
Script profile_from_txt
-----------------------
Use the TAMOC ambient module to create profiles for use by
TAMOC from data in text files. This file demonstrates working with data
digitized from plots of temperature and salinity in the SINTEF DeepSpill
report.
This script demonstrates new capabilities of the `ambient.Profile` object, which allow instantiation from np.ndarray objects. For the older version, which used netCDF datasets, see the script with the same file name but prepended by 'nc'.
Notes
-----
Much of the input data coded in the script (e.g., columns to extract, column
names, lat and lon location data, date and time, etc.) must be known by the
user (e.g., from the SINTEF report) and is hand-coded in the script code.
Requires
--------
This script read data from the files::
./Profiles/Raw_Data/C.dat
./Profiles/Raw_Data/T.dat
Returns
-------
This script generates a `ambient.Profile` object, whose netCDF file is written
to the file::
./Profiles/Profiles/DS.nc
"""
# S. Socolofsky, July 2013, Texas A&M University <socolofs@tamu.edu>.
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from tamoc import ambient
from tamoc import seawater
from netCDF4 import date2num
from datetime import datetime
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import os
if __name__ == '__main__':
# Get the path to the input file
__location__ = os.path.realpath(os.path.join(os.getcwd(),
os.path.dirname(__file__),
'../../tamoc/data'))
C_file = os.path.join(__location__,'C.dat')
T_file = os.path.join(__location__,'T.dat')
# Load in the data using numpy.loadtxt
C_raw = np.loadtxt(C_file, comments = '%')
T_raw = np.loadtxt(T_file, comments = '%')
# Clean the profiles to remove depth reversals
C_data = ambient.extract_profile(C_raw, 1, 25.0)
T_data = ambient.extract_profile(T_raw, 1, 25.0)
# Create a Profile object with these data. Note: this is not a complete
# profile as the minimum requirements are to provide temperature and
# salinity. We will use this profile to merge the two dataset, then
# we will re-build the profile.
data = np.zeros(C_data.shape)
data[:,0] = C_data[:,1]
data[:,1] = C_data[:,0]
ztsp = ['z', 'salinity']
ztsp_units = ['m', 'psu']
profile = ambient.Profile(data, ztsp, ztsp_units=ztsp_units, err=0.)
# Insert the temperature data
profile.append(T_data, ['temperature', 'z'], ['deg C', 'm'], z_col=1)
# Get the dataset out of this profile object
ds = profile.ds
# Add some optional attributes to the dataset
ds.attrs['summary'] = 'Dataset created by profile_from_txt in the ./bin'\
' directory of TAMOC'
ds.attrs['source'] = 'Digitized data from the average CTD profile in'\
' the SINTEF DeepSpill Report'
ds.attrs['sea_name'] = 'Norwegian Sea'
ds.coords['lat'] = 64.99066
ds.coords['lon'] = 4.84725
ds.coords['time'] = date2num(datetime(2000, 6, 27, 12, 0, 0),
units = 'seconds since 1970-01-01 00:00:00 0:00',
calendar = 'julian')
# Create a "complete" profile with these merged data...Note: this Profile
# initializer will fill in the pressure data
ztsp = ['z', 'temperature', 'salinity', 'pressure']
ztsp_units = ['m']
ztsp_units += [ds['temperature'].attrs['units']]
ztsp_units += [ds['salinity'].attrs['units']]
ztsp_units += ['Pa']
profile = ambient.Profile(ds, ztsp, ztsp_units=ztsp_units, err=0.)
# Plot the density profile using the interpolation function
z = np.linspace(profile.z_min,
profile.z_max, 250)
rho = np.zeros(z.shape)
tsp = profile.get_values(z, ['temperature', 'salinity', 'pressure'])
for i in range(len(z)):
rho[i] = seawater.density(tsp[i,0], tsp[i,1], tsp[i,2])
fig = plt.figure()
ax1 = plt.subplot(121)
ax1.plot(rho, z)
ax1.set_xlabel('Density (kg/m^3)')
ax1.set_ylabel('Depth (m)')
ax1.invert_yaxis()
ax1.set_title('Computed data')
plt.show()
| socolofs/tamoc | bin/ambient/np_profile_from_txt.py | Python | mit | 4,329 | [
"NetCDF"
] | 976934e2de094c5dd9c4455e92a89adcd5a81c7c41fbfa8145a62b9529b052a6 |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2007-2008 Brian G. Matherly
# Copyright (C) 2008 Gary Burton
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""
Option class representing a family.
"""
#-------------------------------------------------------------------------
#
# gramps modules
#
#-------------------------------------------------------------------------
from . import StringOption
#-------------------------------------------------------------------------
#
# FamilyOption class
#
#-------------------------------------------------------------------------
class FamilyOption(StringOption):
"""
This class describes an option that allows a family from the
database to be selected.
"""
def __init__(self, label):
"""
:param label: A friendly label to be applied to this option.
Example: "Center Family"
:type label: string
:param value: A Gramps ID of a family for this option.
Example: "f11"
:type value: string
:return: nothing
"""
StringOption.__init__(self, label, "")
| sam-m888/gramps | gramps/gen/plug/menu/_family.py | Python | gpl-2.0 | 1,787 | [
"Brian"
] | 9d27508fa3807ec3e3cc32fc980ed607baf0129229b5be6e2ef8da55b9044374 |
from __future__ import absolute_import
import copy
import cython
cython.declare(PyrexTypes=object, Naming=object, ExprNodes=object, Nodes=object,
Options=object, UtilNodes=object, LetNode=object,
LetRefNode=object, TreeFragment=object, EncodedString=object,
error=object, warning=object, copy=object)
from . import PyrexTypes
from . import Naming
from . import ExprNodes
from . import Nodes
from . import Options
from . import Builtin
from .Visitor import VisitorTransform, TreeVisitor
from .Visitor import CythonTransform, EnvTransform, ScopeTrackingTransform
from .UtilNodes import LetNode, LetRefNode, ResultRefNode
from .TreeFragment import TreeFragment
from .StringEncoding import EncodedString
from .Errors import error, warning, CompileError, InternalError
from .Code import UtilityCode
class NameNodeCollector(TreeVisitor):
"""Collect all NameNodes of a (sub-)tree in the ``name_nodes``
attribute.
"""
def __init__(self):
super(NameNodeCollector, self).__init__()
self.name_nodes = []
def visit_NameNode(self, node):
self.name_nodes.append(node)
def visit_Node(self, node):
self._visitchildren(node, None)
class SkipDeclarations(object):
"""
Variable and function declarations can often have a deep tree structure,
and yet most transformations don't need to descend to this depth.
Declaration nodes are removed after AnalyseDeclarationsTransform, so there
is no need to use this for transformations after that point.
"""
def visit_CTypeDefNode(self, node):
return node
def visit_CVarDefNode(self, node):
return node
def visit_CDeclaratorNode(self, node):
return node
def visit_CBaseTypeNode(self, node):
return node
def visit_CEnumDefNode(self, node):
return node
def visit_CStructOrUnionDefNode(self, node):
return node
class NormalizeTree(CythonTransform):
"""
This transform fixes up a few things after parsing
in order to make the parse tree more suitable for
transforms.
a) After parsing, blocks with only one statement will
be represented by that statement, not by a StatListNode.
When doing transforms this is annoying and inconsistent,
as one cannot in general remove a statement in a consistent
way and so on. This transform wraps any single statements
in a StatListNode containing a single statement.
b) The PassStatNode is a noop and serves no purpose beyond
plugging such one-statement blocks; i.e., once parsed a
` "pass" can just as well be represented using an empty
StatListNode. This means less special cases to worry about
in subsequent transforms (one always checks to see if a
StatListNode has no children to see if the block is empty).
"""
def __init__(self, context):
super(NormalizeTree, self).__init__(context)
self.is_in_statlist = False
self.is_in_expr = False
def visit_ExprNode(self, node):
stacktmp = self.is_in_expr
self.is_in_expr = True
self.visitchildren(node)
self.is_in_expr = stacktmp
return node
def visit_StatNode(self, node, is_listcontainer=False):
stacktmp = self.is_in_statlist
self.is_in_statlist = is_listcontainer
self.visitchildren(node)
self.is_in_statlist = stacktmp
if not self.is_in_statlist and not self.is_in_expr:
return Nodes.StatListNode(pos=node.pos, stats=[node])
else:
return node
def visit_StatListNode(self, node):
self.is_in_statlist = True
self.visitchildren(node)
self.is_in_statlist = False
return node
def visit_ParallelAssignmentNode(self, node):
return self.visit_StatNode(node, True)
def visit_CEnumDefNode(self, node):
return self.visit_StatNode(node, True)
def visit_CStructOrUnionDefNode(self, node):
return self.visit_StatNode(node, True)
def visit_PassStatNode(self, node):
"""Eliminate PassStatNode"""
if not self.is_in_statlist:
return Nodes.StatListNode(pos=node.pos, stats=[])
else:
return []
def visit_ExprStatNode(self, node):
"""Eliminate useless string literals"""
if node.expr.is_string_literal:
return self.visit_PassStatNode(node)
else:
return self.visit_StatNode(node)
def visit_CDeclaratorNode(self, node):
return node
class PostParseError(CompileError): pass
# error strings checked by unit tests, so define them
ERR_CDEF_INCLASS = 'Cannot assign default value to fields in cdef classes, structs or unions'
ERR_BUF_DEFAULTS = 'Invalid buffer defaults specification (see docs)'
ERR_INVALID_SPECIALATTR_TYPE = 'Special attributes must not have a type declared'
class PostParse(ScopeTrackingTransform):
"""
Basic interpretation of the parse tree, as well as validity
checking that can be done on a very basic level on the parse
tree (while still not being a problem with the basic syntax,
as such).
Specifically:
- Default values to cdef assignments are turned into single
assignments following the declaration (everywhere but in class
bodies, where they raise a compile error)
- Interpret some node structures into Python runtime values.
Some nodes take compile-time arguments (currently:
TemplatedTypeNode[args] and __cythonbufferdefaults__ = {args}),
which should be interpreted. This happens in a general way
and other steps should be taken to ensure validity.
Type arguments cannot be interpreted in this way.
- For __cythonbufferdefaults__ the arguments are checked for
validity.
TemplatedTypeNode has its directives interpreted:
Any first positional argument goes into the "dtype" attribute,
any "ndim" keyword argument goes into the "ndim" attribute and
so on. Also it is checked that the directive combination is valid.
- __cythonbufferdefaults__ attributes are parsed and put into the
type information.
Note: Currently Parsing.py does a lot of interpretation and
reorganization that can be refactored into this transform
if a more pure Abstract Syntax Tree is wanted.
"""
def __init__(self, context):
super(PostParse, self).__init__(context)
self.specialattribute_handlers = {
'__cythonbufferdefaults__' : self.handle_bufferdefaults
}
def visit_LambdaNode(self, node):
# unpack a lambda expression into the corresponding DefNode
collector = YieldNodeCollector()
collector.visitchildren(node.result_expr)
if collector.yields or collector.awaits or isinstance(node.result_expr, ExprNodes.YieldExprNode):
body = Nodes.ExprStatNode(
node.result_expr.pos, expr=node.result_expr)
else:
body = Nodes.ReturnStatNode(
node.result_expr.pos, value=node.result_expr)
node.def_node = Nodes.DefNode(
node.pos, name=node.name,
args=node.args, star_arg=node.star_arg,
starstar_arg=node.starstar_arg,
body=body, doc=None)
self.visitchildren(node)
return node
def visit_GeneratorExpressionNode(self, node):
# unpack a generator expression into the corresponding DefNode
node.def_node = Nodes.DefNode(node.pos, name=node.name,
doc=None,
args=[], star_arg=None,
starstar_arg=None,
body=node.loop)
self.visitchildren(node)
return node
# cdef variables
def handle_bufferdefaults(self, decl):
if not isinstance(decl.default, ExprNodes.DictNode):
raise PostParseError(decl.pos, ERR_BUF_DEFAULTS)
self.scope_node.buffer_defaults_node = decl.default
self.scope_node.buffer_defaults_pos = decl.pos
def visit_CVarDefNode(self, node):
# This assumes only plain names and pointers are assignable on
# declaration. Also, it makes use of the fact that a cdef decl
# must appear before the first use, so we don't have to deal with
# "i = 3; cdef int i = i" and can simply move the nodes around.
try:
self.visitchildren(node)
stats = [node]
newdecls = []
for decl in node.declarators:
declbase = decl
while isinstance(declbase, Nodes.CPtrDeclaratorNode):
declbase = declbase.base
if isinstance(declbase, Nodes.CNameDeclaratorNode):
if declbase.default is not None:
if self.scope_type in ('cclass', 'pyclass', 'struct'):
if isinstance(self.scope_node, Nodes.CClassDefNode):
handler = self.specialattribute_handlers.get(decl.name)
if handler:
if decl is not declbase:
raise PostParseError(decl.pos, ERR_INVALID_SPECIALATTR_TYPE)
handler(decl)
continue # Remove declaration
raise PostParseError(decl.pos, ERR_CDEF_INCLASS)
first_assignment = self.scope_type != 'module'
stats.append(Nodes.SingleAssignmentNode(node.pos,
lhs=ExprNodes.NameNode(node.pos, name=declbase.name),
rhs=declbase.default, first=first_assignment))
declbase.default = None
newdecls.append(decl)
node.declarators = newdecls
return stats
except PostParseError, e:
# An error in a cdef clause is ok, simply remove the declaration
# and try to move on to report more errors
self.context.nonfatal_error(e)
return None
# Split parallel assignments (a,b = b,a) into separate partial
# assignments that are executed rhs-first using temps. This
# restructuring must be applied before type analysis so that known
# types on rhs and lhs can be matched directly. It is required in
# the case that the types cannot be coerced to a Python type in
# order to assign from a tuple.
def visit_SingleAssignmentNode(self, node):
self.visitchildren(node)
return self._visit_assignment_node(node, [node.lhs, node.rhs])
def visit_CascadedAssignmentNode(self, node):
self.visitchildren(node)
return self._visit_assignment_node(node, node.lhs_list + [node.rhs])
def _visit_assignment_node(self, node, expr_list):
"""Flatten parallel assignments into separate single
assignments or cascaded assignments.
"""
if sum([ 1 for expr in expr_list
if expr.is_sequence_constructor or expr.is_string_literal ]) < 2:
# no parallel assignments => nothing to do
return node
expr_list_list = []
flatten_parallel_assignments(expr_list, expr_list_list)
temp_refs = []
eliminate_rhs_duplicates(expr_list_list, temp_refs)
nodes = []
for expr_list in expr_list_list:
lhs_list = expr_list[:-1]
rhs = expr_list[-1]
if len(lhs_list) == 1:
node = Nodes.SingleAssignmentNode(rhs.pos,
lhs = lhs_list[0], rhs = rhs)
else:
node = Nodes.CascadedAssignmentNode(rhs.pos,
lhs_list = lhs_list, rhs = rhs)
nodes.append(node)
if len(nodes) == 1:
assign_node = nodes[0]
else:
assign_node = Nodes.ParallelAssignmentNode(nodes[0].pos, stats = nodes)
if temp_refs:
duplicates_and_temps = [ (temp.expression, temp)
for temp in temp_refs ]
sort_common_subsequences(duplicates_and_temps)
for _, temp_ref in duplicates_and_temps[::-1]:
assign_node = LetNode(temp_ref, assign_node)
return assign_node
def _flatten_sequence(self, seq, result):
for arg in seq.args:
if arg.is_sequence_constructor:
self._flatten_sequence(arg, result)
else:
result.append(arg)
return result
def visit_DelStatNode(self, node):
self.visitchildren(node)
node.args = self._flatten_sequence(node, [])
return node
def visit_ExceptClauseNode(self, node):
if node.is_except_as:
# except-as must delete NameNode target at the end
del_target = Nodes.DelStatNode(
node.pos,
args=[ExprNodes.NameNode(
node.target.pos, name=node.target.name)],
ignore_nonexisting=True)
node.body = Nodes.StatListNode(
node.pos,
stats=[Nodes.TryFinallyStatNode(
node.pos,
body=node.body,
finally_clause=Nodes.StatListNode(
node.pos,
stats=[del_target]))])
self.visitchildren(node)
return node
def eliminate_rhs_duplicates(expr_list_list, ref_node_sequence):
"""Replace rhs items by LetRefNodes if they appear more than once.
Creates a sequence of LetRefNodes that set up the required temps
and appends them to ref_node_sequence. The input list is modified
in-place.
"""
seen_nodes = set()
ref_nodes = {}
def find_duplicates(node):
if node.is_literal or node.is_name:
# no need to replace those; can't include attributes here
# as their access is not necessarily side-effect free
return
if node in seen_nodes:
if node not in ref_nodes:
ref_node = LetRefNode(node)
ref_nodes[node] = ref_node
ref_node_sequence.append(ref_node)
else:
seen_nodes.add(node)
if node.is_sequence_constructor:
for item in node.args:
find_duplicates(item)
for expr_list in expr_list_list:
rhs = expr_list[-1]
find_duplicates(rhs)
if not ref_nodes:
return
def substitute_nodes(node):
if node in ref_nodes:
return ref_nodes[node]
elif node.is_sequence_constructor:
node.args = list(map(substitute_nodes, node.args))
return node
# replace nodes inside of the common subexpressions
for node in ref_nodes:
if node.is_sequence_constructor:
node.args = list(map(substitute_nodes, node.args))
# replace common subexpressions on all rhs items
for expr_list in expr_list_list:
expr_list[-1] = substitute_nodes(expr_list[-1])
def sort_common_subsequences(items):
"""Sort items/subsequences so that all items and subsequences that
an item contains appear before the item itself. This is needed
because each rhs item must only be evaluated once, so its value
must be evaluated first and then reused when packing sequences
that contain it.
This implies a partial order, and the sort must be stable to
preserve the original order as much as possible, so we use a
simple insertion sort (which is very fast for short sequences, the
normal case in practice).
"""
def contains(seq, x):
for item in seq:
if item is x:
return True
elif item.is_sequence_constructor and contains(item.args, x):
return True
return False
def lower_than(a,b):
return b.is_sequence_constructor and contains(b.args, a)
for pos, item in enumerate(items):
key = item[1] # the ResultRefNode which has already been injected into the sequences
new_pos = pos
for i in xrange(pos-1, -1, -1):
if lower_than(key, items[i][0]):
new_pos = i
if new_pos != pos:
for i in xrange(pos, new_pos, -1):
items[i] = items[i-1]
items[new_pos] = item
def unpack_string_to_character_literals(literal):
chars = []
pos = literal.pos
stype = literal.__class__
sval = literal.value
sval_type = sval.__class__
for char in sval:
cval = sval_type(char)
chars.append(stype(pos, value=cval, constant_result=cval))
return chars
def flatten_parallel_assignments(input, output):
# The input is a list of expression nodes, representing the LHSs
# and RHS of one (possibly cascaded) assignment statement. For
# sequence constructors, rearranges the matching parts of both
# sides into a list of equivalent assignments between the
# individual elements. This transformation is applied
# recursively, so that nested structures get matched as well.
rhs = input[-1]
if (not (rhs.is_sequence_constructor or isinstance(rhs, ExprNodes.UnicodeNode))
or not sum([lhs.is_sequence_constructor for lhs in input[:-1]])):
output.append(input)
return
complete_assignments = []
if rhs.is_sequence_constructor:
rhs_args = rhs.args
elif rhs.is_string_literal:
rhs_args = unpack_string_to_character_literals(rhs)
rhs_size = len(rhs_args)
lhs_targets = [ [] for _ in xrange(rhs_size) ]
starred_assignments = []
for lhs in input[:-1]:
if not lhs.is_sequence_constructor:
if lhs.is_starred:
error(lhs.pos, "starred assignment target must be in a list or tuple")
complete_assignments.append(lhs)
continue
lhs_size = len(lhs.args)
starred_targets = sum([1 for expr in lhs.args if expr.is_starred])
if starred_targets > 1:
error(lhs.pos, "more than 1 starred expression in assignment")
output.append([lhs,rhs])
continue
elif lhs_size - starred_targets > rhs_size:
error(lhs.pos, "need more than %d value%s to unpack"
% (rhs_size, (rhs_size != 1) and 's' or ''))
output.append([lhs,rhs])
continue
elif starred_targets:
map_starred_assignment(lhs_targets, starred_assignments,
lhs.args, rhs_args)
elif lhs_size < rhs_size:
error(lhs.pos, "too many values to unpack (expected %d, got %d)"
% (lhs_size, rhs_size))
output.append([lhs,rhs])
continue
else:
for targets, expr in zip(lhs_targets, lhs.args):
targets.append(expr)
if complete_assignments:
complete_assignments.append(rhs)
output.append(complete_assignments)
# recursively flatten partial assignments
for cascade, rhs in zip(lhs_targets, rhs_args):
if cascade:
cascade.append(rhs)
flatten_parallel_assignments(cascade, output)
# recursively flatten starred assignments
for cascade in starred_assignments:
if cascade[0].is_sequence_constructor:
flatten_parallel_assignments(cascade, output)
else:
output.append(cascade)
def map_starred_assignment(lhs_targets, starred_assignments, lhs_args, rhs_args):
# Appends the fixed-position LHS targets to the target list that
# appear left and right of the starred argument.
#
# The starred_assignments list receives a new tuple
# (lhs_target, rhs_values_list) that maps the remaining arguments
# (those that match the starred target) to a list.
# left side of the starred target
for i, (targets, expr) in enumerate(zip(lhs_targets, lhs_args)):
if expr.is_starred:
starred = i
lhs_remaining = len(lhs_args) - i - 1
break
targets.append(expr)
else:
raise InternalError("no starred arg found when splitting starred assignment")
# right side of the starred target
for i, (targets, expr) in enumerate(zip(lhs_targets[-lhs_remaining:],
lhs_args[starred + 1:])):
targets.append(expr)
# the starred target itself, must be assigned a (potentially empty) list
target = lhs_args[starred].target # unpack starred node
starred_rhs = rhs_args[starred:]
if lhs_remaining:
starred_rhs = starred_rhs[:-lhs_remaining]
if starred_rhs:
pos = starred_rhs[0].pos
else:
pos = target.pos
starred_assignments.append([
target, ExprNodes.ListNode(pos=pos, args=starred_rhs)])
class PxdPostParse(CythonTransform, SkipDeclarations):
"""
Basic interpretation/validity checking that should only be
done on pxd trees.
A lot of this checking currently happens in the parser; but
what is listed below happens here.
- "def" functions are let through only if they fill the
getbuffer/releasebuffer slots
- cdef functions are let through only if they are on the
top level and are declared "inline"
"""
ERR_INLINE_ONLY = "function definition in pxd file must be declared 'cdef inline'"
ERR_NOGO_WITH_INLINE = "inline function definition in pxd file cannot be '%s'"
def __call__(self, node):
self.scope_type = 'pxd'
return super(PxdPostParse, self).__call__(node)
def visit_CClassDefNode(self, node):
old = self.scope_type
self.scope_type = 'cclass'
self.visitchildren(node)
self.scope_type = old
return node
def visit_FuncDefNode(self, node):
# FuncDefNode always come with an implementation (without
# an imp they are CVarDefNodes..)
err = self.ERR_INLINE_ONLY
if (isinstance(node, Nodes.DefNode) and self.scope_type == 'cclass'
and node.name in ('__getbuffer__', '__releasebuffer__')):
err = None # allow these slots
if isinstance(node, Nodes.CFuncDefNode):
if (u'inline' in node.modifiers and
self.scope_type in ('pxd', 'cclass')):
node.inline_in_pxd = True
if node.visibility != 'private':
err = self.ERR_NOGO_WITH_INLINE % node.visibility
elif node.api:
err = self.ERR_NOGO_WITH_INLINE % 'api'
else:
err = None # allow inline function
else:
err = self.ERR_INLINE_ONLY
if err:
self.context.nonfatal_error(PostParseError(node.pos, err))
return None
else:
return node
class InterpretCompilerDirectives(CythonTransform, SkipDeclarations):
"""
After parsing, directives can be stored in a number of places:
- #cython-comments at the top of the file (stored in ModuleNode)
- Command-line arguments overriding these
- @cython.directivename decorators
- with cython.directivename: statements
This transform is responsible for interpreting these various sources
and store the directive in two ways:
- Set the directives attribute of the ModuleNode for global directives.
- Use a CompilerDirectivesNode to override directives for a subtree.
(The first one is primarily to not have to modify with the tree
structure, so that ModuleNode stay on top.)
The directives are stored in dictionaries from name to value in effect.
Each such dictionary is always filled in for all possible directives,
using default values where no value is given by the user.
The available directives are controlled in Options.py.
Note that we have to run this prior to analysis, and so some minor
duplication of functionality has to occur: We manually track cimports
and which names the "cython" module may have been imported to.
"""
unop_method_nodes = {
'typeof': ExprNodes.TypeofNode,
'operator.address': ExprNodes.AmpersandNode,
'operator.dereference': ExprNodes.DereferenceNode,
'operator.preincrement' : ExprNodes.inc_dec_constructor(True, '++'),
'operator.predecrement' : ExprNodes.inc_dec_constructor(True, '--'),
'operator.postincrement': ExprNodes.inc_dec_constructor(False, '++'),
'operator.postdecrement': ExprNodes.inc_dec_constructor(False, '--'),
# For backwards compatability.
'address': ExprNodes.AmpersandNode,
}
binop_method_nodes = {
'operator.comma' : ExprNodes.c_binop_constructor(','),
}
special_methods = set(['declare', 'union', 'struct', 'typedef',
'sizeof', 'cast', 'pointer', 'compiled',
'NULL', 'fused_type', 'parallel'])
special_methods.update(unop_method_nodes.keys())
valid_parallel_directives = set([
"parallel",
"prange",
"threadid",
#"threadsavailable",
])
def __init__(self, context, compilation_directive_defaults):
super(InterpretCompilerDirectives, self).__init__(context)
self.cython_module_names = set()
self.directive_names = {'staticmethod': 'staticmethod'}
self.parallel_directives = {}
directives = copy.deepcopy(Options.directive_defaults)
for key, value in compilation_directive_defaults.items():
directives[unicode(key)] = copy.deepcopy(value)
self.directives = directives
def check_directive_scope(self, pos, directive, scope):
legal_scopes = Options.directive_scopes.get(directive, None)
if legal_scopes and scope not in legal_scopes:
self.context.nonfatal_error(PostParseError(pos, 'The %s compiler directive '
'is not allowed in %s scope' % (directive, scope)))
return False
else:
if (directive not in Options.directive_defaults
and directive not in Options.directive_types):
error(pos, "Invalid directive: '%s'." % (directive,))
return True
# Set up processing and handle the cython: comments.
def visit_ModuleNode(self, node):
for key in sorted(node.directive_comments):
if not self.check_directive_scope(node.pos, key, 'module'):
self.wrong_scope_error(node.pos, key, 'module')
del node.directive_comments[key]
self.module_scope = node.scope
self.directives.update(node.directive_comments)
node.directives = self.directives
node.parallel_directives = self.parallel_directives
self.visitchildren(node)
node.cython_module_names = self.cython_module_names
return node
# The following four functions track imports and cimports that
# begin with "cython"
def is_cython_directive(self, name):
return (name in Options.directive_types or
name in self.special_methods or
PyrexTypes.parse_basic_type(name))
def is_parallel_directive(self, full_name, pos):
"""
Checks to see if fullname (e.g. cython.parallel.prange) is a valid
parallel directive. If it is a star import it also updates the
parallel_directives.
"""
result = (full_name + ".").startswith("cython.parallel.")
if result:
directive = full_name.split('.')
if full_name == u"cython.parallel":
self.parallel_directives[u"parallel"] = u"cython.parallel"
elif full_name == u"cython.parallel.*":
for name in self.valid_parallel_directives:
self.parallel_directives[name] = u"cython.parallel.%s" % name
elif (len(directive) != 3 or
directive[-1] not in self.valid_parallel_directives):
error(pos, "No such directive: %s" % full_name)
self.module_scope.use_utility_code(
UtilityCode.load_cached("InitThreads", "ModuleSetupCode.c"))
return result
def visit_CImportStatNode(self, node):
if node.module_name == u"cython":
self.cython_module_names.add(node.as_name or u"cython")
elif node.module_name.startswith(u"cython."):
if node.module_name.startswith(u"cython.parallel."):
error(node.pos, node.module_name + " is not a module")
if node.module_name == u"cython.parallel":
if node.as_name and node.as_name != u"cython":
self.parallel_directives[node.as_name] = node.module_name
else:
self.cython_module_names.add(u"cython")
self.parallel_directives[
u"cython.parallel"] = node.module_name
self.module_scope.use_utility_code(
UtilityCode.load_cached("InitThreads", "ModuleSetupCode.c"))
elif node.as_name:
self.directive_names[node.as_name] = node.module_name[7:]
else:
self.cython_module_names.add(u"cython")
# if this cimport was a compiler directive, we don't
# want to leave the cimport node sitting in the tree
return None
return node
def visit_FromCImportStatNode(self, node):
if not node.relative_level and (
node.module_name == u"cython" or node.module_name.startswith(u"cython.")):
submodule = (node.module_name + u".")[7:]
newimp = []
for pos, name, as_name, kind in node.imported_names:
full_name = submodule + name
qualified_name = u"cython." + full_name
if self.is_parallel_directive(qualified_name, node.pos):
# from cython cimport parallel, or
# from cython.parallel cimport parallel, prange, ...
self.parallel_directives[as_name or name] = qualified_name
elif self.is_cython_directive(full_name):
self.directive_names[as_name or name] = full_name
if kind is not None:
self.context.nonfatal_error(PostParseError(pos,
"Compiler directive imports must be plain imports"))
else:
newimp.append((pos, name, as_name, kind))
if not newimp:
return None
node.imported_names = newimp
return node
def visit_FromImportStatNode(self, node):
if (node.module.module_name.value == u"cython") or \
node.module.module_name.value.startswith(u"cython."):
submodule = (node.module.module_name.value + u".")[7:]
newimp = []
for name, name_node in node.items:
full_name = submodule + name
qualified_name = u"cython." + full_name
if self.is_parallel_directive(qualified_name, node.pos):
self.parallel_directives[name_node.name] = qualified_name
elif self.is_cython_directive(full_name):
self.directive_names[name_node.name] = full_name
else:
newimp.append((name, name_node))
if not newimp:
return None
node.items = newimp
return node
def visit_SingleAssignmentNode(self, node):
if isinstance(node.rhs, ExprNodes.ImportNode):
module_name = node.rhs.module_name.value
is_parallel = (module_name + u".").startswith(u"cython.parallel.")
if module_name != u"cython" and not is_parallel:
return node
module_name = node.rhs.module_name.value
as_name = node.lhs.name
node = Nodes.CImportStatNode(node.pos,
module_name = module_name,
as_name = as_name)
node = self.visit_CImportStatNode(node)
else:
self.visitchildren(node)
return node
def visit_NameNode(self, node):
if node.name in self.cython_module_names:
node.is_cython_module = True
else:
node.cython_attribute = self.directive_names.get(node.name)
return node
def try_to_parse_directives(self, node):
# If node is the contents of an directive (in a with statement or
# decorator), returns a list of (directivename, value) pairs.
# Otherwise, returns None
if isinstance(node, ExprNodes.CallNode):
self.visit(node.function)
optname = node.function.as_cython_attribute()
if optname:
directivetype = Options.directive_types.get(optname)
if directivetype:
args, kwds = node.explicit_args_kwds()
directives = []
key_value_pairs = []
if kwds is not None and directivetype is not dict:
for keyvalue in kwds.key_value_pairs:
key, value = keyvalue
sub_optname = "%s.%s" % (optname, key.value)
if Options.directive_types.get(sub_optname):
directives.append(self.try_to_parse_directive(sub_optname, [value], None, keyvalue.pos))
else:
key_value_pairs.append(keyvalue)
if not key_value_pairs:
kwds = None
else:
kwds.key_value_pairs = key_value_pairs
if directives and not kwds and not args:
return directives
directives.append(self.try_to_parse_directive(optname, args, kwds, node.function.pos))
return directives
elif isinstance(node, (ExprNodes.AttributeNode, ExprNodes.NameNode)):
self.visit(node)
optname = node.as_cython_attribute()
if optname:
directivetype = Options.directive_types.get(optname)
if directivetype is bool:
return [(optname, True)]
elif directivetype is None:
return [(optname, None)]
else:
raise PostParseError(
node.pos, "The '%s' directive should be used as a function call." % optname)
return None
def try_to_parse_directive(self, optname, args, kwds, pos):
directivetype = Options.directive_types.get(optname)
if len(args) == 1 and isinstance(args[0], ExprNodes.NoneNode):
return optname, Options.directive_defaults[optname]
elif directivetype is bool:
if kwds is not None or len(args) != 1 or not isinstance(args[0], ExprNodes.BoolNode):
raise PostParseError(pos,
'The %s directive takes one compile-time boolean argument' % optname)
return (optname, args[0].value)
elif directivetype is int:
if kwds is not None or len(args) != 1 or not isinstance(args[0], ExprNodes.IntNode):
raise PostParseError(pos,
'The %s directive takes one compile-time integer argument' % optname)
return (optname, int(args[0].value))
elif directivetype is str:
if kwds is not None or len(args) != 1 or not isinstance(
args[0], (ExprNodes.StringNode, ExprNodes.UnicodeNode)):
raise PostParseError(pos,
'The %s directive takes one compile-time string argument' % optname)
return (optname, str(args[0].value))
elif directivetype is type:
if kwds is not None or len(args) != 1:
raise PostParseError(pos,
'The %s directive takes one type argument' % optname)
return (optname, args[0])
elif directivetype is dict:
if len(args) != 0:
raise PostParseError(pos,
'The %s directive takes no prepositional arguments' % optname)
return optname, dict([(key.value, value) for key, value in kwds.key_value_pairs])
elif directivetype is list:
if kwds and len(kwds) != 0:
raise PostParseError(pos,
'The %s directive takes no keyword arguments' % optname)
return optname, [ str(arg.value) for arg in args ]
elif callable(directivetype):
if kwds is not None or len(args) != 1 or not isinstance(
args[0], (ExprNodes.StringNode, ExprNodes.UnicodeNode)):
raise PostParseError(pos,
'The %s directive takes one compile-time string argument' % optname)
return (optname, directivetype(optname, str(args[0].value)))
else:
assert False
def visit_with_directives(self, body, directives):
olddirectives = self.directives
newdirectives = copy.copy(olddirectives)
newdirectives.update(directives)
self.directives = newdirectives
assert isinstance(body, Nodes.StatListNode), body
retbody = self.visit_Node(body)
directive = Nodes.CompilerDirectivesNode(pos=retbody.pos, body=retbody,
directives=newdirectives)
self.directives = olddirectives
return directive
# Handle decorators
def visit_FuncDefNode(self, node):
directives = self._extract_directives(node, 'function')
if not directives:
return self.visit_Node(node)
body = Nodes.StatListNode(node.pos, stats=[node])
return self.visit_with_directives(body, directives)
def visit_CVarDefNode(self, node):
directives = self._extract_directives(node, 'function')
if not directives:
return node
for name, value in directives.iteritems():
if name == 'locals':
node.directive_locals = value
elif name not in ('final', 'staticmethod'):
self.context.nonfatal_error(PostParseError(
node.pos,
"Cdef functions can only take cython.locals(), "
"staticmethod, or final decorators, got %s." % name))
body = Nodes.StatListNode(node.pos, stats=[node])
return self.visit_with_directives(body, directives)
def visit_CClassDefNode(self, node):
directives = self._extract_directives(node, 'cclass')
if not directives:
return self.visit_Node(node)
body = Nodes.StatListNode(node.pos, stats=[node])
return self.visit_with_directives(body, directives)
def visit_CppClassNode(self, node):
directives = self._extract_directives(node, 'cppclass')
if not directives:
return self.visit_Node(node)
body = Nodes.StatListNode(node.pos, stats=[node])
return self.visit_with_directives(body, directives)
def visit_PyClassDefNode(self, node):
directives = self._extract_directives(node, 'class')
if not directives:
return self.visit_Node(node)
body = Nodes.StatListNode(node.pos, stats=[node])
return self.visit_with_directives(body, directives)
def _extract_directives(self, node, scope_name):
if not node.decorators:
return {}
# Split the decorators into two lists -- real decorators and directives
directives = []
realdecs = []
both = []
for dec in node.decorators:
new_directives = self.try_to_parse_directives(dec.decorator)
if new_directives is not None:
for directive in new_directives:
if self.check_directive_scope(node.pos, directive[0], scope_name):
name, value = directive
if self.directives.get(name, object()) != value:
directives.append(directive)
if directive[0] == 'staticmethod':
both.append(dec)
else:
realdecs.append(dec)
if realdecs and isinstance(node, (Nodes.CFuncDefNode, Nodes.CClassDefNode, Nodes.CVarDefNode)):
raise PostParseError(realdecs[0].pos, "Cdef functions/classes cannot take arbitrary decorators.")
else:
node.decorators = realdecs + both
# merge or override repeated directives
optdict = {}
directives.reverse() # Decorators coming first take precedence
for directive in directives:
name, value = directive
if name in optdict:
old_value = optdict[name]
# keywords and arg lists can be merged, everything
# else overrides completely
if isinstance(old_value, dict):
old_value.update(value)
elif isinstance(old_value, list):
old_value.extend(value)
else:
optdict[name] = value
else:
optdict[name] = value
return optdict
# Handle with statements
def visit_WithStatNode(self, node):
directive_dict = {}
for directive in self.try_to_parse_directives(node.manager) or []:
if directive is not None:
if node.target is not None:
self.context.nonfatal_error(
PostParseError(node.pos, "Compiler directive with statements cannot contain 'as'"))
else:
name, value = directive
if name in ('nogil', 'gil'):
# special case: in pure mode, "with nogil" spells "with cython.nogil"
node = Nodes.GILStatNode(node.pos, state = name, body = node.body)
return self.visit_Node(node)
if self.check_directive_scope(node.pos, name, 'with statement'):
directive_dict[name] = value
if directive_dict:
return self.visit_with_directives(node.body, directive_dict)
return self.visit_Node(node)
class ParallelRangeTransform(CythonTransform, SkipDeclarations):
"""
Transform cython.parallel stuff. The parallel_directives come from the
module node, set there by InterpretCompilerDirectives.
x = cython.parallel.threadavailable() -> ParallelThreadAvailableNode
with nogil, cython.parallel.parallel(): -> ParallelWithBlockNode
print cython.parallel.threadid() -> ParallelThreadIdNode
for i in cython.parallel.prange(...): -> ParallelRangeNode
...
"""
# a list of names, maps 'cython.parallel.prange' in the code to
# ['cython', 'parallel', 'prange']
parallel_directive = None
# Indicates whether a namenode in an expression is the cython module
namenode_is_cython_module = False
# Keep track of whether we are the context manager of a 'with' statement
in_context_manager_section = False
# One of 'prange' or 'with parallel'. This is used to disallow closely
# nested 'with parallel:' blocks
state = None
directive_to_node = {
u"cython.parallel.parallel": Nodes.ParallelWithBlockNode,
# u"cython.parallel.threadsavailable": ExprNodes.ParallelThreadsAvailableNode,
u"cython.parallel.threadid": ExprNodes.ParallelThreadIdNode,
u"cython.parallel.prange": Nodes.ParallelRangeNode,
}
def node_is_parallel_directive(self, node):
return node.name in self.parallel_directives or node.is_cython_module
def get_directive_class_node(self, node):
"""
Figure out which parallel directive was used and return the associated
Node class.
E.g. for a cython.parallel.prange() call we return ParallelRangeNode
"""
if self.namenode_is_cython_module:
directive = '.'.join(self.parallel_directive)
else:
directive = self.parallel_directives[self.parallel_directive[0]]
directive = '%s.%s' % (directive,
'.'.join(self.parallel_directive[1:]))
directive = directive.rstrip('.')
cls = self.directive_to_node.get(directive)
if cls is None and not (self.namenode_is_cython_module and
self.parallel_directive[0] != 'parallel'):
error(node.pos, "Invalid directive: %s" % directive)
self.namenode_is_cython_module = False
self.parallel_directive = None
return cls
def visit_ModuleNode(self, node):
"""
If any parallel directives were imported, copy them over and visit
the AST
"""
if node.parallel_directives:
self.parallel_directives = node.parallel_directives
return self.visit_Node(node)
# No parallel directives were imported, so they can't be used :)
return node
def visit_NameNode(self, node):
if self.node_is_parallel_directive(node):
self.parallel_directive = [node.name]
self.namenode_is_cython_module = node.is_cython_module
return node
def visit_AttributeNode(self, node):
self.visitchildren(node)
if self.parallel_directive:
self.parallel_directive.append(node.attribute)
return node
def visit_CallNode(self, node):
self.visit(node.function)
if not self.parallel_directive:
return node
# We are a parallel directive, replace this node with the
# corresponding ParallelSomethingSomething node
if isinstance(node, ExprNodes.GeneralCallNode):
args = node.positional_args.args
kwargs = node.keyword_args
else:
args = node.args
kwargs = {}
parallel_directive_class = self.get_directive_class_node(node)
if parallel_directive_class:
# Note: in case of a parallel() the body is set by
# visit_WithStatNode
node = parallel_directive_class(node.pos, args=args, kwargs=kwargs)
return node
def visit_WithStatNode(self, node):
"Rewrite with cython.parallel.parallel() blocks"
newnode = self.visit(node.manager)
if isinstance(newnode, Nodes.ParallelWithBlockNode):
if self.state == 'parallel with':
error(node.manager.pos,
"Nested parallel with blocks are disallowed")
self.state = 'parallel with'
body = self.visit(node.body)
self.state = None
newnode.body = body
return newnode
elif self.parallel_directive:
parallel_directive_class = self.get_directive_class_node(node)
if not parallel_directive_class:
# There was an error, stop here and now
return None
if parallel_directive_class is Nodes.ParallelWithBlockNode:
error(node.pos, "The parallel directive must be called")
return None
node.body = self.visit(node.body)
return node
def visit_ForInStatNode(self, node):
"Rewrite 'for i in cython.parallel.prange(...):'"
self.visit(node.iterator)
self.visit(node.target)
in_prange = isinstance(node.iterator.sequence,
Nodes.ParallelRangeNode)
previous_state = self.state
if in_prange:
# This will replace the entire ForInStatNode, so copy the
# attributes
parallel_range_node = node.iterator.sequence
parallel_range_node.target = node.target
parallel_range_node.body = node.body
parallel_range_node.else_clause = node.else_clause
node = parallel_range_node
if not isinstance(node.target, ExprNodes.NameNode):
error(node.target.pos,
"Can only iterate over an iteration variable")
self.state = 'prange'
self.visit(node.body)
self.state = previous_state
self.visit(node.else_clause)
return node
def visit(self, node):
"Visit a node that may be None"
if node is not None:
return super(ParallelRangeTransform, self).visit(node)
class WithTransform(CythonTransform, SkipDeclarations):
def visit_WithStatNode(self, node):
self.visitchildren(node, 'body')
pos = node.pos
is_async = node.is_async
body, target, manager = node.body, node.target, node.manager
node.enter_call = ExprNodes.SimpleCallNode(
pos, function=ExprNodes.AttributeNode(
pos, obj=ExprNodes.CloneNode(manager),
attribute=EncodedString('__aenter__' if is_async else '__enter__'),
is_special_lookup=True),
args=[],
is_temp=True)
if is_async:
node.enter_call = ExprNodes.AwaitExprNode(pos, arg=node.enter_call)
if target is not None:
body = Nodes.StatListNode(
pos, stats=[
Nodes.WithTargetAssignmentStatNode(
pos, lhs=target, with_node=node),
body])
excinfo_target = ExprNodes.TupleNode(pos, slow=True, args=[
ExprNodes.ExcValueNode(pos) for _ in range(3)])
except_clause = Nodes.ExceptClauseNode(
pos, body=Nodes.IfStatNode(
pos, if_clauses=[
Nodes.IfClauseNode(
pos, condition=ExprNodes.NotNode(
pos, operand=ExprNodes.WithExitCallNode(
pos, with_stat=node,
test_if_run=False,
args=excinfo_target,
await=ExprNodes.AwaitExprNode(pos, arg=None) if is_async else None)),
body=Nodes.ReraiseStatNode(pos),
),
],
else_clause=None),
pattern=None,
target=None,
excinfo_target=excinfo_target,
)
node.body = Nodes.TryFinallyStatNode(
pos, body=Nodes.TryExceptStatNode(
pos, body=body,
except_clauses=[except_clause],
else_clause=None,
),
finally_clause=Nodes.ExprStatNode(
pos, expr=ExprNodes.WithExitCallNode(
pos, with_stat=node,
test_if_run=True,
args=ExprNodes.TupleNode(
pos, args=[ExprNodes.NoneNode(pos) for _ in range(3)]),
await=ExprNodes.AwaitExprNode(pos, arg=None) if is_async else None)),
handle_error_case=False,
)
return node
def visit_ExprNode(self, node):
# With statements are never inside expressions.
return node
class DecoratorTransform(ScopeTrackingTransform, SkipDeclarations):
"""Originally, this was the only place where decorators were
transformed into the corresponding calling code. Now, this is
done directly in DefNode and PyClassDefNode to avoid reassignments
to the function/class name - except for cdef class methods. For
those, the reassignment is required as methods are originally
defined in the PyMethodDef struct.
The IndirectionNode allows DefNode to override the decorator
"""
def visit_DefNode(self, func_node):
scope_type = self.scope_type
func_node = self.visit_FuncDefNode(func_node)
if scope_type != 'cclass' or not func_node.decorators:
return func_node
return self.handle_decorators(func_node, func_node.decorators,
func_node.name)
def handle_decorators(self, node, decorators, name):
decorator_result = ExprNodes.NameNode(node.pos, name = name)
for decorator in decorators[::-1]:
decorator_result = ExprNodes.SimpleCallNode(
decorator.pos,
function = decorator.decorator,
args = [decorator_result])
name_node = ExprNodes.NameNode(node.pos, name = name)
reassignment = Nodes.SingleAssignmentNode(
node.pos,
lhs = name_node,
rhs = decorator_result)
reassignment = Nodes.IndirectionNode([reassignment])
node.decorator_indirection = reassignment
return [node, reassignment]
class CnameDirectivesTransform(CythonTransform, SkipDeclarations):
"""
Only part of the CythonUtilityCode pipeline. Must be run before
DecoratorTransform in case this is a decorator for a cdef class.
It filters out @cname('my_cname') decorators and rewrites them to
CnameDecoratorNodes.
"""
def handle_function(self, node):
if not getattr(node, 'decorators', None):
return self.visit_Node(node)
for i, decorator in enumerate(node.decorators):
decorator = decorator.decorator
if (isinstance(decorator, ExprNodes.CallNode) and
decorator.function.is_name and
decorator.function.name == 'cname'):
args, kwargs = decorator.explicit_args_kwds()
if kwargs:
raise AssertionError(
"cname decorator does not take keyword arguments")
if len(args) != 1:
raise AssertionError(
"cname decorator takes exactly one argument")
if not (args[0].is_literal and
args[0].type == Builtin.str_type):
raise AssertionError(
"argument to cname decorator must be a string literal")
cname = args[0].compile_time_value(None).decode('UTF-8')
del node.decorators[i]
node = Nodes.CnameDecoratorNode(pos=node.pos, node=node,
cname=cname)
break
return self.visit_Node(node)
visit_FuncDefNode = handle_function
visit_CClassDefNode = handle_function
visit_CEnumDefNode = handle_function
visit_CStructOrUnionDefNode = handle_function
class ForwardDeclareTypes(CythonTransform):
def visit_CompilerDirectivesNode(self, node):
env = self.module_scope
old = env.directives
env.directives = node.directives
self.visitchildren(node)
env.directives = old
return node
def visit_ModuleNode(self, node):
self.module_scope = node.scope
self.module_scope.directives = node.directives
self.visitchildren(node)
return node
def visit_CDefExternNode(self, node):
old_cinclude_flag = self.module_scope.in_cinclude
self.module_scope.in_cinclude = 1
self.visitchildren(node)
self.module_scope.in_cinclude = old_cinclude_flag
return node
def visit_CEnumDefNode(self, node):
node.declare(self.module_scope)
return node
def visit_CStructOrUnionDefNode(self, node):
if node.name not in self.module_scope.entries:
node.declare(self.module_scope)
return node
def visit_CClassDefNode(self, node):
if node.class_name not in self.module_scope.entries:
node.declare(self.module_scope)
return node
class AnalyseDeclarationsTransform(EnvTransform):
basic_property = TreeFragment(u"""
property NAME:
def __get__(self):
return ATTR
def __set__(self, value):
ATTR = value
""", level='c_class', pipeline=[NormalizeTree(None)])
basic_pyobject_property = TreeFragment(u"""
property NAME:
def __get__(self):
return ATTR
def __set__(self, value):
ATTR = value
def __del__(self):
ATTR = None
""", level='c_class', pipeline=[NormalizeTree(None)])
basic_property_ro = TreeFragment(u"""
property NAME:
def __get__(self):
return ATTR
""", level='c_class', pipeline=[NormalizeTree(None)])
struct_or_union_wrapper = TreeFragment(u"""
cdef class NAME:
cdef TYPE value
def __init__(self, MEMBER=None):
cdef int count
count = 0
INIT_ASSIGNMENTS
if IS_UNION and count > 1:
raise ValueError, "At most one union member should be specified."
def __str__(self):
return STR_FORMAT % MEMBER_TUPLE
def __repr__(self):
return REPR_FORMAT % MEMBER_TUPLE
""", pipeline=[NormalizeTree(None)])
init_assignment = TreeFragment(u"""
if VALUE is not None:
ATTR = VALUE
count += 1
""", pipeline=[NormalizeTree(None)])
fused_function = None
in_lambda = 0
def __call__(self, root):
# needed to determine if a cdef var is declared after it's used.
self.seen_vars_stack = []
self.fused_error_funcs = set()
super_class = super(AnalyseDeclarationsTransform, self)
self._super_visit_FuncDefNode = super_class.visit_FuncDefNode
return super_class.__call__(root)
def visit_NameNode(self, node):
self.seen_vars_stack[-1].add(node.name)
return node
def visit_ModuleNode(self, node):
self.seen_vars_stack.append(set())
node.analyse_declarations(self.current_env())
self.visitchildren(node)
self.seen_vars_stack.pop()
return node
def visit_LambdaNode(self, node):
self.in_lambda += 1
node.analyse_declarations(self.current_env())
self.visitchildren(node)
self.in_lambda -= 1
return node
def visit_CClassDefNode(self, node):
node = self.visit_ClassDefNode(node)
if node.scope and node.scope.implemented and node.body:
stats = []
for entry in node.scope.var_entries:
if entry.needs_property:
property = self.create_Property(entry)
property.analyse_declarations(node.scope)
self.visit(property)
stats.append(property)
if stats:
node.body.stats += stats
return node
def _handle_fused_def_decorators(self, old_decorators, env, node):
"""
Create function calls to the decorators and reassignments to
the function.
"""
# Delete staticmethod and classmethod decorators, this is
# handled directly by the fused function object.
decorators = []
for decorator in old_decorators:
func = decorator.decorator
if (not func.is_name or
func.name not in ('staticmethod', 'classmethod') or
env.lookup_here(func.name)):
# not a static or classmethod
decorators.append(decorator)
if decorators:
transform = DecoratorTransform(self.context)
def_node = node.node
_, reassignments = transform.handle_decorators(
def_node, decorators, def_node.name)
reassignments.analyse_declarations(env)
node = [node, reassignments]
return node
def _handle_def(self, decorators, env, node):
"Handle def or cpdef fused functions"
# Create PyCFunction nodes for each specialization
node.stats.insert(0, node.py_func)
node.py_func = self.visit(node.py_func)
node.update_fused_defnode_entry(env)
pycfunc = ExprNodes.PyCFunctionNode.from_defnode(node.py_func,
True)
pycfunc = ExprNodes.ProxyNode(pycfunc.coerce_to_temp(env))
node.resulting_fused_function = pycfunc
# Create assignment node for our def function
node.fused_func_assignment = self._create_assignment(
node.py_func, ExprNodes.CloneNode(pycfunc), env)
if decorators:
node = self._handle_fused_def_decorators(decorators, env, node)
return node
def _create_fused_function(self, env, node):
"Create a fused function for a DefNode with fused arguments"
from . import FusedNode
if self.fused_function or self.in_lambda:
if self.fused_function not in self.fused_error_funcs:
if self.in_lambda:
error(node.pos, "Fused lambdas not allowed")
else:
error(node.pos, "Cannot nest fused functions")
self.fused_error_funcs.add(self.fused_function)
node.body = Nodes.PassStatNode(node.pos)
for arg in node.args:
if arg.type.is_fused:
arg.type = arg.type.get_fused_types()[0]
return node
decorators = getattr(node, 'decorators', None)
node = FusedNode.FusedCFuncDefNode(node, env)
self.fused_function = node
self.visitchildren(node)
self.fused_function = None
if node.py_func:
node = self._handle_def(decorators, env, node)
return node
def _handle_nogil_cleanup(self, lenv, node):
"Handle cleanup for 'with gil' blocks in nogil functions."
if lenv.nogil and lenv.has_with_gil_block:
# Acquire the GIL for cleanup in 'nogil' functions, by wrapping
# the entire function body in try/finally.
# The corresponding release will be taken care of by
# Nodes.FuncDefNode.generate_function_definitions()
node.body = Nodes.NogilTryFinallyStatNode(
node.body.pos,
body=node.body,
finally_clause=Nodes.EnsureGILNode(node.body.pos),
finally_except_clause=Nodes.EnsureGILNode(node.body.pos))
def _handle_fused(self, node):
if node.is_generator and node.has_fused_arguments:
node.has_fused_arguments = False
error(node.pos, "Fused generators not supported")
node.gbody = Nodes.StatListNode(node.pos,
stats=[],
body=Nodes.PassStatNode(node.pos))
return node.has_fused_arguments
def visit_FuncDefNode(self, node):
"""
Analyse a function and its body, as that hasn't happend yet. Also
analyse the directive_locals set by @cython.locals().
Then, if we are a function with fused arguments, replace the function
(after it has declared itself in the symbol table!) with a
FusedCFuncDefNode, and analyse its children (which are in turn normal
functions). If we're a normal function, just analyse the body of the
function.
"""
env = self.current_env()
self.seen_vars_stack.append(set())
lenv = node.local_scope
node.declare_arguments(lenv)
# @cython.locals(...)
for var, type_node in node.directive_locals.items():
if not lenv.lookup_here(var): # don't redeclare args
type = type_node.analyse_as_type(lenv)
if type:
lenv.declare_var(var, type, type_node.pos)
else:
error(type_node.pos, "Not a type")
if self._handle_fused(node):
node = self._create_fused_function(env, node)
else:
node.body.analyse_declarations(lenv)
self._handle_nogil_cleanup(lenv, node)
self._super_visit_FuncDefNode(node)
self.seen_vars_stack.pop()
return node
def visit_DefNode(self, node):
node = self.visit_FuncDefNode(node)
env = self.current_env()
if (not isinstance(node, Nodes.DefNode) or
node.fused_py_func or node.is_generator_body or
not node.needs_assignment_synthesis(env)):
return node
return [node, self._synthesize_assignment(node, env)]
def visit_GeneratorBodyDefNode(self, node):
return self.visit_FuncDefNode(node)
def _synthesize_assignment(self, node, env):
# Synthesize assignment node and put it right after defnode
genv = env
while genv.is_py_class_scope or genv.is_c_class_scope:
genv = genv.outer_scope
if genv.is_closure_scope:
rhs = node.py_cfunc_node = ExprNodes.InnerFunctionNode(
node.pos, def_node=node,
pymethdef_cname=node.entry.pymethdef_cname,
code_object=ExprNodes.CodeObjectNode(node))
else:
binding = self.current_directives.get('binding')
rhs = ExprNodes.PyCFunctionNode.from_defnode(node, binding)
node.code_object = rhs.code_object
if env.is_py_class_scope:
rhs.binding = True
node.is_cyfunction = rhs.binding
return self._create_assignment(node, rhs, env)
def _create_assignment(self, def_node, rhs, env):
if def_node.decorators:
for decorator in def_node.decorators[::-1]:
rhs = ExprNodes.SimpleCallNode(
decorator.pos,
function = decorator.decorator,
args = [rhs])
def_node.decorators = None
assmt = Nodes.SingleAssignmentNode(
def_node.pos,
lhs=ExprNodes.NameNode(def_node.pos, name=def_node.name),
rhs=rhs)
assmt.analyse_declarations(env)
return assmt
def visit_ScopedExprNode(self, node):
env = self.current_env()
node.analyse_declarations(env)
# the node may or may not have a local scope
if node.has_local_scope:
self.seen_vars_stack.append(set(self.seen_vars_stack[-1]))
self.enter_scope(node, node.expr_scope)
node.analyse_scoped_declarations(node.expr_scope)
self.visitchildren(node)
self.exit_scope()
self.seen_vars_stack.pop()
else:
node.analyse_scoped_declarations(env)
self.visitchildren(node)
return node
def visit_TempResultFromStatNode(self, node):
self.visitchildren(node)
node.analyse_declarations(self.current_env())
return node
def visit_CppClassNode(self, node):
if node.visibility == 'extern':
return None
else:
return self.visit_ClassDefNode(node)
def visit_CStructOrUnionDefNode(self, node):
# Create a wrapper node if needed.
# We want to use the struct type information (so it can't happen
# before this phase) but also create new objects to be declared
# (so it can't happen later).
# Note that we don't return the original node, as it is
# never used after this phase.
if True: # private (default)
return None
self_value = ExprNodes.AttributeNode(
pos = node.pos,
obj = ExprNodes.NameNode(pos=node.pos, name=u"self"),
attribute = EncodedString(u"value"))
var_entries = node.entry.type.scope.var_entries
attributes = []
for entry in var_entries:
attributes.append(ExprNodes.AttributeNode(pos = entry.pos,
obj = self_value,
attribute = entry.name))
# __init__ assignments
init_assignments = []
for entry, attr in zip(var_entries, attributes):
# TODO: branch on visibility
init_assignments.append(self.init_assignment.substitute({
u"VALUE": ExprNodes.NameNode(entry.pos, name = entry.name),
u"ATTR": attr,
}, pos = entry.pos))
# create the class
str_format = u"%s(%s)" % (node.entry.type.name, ("%s, " * len(attributes))[:-2])
wrapper_class = self.struct_or_union_wrapper.substitute({
u"INIT_ASSIGNMENTS": Nodes.StatListNode(node.pos, stats = init_assignments),
u"IS_UNION": ExprNodes.BoolNode(node.pos, value = not node.entry.type.is_struct),
u"MEMBER_TUPLE": ExprNodes.TupleNode(node.pos, args=attributes),
u"STR_FORMAT": ExprNodes.StringNode(node.pos, value = EncodedString(str_format)),
u"REPR_FORMAT": ExprNodes.StringNode(node.pos, value = EncodedString(str_format.replace("%s", "%r"))),
}, pos = node.pos).stats[0]
wrapper_class.class_name = node.name
wrapper_class.shadow = True
class_body = wrapper_class.body.stats
# fix value type
assert isinstance(class_body[0].base_type, Nodes.CSimpleBaseTypeNode)
class_body[0].base_type.name = node.name
# fix __init__ arguments
init_method = class_body[1]
assert isinstance(init_method, Nodes.DefNode) and init_method.name == '__init__'
arg_template = init_method.args[1]
if not node.entry.type.is_struct:
arg_template.kw_only = True
del init_method.args[1]
for entry, attr in zip(var_entries, attributes):
arg = copy.deepcopy(arg_template)
arg.declarator.name = entry.name
init_method.args.append(arg)
# setters/getters
for entry, attr in zip(var_entries, attributes):
# TODO: branch on visibility
if entry.type.is_pyobject:
template = self.basic_pyobject_property
else:
template = self.basic_property
property = template.substitute({
u"ATTR": attr,
}, pos = entry.pos).stats[0]
property.name = entry.name
wrapper_class.body.stats.append(property)
wrapper_class.analyse_declarations(self.current_env())
return self.visit_CClassDefNode(wrapper_class)
# Some nodes are no longer needed after declaration
# analysis and can be dropped. The analysis was performed
# on these nodes in a seperate recursive process from the
# enclosing function or module, so we can simply drop them.
def visit_CDeclaratorNode(self, node):
# necessary to ensure that all CNameDeclaratorNodes are visited.
self.visitchildren(node)
return node
def visit_CTypeDefNode(self, node):
return node
def visit_CBaseTypeNode(self, node):
return None
def visit_CEnumDefNode(self, node):
if node.visibility == 'public':
return node
else:
return None
def visit_CNameDeclaratorNode(self, node):
if node.name in self.seen_vars_stack[-1]:
entry = self.current_env().lookup(node.name)
if (entry is None or entry.visibility != 'extern'
and not entry.scope.is_c_class_scope):
warning(node.pos, "cdef variable '%s' declared after it is used" % node.name, 2)
self.visitchildren(node)
return node
def visit_CVarDefNode(self, node):
# to ensure all CNameDeclaratorNodes are visited.
self.visitchildren(node)
return None
def visit_CnameDecoratorNode(self, node):
child_node = self.visit(node.node)
if not child_node:
return None
if type(child_node) is list: # Assignment synthesized
node.child_node = child_node[0]
return [node] + child_node[1:]
node.node = child_node
return node
def create_Property(self, entry):
if entry.visibility == 'public':
if entry.type.is_pyobject:
template = self.basic_pyobject_property
else:
template = self.basic_property
elif entry.visibility == 'readonly':
template = self.basic_property_ro
property = template.substitute({
u"ATTR": ExprNodes.AttributeNode(pos=entry.pos,
obj=ExprNodes.NameNode(pos=entry.pos, name="self"),
attribute=entry.name),
}, pos=entry.pos).stats[0]
property.name = entry.name
property.doc = entry.doc
return property
class CalculateQualifiedNamesTransform(EnvTransform):
"""
Calculate and store the '__qualname__' and the global
module name on some nodes.
"""
def visit_ModuleNode(self, node):
self.module_name = self.global_scope().qualified_name
self.qualified_name = []
_super = super(CalculateQualifiedNamesTransform, self)
self._super_visit_FuncDefNode = _super.visit_FuncDefNode
self._super_visit_ClassDefNode = _super.visit_ClassDefNode
self.visitchildren(node)
return node
def _set_qualname(self, node, name=None):
if name:
qualname = self.qualified_name[:]
qualname.append(name)
else:
qualname = self.qualified_name
node.qualname = EncodedString('.'.join(qualname))
node.module_name = self.module_name
def _append_entry(self, entry):
if entry.is_pyglobal and not entry.is_pyclass_attr:
self.qualified_name = [entry.name]
else:
self.qualified_name.append(entry.name)
def visit_ClassNode(self, node):
self._set_qualname(node, node.name)
self.visitchildren(node)
return node
def visit_PyClassNamespaceNode(self, node):
# class name was already added by parent node
self._set_qualname(node)
self.visitchildren(node)
return node
def visit_PyCFunctionNode(self, node):
self._set_qualname(node, node.def_node.name)
self.visitchildren(node)
return node
def visit_DefNode(self, node):
self._set_qualname(node, node.name)
return self.visit_FuncDefNode(node)
def visit_FuncDefNode(self, node):
orig_qualified_name = self.qualified_name[:]
if getattr(node, 'name', None) == '<lambda>':
self.qualified_name.append('<lambda>')
else:
self._append_entry(node.entry)
self.qualified_name.append('<locals>')
self._super_visit_FuncDefNode(node)
self.qualified_name = orig_qualified_name
return node
def visit_ClassDefNode(self, node):
orig_qualified_name = self.qualified_name[:]
entry = (getattr(node, 'entry', None) or # PyClass
self.current_env().lookup_here(node.name)) # CClass
self._append_entry(entry)
self._super_visit_ClassDefNode(node)
self.qualified_name = orig_qualified_name
return node
class AnalyseExpressionsTransform(CythonTransform):
def visit_ModuleNode(self, node):
node.scope.infer_types()
node.body = node.body.analyse_expressions(node.scope)
self.visitchildren(node)
return node
def visit_FuncDefNode(self, node):
node.local_scope.infer_types()
node.body = node.body.analyse_expressions(node.local_scope)
self.visitchildren(node)
return node
def visit_ScopedExprNode(self, node):
if node.has_local_scope:
node.expr_scope.infer_types()
node = node.analyse_scoped_expressions(node.expr_scope)
self.visitchildren(node)
return node
def visit_IndexNode(self, node):
"""
Replace index nodes used to specialize cdef functions with fused
argument types with the Attribute- or NameNode referring to the
function. We then need to copy over the specialization properties to
the attribute or name node.
Because the indexing might be a Python indexing operation on a fused
function, or (usually) a Cython indexing operation, we need to
re-analyse the types.
"""
self.visit_Node(node)
if node.is_fused_index and not node.type.is_error:
node = node.base
elif node.memslice_ellipsis_noop:
# memoryviewslice[...] expression, drop the IndexNode
node = node.base
return node
class FindInvalidUseOfFusedTypes(CythonTransform):
def visit_FuncDefNode(self, node):
# Errors related to use in functions with fused args will already
# have been detected
if not node.has_fused_arguments:
if not node.is_generator_body and node.return_type.is_fused:
error(node.pos, "Return type is not specified as argument type")
else:
self.visitchildren(node)
return node
def visit_ExprNode(self, node):
if node.type and node.type.is_fused:
error(node.pos, "Invalid use of fused types, type cannot be specialized")
else:
self.visitchildren(node)
return node
class ExpandInplaceOperators(EnvTransform):
def visit_InPlaceAssignmentNode(self, node):
lhs = node.lhs
rhs = node.rhs
if lhs.type.is_cpp_class:
# No getting around this exact operator here.
return node
if isinstance(lhs, ExprNodes.IndexNode) and lhs.is_buffer_access:
# There is code to handle this case.
return node
env = self.current_env()
def side_effect_free_reference(node, setting=False):
if isinstance(node, ExprNodes.NameNode):
return node, []
elif node.type.is_pyobject and not setting:
node = LetRefNode(node)
return node, [node]
elif isinstance(node, ExprNodes.IndexNode):
if node.is_buffer_access:
raise ValueError("Buffer access")
base, temps = side_effect_free_reference(node.base)
index = LetRefNode(node.index)
return ExprNodes.IndexNode(node.pos, base=base, index=index), temps + [index]
elif isinstance(node, ExprNodes.AttributeNode):
obj, temps = side_effect_free_reference(node.obj)
return ExprNodes.AttributeNode(node.pos, obj=obj, attribute=node.attribute), temps
else:
node = LetRefNode(node)
return node, [node]
try:
lhs, let_ref_nodes = side_effect_free_reference(lhs, setting=True)
except ValueError:
return node
dup = lhs.__class__(**lhs.__dict__)
binop = ExprNodes.binop_node(node.pos,
operator = node.operator,
operand1 = dup,
operand2 = rhs,
inplace=True)
# Manually analyse types for new node.
lhs.analyse_target_types(env)
dup.analyse_types(env)
binop.analyse_operation(env)
node = Nodes.SingleAssignmentNode(
node.pos,
lhs = lhs,
rhs=binop.coerce_to(lhs.type, env))
# Use LetRefNode to avoid side effects.
let_ref_nodes.reverse()
for t in let_ref_nodes:
node = LetNode(t, node)
return node
def visit_ExprNode(self, node):
# In-place assignments can't happen within an expression.
return node
class AdjustDefByDirectives(CythonTransform, SkipDeclarations):
"""
Adjust function and class definitions by the decorator directives:
@cython.cfunc
@cython.cclass
@cython.ccall
@cython.inline
"""
def visit_ModuleNode(self, node):
self.directives = node.directives
self.in_py_class = False
self.visitchildren(node)
return node
def visit_CompilerDirectivesNode(self, node):
old_directives = self.directives
self.directives = node.directives
self.visitchildren(node)
self.directives = old_directives
return node
def visit_DefNode(self, node):
modifiers = []
if 'inline' in self.directives:
modifiers.append('inline')
if 'ccall' in self.directives:
node = node.as_cfunction(
overridable=True, returns=self.directives.get('returns'), modifiers=modifiers)
return self.visit(node)
if 'cfunc' in self.directives:
if self.in_py_class:
error(node.pos, "cfunc directive is not allowed here")
else:
node = node.as_cfunction(
overridable=False, returns=self.directives.get('returns'), modifiers=modifiers)
return self.visit(node)
if 'inline' in modifiers:
error(node.pos, "Python functions cannot be declared 'inline'")
self.visitchildren(node)
return node
def visit_PyClassDefNode(self, node):
if 'cclass' in self.directives:
node = node.as_cclass()
return self.visit(node)
else:
old_in_pyclass = self.in_py_class
self.in_py_class = True
self.visitchildren(node)
self.in_py_class = old_in_pyclass
return node
def visit_CClassDefNode(self, node):
old_in_pyclass = self.in_py_class
self.in_py_class = False
self.visitchildren(node)
self.in_py_class = old_in_pyclass
return node
class AlignFunctionDefinitions(CythonTransform):
"""
This class takes the signatures from a .pxd file and applies them to
the def methods in a .py file.
"""
def visit_ModuleNode(self, node):
self.scope = node.scope
self.directives = node.directives
self.imported_names = set() # hack, see visit_FromImportStatNode()
self.visitchildren(node)
return node
def visit_PyClassDefNode(self, node):
pxd_def = self.scope.lookup(node.name)
if pxd_def:
if pxd_def.is_cclass:
return self.visit_CClassDefNode(node.as_cclass(), pxd_def)
elif not pxd_def.scope or not pxd_def.scope.is_builtin_scope:
error(node.pos, "'%s' redeclared" % node.name)
if pxd_def.pos:
error(pxd_def.pos, "previous declaration here")
return None
return node
def visit_CClassDefNode(self, node, pxd_def=None):
if pxd_def is None:
pxd_def = self.scope.lookup(node.class_name)
if pxd_def:
outer_scope = self.scope
self.scope = pxd_def.type.scope
self.visitchildren(node)
if pxd_def:
self.scope = outer_scope
return node
def visit_DefNode(self, node):
pxd_def = self.scope.lookup(node.name)
if pxd_def and (not pxd_def.scope or not pxd_def.scope.is_builtin_scope):
if not pxd_def.is_cfunction:
error(node.pos, "'%s' redeclared" % node.name)
if pxd_def.pos:
error(pxd_def.pos, "previous declaration here")
return None
node = node.as_cfunction(pxd_def)
elif (self.scope.is_module_scope and self.directives['auto_cpdef']
and not node.name in self.imported_names
and node.is_cdef_func_compatible()):
# FIXME: cpdef-ing should be done in analyse_declarations()
node = node.as_cfunction(scope=self.scope)
# Enable this when nested cdef functions are allowed.
# self.visitchildren(node)
return node
def visit_FromImportStatNode(self, node):
# hack to prevent conditional import fallback functions from
# being cdpef-ed (global Python variables currently conflict
# with imports)
if self.scope.is_module_scope:
for name, _ in node.items:
self.imported_names.add(name)
return node
def visit_ExprNode(self, node):
# ignore lambdas and everything else that appears in expressions
return node
class RemoveUnreachableCode(CythonTransform):
def visit_StatListNode(self, node):
if not self.current_directives['remove_unreachable']:
return node
self.visitchildren(node)
for idx, stat in enumerate(node.stats):
idx += 1
if stat.is_terminator:
if idx < len(node.stats):
if self.current_directives['warn.unreachable']:
warning(node.stats[idx].pos, "Unreachable code", 2)
node.stats = node.stats[:idx]
node.is_terminator = True
break
return node
def visit_IfClauseNode(self, node):
self.visitchildren(node)
if node.body.is_terminator:
node.is_terminator = True
return node
def visit_IfStatNode(self, node):
self.visitchildren(node)
if node.else_clause and node.else_clause.is_terminator:
for clause in node.if_clauses:
if not clause.is_terminator:
break
else:
node.is_terminator = True
return node
def visit_TryExceptStatNode(self, node):
self.visitchildren(node)
if node.body.is_terminator and node.else_clause:
if self.current_directives['warn.unreachable']:
warning(node.else_clause.pos, "Unreachable code", 2)
node.else_clause = None
return node
class YieldNodeCollector(TreeVisitor):
def __init__(self):
super(YieldNodeCollector, self).__init__()
self.yields = []
self.awaits = []
self.returns = []
self.has_return_value = False
def visit_Node(self, node):
self.visitchildren(node)
def visit_YieldExprNode(self, node):
self.yields.append(node)
self.visitchildren(node)
def visit_AwaitExprNode(self, node):
self.awaits.append(node)
self.visitchildren(node)
def visit_ReturnStatNode(self, node):
self.visitchildren(node)
if node.value:
self.has_return_value = True
self.returns.append(node)
def visit_ClassDefNode(self, node):
pass
def visit_FuncDefNode(self, node):
pass
def visit_LambdaNode(self, node):
pass
def visit_GeneratorExpressionNode(self, node):
pass
class MarkClosureVisitor(CythonTransform):
def visit_ModuleNode(self, node):
self.needs_closure = False
self.visitchildren(node)
return node
def visit_FuncDefNode(self, node):
self.needs_closure = False
self.visitchildren(node)
node.needs_closure = self.needs_closure
self.needs_closure = True
collector = YieldNodeCollector()
collector.visitchildren(node)
if node.is_async_def:
if collector.yields:
error(collector.yields[0].pos, "'yield' not allowed in async coroutines (use 'await')")
yields = collector.awaits
elif collector.yields:
if collector.awaits:
error(collector.yields[0].pos, "'await' not allowed in generators (use 'yield')")
yields = collector.yields
else:
return node
for i, yield_expr in enumerate(yields, 1):
yield_expr.label_num = i
for retnode in collector.returns:
retnode.in_generator = True
gbody = Nodes.GeneratorBodyDefNode(
pos=node.pos, name=node.name, body=node.body)
coroutine = (Nodes.AsyncDefNode if node.is_async_def else Nodes.GeneratorDefNode)(
pos=node.pos, name=node.name, args=node.args,
star_arg=node.star_arg, starstar_arg=node.starstar_arg,
doc=node.doc, decorators=node.decorators,
gbody=gbody, lambda_name=node.lambda_name)
return coroutine
def visit_CFuncDefNode(self, node):
self.needs_closure = False
self.visitchildren(node)
node.needs_closure = self.needs_closure
self.needs_closure = True
if node.needs_closure and node.overridable:
error(node.pos, "closures inside cpdef functions not yet supported")
return node
def visit_LambdaNode(self, node):
self.needs_closure = False
self.visitchildren(node)
node.needs_closure = self.needs_closure
self.needs_closure = True
return node
def visit_ClassDefNode(self, node):
self.visitchildren(node)
self.needs_closure = True
return node
class CreateClosureClasses(CythonTransform):
# Output closure classes in module scope for all functions
# that really need it.
def __init__(self, context):
super(CreateClosureClasses, self).__init__(context)
self.path = []
self.in_lambda = False
def visit_ModuleNode(self, node):
self.module_scope = node.scope
self.visitchildren(node)
return node
def find_entries_used_in_closures(self, node):
from_closure = []
in_closure = []
for name, entry in node.local_scope.entries.items():
if entry.from_closure:
from_closure.append((name, entry))
elif entry.in_closure:
in_closure.append((name, entry))
return from_closure, in_closure
def create_class_from_scope(self, node, target_module_scope, inner_node=None):
# move local variables into closure
if node.is_generator:
for entry in node.local_scope.entries.values():
if not entry.from_closure:
entry.in_closure = True
from_closure, in_closure = self.find_entries_used_in_closures(node)
in_closure.sort()
# Now from the begining
node.needs_closure = False
node.needs_outer_scope = False
func_scope = node.local_scope
cscope = node.entry.scope
while cscope.is_py_class_scope or cscope.is_c_class_scope:
cscope = cscope.outer_scope
if not from_closure and (self.path or inner_node):
if not inner_node:
if not node.py_cfunc_node:
raise InternalError("DefNode does not have assignment node")
inner_node = node.py_cfunc_node
inner_node.needs_self_code = False
node.needs_outer_scope = False
if node.is_generator:
pass
elif not in_closure and not from_closure:
return
elif not in_closure:
func_scope.is_passthrough = True
func_scope.scope_class = cscope.scope_class
node.needs_outer_scope = True
return
as_name = '%s_%s' % (
target_module_scope.next_id(Naming.closure_class_prefix),
node.entry.cname)
entry = target_module_scope.declare_c_class(
name=as_name, pos=node.pos, defining=True,
implementing=True)
entry.type.is_final_type = True
func_scope.scope_class = entry
class_scope = entry.type.scope
class_scope.is_internal = True
if Options.closure_freelist_size:
class_scope.directives['freelist'] = Options.closure_freelist_size
if from_closure:
assert cscope.is_closure_scope
class_scope.declare_var(pos=node.pos,
name=Naming.outer_scope_cname,
cname=Naming.outer_scope_cname,
type=cscope.scope_class.type,
is_cdef=True)
node.needs_outer_scope = True
for name, entry in in_closure:
closure_entry = class_scope.declare_var(pos=entry.pos,
name=entry.name,
cname=entry.cname,
type=entry.type,
is_cdef=True)
if entry.is_declared_generic:
closure_entry.is_declared_generic = 1
node.needs_closure = True
# Do it here because other classes are already checked
target_module_scope.check_c_class(func_scope.scope_class)
def visit_LambdaNode(self, node):
if not isinstance(node.def_node, Nodes.DefNode):
# fused function, an error has been previously issued
return node
was_in_lambda = self.in_lambda
self.in_lambda = True
self.create_class_from_scope(node.def_node, self.module_scope, node)
self.visitchildren(node)
self.in_lambda = was_in_lambda
return node
def visit_FuncDefNode(self, node):
if self.in_lambda:
self.visitchildren(node)
return node
if node.needs_closure or self.path:
self.create_class_from_scope(node, self.module_scope)
self.path.append(node)
self.visitchildren(node)
self.path.pop()
return node
def visit_GeneratorBodyDefNode(self, node):
self.visitchildren(node)
return node
def visit_CFuncDefNode(self, node):
if not node.overridable:
return self.visit_FuncDefNode(node)
else:
self.visitchildren(node)
return node
class GilCheck(VisitorTransform):
"""
Call `node.gil_check(env)` on each node to make sure we hold the
GIL when we need it. Raise an error when on Python operations
inside a `nogil` environment.
Additionally, raise exceptions for closely nested with gil or with nogil
statements. The latter would abort Python.
"""
def __call__(self, root):
self.env_stack = [root.scope]
self.nogil = False
# True for 'cdef func() nogil:' functions, as the GIL may be held while
# calling this function (thus contained 'nogil' blocks may be valid).
self.nogil_declarator_only = False
return super(GilCheck, self).__call__(root)
def visit_FuncDefNode(self, node):
self.env_stack.append(node.local_scope)
was_nogil = self.nogil
self.nogil = node.local_scope.nogil
if self.nogil:
self.nogil_declarator_only = True
if self.nogil and node.nogil_check:
node.nogil_check(node.local_scope)
self.visitchildren(node)
# This cannot be nested, so it doesn't need backup/restore
self.nogil_declarator_only = False
self.env_stack.pop()
self.nogil = was_nogil
return node
def visit_GILStatNode(self, node):
if self.nogil and node.nogil_check:
node.nogil_check()
was_nogil = self.nogil
self.nogil = (node.state == 'nogil')
if was_nogil == self.nogil and not self.nogil_declarator_only:
if not was_nogil:
error(node.pos, "Trying to acquire the GIL while it is "
"already held.")
else:
error(node.pos, "Trying to release the GIL while it was "
"previously released.")
if isinstance(node.finally_clause, Nodes.StatListNode):
# The finally clause of the GILStatNode is a GILExitNode,
# which is wrapped in a StatListNode. Just unpack that.
node.finally_clause, = node.finally_clause.stats
self.visitchildren(node)
self.nogil = was_nogil
return node
def visit_ParallelRangeNode(self, node):
if node.nogil:
node.nogil = False
node = Nodes.GILStatNode(node.pos, state='nogil', body=node)
return self.visit_GILStatNode(node)
if not self.nogil:
error(node.pos, "prange() can only be used without the GIL")
# Forget about any GIL-related errors that may occur in the body
return None
node.nogil_check(self.env_stack[-1])
self.visitchildren(node)
return node
def visit_ParallelWithBlockNode(self, node):
if not self.nogil:
error(node.pos, "The parallel section may only be used without "
"the GIL")
return None
if node.nogil_check:
# It does not currently implement this, but test for it anyway to
# avoid potential future surprises
node.nogil_check(self.env_stack[-1])
self.visitchildren(node)
return node
def visit_TryFinallyStatNode(self, node):
"""
Take care of try/finally statements in nogil code sections.
"""
if not self.nogil or isinstance(node, Nodes.GILStatNode):
return self.visit_Node(node)
node.nogil_check = None
node.is_try_finally_in_nogil = True
self.visitchildren(node)
return node
def visit_Node(self, node):
if self.env_stack and self.nogil and node.nogil_check:
node.nogil_check(self.env_stack[-1])
self.visitchildren(node)
node.in_nogil_context = self.nogil
return node
class TransformBuiltinMethods(EnvTransform):
"""
Replace Cython's own cython.* builtins by the corresponding tree nodes.
"""
def visit_SingleAssignmentNode(self, node):
if node.declaration_only:
return None
else:
self.visitchildren(node)
return node
def visit_AttributeNode(self, node):
self.visitchildren(node)
return self.visit_cython_attribute(node)
def visit_NameNode(self, node):
return self.visit_cython_attribute(node)
def visit_cython_attribute(self, node):
attribute = node.as_cython_attribute()
if attribute:
if attribute == u'compiled':
node = ExprNodes.BoolNode(node.pos, value=True)
elif attribute == u'__version__':
from .. import __version__ as version
node = ExprNodes.StringNode(node.pos, value=EncodedString(version))
elif attribute == u'NULL':
node = ExprNodes.NullNode(node.pos)
elif attribute in (u'set', u'frozenset', u'staticmethod'):
node = ExprNodes.NameNode(node.pos, name=EncodedString(attribute),
entry=self.current_env().builtin_scope().lookup_here(attribute))
elif PyrexTypes.parse_basic_type(attribute):
pass
elif self.context.cython_scope.lookup_qualified_name(attribute):
pass
else:
error(node.pos, u"'%s' not a valid cython attribute or is being used incorrectly" % attribute)
return node
def visit_ExecStatNode(self, node):
lenv = self.current_env()
self.visitchildren(node)
if len(node.args) == 1:
node.args.append(ExprNodes.GlobalsExprNode(node.pos))
if not lenv.is_module_scope:
node.args.append(
ExprNodes.LocalsExprNode(
node.pos, self.current_scope_node(), lenv))
return node
def _inject_locals(self, node, func_name):
# locals()/dir()/vars() builtins
lenv = self.current_env()
entry = lenv.lookup_here(func_name)
if entry:
# not the builtin
return node
pos = node.pos
if func_name in ('locals', 'vars'):
if func_name == 'locals' and len(node.args) > 0:
error(self.pos, "Builtin 'locals()' called with wrong number of args, expected 0, got %d"
% len(node.args))
return node
elif func_name == 'vars':
if len(node.args) > 1:
error(self.pos, "Builtin 'vars()' called with wrong number of args, expected 0-1, got %d"
% len(node.args))
if len(node.args) > 0:
return node # nothing to do
return ExprNodes.LocalsExprNode(pos, self.current_scope_node(), lenv)
else: # dir()
if len(node.args) > 1:
error(self.pos, "Builtin 'dir()' called with wrong number of args, expected 0-1, got %d"
% len(node.args))
if len(node.args) > 0:
# optimised in Builtin.py
return node
if lenv.is_py_class_scope or lenv.is_module_scope:
if lenv.is_py_class_scope:
pyclass = self.current_scope_node()
locals_dict = ExprNodes.CloneNode(pyclass.dict)
else:
locals_dict = ExprNodes.GlobalsExprNode(pos)
return ExprNodes.SortedDictKeysNode(locals_dict)
local_names = sorted(var.name for var in lenv.entries.values() if var.name)
items = [ExprNodes.IdentifierStringNode(pos, value=var)
for var in local_names]
return ExprNodes.ListNode(pos, args=items)
def visit_PrimaryCmpNode(self, node):
# special case: for in/not-in test, we do not need to sort locals()
self.visitchildren(node)
if node.operator in 'not_in': # in/not_in
if isinstance(node.operand2, ExprNodes.SortedDictKeysNode):
arg = node.operand2.arg
if isinstance(arg, ExprNodes.NoneCheckNode):
arg = arg.arg
node.operand2 = arg
return node
def visit_CascadedCmpNode(self, node):
return self.visit_PrimaryCmpNode(node)
def _inject_eval(self, node, func_name):
lenv = self.current_env()
entry = lenv.lookup_here(func_name)
if entry or len(node.args) != 1:
return node
# Inject globals and locals
node.args.append(ExprNodes.GlobalsExprNode(node.pos))
if not lenv.is_module_scope:
node.args.append(
ExprNodes.LocalsExprNode(
node.pos, self.current_scope_node(), lenv))
return node
def _inject_super(self, node, func_name):
lenv = self.current_env()
entry = lenv.lookup_here(func_name)
if entry or node.args:
return node
# Inject no-args super
def_node = self.current_scope_node()
if (not isinstance(def_node, Nodes.DefNode) or not def_node.args or
len(self.env_stack) < 2):
return node
class_node, class_scope = self.env_stack[-2]
if class_scope.is_py_class_scope:
def_node.requires_classobj = True
class_node.class_cell.is_active = True
node.args = [
ExprNodes.ClassCellNode(
node.pos, is_generator=def_node.is_generator),
ExprNodes.NameNode(node.pos, name=def_node.args[0].name)
]
elif class_scope.is_c_class_scope:
node.args = [
ExprNodes.NameNode(
node.pos, name=class_node.scope.name,
entry=class_node.entry),
ExprNodes.NameNode(node.pos, name=def_node.args[0].name)
]
return node
def visit_SimpleCallNode(self, node):
# cython.foo
function = node.function.as_cython_attribute()
if function:
if function in InterpretCompilerDirectives.unop_method_nodes:
if len(node.args) != 1:
error(node.function.pos, u"%s() takes exactly one argument" % function)
else:
node = InterpretCompilerDirectives.unop_method_nodes[function](
node.function.pos, operand=node.args[0])
elif function in InterpretCompilerDirectives.binop_method_nodes:
if len(node.args) != 2:
error(node.function.pos, u"%s() takes exactly two arguments" % function)
else:
node = InterpretCompilerDirectives.binop_method_nodes[function](
node.function.pos, operand1=node.args[0], operand2=node.args[1])
elif function == u'cast':
if len(node.args) != 2:
error(node.function.pos, u"cast() takes exactly two arguments")
else:
type = node.args[0].analyse_as_type(self.current_env())
if type:
node = ExprNodes.TypecastNode(node.function.pos, type=type, operand=node.args[1])
else:
error(node.args[0].pos, "Not a type")
elif function == u'sizeof':
if len(node.args) != 1:
error(node.function.pos, u"sizeof() takes exactly one argument")
else:
type = node.args[0].analyse_as_type(self.current_env())
if type:
node = ExprNodes.SizeofTypeNode(node.function.pos, arg_type=type)
else:
node = ExprNodes.SizeofVarNode(node.function.pos, operand=node.args[0])
elif function == 'cmod':
if len(node.args) != 2:
error(node.function.pos, u"cmod() takes exactly two arguments")
else:
node = ExprNodes.binop_node(node.function.pos, '%', node.args[0], node.args[1])
node.cdivision = True
elif function == 'cdiv':
if len(node.args) != 2:
error(node.function.pos, u"cdiv() takes exactly two arguments")
else:
node = ExprNodes.binop_node(node.function.pos, '/', node.args[0], node.args[1])
node.cdivision = True
elif function == u'set':
node.function = ExprNodes.NameNode(node.pos, name=EncodedString('set'))
elif function == u'staticmethod':
node.function = ExprNodes.NameNode(node.pos, name=EncodedString('staticmethod'))
elif self.context.cython_scope.lookup_qualified_name(function):
pass
else:
error(node.function.pos,
u"'%s' not a valid cython language construct" % function)
self.visitchildren(node)
if isinstance(node, ExprNodes.SimpleCallNode) and node.function.is_name:
func_name = node.function.name
if func_name in ('dir', 'locals', 'vars'):
return self._inject_locals(node, func_name)
if func_name == 'eval':
return self._inject_eval(node, func_name)
if func_name == 'super':
return self._inject_super(node, func_name)
return node
class ReplaceFusedTypeChecks(VisitorTransform):
"""
This is not a transform in the pipeline. It is invoked on the specific
versions of a cdef function with fused argument types. It filters out any
type branches that don't match. e.g.
if fused_t is mytype:
...
elif fused_t in other_fused_type:
...
"""
def __init__(self, local_scope):
super(ReplaceFusedTypeChecks, self).__init__()
self.local_scope = local_scope
# defer the import until now to avoid circular import time dependencies
from .Optimize import ConstantFolding
self.transform = ConstantFolding(reevaluate=True)
def visit_IfStatNode(self, node):
"""
Filters out any if clauses with false compile time type check
expression.
"""
self.visitchildren(node)
return self.transform(node)
def visit_PrimaryCmpNode(self, node):
type1 = node.operand1.analyse_as_type(self.local_scope)
type2 = node.operand2.analyse_as_type(self.local_scope)
if type1 and type2:
false_node = ExprNodes.BoolNode(node.pos, value=False)
true_node = ExprNodes.BoolNode(node.pos, value=True)
type1 = self.specialize_type(type1, node.operand1.pos)
op = node.operator
if op in ('is', 'is_not', '==', '!='):
type2 = self.specialize_type(type2, node.operand2.pos)
is_same = type1.same_as(type2)
eq = op in ('is', '==')
if (is_same and eq) or (not is_same and not eq):
return true_node
elif op in ('in', 'not_in'):
# We have to do an instance check directly, as operand2
# needs to be a fused type and not a type with a subtype
# that is fused. First unpack the typedef
if isinstance(type2, PyrexTypes.CTypedefType):
type2 = type2.typedef_base_type
if type1.is_fused:
error(node.operand1.pos, "Type is fused")
elif not type2.is_fused:
error(node.operand2.pos,
"Can only use 'in' or 'not in' on a fused type")
else:
types = PyrexTypes.get_specialized_types(type2)
for specialized_type in types:
if type1.same_as(specialized_type):
if op == 'in':
return true_node
else:
return false_node
if op == 'not_in':
return true_node
return false_node
return node
def specialize_type(self, type, pos):
try:
return type.specialize(self.local_scope.fused_to_specific)
except KeyError:
error(pos, "Type is not specific")
return type
def visit_Node(self, node):
self.visitchildren(node)
return node
class DebugTransform(CythonTransform):
"""
Write debug information for this Cython module.
"""
def __init__(self, context, options, result):
super(DebugTransform, self).__init__(context)
self.visited = set()
# our treebuilder and debug output writer
# (see Cython.Debugger.debug_output.CythonDebugWriter)
self.tb = self.context.gdb_debug_outputwriter
#self.c_output_file = options.output_file
self.c_output_file = result.c_file
# Closure support, basically treat nested functions as if the AST were
# never nested
self.nested_funcdefs = []
# tells visit_NameNode whether it should register step-into functions
self.register_stepinto = False
def visit_ModuleNode(self, node):
self.tb.module_name = node.full_module_name
attrs = dict(
module_name=node.full_module_name,
filename=node.pos[0].filename,
c_filename=self.c_output_file)
self.tb.start('Module', attrs)
# serialize functions
self.tb.start('Functions')
# First, serialize functions normally...
self.visitchildren(node)
# ... then, serialize nested functions
for nested_funcdef in self.nested_funcdefs:
self.visit_FuncDefNode(nested_funcdef)
self.register_stepinto = True
self.serialize_modulenode_as_function(node)
self.register_stepinto = False
self.tb.end('Functions')
# 2.3 compatibility. Serialize global variables
self.tb.start('Globals')
entries = {}
for k, v in node.scope.entries.iteritems():
if (v.qualified_name not in self.visited and not
v.name.startswith('__pyx_') and not
v.type.is_cfunction and not
v.type.is_extension_type):
entries[k]= v
self.serialize_local_variables(entries)
self.tb.end('Globals')
# self.tb.end('Module') # end Module after the line number mapping in
# Cython.Compiler.ModuleNode.ModuleNode._serialize_lineno_map
return node
def visit_FuncDefNode(self, node):
self.visited.add(node.local_scope.qualified_name)
if getattr(node, 'is_wrapper', False):
return node
if self.register_stepinto:
self.nested_funcdefs.append(node)
return node
# node.entry.visibility = 'extern'
if node.py_func is None:
pf_cname = ''
else:
pf_cname = node.py_func.entry.func_cname
attrs = dict(
name=node.entry.name or getattr(node, 'name', '<unknown>'),
cname=node.entry.func_cname,
pf_cname=pf_cname,
qualified_name=node.local_scope.qualified_name,
lineno=str(node.pos[1]))
self.tb.start('Function', attrs=attrs)
self.tb.start('Locals')
self.serialize_local_variables(node.local_scope.entries)
self.tb.end('Locals')
self.tb.start('Arguments')
for arg in node.local_scope.arg_entries:
self.tb.start(arg.name)
self.tb.end(arg.name)
self.tb.end('Arguments')
self.tb.start('StepIntoFunctions')
self.register_stepinto = True
self.visitchildren(node)
self.register_stepinto = False
self.tb.end('StepIntoFunctions')
self.tb.end('Function')
return node
def visit_NameNode(self, node):
if (self.register_stepinto and
node.type is not None and
node.type.is_cfunction and
getattr(node, 'is_called', False) and
node.entry.func_cname is not None):
# don't check node.entry.in_cinclude, as 'cdef extern: ...'
# declared functions are not 'in_cinclude'.
# This means we will list called 'cdef' functions as
# "step into functions", but this is not an issue as they will be
# recognized as Cython functions anyway.
attrs = dict(name=node.entry.func_cname)
self.tb.start('StepIntoFunction', attrs=attrs)
self.tb.end('StepIntoFunction')
self.visitchildren(node)
return node
def serialize_modulenode_as_function(self, node):
"""
Serialize the module-level code as a function so the debugger will know
it's a "relevant frame" and it will know where to set the breakpoint
for 'break modulename'.
"""
name = node.full_module_name.rpartition('.')[-1]
cname_py2 = 'init' + name
cname_py3 = 'PyInit_' + name
py2_attrs = dict(
name=name,
cname=cname_py2,
pf_cname='',
# Ignore the qualified_name, breakpoints should be set using
# `cy break modulename:lineno` for module-level breakpoints.
qualified_name='',
lineno='1',
is_initmodule_function="True",
)
py3_attrs = dict(py2_attrs, cname=cname_py3)
self._serialize_modulenode_as_function(node, py2_attrs)
self._serialize_modulenode_as_function(node, py3_attrs)
def _serialize_modulenode_as_function(self, node, attrs):
self.tb.start('Function', attrs=attrs)
self.tb.start('Locals')
self.serialize_local_variables(node.scope.entries)
self.tb.end('Locals')
self.tb.start('Arguments')
self.tb.end('Arguments')
self.tb.start('StepIntoFunctions')
self.register_stepinto = True
self.visitchildren(node)
self.register_stepinto = False
self.tb.end('StepIntoFunctions')
self.tb.end('Function')
def serialize_local_variables(self, entries):
for entry in entries.values():
if not entry.cname:
# not a local variable
continue
if entry.type.is_pyobject:
vartype = 'PythonObject'
else:
vartype = 'CObject'
if entry.from_closure:
# We're dealing with a closure where a variable from an outer
# scope is accessed, get it from the scope object.
cname = '%s->%s' % (Naming.cur_scope_cname,
entry.outer_entry.cname)
qname = '%s.%s.%s' % (entry.scope.outer_scope.qualified_name,
entry.scope.name,
entry.name)
elif entry.in_closure:
cname = '%s->%s' % (Naming.cur_scope_cname,
entry.cname)
qname = entry.qualified_name
else:
cname = entry.cname
qname = entry.qualified_name
if not entry.pos:
# this happens for variables that are not in the user's code,
# e.g. for the global __builtins__, __doc__, etc. We can just
# set the lineno to 0 for those.
lineno = '0'
else:
lineno = str(entry.pos[1])
attrs = dict(
name=entry.name,
cname=cname,
qualified_name=qname,
type=vartype,
lineno=lineno)
self.tb.start('LocalVar', attrs)
self.tb.end('LocalVar')
| madjar/cython | Cython/Compiler/ParseTreeTransforms.py | Python | apache-2.0 | 117,644 | [
"VisIt"
] | 1fc3ca7e05393fbebbcde66acd015e0ead9b4f3333b70d7d965619f82fdcaf02 |
#!/usr/bin/env python
"""Basic authentication example
This example demonstrates how to protect Flask endpoints with basic
authentication, using secure hashed passwords.
After running this example, visit http://localhost:5000 in your browser. To
gain access, you can use (username=john, password=hello) or
(username=susan, password=bye).
"""
from flask import Flask
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash
app = Flask(__name__)
auth = HTTPBasicAuth()
users = {
"john": generate_password_hash("hello"),
"susan": generate_password_hash("bye")
}
@auth.verify_password
def verify_password(username, password):
if username in users and check_password_hash(users.get(username),
password):
return username
@app.route('/')
@auth.login_required
def index():
return "Hello, %s!" % auth.current_user()
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
| miguelgrinberg/Flask-HTTPAuth | examples/basic_auth.py | Python | mit | 1,015 | [
"VisIt"
] | f31dcbdeb00c620f8bd5194cc626bf7833028b3124707af6c47ec2376563d3bc |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches
def new_pulse_fig(figsize):
'''
Open a new figure and configure it to plot pulse schemes.
'''
fig, ax = plt.subplots(1, 1, figsize=figsize, frameon=False)
ax.axis('off')
fig.subplots_adjust(bottom=0, top=1, left=0, right=1)
ax.axhline(0, color='0.75')
return fig, ax
def new_pulse_subplot(fig, *args, **kwargs):
'''
Add a new subplot configured for plotting pulse schemes to a figure.
All *args and **kwargs are passed to fig.add_subplot.
'''
ax = fig.add_subplot(*args, **kwargs)
ax.axis('off')
fig.subplots_adjust(bottom=0, top=1, left=0, right=1)
ax.axhline(0, color='0.75')
return ax
def mwPulse(ax, pos, y_offs=0, width=1.5, amp=1, label=None, phase=0, labelHeight=1.3,
color='C0', modulation='normal', **plot_kws):
'''
Draw a microwave pulse: Gaussian envelope with modulation.
'''
x = np.linspace(pos, pos + width, 100)
envPos = amp * np.exp(-(x - (pos + width / 2))**2 / (width / 4)**2)
envNeg = -amp * np.exp(-(x - (pos + width / 2))**2 / (width / 4)**2)
if modulation == 'normal':
mod = envPos * np.sin(2 * np.pi * 3 / width * x + phase)
elif modulation == 'high':
mod = envPos * np.sin(5 * np.pi * 3 / width * x + phase)
else:
raise ValueError()
ax.plot(x, envPos+y_offs, '--', color=color, **plot_kws)
ax.plot(x, envNeg+y_offs, '--', color=color, **plot_kws)
ax.plot(x, mod+y_offs, '-', color=color, **plot_kws)
if label is not None:
ax.text(pos + width / 2, labelHeight, label,
horizontalalignment='right', color=color)
return pos + width
def fluxPulse(ax, pos, y_offs=0, width=2.5, s=.1, amp=1.5, label=None, labelHeight=1.7,
color='C1', **plot_kws):
'''
Draw a smooth flux pulse, where the rising and falling edges are given by
Fermi-Dirac functions.
s: smoothness of edge
'''
x = np.linspace(pos, pos + width, 100)
y = amp / ((np.exp(-(x - (pos + 5.5 * s)) / s) + 1) *
(np.exp((x - (pos + width - 5.5 * s)) / s) + 1))
ax.fill_between(x, y+y_offs, color=color, alpha=0.3)
ax.plot(x, y+y_offs, color=color, **plot_kws)
if label is not None:
ax.text(pos + width / 2, labelHeight, label,
horizontalalignment='center', color=color)
return pos + width
def ramZPulse(ax, pos, y_offs=0, width=2.5, s=0.1, amp=1.5, sep=1.5, color='C1'):
'''
Draw a Ram-Z flux pulse, i.e. only part of the pulse is shaded, to indicate
cutting off the pulse at some time.
'''
xLeft = np.linspace(pos, pos + sep, 100)
xRight = np.linspace(pos + sep, pos + width, 100)
xFull = np.concatenate((xLeft, xRight))
y = amp / ((np.exp(-(xFull - (pos + 5.5 * s)) / s) + 1) *
(np.exp((xFull - (pos + width - 5.5 * s)) / s) + 1))
yLeft = y[:len(xLeft)]
ax.fill_between(xLeft, yLeft+y_offs, alpha=0.3, color=color, linewidth=0.0)
ax.plot(xFull, y+y_offs, color=color)
return pos + width
def modZPulse(ax, pos, y_offs=0, width=2.5, s=0.1, amp=1.5, sep=1.5, color='C1'):
'''
Draw a modulated Z pulse.
'''
return pos + width
def interval(ax, start, stop, y_offs = 0, height=1.5, label=None, labelHeight=None,
vlines=True, color='k', arrowstyle='<|-|>', **plot_kws):
'''
Draw an arrow to indicate an interval.
'''
if labelHeight is None:
labelHeight = height + 0.2
arrow = matplotlib.patches.FancyArrowPatch(
posA=(start, height+y_offs), posB=(stop, height+y_offs), arrowstyle=arrowstyle,
color=color, mutation_scale=7, **plot_kws)
ax.add_patch(arrow)
if vlines:
ax.plot([start, start], [0+y_offs, height+y_offs], '--', color=color, **plot_kws)
ax.plot([stop, stop], [0+y_offs, height+y_offs], '--', color=color, **plot_kws)
if label is not None:
ax.text((start + stop) / 2, labelHeight+y_offs, label, color=color,
horizontalalignment='center')
def interval_vertical(ax, start, stop, position, label=None, labelHeight=None,
color='k', arrowstyle='<|-|>', labeloffset: float = 0,
horizontalalignment='center'):
'''
Draw an arrow to indicate an interval.
'''
if labelHeight is None:
labelHeight = (start+stop)/2
arrow = matplotlib.patches.FancyArrowPatch(
posA=(position, start), posB=(position, stop), arrowstyle=arrowstyle,
color=color, mutation_scale=7)
ax.add_patch(arrow)
if label is not None:
ax.text(position+labeloffset, labelHeight, label, color=color,
horizontalalignment=horizontalalignment)
def meter(ax, x0, y0, y_offs=0, w=1.1, h=.8, color='black', fillcolor=None):
"""
Draws a measurement meter on the specified position.
"""
if fillcolor == None:
fill = False
else:
fill = True
p1 = matplotlib.patches.Rectangle(
(x0-w/2, y0-h/2+y_offs), w, h, facecolor=fillcolor, edgecolor=color,
fill=fill, zorder=5)
ax.add_patch(p1)
p0 = matplotlib.patches.Wedge(
(x0, y0-h/4+y_offs), .4, theta1=40, theta2=180-40, color=color, lw=2,
width=.01, zorder=5)
ax.add_patch(p0)
ax.arrow(x0, y0-h/4+y_offs, dx=.5*np.cos(np.deg2rad(70)),
dy=.5*np.sin(np.deg2rad(60)), width=.03, color=color, zorder=5)
| DiCarloLab-Delft/PycQED_py3 | pycqed/utilities/pulse_scheme.py | Python | mit | 5,469 | [
"DIRAC",
"Gaussian"
] | 30768906bf0a132408092db72f4e18a3effd0ae7175209483752f3731b7a8d55 |
######################################################################
# Alchemical Analysis: An open tool implementing some recommended practices for analyzing alchemical free energy calculations
# Copyright 2011-2015 UC Irvine and the Authors
#
# Authors: Pavel Klimovich, Michael Shirts and David Mobley
#
#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, see <http://www.gnu.org/licenses/>.
######################################################################
import numpy
import os # for os interface
import re # for regular expressions
from glob import glob # for pathname matching
from collections import Counter # for counting elements in an array
import unixlike # some implemented unixlike commands
from utils.corruptxvg import *
#===================================================================================================
# FUNCTIONS: This is the Gromacs dhdl.xvg file parser.
#===================================================================================================
def readDataGromacs(P):
"""Read in .xvg files; return nsnapshots, lv, dhdlt, and u_klt."""
class F:
"""This is the object to be built on the filename."""
def __init__(self, filename):
self.filename = filename
def sortedHelper(self):
"""This function will assist the built-in 'sorted' to sort filenames.
Returns a tuple whose first element is an integer while others are strings."""
meat = os.path.basename(self.filename).replace(P.prefix, '').replace(P.suffix, '')
l = [i for i in re.split('\.|-|_', meat) if i]
try:
self.state = l[0] = int(l[0]) # Will be of use for selective MBAR analysis.
except:
print "\nERROR!\nFile's prefix should be followed by a numerical character. Cannot sort the files.\n"
raise
return tuple(l)
def readHeader(self):
self.skip_lines = 0 # Number of lines from the top that are to be skipped.
self.lv_names = () # Lambda type names, e.g. 'coul', 'vdw'.
snap_size = [] # Time from first two snapshots to determine snapshot's size.
self.lv = [] # Lambda vectors, e.g. (0, 0), (0.2, 0), (0.5, 0).
self.bEnergy = False
self.bPV = False
self.bExpanded = False
self.temperature= False
print "Reading metadata from %s..." % self.filename
with open(self.filename,'r') as infile:
for line in infile:
if line.startswith('#'):
self.skip_lines += 1
elif line.startswith('@'):
self.skip_lines += 1
elements = unixlike.trPy(line).split()
if not 'legend' in elements:
if 'T' in elements:
self.temperature = elements[4]
continue
if 'Energy' in elements:
self.bEnergy = True
if 'pV' in elements:
self.bPV = True
if 'state' in elements:
self.bExpanded = True
if 'dH' in elements:
self.lv_names += elements[7],
if 'xD' in elements:
self.lv.append(elements[-len(self.lv_names):])
else:
snap_size.append(float(line.split()[0]))
if len(snap_size) > 1:
self.snap_size = numpy.diff(snap_size)[0]
P.snap_size.append(self.snap_size)
break
return self.lv
def iter_loadtxt(self, state):
"""Houstonian Joe Kington claims it is faster than numpy.loadtxt:
http://stackoverflow.com/questions/8956832/python-out-of-memory-on-large-csv-file-numpy"""
def iter_func():
with open(self.filename, 'r') as infile:
for _ in range(self.skip_lines):
next(infile)
for line in infile:
line = line.split()
for item in line:
yield item
def slice_data(data, state=state):
# Where the dE columns should be stored.
if (len(ndE_unique)>1 and ndE[state]<4):
# If BAR, store shifted 2/3 arrays.
s1, s2 = numpy.array((0, ndE[state])) + state-(state>0)
else:
# If MBAR or selective MBAR or BAR/MBAR, store all.
s1, s2 = (0, K)
# Which dhdl columns are to be read.
read_dhdl_sta = 1+self.bEnergy+self.bExpanded
read_dhdl_end = read_dhdl_sta + n_components
data = data.T
dhdlt[state, :, nsnapshots_l[state]:nsnapshots_r[state]] = data[read_dhdl_sta : read_dhdl_end, :]
if not bSelective_MBAR:
r1, r2 = ( read_dhdl_end, read_dhdl_end + (ndE[state] if not self.bExpanded else K) )
if bPV:
u_klt[state, s1:s2, nsnapshots_l[state]:nsnapshots_r[state]] = P.beta * ( data[r1:r2, :] + data[-1,:] )
else:
u_klt[state, s1:s2, nsnapshots_l[state]:nsnapshots_r[state]] = P.beta * data[r1:r2, :]
else: # can't do slicing; prepare a mask (slicing is thought to be faster/less memory consuming than masking)
mask_read_uklt = numpy.array( [0]*read_dhdl_end + [1 if (k in sel_states) else 0 for k in range(ndE[0])] + ([0] if bPV else []), bool )
if bPV:
u_klt[state, s1:s2, nsnapshots_l[state]:nsnapshots_r[state]] = P.beta * ( data[mask_read_uklt, :] + data[-1,:] )
else:
u_klt[state, s1:s2, nsnapshots_l[state]:nsnapshots_r[state]] = P.beta * data[mask_read_uklt, :]
return
print "Loading in data from %s (%s) ..." % (self.filename, "all states" if self.bExpanded else 'state %d' % state)
data = numpy.fromiter(iter_func(), dtype=float)
if not self.len_first == self.len_last:
data = data[: -self.len_last]
data = data.reshape((-1, self.len_first))
if self.bExpanded:
for k in range(K):
mask_k = (data[:, 1] == k)
data_k = data[mask_k]
slice_data(data_k, k)
else:
slice_data(data)
def parseLog(self):
"""By parsing the .log file of the expanded-ensemble simulation
find out the time in ps when the WL equilibration has been reached.
Return the greater of WLequiltime and equiltime."""
if not(P.bIgnoreWL):
logfilename = self.filename.replace('.xvg', '.log')
if not os.path.isfile(logfilename):
raise SystemExit("\nERROR!\nThe .log file '%s' is needed to figure out when the Wang-Landau weights have been equilibrated, and it was not found.\nYou may rerun with the -x flag and the data will be discarded to 'equiltime', not bothering\nwith the extraction of the information on when the WL weights equilibration was reached.\nOtherwise, put the proper log file into the directory which is subject to the analysis." % logfilename)
try:
with open(logfilename, 'r') as infile:
dt = float(unixlike.grepPy(infile, s='delta-t').split()[-1])
WLstep = int(unixlike.grepPy(infile, s='equilibrated').split()[1].replace(':', ''))
except:
print "\nERROR!\nThe Wang-Landau weights haven't equilibrated yet.\nIf you comprehend the consequences,\nrerun with the -x flag and the data\nwill be discarded to 'equiltime'.\n"
raise
WLtime = WLstep * dt
else:
WLtime = -1
return max(WLtime, P.equiltime)
#===================================================================================================
# Preliminaries I: Sort the dhdl.xvg files; read in the @-header.
#===================================================================================================
datafile_tuple = P.datafile_directory, P.prefix, P.suffix
fs = [ F(filename) for filename in glob( '%s/%s*%s' % datafile_tuple ) ]
n_files = len(fs)
#NML: Clean up corrupted lines
print 'Checking for corrupted xvg files....'
xvgs = [filename for filename in sorted(glob( '%s/%s*%s' % datafile_tuple )) ]
for f in xvgs:
removeCorruptLines(f,f)
if not n_files:
raise SystemExit("\nERROR!\nNo files found within directory '%s' with prefix '%s' and suffix '%s': check your inputs." % datafile_tuple)
if n_files > 1:
fs = sorted(fs, key=F.sortedHelper)
if P.bSkipLambdaIndex:
try:
lambdas_to_skip = [int(l) for l in unixlike.trPy(P.bSkipLambdaIndex, '-').split()]
except:
print '\nERROR!\nDo not understand the format of the string that follows -k.\nIt should be a string of lambda indices linked by "-".\n'
raise
fs = [f for f in fs if not f.state in lambdas_to_skip]
n_files = len(fs)
lv = [] # ***
P.snap_size = []
for nf, f in enumerate(fs):
lv.append(f.readHeader())
if nf>0:
if not f.lv_names == lv_names:
if not len(f.lv_names) == n_components:
raise SystemExit("\nERROR!\nFiles do not contain the same number of lambda gradient components; I cannot combine the data.")
else:
raise SystemExit("\nERROR!\nThe lambda gradient components have different names; I cannot combine the data.")
if not f.bPV == bPV:
raise SystemExit("\nERROR!\nSome files contain the PV energies, some do not; I cannot combine the files.")
if not f.temperature == temperature: # compare against a string, not a float.
raise SystemExit("\nERROR!\nTemperature is not the same in all .xvg files.")
else:
P.lv_names = lv_names = f.lv_names
temperature = f.temperature
if temperature:
temperature_float = float(temperature)
P.beta *= P.temperature/temperature_float
P.beta_report *= P.temperature/temperature_float
P.temperature = temperature_float
print "Temperature is %s K." % temperature
else:
print "Temperature not present in xvg files. Using %g K." % P.temperature
n_components = len(lv_names)
bPV = f.bPV
P.bExpanded = f.bExpanded
#===================================================================================================
# Preliminaries II: Analyze data for validity; build up proper 'lv' and count up lambda states 'K'.
#===================================================================================================
ndE = [len(i) for i in lv] # ***
ndE_unique = numpy.unique(ndE) # ***
# Scenario #1: Each file has all the dE columns -- can use MBAR.
if len(ndE_unique) == 1: # [K]
if not numpy.array([i == lv[0] for i in lv]).all():
raise SystemExit("\nERROR!\nArrays of lambda vectors are different; I cannot combine the data.")
else:
lv = lv[0]
# Handle the case when only some particular files/lambdas are given.
if 1 < n_files < len(lv) and not P.bExpanded:
bSelective_MBAR = True
sel_states = [f.state for f in fs]
lv = [lv[i] for i in sel_states]
else:
bSelective_MBAR = False
elif len(ndE_unique) <= 3:
bSelective_MBAR = False
# Scenario #2: Have the adjacent states only; 2 dE columns for the terminal states, 3 for inner ones.
if ndE_unique.tolist() == [2, 3]:
lv = [l[i>0] for i,l in enumerate(lv)]
# Scenario #3: Have a mixture of formats (adjacent and all): either [2,3,K], or [2,K], or [3,K].
else:
lv = lv[ndE_unique.argmax()]
if 'MBAR' in P.methods:
print "\nNumber of states is NOT the same for all simulations; I'm assuming that we only evaluate"
print "nearest neighbor states, and so cannot use MBAR, removing the method."
P.methods.remove('MBAR')
print "\nStitching together the dhdl files. I am assuming that the files are numbered in order of"
print "increasing lambda; otherwise, results will not be correct."
else:
print "The files contain the number of the dE columns I cannot deal with; will terminate.\n\n%-10s %s " % ("# of dE's", "File")
for nf, f in enumerate(fs):
print "%6d %s" % (ndE[nf], f.filename)
raise SystemExit("\nERROR!\nThere are more than 3 groups of files (%s, to be exact) each having different number of the dE columns; I cannot combine the data." % len(ndE_unique))
lv = numpy.array(lv, float) # *** Lambda vectors.
K = len(lv) # *** Number of lambda states.
#===================================================================================================
# Preliminaries III: Count up the equilibrated snapshots.
#===================================================================================================
equiltime = P.equiltime
nsnapshots = numpy.zeros((n_files, K), int)
for nf, f in enumerate(fs):
f.len_first, f.len_last = (len(line.split()) for line in unixlike.tailPy(f.filename, 2))
bLenConsistency = (f.len_first != f.len_last)
if f.bExpanded:
equiltime = f.parseLog()
equilsnapshots = int(round(equiltime/f.snap_size))
f.skip_lines += equilsnapshots
extract_states = (numpy.genfromtxt(f.filename, dtype=float, skip_header=f.skip_lines, skip_footer=1*bLenConsistency, usecols=1)).astype(int)
if np.max(extract_states) > K:
# The number of states is actually bigger. we need to make the array larger.
# for some reason, resize isn't working. So do it more brute force.
old_K = K
K = np.max(extract_states)
temp_array = numpy.zeros([n_files,K],int)
temp_array[:,:old_K] = nsnapshots.copy()
nsnapshots = temp_array.copy()
c = Counter(extract_states) # need to make sure states with zero counts are properly counted.
# It's OK for some of the expanded files to have no samples as long
# at least one has samples for all states
for k in range(K):
nsnapshots[nf,k] += c[k]
#nsnapshots[nf] += numpy.array(Counter(extract_states).values())
else:
equilsnapshots = int(equiltime/f.snap_size)
f.skip_lines += equilsnapshots
nsnapshots[nf,nf] += unixlike.wcPy(f.filename) - f.skip_lines - 1*bLenConsistency
print "First %s ps (%s snapshots) will be discarded due to equilibration from file %s..." % (equiltime, equilsnapshots, f.filename)
#===================================================================================================
# Preliminaries IV: Load in equilibrated data.
#===================================================================================================
maxn = max(nsnapshots.sum(axis=0)) # maximum number of the equilibrated snapshots from any state
dhdlt = numpy.zeros([K,n_components,int(maxn)], float) # dhdlt[k,n,t] is the derivative of energy component n with respect to state k of snapshot t
u_klt = numpy.zeros([K,K,int(maxn)], numpy.float64) # u_klt[k,m,t] is the reduced potential energy of snapshot t of state k evaluated at state m
nsnapshots = numpy.concatenate((numpy.zeros([1, K], int), nsnapshots))
for nf, f in enumerate(fs):
nsnapshots_l = nsnapshots[:nf+1].sum(axis=0)
nsnapshots_r = nsnapshots[:nf+2].sum(axis=0)
f.iter_loadtxt(nf)
return nsnapshots.sum(axis=0), lv, dhdlt, u_klt
| MobleyLab/alchemical-analysis | alchemical_analysis/parser_gromacs.py | Python | mit | 16,620 | [
"Gromacs"
] | aa24877eb82b2ca23ee3b755ff5d93379f415a031a54557a4451e9958df9360e |
"""
Acceptance tests for Studio.
"""
from bok_choy.web_app_test import WebAppTest
from ...pages.studio.asset_index import AssetIndexPage
from ...pages.studio.auto_auth import AutoAuthPage
from ...pages.studio.course_info import CourseUpdatesPage
from ...pages.studio.edit_tabs import PagesPage
from ...pages.studio.import_export import ExportCoursePage, ImportCoursePage
from ...pages.studio.howitworks import HowitworksPage
from ...pages.studio.index import DashboardPage
from ...pages.studio.login import LoginPage
from ...pages.studio.users import CourseTeamPage
from ...pages.studio.overview import CourseOutlinePage
from ...pages.studio.settings import SettingsPage
from ...pages.studio.settings_advanced import AdvancedSettingsPage
from ...pages.studio.settings_graders import GradingPage
from ...pages.studio.signup import SignupPage
from ...pages.studio.textbook_upload import TextbookUploadPage
from ...fixtures.course import XBlockFixtureDesc
from base_studio_test import StudioCourseTest
class LoggedOutTest(WebAppTest):
"""
Smoke test for pages in Studio that are visible when logged out.
"""
def setUp(self):
super(LoggedOutTest, self).setUp()
self.pages = [LoginPage(self.browser), HowitworksPage(self.browser), SignupPage(self.browser)]
def test_page_existence(self):
"""
Make sure that all the pages are accessible.
Rather than fire up the browser just to check each url,
do them all sequentially in this testcase.
"""
for page in self.pages:
page.visit()
class LoggedInPagesTest(WebAppTest):
"""
Tests that verify the pages in Studio that you can get to when logged
in and do not have a course yet.
"""
def setUp(self):
super(LoggedInPagesTest, self).setUp()
self.auth_page = AutoAuthPage(self.browser, staff=True)
self.dashboard_page = DashboardPage(self.browser)
def test_dashboard_no_courses(self):
"""
Make sure that you can get to the dashboard page without a course.
"""
self.auth_page.visit()
self.dashboard_page.visit()
class CoursePagesTest(StudioCourseTest):
"""
Tests that verify the pages in Studio that you can get to when logged
in and have a course.
"""
COURSE_ID_SEPARATOR = "."
def setUp(self):
"""
Install a course with no content using a fixture.
"""
super(CoursePagesTest, self).setUp()
self.pages = [
clz(self.browser, self.course_info['org'], self.course_info['number'], self.course_info['run'])
for clz in [
# AssetIndexPage, # TODO: Skip testing this page due to FEDX-88
CourseUpdatesPage,
PagesPage, ExportCoursePage, ImportCoursePage, CourseTeamPage, CourseOutlinePage, SettingsPage,
AdvancedSettingsPage, GradingPage, TextbookUploadPage
]
]
def test_page_redirect(self):
"""
/course/ is the base URL for all courses, but by itself, it should
redirect to /home/.
"""
self.dashboard_page = DashboardPage(self.browser) # pylint: disable=attribute-defined-outside-init
self.dashboard_page.visit()
self.assertEqual(self.browser.current_url.strip('/').rsplit('/')[-1], 'home')
def test_page_existence(self):
"""
Make sure that all these pages are accessible once you have a course.
Rather than fire up the browser just to check each url,
do them all sequentially in this testcase.
"""
# In the real workflow you will be at the dashboard page
# after you log in. This test was intermittently failing on the
# first (asset) page load with a 404.
# Not exactly sure why, so adding in a visit
# to the dashboard page here to replicate the usual flow.
self.dashboard_page = DashboardPage(self.browser)
self.dashboard_page.visit()
# Verify that each page is available
for page in self.pages:
page.visit()
class DiscussionPreviewTest(StudioCourseTest):
"""
Tests that Inline Discussions are rendered with a custom preview in Studio
"""
def setUp(self):
super(DiscussionPreviewTest, self).setUp()
cop = CourseOutlinePage(
self.browser,
self.course_info['org'],
self.course_info['number'],
self.course_info['run']
)
cop.visit()
self.unit = cop.section('Test Section').subsection('Test Subsection').expand_subsection().unit('Test Unit')
self.unit.go_to()
def populate_course_fixture(self, course_fixture):
"""
Return a test course fixture containing a discussion component.
"""
course_fixture.add_children(
XBlockFixtureDesc("chapter", "Test Section").add_children(
XBlockFixtureDesc("sequential", "Test Subsection").add_children(
XBlockFixtureDesc("vertical", "Test Unit").add_children(
XBlockFixtureDesc(
"discussion",
"Test Discussion",
)
)
)
)
)
def test_is_preview(self):
"""
Ensure that the preview version of the discussion is rendered.
"""
self.assertTrue(self.unit.q(css=".discussion-preview").present)
self.assertFalse(self.unit.q(css=".discussion-show").present)
| shabab12/edx-platform | common/test/acceptance/tests/studio/test_studio_general.py | Python | agpl-3.0 | 5,572 | [
"VisIt"
] | 238b2f09d12da7a48c0cdae4e57839852188f8292df2d1d556f063a5e7b25be0 |
from collections import deque
import numpy as np
from scipy.spatial.distance import cdist
def precision_recall(swc1, swc2, dist1=4, dist2=4):
'''
Calculate the precision, recall and F1 score between swc1 and swc2 (ground truth)
It generates a new swc file with node types indicating the agreement between two input swc files
In the output swc file: node type - 1. the node is in both swc1 agree with swc2
- 2. the node is in swc1, not in swc2 (over-traced)
- 3. the node is in swc2, not in swc1 (under-traced)
target: The swc from the tracing method
gt: The swc from the ground truth
dist1: The distance to consider for precision
dist2: The distance to consider for recall
'''
TPCOLOUR, FPCOLOUR, FNCOLOUR = 3, 2, 180 # COLOUR is the SWC node type defined for visualising in V3D
d = cdist(swc1[:, 2:5], swc2[:, 2:5])
mindist1 = d.min(axis=1)
tp = (mindist1 < dist1).sum()
fp = swc1.shape[0] - tp
mindist2 = d.min(axis=0)
fn = (mindist2 > dist2).sum()
precision = tp / (tp + fp)
recall = tp / (tp + fn)
f1 = 2 * precision * recall / (precision + recall)
# Make the swc for visual comparison
swc1[mindist1 <= dist1, 1] = TPCOLOUR
swc1[mindist1 > dist1, 1] = FPCOLOUR
swc2_fn = swc2[mindist2 > dist2, :]
swc2_fn[:, 0] = swc2_fn[:, 0] + 100000
swc2_fn[:, -1] = swc2_fn[:, -1] + 100000
swc2_fn[:, 1] = FNCOLOUR
swc_compare = np.vstack((swc1, swc2_fn))
swc_compare[:, -2] = 1
# Compute the SD, SSD, SSD% defined in Peng.et.al 2010
SD = (np.mean(mindist1) + np.mean(mindist2)) / 2
far1, far2 = mindist1[mindist1 > dist1], mindist2[mindist2 > dist2]
SSD = (np.mean(far1) + np.mean(far2)) / 2
pSSD = (len(far1) / len(mindist1) + len(far2) / len(mindist2)) / 2
return (precision, recall, f1), (SD, SSD, pSSD), swc_compare
def upsample_swc(swc):
tswc = swc.copy()
id_idx = {}
# Build a nodeid->idx hash table
for nodeidx in range(tswc.shape[0]):
id_idx[tswc[nodeidx, 0]] = nodeidx
newid = tswc[:,0].max() + 1
newnodes = []
for nodeidx in range(tswc.shape[0]):
pid = tswc[nodeidx, -1] # parent id
if pid not in id_idx:
# raise Exception('Parent with id %d not found' % pid)
continue
nodepos = tswc[nodeidx, 2:5]
parentpos = tswc[id_idx[pid], 2:5]
if np.linalg.norm(nodepos - parentpos) > 1.: # Add a node in the middle if too far
mid_pos = nodepos + 0.5 * (parentpos - nodepos)
newnodes.append( np.asarray([newid, 2, mid_pos[0], mid_pos[1], mid_pos[2], 1, pid]) )
newid += 1
tswc[nodeidx, -1] = newid
# Stack the new nodes to the end of the swc file
newnodes = np.vstack(newnodes)
tswc = np.vstack((tswc, newnodes))
return tswc
def gaussian_distance(swc1, swc2, sigma=2.):
'''
The geometric metrics of NetMets. The gaussian distances between the closest neighbours
returns : (M1, M2) where M1 is the gaussian distances from the nodes in swc1 to their closest neighbour in swc2;
vise versa for M2
D. Mayerich, C. Bjornsson, J. Taylor, and B. Roysam,
“NetMets: software for quantifying and visualizing errors in biological network segmentation.,”
BMC Bioinformatics, vol. 13 Suppl 8, no. Suppl 8, p. S7, 2012.
'''
swc1 = upsample_swc(swc1)
swc2 = upsample_swc(swc2)
d = cdist(swc1[:, 2:5], swc2[:, 2:5]) # Pairwise distances between 2 swc files
mindist1 = d.min(axis=1)
M1 = 1 - np.exp(mindist1 ** 2 / (2 * sigma ** 2))
mindist2 = d.min(axis=0)
M2 = 1 - np.exp(mindist2 ** 2 / (2 * sigma ** 2))
return M1, M2
def connectivity_distance(swc1, swc2, sigma=2., ignore_leaf=True):
'''
The connectivity metrics of NetMets.
Returns (midx1, midx2): the indices of nodes in each swc that have connection errors
D. Mayerich, C. Bjornsson, J. Taylor, and B. Roysam,
“NetMets: software for quantifying and visualizing errors in biological network segmentation.,”
BMC Bioinformatics, vol. 13 Suppl 8, no. Suppl 8, p. S7, 2012.
'''
# graph Initialisation
d = cdist(swc1[:, 2:5], swc2[:, 2:5]) # Pairwise distances between 2 swc files
mindist1, mindist2 = d.min(axis=1), d.min(axis=0)
minidx1, minidx2 = d.argmin(axis=1), d.argmin(axis=0)
# Colour nodes - matched nodes have the same colour
cnodes1, cnodes2 = {}, {}# Coloured Nodes <id, colour>
for i in range(swc1.shape[0]):
if mindist1[i] < sigma:
cnodes1[swc1[i, 0]] = i
cnodes2[swc2[minidx1[i], 0]] = i
# Build Initial graphs, Edge: <id_i, id_j>: 1
g1 = build_graph_from_swc(swc1)
g2 = build_graph_from_swc(swc2)
# BFS to build the core graph for both swc, returns the remaining edges not used to build the core graph
dg1 = build_core_graph(g1, cnodes1)
dg2 = build_core_graph(g2, cnodes2)
# Find the diff edges with coloured nodes involved
mid1 = set()
for id in dg1:
for nid in g1[id]:
if nid in cnodes1: mid1.add(nid)
mid2 = set()
for id in dg2:
for nid in g2[id]:
if nid in cnodes2: mid2.add(nid)
id_idx_hash1 = {}
for i in range(swc1.shape[0]): id_idx_hash1[swc1[i, 0]] = i
id_idx_hash2 = {}
for i in range(swc2.shape[0]): id_idx_hash2[swc2[i, 0]] = i
midx1 = [ int(id_idx_hash1[id]) for id in mid1 ] # Mistake coloured nodes in edges of dg1
midx2 = [ int(id_idx_hash2[id]) for id in mid2 ] # Mistake coloured nodes in edges of dg2
# Filter out the midx of nodes on leaf segments
if ignore_leaf:
leafidx1 = find_leaf_idx(swc1)
midx1 = set(midx1) - set(leafidx1)
leafidx2 = find_leaf_idx(swc2)
midx2 = set(midx2) - set(leafidx2)
return len(midx1) / len(mid1), len(midx2) / len(mid2)
def find_leaf_idx(swc):
# The degree of a node is the number of children + 1 except the root
degree = np.zeros(swc.shape[0])
for i in range(swc.shape[0]):
degree[i] = np.count_nonzero(swc[:, -1] == swc[i, 0]) + 1
# A node is a leaf node if it is parent to no other node
leaf_segment_idx = []
leaf_node_idx = np.where(degree == 1)[0]
for idx in leaf_node_idx:
# Add its parent to the leaf segment idx list if its parent degree < 3
nodeidx = idx
while degree[nodeidx] < 3:
leaf_segment_idx.append(int(nodeidx))
if swc[nodeidx, -1] < 0:
break
nodeidx = np.where(swc[:, 0] == swc[nodeidx, -1])[0]
return leaf_segment_idx
def build_graph_from_swc(swc):
g = {}
for i in range(swc.shape[0]):
id, pid = swc[i, 0], swc[i, -1]
if id in g:
g[id].append(pid)
else:
g[id] = [pid]
if pid in g:
g[pid].append(id)
else:
g[pid] = [id]
for key, value in g.items():
g[key] = set(value)
return g
def build_core_graph(g, cnodes):
'''
Returns the edges not used in building the core graph (topologically matched between two graphs)
'''
cnodes = cnodes.copy() # Coloured node list to mark which have not been discovered
dg = g.copy()
while cnodes:
root = next(iter(cnodes))
core_neighbours = find_core_neighbours_bfs(dg, root, cnodes) # BFS to discover the neighbour
nodes_on_path = set()
if core_neighbours:
for id in core_neighbours:
nodes_on_path = nodes_on_path.union(track_path_nodes_dijstra(dg, id, root))
else:
nodes_on_path.add(root)
cnodes.pop(root) # Remove the discovered coloured nodes
for n in nodes_on_path:
dg.pop(n, None)
for n in dg:
dg[n] = dg[n].difference(nodes_on_path)
return dg
def find_core_neighbours_bfs(g, root, cnodes):
'''
Find the coloured neighbours of root node with BFS search
'''
visited = {}
node_queue = deque()
visited[root] = True
node_queue.append(root)
core_neighbours = []
while node_queue:
r = node_queue.popleft()
if r in cnodes and r != root:
core_neighbours.append(r) # If this node is coloured, bfs stops on it and add it to the core neighbours
else:
for n in g[r]: # visit all the neighbours of r
if n not in visited:
visited[n] = True
node_queue.append(n)
return core_neighbours
def track_path_nodes_dijstra(g, target, source):
path = {}
visited = {source: 0}
nodes = g.copy()
while nodes:
min_node = None
for node in nodes:
if node in visited:
if min_node is None:
min_node = node
elif visited[node] < visited[min_node]:
min_node = node
if min_node is None:
break
nodes.pop(min_node)
tweight = visited[min_node]
for n in g[min_node]:
weight = tweight + 1
if n not in visited or weight < visited[n]:
visited[n] = weight
path[n] = min_node
if min_node == target:
break
nodes_on_path, n = set(), target
while n != source:
n = path[n]
nodes_on_path.add(n)
return nodes_on_path
| RivuletStudio/rivuletpy | rivuletpy/utils/metrics.py | Python | bsd-3-clause | 9,523 | [
"Gaussian",
"VisIt"
] | fee2bcbcbfe4f5fe290c7b43d44eab29b16a0a5a29b2a49041fb7c8b8dd8dcd3 |
import unittest
from pprint import pprint as pp
import diffier
text_1 = """
Using scent:
nose.config: INFO: Ignoring files matching ['^\\.', '^_', '^setup\\.py$']
test_config (tests.test_common.test_config.Test_Config) ... ok
----------------------------------------------------------------------
Ran 1 test in 0.003s
<make></make>
OK
<ASDf> asdfasdf </ASDF>
In good standing
"""
text_2 = """
Using scent:
nose.config: INFO: Ignoring files matching ['^\\.', '^_', '^setup\\.py$']
adf
test_config (tests.test_common.test_config.Test_Config) ... ok
----------------------------------------------------------------------
Ran 1 test in 0.003s
OK
<ASDf> asdfasdf </ASDF1>
In good standing
"""
class TestDiffy(unittest.TestCase):
def setUp(self):
self.diffy = diffier.Diffy()
def test_calculate_diff(self):
result1, result2 = self.diffy.calculate_diff(text_1.split('\n'), text_2.split('\n'))
self.assertEqual(
[r.get_data() for r in result1],
[(6, 0), (9, 24)]
)
self.assertEqual(
[r.get_data() for r in result2],
[(3, 0), (8, 0), (9, 0), (10, 0), (12, 24)]
)
if __name__ == '__main__':
unittest.main() | zsong/diffy | diffy_lib/diffy_test.py | Python | mit | 1,225 | [
"ADF"
] | 3ff030495b93cc581d6d6251bce2fb042410733151749856ec3ec7888b4091d5 |
#!/usr/bin/env python
# Created by: Lee Bergstrand
# Description: A simple python program that uses HMMER to search for 16S genes within a genome. Checks
# both the forward and reverse strand DNA strand of the genome.
#
# Requirements: - This program requires the Biopython module: http://biopython.org/wiki/Download
# - This script requires HMMER 3.0 or later.
#
# Usage: BackBLAST.py <Querygenome.faa> <16S.hmm>
# Example: BackBLAST.py <Querygenome.faa> AUUJ00000000.faa
# ----------------------------------------------------------------------------------------
# ===========================================================================================================
import cStringIO
import subprocess
# Imports & Setup:
import sys
from multiprocessing import cpu_count
from os import path
from Bio import SeqIO
processors = cpu_count() # Gets number of processor cores for HMMER.
# ===========================================================================================================
# Functions:
# 1: Checks if in proper number of arguments are passed gives instructions on proper use.
def argsCheck():
if len(sys.argv) < 3:
print("Orthologous Gene Finder")
print("By Lee Bergstrand\n")
print("Please refer to source code for documentation\n")
print("Usage: " + sys.argv[0] + "<Querygenome.faa> <16S.hmm>\n")
print("Examples:" + sys.argv[0] + "Querygenome.faa <16S.hmm>")
exit(1) # Aborts program. (exit(1) indicates that an error occurred)
# -------------------------------------------------------------------------------------------------
# 2: Runs HMMER with settings specific for extracting subject sequences.
def runHMMSearch(FASTA, HMMERDBFile):
Found16S = True
process = subprocess.Popen(
["hmmsearch", "--acc", "--cpu", str(processors), "-A", "tempAlign.sto", HMMERDBFile, "-"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=1)
stdout = process.communicate(FASTA)[
0] # This returns a list with both stderr and stdout. Only want stdout which is first element.
if "No hits detected that satisfy reporting thresholds" in stdout:
Found16S = False
return Found16S
# -------------------------------------------------------------------------------------------------
# 3: Converts the sequence record object from an RNA Stockholm file to a DNA FASTA file.
def getDNAFasta(SeqRecord):
SeqRecord.letter_annotations = {} # Removes per letter annotations. Biopython throws an error if you try to
# reverse complement a sequence with per letter annotations (since afterward
# these annotations would no longer be valid). We strip these per letter
# annotions since they are not a part of the FASTA format anyways.
DNA = SeqRecord.seq.back_transcribe()
SeqRecord.seq = DNA
FASTA = SeqRecord.format("fasta")
FASTA = fastaClean(FASTA)
return FASTA
# -------------------------------------------------------------------------------------------------
# 4: Addes sequence files to the lists.
def add16SSequences(SixteenSSubunits):
handle2 = open("tempAlign.sto", "rU") # Read in the alignment file created by runHMMSearch.
SixTeens = SeqIO.parse(handle2, "stockholm") # Parse the alignment file into sequence record objects
for Sixteen in SixTeens:
SixteenFasta = getDNAFasta(Sixteen)
SixteenSSubunits.append(SixteenFasta)
handle2.close()
# -------------------------------------------------------------------------------------------------
# 5: Converts sequence record object as a reverse complement FASTA formatted sequence.
def getReverseComplementFasta(SeqRecord):
reverseCompSeq = SeqRecord.seq.reverse_complement()
SeqRecord.seq = reverseCompSeq
FASTA = SeqRecord.format("fasta")
FASTA = fastaClean(FASTA)
return FASTA
# -------------------------------------------------------------------------------------------------
# 6: Cleans up FASTA formatted sequences.
def fastaClean(FASTA):
FASTAHeader, FASTACode = FASTA.split("\n", 1) # Splits FASTA's into header and genetic code.
# Removes alignment markers and converts FASTA file sequence into a single line.
FASTACode = FASTACode.replace("-", "").replace("\n", "")
FASTA = FASTAHeader + "\n" + FASTACode
return FASTA
# -------------------------------------------------------------------------------------------------
# 7: Creates a more informative header for the 16S gene.
def fastaHeaderSwap(FASTA, subjectAccession):
FASTAHeader, FASTACode = FASTA.split("\n", 1) # Splits FASTA's into header and genetic code.
FASTAHeader = ">" + subjectAccession
FASTA = FASTAHeader + "\n" + FASTACode
return FASTA
# -------------------------------------------------------------------------------------------------
# 8: Appends genome accession to a file that acts as a list of bad accessions..
def appendBadGenomeList(genome):
global outfile
badAccession = path.split(genome)[1].strip(".fna")
try:
outfile = open("No16SGenomesHMM.txt", "a")
outfile.write(badAccession + "\n")
outfile.close()
except IOError:
print("Failed to open {0}".format(outfile))
exit(1)
# -------------------------------------------------------------------------------------------------
# 9: Adds SixteenS gene to a FASTA file.
def write16SToFile(SixteenSGene):
global outfile
try:
outfile = open("Found16SGenesHMM.fna", "a")
outfile.write(SixteenSGene + "\n")
outfile.close()
except IOError:
print("Failed to open {0}".format(outfile))
exit(1)
# ===========================================================================================================
# Main program code:
# House keeping...
argsCheck() # Checks if the number of arguments are correct.
genome = sys.argv[1]
print("Opening " + genome + "...")
subjectAccession = path.split(genome)[1].strip(".fna")
# File extension check
if not genome.endswith(".fna"):
print("[Warning] " + genome + " may not be a nucleic acid fasta file!")
HMMERDBFile = sys.argv[2]
print("Opening " + HMMERDBFile + "...")
print("Searching " + genome + " with " + HMMERDBFile + "...")
SixteenSSubunits = []
Found16S = False
try:
inFile = open(genome, "rU")
FASTA = inFile.read()
inFile.close()
Found16S = runHMMSearch(FASTA,
HMMERDBFile) # Pass this FASTA to hmmsearch. runHMMSearch returns true if a 16S was found.
if Found16S: # If we get a result from hmmsearch, check the alignment file.
print("Found a 16S in the positive strand.")
add16SSequences(SixteenSSubunits)
else:
print("No 16S found in the positive strand.")
handle = cStringIO.StringIO(
FASTA) # Instead reading from the file again we make a virtual file from a string and pass this.
FASTA = []
SeqRecords = SeqIO.parse(handle, "fasta")
for record in SeqRecords:
FASTA.append(getReverseComplementFasta(record))
FASTA = "\n".join(FASTA)
handle.close()
Found16S = runHMMSearch(FASTA,
HMMERDBFile) # Pass this FASTA to hmmsearch. runHMMSearch returns true if a 16S was found.
if Found16S: # If we get a result from hmmsearch, check the alignment file.
print("Found a 16S in the negative strand.")
add16SSequences(SixteenSSubunits)
else:
print("No 16S found in the negative strand.")
except IOError:
print("Failed to open " + genome)
exit(1)
Top16S = ""
if SixteenSSubunits:
Top16SLength = 0
for s in SixteenSSubunits:
Current16SSeqLength = len(
s.split("\n", 1)[1]) # Splits FASTA into a two element list (Header, Sequence). Gets length of the Seq.
if Current16SSeqLength >= Top16SLength:
Top16S = s
Top16SLength = Current16SSeqLength
# 16S genes are around 1500 B.P. This filters out partial sequence or really large sequences.
if len(Top16S) < 2000 and len(
Top16S) > 1000:
Top16S = fastaHeaderSwap(Top16S, subjectAccession)
write16SToFile(Top16S)
print("Writing best 16S to file.")
else:
appendBadGenomeList(genome) # If 16S gene is too partial to be used.
print("Though a partial 16S was found, it was of low quality.")
print("Writing genome accession to No16SGenomesHMM.txt")
else:
appendBadGenomeList(genome)
print("No 16S found. Writing genome accession to No16SGenomesHMM.txt")
print("Done!\n")
| LeeBergstrand/Phylogenetic-Tree-Building | HMMToFind16S/16SHMMER.py | Python | mit | 8,578 | [
"Biopython"
] | d26787cbf528f735eeb2d9f39b0161121a02797056c16b2d3fd88d06f144a8c2 |
#!/usr/bin/env python
#
# Appcelerator Titanium Module Packager
#
#
import os, sys, glob, string
import zipfile
from datetime import date
cwd = os.path.abspath(os.path.dirname(sys._getframe(0).f_code.co_filename))
os.chdir(cwd)
required_module_keys = ['name','version','moduleid','description','copyright','license','copyright','platform','minsdk']
module_defaults = {
'description':'My module',
'author': 'Your Name',
'license' : 'Specify your license',
'copyright' : 'Copyright (c) %s by Your Company' % str(date.today().year),
}
module_license_default = "TODO: place your license here and we'll include it in the module distribution"
def replace_vars(config,token):
idx = token.find('$(')
while idx != -1:
idx2 = token.find(')',idx+2)
if idx2 == -1: break
key = token[idx+2:idx2]
if not config.has_key(key): break
token = token.replace('$(%s)' % key, config[key])
idx = token.find('$(')
return token
def read_ti_xcconfig():
contents = open(os.path.join(cwd,'titanium.xcconfig')).read()
config = {}
for line in contents.splitlines(False):
line = line.strip()
if line[0:2]=='//': continue
idx = line.find('=')
if idx > 0:
key = line[0:idx].strip()
value = line[idx+1:].strip()
config[key] = replace_vars(config,value)
return config
def generate_doc(config):
docdir = os.path.join(cwd,'documentation')
if not os.path.exists(docdir):
print "Couldn't find documentation file at: %s" % docdir
return None
sdk = config['TITANIUM_SDK']
support_dir = os.path.join(sdk,'module','support')
sys.path.append(support_dir)
try:
import markdown2 as markdown
except ImportError:
import markdown
documentation = []
for file in os.listdir(docdir):
if file in ignoreFiles or os.path.isdir(os.path.join(docdir, file)):
continue
md = open(os.path.join(docdir,file)).read()
html = markdown.markdown(md)
documentation.append({file:html});
return documentation
def compile_js(manifest,config):
js_file = os.path.join(cwd,'assets','com.test.js')
if not os.path.exists(js_file): return
sdk = config['TITANIUM_SDK']
iphone_dir = os.path.join(sdk,'iphone')
sys.path.insert(0,iphone_dir)
from compiler import Compiler
path = os.path.basename(js_file)
metadata = Compiler.make_function_from_file(path,js_file)
method = metadata['method']
eq = path.replace('.','_')
method = ' return %s;' % method
f = os.path.join(cwd,'Classes','ComTestModuleAssets.m')
c = open(f).read()
idx = c.find('return ')
before = c[0:idx]
after = """
}
@end
"""
newc = before + method + after
if newc!=c:
x = open(f,'w')
x.write(newc)
x.close()
def die(msg):
print msg
sys.exit(1)
def warn(msg):
print "[WARN] %s" % msg
def validate_license():
c = open(os.path.join(cwd,'LICENSE')).read()
if c.find(module_license_default)!=-1:
warn('please update the LICENSE file with your license text before distributing')
def validate_manifest():
path = os.path.join(cwd,'manifest')
f = open(path)
if not os.path.exists(path): die("missing %s" % path)
manifest = {}
for line in f.readlines():
line = line.strip()
if line[0:1]=='#': continue
if line.find(':') < 0: continue
key,value = line.split(':')
manifest[key.strip()]=value.strip()
for key in required_module_keys:
if not manifest.has_key(key): die("missing required manifest key '%s'" % key)
if module_defaults.has_key(key):
defvalue = module_defaults[key]
curvalue = manifest[key]
if curvalue==defvalue: warn("please update the manifest key: '%s' to a non-default value" % key)
return manifest,path
ignoreFiles = ['.DS_Store','.gitignore','libTitanium.a','titanium.jar','README','com.test.js']
ignoreDirs = ['.DS_Store','.svn','.git','CVSROOT']
def zip_dir(zf,dir,basepath,ignore=[]):
for root, dirs, files in os.walk(dir):
for name in ignoreDirs:
if name in dirs:
dirs.remove(name) # don't visit ignored directories
for file in files:
if file in ignoreFiles: continue
e = os.path.splitext(file)
if len(e)==2 and e[1]=='.pyc':continue
from_ = os.path.join(root, file)
to_ = from_.replace(dir, basepath, 1)
zf.write(from_, to_)
def glob_libfiles():
files = []
for libfile in glob.glob('build/**/*.a'):
if libfile.find('Release-')!=-1:
files.append(libfile)
return files
def build_module(manifest,config):
rc = os.system("xcodebuild -sdk iphoneos -configuration Release")
if rc != 0:
die("xcodebuild failed")
rc = os.system("xcodebuild -sdk iphonesimulator -configuration Release")
if rc != 0:
die("xcodebuild failed")
# build the merged library using lipo
moduleid = manifest['moduleid']
libpaths = ''
for libfile in glob_libfiles():
libpaths+='%s ' % libfile
os.system("lipo %s -create -output build/lib%s.a" %(libpaths,moduleid))
def package_module(manifest,mf,config):
name = manifest['name'].lower()
moduleid = manifest['moduleid'].lower()
version = manifest['version']
modulezip = '%s-iphone-%s.zip' % (moduleid,version)
if os.path.exists(modulezip): os.remove(modulezip)
zf = zipfile.ZipFile(modulezip, 'w', zipfile.ZIP_DEFLATED)
modulepath = 'modules/iphone/%s/%s' % (moduleid,version)
zf.write(mf,'%s/manifest' % modulepath)
libname = 'lib%s.a' % moduleid
zf.write('build/%s' % libname, '%s/%s' % (modulepath,libname))
docs = generate_doc(config)
if docs!=None:
for doc in docs:
for file, html in doc.iteritems():
filename = string.replace(file,'.md','.html')
zf.writestr('%s/documentation/%s'%(modulepath,filename),html)
for dn in ('assets','example','platform'):
if os.path.exists(dn):
zip_dir(zf,dn,'%s/%s' % (modulepath,dn),['README'])
zf.write('LICENSE','%s/LICENSE' % modulepath)
zf.write('module.xcconfig','%s/module.xcconfig' % modulepath)
zf.close()
if __name__ == '__main__':
manifest,mf = validate_manifest()
validate_license()
config = read_ti_xcconfig()
compile_js(manifest,config)
build_module(manifest,config)
package_module(manifest,mf,config)
sys.exit(0)
| rubenfonseca/titanium-dropbox | build.py | Python | mit | 5,951 | [
"VisIt"
] | 82ea3ffd0ba47a45f473289ef31b4f477e6c85c68afd198fb8ee63a4963095ce |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham
# Copyright (C) 2008 Brian G. Matherly
# Copyright (C) 2010 Jakim Friant
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#-------------------------------------------------------------------------
#
# GTK libraries
#
#-------------------------------------------------------------------------
from gi.repository import Gtk
#-------------------------------------------------------------------------
#
# Standard Python modules
#
#-------------------------------------------------------------------------
from collections import defaultdict
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
from gramps.gen.const import PLUGINS_GLADE
from gramps.gen.plug.report._constants import standalone_categories
from . import tool
from gramps.gen.plug import REPORT
from .report import report
from ..pluginmanager import GuiPluginManager
from ..managedwindow import ManagedWindow
#-------------------------------------------------------------------------
#
# Constants
#
#-------------------------------------------------------------------------
_REPORTS = 0
_TOOLS = 1
_UNSUPPORTED = _("Unsupported")
#-------------------------------------------------------------------------
#
# PluginDialog interface class
#
#-------------------------------------------------------------------------
class PluginDialog(ManagedWindow):
"""
Displays the dialog box that allows the user to select the
plugin that is desired.
"""
def __init__(self, state, uistate, track, categories, msg,
label=None, button_label=None, tool_tip=None,
content=_REPORTS):
"""
Display the dialog box, and build up the list of available
reports. This is used to build the selection tree on the left
hand side of the dialog box.
"""
self.active = uistate.get_active('Person')
self.imap = {}
self.msg = msg
self.content = content
self._pmgr = GuiPluginManager.get_instance()
ManagedWindow.__init__(self, uistate, track, self.__class__)
self.state = state
self.uistate = uistate
self.dialog = Gtk.Builder()
self.dialog.set_translation_domain(glocale.get_localedomain())
self.dialog.add_from_file(PLUGINS_GLADE)
self.dialog.connect_signals({
"on_report_apply_clicked" : self.on_apply_clicked,
"destroy_passed_object" : self.close,
"on_delete_event": self.close,
})
self.tree = self.dialog.get_object("tree")
window = self.dialog.get_object("report")
self.title = self.dialog.get_object("title")
self.set_window(window, self.title, msg)
if content == _REPORTS:
self.setup_configs('interface.reportplugindialog', 600, 400)
elif content == _TOOLS:
self.setup_configs('interface.toolplugindialog', 600, 400)
else:
raise ValueError("PluginDialog selection must be a report or tool")
self.store = Gtk.TreeStore(str)
self.selection = self.tree.get_selection()
self.selection.connect('changed', self.on_node_selected)
col = Gtk.TreeViewColumn('', Gtk.CellRendererText(), text=0)
self.tree.append_column(col)
self.tree.set_model(self.store)
self.description = self.dialog.get_object("description")
if label:
self.description.set_text(label)
self.status = self.dialog.get_object("report_status")
self.author_name = self.dialog.get_object("author_name")
self.author_email = self.dialog.get_object("author_email")
self.apply_button = self.dialog.get_object("apply")
if button_label:
self.apply_button.set_label(button_label)
else:
self.apply_button.set_label(_("_Apply"))
self.apply_button.set_use_underline(True)
if tool_tip:
self.apply_button.set_tooltip_text(tool_tip)
self.item = None
if content == _REPORTS:
reg_list = self._pmgr.get_reg_reports()
elif content == _TOOLS:
reg_list = self._pmgr.get_reg_tools()
else:
reg_list = []
self.build_plugin_tree(reg_list, categories)
self.show()
def rebuild(self):
# This method needs to be overridden in the subclass
assert False, "This method needs to be overridden in the subclass."
def build_menu_names(self, obj):
return (self.msg, None)
def on_apply_clicked(self, obj):
"""Execute the selected report"""
if not self.item:
return
self.run_plugin(self.item)
def on_node_selected(self, obj):
"""Updates the informational display on the right hand side of
the dialog box with the description of the selected report"""
store, node = self.selection.get_selected()
if node:
path = store.get_path(node).to_string()
if not node or path not in self.imap:
return
pdata = self.imap[path]
#(report_class, options_class, title, category, name,
# doc,status,author,email,unsupported,require_active) = data
self.description.set_text(pdata.description)
if not pdata.supported:
status = _UNSUPPORTED
self.status.set_text(pdata.statustext())
self.title.set_text('<span weight="bold" size="larger">%s</span>' \
% pdata.name)
self.title.set_use_markup(1)
# TODO for Arabic, should the next two lines' commas be translated?
self.author_name.set_text(', '.join(pdata.authors))
self.author_email.set_text(', '.join(pdata.authors_email))
self.item = pdata
def build_plugin_tree(self, reg_list, categories):
"""Populates a GtkTree with each menu item associated with a entry
in the lists. The list consists of PluginData objects for reports or
tools.
old data was (item_class, options_class,title,category, name,
doc,status,author,email)
Items in the same category are grouped under the same submenu.
The categories must be dicts from integer to string.
"""
ilist = []
self.store.clear()
# build the tree items and group together based on the category name
item_hash = defaultdict(list)
for plugin in reg_list:
if not plugin.supported:
category = _UNSUPPORTED
else:
category = categories[plugin.category]
item_hash[category].append(plugin)
# add a submenu for each category, and populate it with the
# GtkTreeItems that are associated with it.
key_list = [item for item in item_hash if item != _UNSUPPORTED]
key_list.sort(reverse=True)
prev = None
if _UNSUPPORTED in item_hash:
key = _UNSUPPORTED
data = item_hash[key]
node = self.store.insert_after(None, prev)
self.store.set(node, 0, key)
next = None
data.sort(key=lambda x: x.name)
for item in data:
next = self.store.insert_after(node, next)
ilist.append((next, item))
self.store.set(next, 0, item.name)
for key in key_list:
data = item_hash[key]
node = self.store.insert_after(None, prev)
self.store.set(node, 0, key[1])
next = None
data.sort(key=lambda k:k.name)
for item in data:
next = self.store.insert_after(node, next)
ilist.append((next, item))
self.store.set(next, 0, item.name)
for next, tab in ilist:
path = self.store.get_path(next).to_string()
self.imap[path] = tab
def run_plugin(self, pdata):
"""
run a plugin based on it's PluginData:
1/ load plugin.
2/ the report is run
"""
mod = self._pmgr.load_plugin(pdata)
if not mod:
#import of plugin failed
return
if pdata.ptype == REPORT:
active_handle = self.uistate.get_active('Person')
report(self.state, self.uistate,
self.state.db.get_person_from_handle(active_handle),
eval('mod.' + pdata.reportclass),
eval('mod.' + pdata.optionclass),
pdata.name, pdata.id,
pdata.category, pdata.require_active)
else:
from ..user import User
tool.gui_tool(
dbstate = self.state,
user = User(uistate=self.uistate),
tool_class = eval('mod.' + pdata.toolclass),
options_class = eval('mod.' + pdata.optionclass),
translated_name = pdata.name,
name = pdata.id,
category = pdata.category,
callback = self.state.db.request_rebuild)
#-------------------------------------------------------------------------
#
# ReportPluginDialog
#
#-------------------------------------------------------------------------
class ReportPluginDialog(PluginDialog):
"""
Displays the dialog box that allows the user to select the
report that is desired.
"""
def __init__(self, dbstate, uistate, track):
"""Display the dialog box, and build up the list of available
reports. This is used to build the selection tree on the left
hand side of the dailog box."""
PluginDialog.__init__(
self,
dbstate,
uistate,
track,
standalone_categories,
_("Report Selection"),
_("Select a report from those available on the left."),
_("_Generate"), _("Generate selected report"),
_REPORTS)
self._pmgr.connect('plugins-reloaded', self.rebuild)
def rebuild(self):
report_list = self._pmgr.get_reg_reports()
self.build_plugin_tree(report_list, standalone_categories)
#-------------------------------------------------------------------------
#
# ToolPluginDialog
#
#-------------------------------------------------------------------------
class ToolPluginDialog(PluginDialog):
"""Displays the dialog box that allows the user to select the tool
that is desired."""
def __init__(self, dbstate, uistate, track):
"""Display the dialog box, and build up the list of available
reports. This is used to build the selection tree on the left
hand side of the dailog box."""
PluginDialog.__init__(
self,
dbstate,
uistate,
track,
tool.tool_categories,
_("Tool Selection"),
_("Select a tool from those available on the left."),
_("_Run"),
_("Run selected tool"),
_TOOLS)
def rebuild(self):
tool_list = self._pmgr.get_reg_tools()
self.build_plugin_tree(tool_list, tool.tool_categories)
| dermoth/gramps | gramps/gui/plug/_dialogs.py | Python | gpl-2.0 | 12,072 | [
"Brian"
] | 65c293de14e4625514ddf654097e869e1a494971f36ba6af61165262329a5295 |
import numpy as np
#print help(np.floor)
#print dir(np.zeros((1,1)))
#exit()
VERBOSE = True
#removes correaltions
class DistrInterface(object):
""" Measures and mimics correlation ininput data"""
def energy(self, state):
pass
def sample(self):
#sample freely, no input condisioned (clamped)
pass
def sample_input(self, x):
#sample given input
pass
def marginal_input(self, x):
#marginal given input
pass
def get_dual(self):
return self.dual
#
def sample_correlation(self):
""" Used for training"""
pass
class Boltzmann1(DistrInterface):
def __init__():
self.W = np.eye()
def energy(self, state):
pass
class RBoltzmann1(DistrInterface):
def get_dual(self):
return self.dual
def energy(self, state):
(v, h) = state
pass
class BinaryDataProvider(object):
def get_raw_sample(self, i):
return None
def samples(self):
return 0
def get_next_sample(self):
yield None
def shuffle(self):
""" prepare for next shuffled"""
pass
def get_next_shuffled(self):
pass
def set_mode(self, mode):
assert mode in ['train', 'test', 'validation']
def format(self, sample_vector):
pass
#http://deeplearning.net/datasets/
#class test_
class MNISTLoader(BinaryDataProvider):
preloaded = False
@staticmethod
def preload(path):
import os
#path = '/home/sohail/ml/datasets/mnist'
absolute_filename = os.path.join(path, 'mnist.pkl.gz')
if VERBOSE:
print 'loading MNIST', ;flush_stdout()
# Loading code from: http://deeplearning.net/tutorial/gettingstarted.html
import cPickle, gzip, numpy
f = gzip.open(absolute_filename, 'rb')
train_set, valid_set, test_set = cPickle.load(f)
f.close()
if VERBOSE:
print 'done.' ;flush_stdout()
MNISTLoader.train_set, MNISTLoader.valid_set, MNISTLoader.test_set = train_set, valid_set, test_set
def __init__(self, mode='train'):
if not MNISTLoader.preloaded:
# Downloaded from http://deeplearning.net/data/mnist/mnist.pkl.gz
MNISTLoader.preload('/home/sohail/ml/datasets/mnist')
MNISTLoader.preloaded = True
self.set_mode(mode)
def set_mode(self, mode):
assert mode in ['train', 'test', 'validation']
mode__dset_lookup = {'train': 0, 'test': 1, 'validation': 2}
datasets = [MNISTLoader.train_set, MNISTLoader.valid_set, MNISTLoader.test_set]
self.active_dataset = datasets[mode__dset_lookup[mode]]
if VERBOSE:
print 'active dataset: \'%s\''%(mode,)
def format(self, sample_vector):
return sample_vector.reshape(28, 28)
def format_text(self, sample_vector):
return sample_vector.reshape(28, 28)
def get_raw_sample(self, i):
vector = self.active_dataset[0][i]
label = self.active_dataset[1][i]
return vector, label
def get_full_data(self):
vects = self.active_dataset[0]
labels = self.active_dataset[0]
return (vects, labels)
def flush_stdout():
import sys
sys.stdout.flush()
def print_image_28x28(image):
#exit()
w = 28
for y in range(784/w):
for x in range(w):
print '.' if image[x+w*y] < 0.5 else '1',
print
print
def test_mnist():
#print 'loading', ;flush_stdout()
d = MNISTLoader()
#print 'done.' ;flush_stdout()
print d
print type(d.train_set)
print len(d.train_set)
print d.train_set
print d.train_set[0].shape #(50000, 784)
print d.train_set[1].shape #(50000,) of int64 #labels
print d.train_set[1][0]
print type(d.train_set[1][0]) # int64
print d.train_set[0][0,0]
print type(d.train_set[0][0,0]) # float32
for t in [MNISTLoader.train_set, MNISTLoader.valid_set, MNISTLoader.test_set]:
print t[1].shape, #labels
print t[0].shape, #data
print type(t[1][0]), # int64
print type(t[0][0,0]) # float32
#(50000,) (50000, 784) <type 'numpy.int64'> <type 'numpy.float32'>
#(10000,) (10000, 784) <type 'numpy.int64'> <type 'numpy.float32'>
#(10000,) (10000, 784) <type 'numpy.int64'> <type 'numpy.float32'>
vector = t[0]
print (np.min(vector), np.max(vector)), #(0,0.996)
i = 100
image = vector[i]
print_image_28x28(image)
#matrix = image.reshape(28, 28)
#print np.floor(matrix*10).astype(int)
def factorize():
print 7.*8.*7.*2
m = 784./7./8./7./2.
print m, ":",
for i in range(2, int(m**0.5)):
if float(m)/float(i) % 1. == 0.:
print i,
print # 2 4 7 8 14 16
import matplotlib.pyplot as plt
def show_image(matrix, show=True):
plt.imshow(matrix, cmap='bone')
if show:
plt.show()
#plt.hist( np.log10(ea+leps), 150)
def show_images(matrix_list, grid_shape=None):
if grid_shape is None:
n = len(matrix_list)
w = int((n-0.000001)**(0.5) + 1)
h = int((n-.00000001)/w) + 1
print w, h
grid_shape = (w, h)
i = 0
for vector in matrix_list:
matrix = vector.reshape(28, 28)
plt.subplot(w, h, i+1)
plt.imshow(matrix, cmap='bone')
i+=1
plt.show()
def load_autocorrel_demo():
d = MNISTLoader('test')
vec, label = d.get_raw_sample(100)
#print vec
print "label=", label
#print d.format((vec*10).astype(int))
print_image_28x28(vec)
vects, labels = d.get_full_data()
vects = (vects > 0.5)*1.
print vects.shape
sample_size, n = vects.shape
#vects.shape =
print "calculating autocorrel-",;flush_stdout()
autocorr = np.dot(vects[:100, :].T, vects[:100, :])
print "lation"; flush_stdout()
print autocorr[::20, ::20].shape
print np.sum(np.fabs(autocorr)/(autocorr.size*1.)) #average: 1.5 ! what?
#print autocorr.size
print np.sum(np.fabs(autocorr)>1.)/(autocorr.size*1.)
#show_image(autocorr)
ac4d = autocorr.reshape(28,28, 28,28)
ac4d_i = np.swapaxes(ac4d, 1, 2)
print ac4d.shape
#show_image(ac4d_i[:,:,10,10]) # rows versus rows, cols=10,10
show_image(ac4d_i[10, 10, :, :])
#shows some pattern.
#There is some continuity here.
#Also 'some' continuity along all 4 dimensions here!
#help(np.swapaxes)
#Why nothing for sampling?
def sampling_demo():
n = 28*28
n1 = n+1
W = np.eye(n1, n1)
v = np.random.rand(n)
v1 = np.hstack((v, 1.))
print v.shape, v1.shape
energy = np.dot(np.dot(v1, W), v1) #W=I => indep. => energy=v^2=|v|.
# Each independent feature adds to energy.
print energy
#activation = activity of one, when all others (Except for that) are given (and condisioned).
def ewnergy1(v):
v1 = np.hstack((v, 1.))
print v.shape, v1.shape
energy = np.dot(np.dot(v1, W), v1) #W=I => indep. => energy=v^2=|v|.
for i in range(100):
v = np.random.rand(n)
e = energy1(v)
#incomplete
class I28x28:
@staticmethod
def shift(v, xshift, yshift, background=0.):
matrix = v.reshape(28, 28).copy() #necessary
#print np.median(matrix)
#matrix[xshift:, yshift:] = matrix[:-1-xshift:, :-1-yshift]
assert int(xshift) == xshift
assert int(yshift) == yshift
assert int(xshift) == xshift
assert int(yshift) == yshift
if xshift > 0:
matrix[xshift:, :] = matrix[:-xshift, :]
matrix[:xshift, :] = background
elif xshift < 0:
matrix[:-xshift, :] = matrix[xshift:, :]
matrix[-xshift:, :] = background
else:
pass
if yshift > 0:
matrix[:, yshift:] = matrix[:, :-yshift]
matrix[:, :yshift] = background
elif yshift < 0:
matrix[:, :-yshift] = matrix[:, yshift:]
matrix[:, -yshift:] = background
else:
pass
return matrix.reshape(28*28)
def naive_gauss_reproduce_demo():
d = MNISTLoader('test')
vects, labels = d.get_full_data()
#ndim = vects.shape[1]
vects = (vects > 0.5)*1.
sample_size, ndim = vects.shape
#num_samples_taken_into_account = 1000
#v_sub = vects[:num_samples_taken_into_account, :]
#REDUCE the number of samples
v_sub = vects[::1, :]; sample_size = v_sub.shape[1]
mu = np.mean(v_sub, axis=0) # * 0.
mu_scalar=np.mean(mu.ravel()) #scalar
mu_scalar = float(mu_scalar)
mu = mu * 0 + mu_scalar
#mu = mu * 0
if False:
for si in range(v_sub.shape[0]):
#v_sub[si] = v_sub[si] - mean(v_sub[i])
#dx, dy = np.random.randint(-15,15), np.random.randint(-15,15) #too scrambled
dx, dy = np.random.randint(-15,15), np.random.randint(-15,15) #too scrambled
v_sub[si] = I28x28.shift(v_sub[si], dx,dy, background=0)
if False:
v_sub[si] = v_sub[si] - mu
i1 = v_sub[si].copy()
v_sub[si] = I28x28.shift(v_sub[si], 0, 15, background=0)
i2 = v_sub[si].copy()
v_sub[si] = I28x28.shift(i1, 0, -15, background=0)
i3 = v_sub[si].copy()
v_sub[si] = I28x28.shift(i1, -15, -15, background=0)
i4 = v_sub[si].copy()
show_images([i1, i2, i3, i4])
if (si+1) % 100 == 1:
print "si:%d \r"%(si,),
print "calculating autocorrelation",;flush_stdout()
autocorr = np.dot(v_sub.T, v_sub) / float(sample_size) * 0.0001
print "."; flush_stdout()
print autocorr.shape
cov = autocorr
#fixme: How come is it NOT positive-semidifinite?
#mu = np.sum(v_sub, axis=0)
ilist = []
for i in range(16):
#Works, but why the mean should not be subtracted?
alpha = 1
s = np.random.multivariate_normal(mu, cov*alpha+(1.-alpha)*np.eye(ndim))
#s = mu
ilist.append(s)
#s28x28 = s.reshape(28, 28)
#show_image(s28x28, show=False)
#plt.show()
show_images(ilist)
#Problem: 3 is too dominant
#Mean/covar bug fixed. Now makes sense in terms of classic mean/covariance.
if __name__ == '__main__':
#test_mnist()
#factorize()
#load_autocorrel_demo()
#sampling_demo()
#Has a form similar to Gaussian. Exp(vWv)
#It is simply a Gaussian, but on (0,1). Damn. (So it is basically Genz)
#My intuition for normalizing Genz was good: Use the lieanr transformation, but not to make it uniform. (how?)
#Learning: W != correl, because we also have a Z. The balance in between that and Z. (only because it's {0,1})
#Boltzmann Machine is simple? As if it's a simpel Gaussian correlation-detector. Which is tained online.
#So, yes, do think of it like a Gaussian.
#Also see Laplace's method, page 341 of 1st edition (D.McKay). He assumed normalisation factor does not exist from beginning. (And it's Taylor)
#Can we make Z easier by the transforamtion?
#So can we reproduce the original samples using the correlation matrix?
#It is intersting that in Gaussian, mue can be inside W.
#fastCopyAndTranspose?
#Now let's generate some Gaussian.
#The autocorrelation is so tighting from all directions that can determine everything!
#Let's try: naive_gauss_reproduce()
naive_gauss_reproduce_demo()
#In Genz, integration is rndom genration (sampling).
# A Bernouli version of Gaussian?
#..
#We limit information by choosing Bernouli {0,1}.
#Restricted BM is another idea.
#It can be seen as just adding dimensions. But what about preserving infomration between V, H?
#A way to increase capacity is to add extra variables (hidden).
#But what will this mean in terms of RBM/multiple layers? (remember: they could be arbitrary). It is attaching them to another Gaussian. So it keeps reducing dimensions untill it "closes" the distribution (by specifyint all dimensions).
#Problem: Combining two Gaussians is Gaussian. To increasing dimensions is useful, but attaching them to another Gaussian is useless. It gives the problem to another external machine to solve. But it would need a nonlinearity.
#Adding the mean in sampling, means we add a white '3'. Which means the raw samples have a hole in '3' otherwise.
#Howdo we improve this? More samples? No, not enough.
#But people already have used Eigenfaces. They probably have tries sampling from that space too.
#And the results now do look like eigenfaces (e.g. DC comonent in back). Back to Gaussian: how can we force eigenfaces to do differently.
#But that's PCA/dim-reduction.
#Yes: Gaussian does reduce the dimenions, but it is not easy to see the reduces dimensiones. But they still obey the eigenvectors. The eigenvectors encode the correaltions. But not explicitly. PCA makes them explicit.
#The PCA/RBM => explicitly extract that space: Some Q where vAv = vQBQv
#What would 'sampling' (as in PatternTheory) mean in a PCA/Eigenface mindset?
#We kind of reduce the dimensions and then reproduce it. But it's still not the sampling idea.
#What RBM adds is notin of marginalisation and condisioning (clamping)
#Marginalising = Activity function. (but plus Expected value?)
#Activity is also population-marginalisation.
#Why is it not smooth anymore?
#We need to inject an external distribution. That is, H distribution in RBM.
#But in MLP, it is the output. In PT (Pattern Theory/sampling approach), it is [generated?].
#BTW, Where is the nonlinearity (of MLP)?
#In Gaussian, crrelation is between pairs only. In one-layer [R]BM, too.
#Observation: When I generate more samples, they all subjectively look similar. First guess, they all use a uniform distribution on the other side of the Gaussian. (Although we dont have hidden units, but we can see this as hidden units that have a purely Gasussian distribution).
#So, it just does a dim-reduction.
#=> Hence, The next step is to do an actual PCA.
#Hinton also compared it to PCA. Because it is really comparable to PCA. IT chooses the dimensions automatically. (Can it put weight on H dimentions?)
#(reminder) Output of RBM is between two Qs in vAv=vQhhQv. (minimizing vQh, and vQh->(Q^T)->v) However, PCA is also about breaking down A into QQ.
#What is added to RBM that makes it different to this PCA (Q)?
#Note, they dont look like the original because I just did sampling.
#The criterion for learning is to reproduce the input. But from what. From its map. But a map of course makes it. The map should reduce it really.
#So a Gaussian extention is a Linear trnaformation that is most faithful to input when the dimensions are Reduced: A PCA which those few dimensions is chosen based on this criterion. (But still the nonlinearity is has not entered.)
#Older Note: note that normalisation is key (implicitly used in Boltzmann's formalism as temperature).
#Brain's temperature: Neormalisation/[Audio-engineering's sense of]Compression.
#So we dont even reproduce the distribution! The only criterion is reproducing it. (How dow it bring non-linearity?)
| sohale/nn-it | boltz1.py | Python | gpl-3.0 | 15,347 | [
"Gaussian"
] | 9c4df2c970c2d1bf151a97c4a40555ae0c662f9b28769fc44168edbec60d1815 |
from queries import queries
#
# Main chart Monthly
#
class main_chart_queries(queries):
def __init__(self, cursor, output, refdate = 'now'):
super(main_chart_queries, self).__init__(cursor, output, refdate)
def generate_main_chart_all(self):
# Visit member
self.cursor.execute('''
SELECT count(distinct(visit.id))
FROM visit
JOIN useragent ON id_useragent=useragent.id
JOIN visitor ON id_visitor=visitor.id
WHERE (useragent.typ = 'Browser' )
AND visitor.userid > 16 AND visitor.userid != 43 ''')
result = list()
for line in self.cursor:
result.append(line[0])
# visit non member
self.cursor.execute('''
SELECT count(distinct(visit.id))
FROM visit
JOIN useragent ON id_useragent=useragent.id
JOIN visitor ON id_visitor=visitor.id
WHERE (useragent.typ = 'Browser' )
AND visitor.userid = -1 ''')
for line in self.cursor:
result.append(line[0])
# tx rebond
self.cursor.execute('''
SELECT count(nbRequests)
FROM SELECT begin_date, count(request.id) as nbRequests
FROM request
JOIN visit ON id_visit=visit.id
JOIN useragent ON id_useragent=useragent.id
JOIN visitor ON id_visitor=visitor.id
WHERE (useragent.typ = 'Browser' )
AND (visitor.userid > 16 ) AND visitor.userid != 43
GROUP BY visit.id)
WHERE nbRequests = 1 ''')
for line in self.cursor:
result.append(line[0])
self.cursor.execute('''
SELECT count(distinct(request.id))
FROM request JOIN visit ON id_visit=visit.id
WHERE url like '/__/payment/doautoresponse%' ''')
for line in self.cursor:
result.append(line[0])
self._array_serialize(open(self.output + "/visits_all.js", "w"), result, "visits_all")
#
# Main chart Monthly
#
def generate_main_chart_monthly(self):
for i in range(1, 31) :
self.cursor.execute('''
INSERT INTO mydates (time)
VALUES (datetime(?, '-30 days', 'start of day', '+%i days'))'''% i, (self.refdate,))
f = open(self.output + "/visits_monthly.js", "w")
# Visit member
self.cursor.execute('''
SELECT quote(time), coalesce(nb, 0) FROM mydates LEFT JOIN (
SELECT strftime('%Y-%m-%d 00:00:00', begin_date) as date , count(distinct(visit.id)) as nb
FROM visit
JOIN visitor ON id_visitor=visitor.id
WHERE real=1
AND visitor.userid != -1
AND begin_date > datetime(?, '-30 days')
GROUP BY strftime('%Y%m%d', begin_date))
ON time = date
WHERE time > datetime(?, '-30 days', 'localtime') ''', (self.refdate,self.refdate))
result_member = list()
for line in self.cursor:
result_member.append([line[0], line[1]])
self._double_array_serialize(f, result_member, "visit_member")
# visit non member
self.cursor.execute('''
SELECT quote(time), coalesce(nb, 0) FROM mydates LEFT JOIN (
SELECT strftime('%Y-%m-%d 00:00:00', begin_date) as date , count(distinct(visit.id)) as nb
FROM visit
JOIN visitor ON id_visitor=visitor.id
WHERE real=1
AND visitor.userid = -1
AND begin_date > datetime(?, '-30 days', 'localtime')
GROUP BY strftime('%Y%m%d', begin_date) )
ON time = date
WHERE time > datetime(?, '-30 days', 'localtime')
''', (self.refdate, self.refdate))
result_non_member = list()
for line in self.cursor:
result_non_member.append([line[0], line[1]])
self._double_array_serialize(f, result_non_member, "visit_non_member")
# tx rebond
self.cursor.execute('''
SELECT quote(time), coalesce(nb, 0) FROM mydates LEFT JOIN (
SELECT strftime('%Y-%m-%d 00:00:00', begin_date) as date , COALESCE(count(nbRequests), 0) as nb
FROM ( SELECT begin_date, count(distinct(request.id)) as nbRequests
FROM request
JOIN visit ON id_visit=visit.id
JOIN visitor ON id_visitor=visitor.id
JOIN useragent ON id_useragent=useragent.id
JOIN externalurl ON externalurl.id=id_externalurl
WHERE (useragent.typ = 'Browser' )
AND (visitor.userid > 16 OR visitor.userid = -1) AND visitor.userid != 43
AND begin_date > datetime(?, '-30 days', 'localtime')
AND netloc NOT LIKE '%%elveos.org'
AND netloc NOT IN ('127.0.0.1', 'localhost', 'mercanet.bnpparibas.net')
AND netloc NOT LIKE '%%.local'
AND url NOT LIKE '/__/resource%'
AND url NOT LIKE '/rest/%'
AND url NOT LIKE '/favicon.ico%'
AND url NOT LIKE '%.png'
AND url NOT LIKE '%.txt'
AND url NOT LIKE '%featurefeed%'
AND url NOT LIKE '%%softwarefeed%%'
AND url NOT LIKE '/__/%login'
AND url NOT LIKE '%/doactivate%'
AND url NOT LIKE '%resource%'
GROUP BY visit.id)
WHERE nbRequests = 1
GROUP BY nbRequests , strftime('%Y%m%d', begin_date))
ON time = date
WHERE time > datetime(?, '-30 days', 'localtime')
''', (self.refdate,self.refdate))
result = list()
i = 0
for line in self.cursor:
nbMember = (result_non_member[i][1] + result_member[i][1])
result.append([line[0], nbMember and (line[1] * 100) / nbMember])
i += 1
self._double_array_serialize(f, result, "txrebond")
self.cursor.execute('''
SELECT quote(time), coalesce(nb, 0) FROM mydates LEFT JOIN (
SELECT strftime('%Y-%m-%d 00:00:00', begin_date) as date , count(distinct(visit.id)) as nb
FROM request JOIN visit ON id_visit=visit.id
WHERE url like '/__/payment/doautoresponse%'
-- user agent is unknown !! (mercanet response)
-- (useragent.typ = 'Browser' )
-- AND visitor.userid != -1
-- AND (visitor.userid > 16 OR visitor.userid = -1) AND visitor.userid != 43
AND begin_date > datetime(?, '-30 days', 'localtime')
GROUP BY strftime('%Y%m%d', begin_date))
ON time = date
WHERE time > datetime(?, '-30 days', 'localtime')
''', (self.refdate,self.refdate))
result = list()
i = 0
for line in self.cursor:
nbMember = (result_non_member[i][1] + result_member[i][1])
result.append([line[0], nbMember and (line[1] * 1000) / nbMember])
i += 1
self._double_array_serialize(f, result, "txconversion")
self.cursor.execute('''delete from mydates''')
#
# Main chart DAILY
#
def generate_main_chart_daily(self):
self.cursor.execute('''delete from mydates''')
for i in range(0, 30) :
self.cursor.execute('''
INSERT INTO mydates (time)
VALUES (strftime('%%Y-%%m-%%d %%H:00:00', datetime(?, '-%i hours', 'localtime')))'''% i, (self.refdate,))
f = open(self.output + "/visits_daily.js", "w")
# Visit member
self.cursor.execute('''
SELECT quote(time), coalesce(nb, 0) FROM mydates LEFT JOIN (
SELECT strftime('%Y-%m-%d %H:00:00', begin_date) as date , count(distinct(visit.id)) as nb
FROM visit
JOIN visitor ON id_visitor=visitor.id
WHERE visit.real=1
AND visitor.userid != -1
AND begin_date > datetime(?, '-2 days', 'localtime')
GROUP BY strftime('%d%H', begin_date))
ON time = date
WHERE time > datetime(?, '-2 days', 'localtime')
''', (self.refdate,self.refdate))
result_member = list()
for line in self.cursor:
result_member.append([line[0], line[1]])
self._double_array_serialize(f, result_member, "visit_member")
# visit non member
self.cursor.execute('''
SELECT quote(time), coalesce(nb, 0) FROM mydates LEFT JOIN (
SELECT strftime('%Y-%m-%d %H:00:00', begin_date) as date , count(distinct(visit.id)) as nb
FROM visit
JOIN visitor ON id_visitor=visitor.id
WHERE real=1
AND visitor.userid = -1
AND begin_date > datetime(?, '-2 days', 'localtime')
GROUP BY strftime('%d%H', begin_date) )
ON time = date
WHERE time > datetime(?, '-2 days', 'localtime')
''', (self.refdate,self.refdate))
result_non_member = list()
for line in self.cursor:
result_non_member.append([line[0], line[1]])
self._double_array_serialize(f, result_non_member, "visit_non_member")
# tx rebond
self.cursor.execute('''
SELECT quote(time), coalesce(nb, 0) FROM mydates LEFT JOIN (
SELECT strftime('%Y-%m-%d %H:00:00', begin_date) as date , COALESCE(count(nbRequests), 0) as nb
FROM ( SELECT begin_date, count(distinct(request.id)) as nbRequests
FROM request JOIN visit ON id_visit=visit.id
JOIN useragent ON id_useragent=useragent.id
JOIN visitor ON id_visitor=visitor.id
JOIN externalurl ON externalurl.id=id_externalurl
WHERE (useragent.typ = 'Browser' )
AND (visitor.userid > 16 OR visitor.userid = -1) AND visitor.userid != 43
AND begin_date > datetime(?, '-2 days', 'localtime')
AND netloc NOT LIKE '%%elveos.org'
AND netloc NOT IN ('127.0.0.1', 'localhost', 'mercanet.bnpparibas.net')
AND netloc NOT LIKE '%%.local'
AND url NOT LIKE '%featurefeed%'
AND url NOT LIKE '%%softwarefeed%%'
AND url NOT LIKE '/__/%login'
AND url NOT LIKE '/__/resource%'
AND url NOT LIKE '/rest/%'
AND url NOT LIKE '/favicon.ico%'
AND url NOT LIKE '%.png'
AND url NOT LIKE '%.txt'
AND url NOT LIKE '%resource%'
GROUP BY visit.id)
WHERE nbRequests = 1
GROUP BY nbRequests , strftime('%d%H', begin_date))
ON time = date
WHERE time > datetime(?, '-2 days', 'localtime')
''', (self.refdate,self.refdate))
result = list()
i = 0
for line in self.cursor:
nbMember = (result_non_member[i][1] + result_member[i][1])
result.append([line[0], nbMember and (line[1] * 100) / nbMember])
i += 1
self._double_array_serialize(f, result, "txrebond")
self.cursor.execute('''
SELECT quote(time), coalesce(nb, 0) FROM mydates LEFT JOIN (
SELECT strftime('%Y-%m-%d %H:00:00', begin_date) as date , count(distinct(visit.id)) as nb
FROM request JOIN visit ON id_visit=visit.id
WHERE url like '/__/payment/doautoresponse%'
-- user agent is unknown !! (mercanet response)
-- (useragent.typ = 'Browser' )
-- AND visitor.userid != -1
-- AND (visitor.userid > 16 OR visitor.userid = -1) AND visitor.userid != 43
AND begin_date > datetime(?, '-2 days', 'localtime')
GROUP BY strftime('%d%H', begin_date))
ON time = date
WHERE time > datetime(?, '-2 days')
''', (self.refdate,self.refdate))
result = list()
i = 0
for line in self.cursor:
nbMember = (result_non_member[i][1] + result_member[i][1])
result.append([line[0], nbMember and (line[1] * 1000) / nbMember])
i += 1
self._double_array_serialize(f, result, "txconversion")
self.cursor.execute('''delete from mydates''')
| niavok/elveos | stats/src/bloatitstats/queries/main_chart_queries.py | Python | agpl-3.0 | 12,399 | [
"VisIt"
] | 35633ea76c12d27206822d8b02b0328a052ff9d3a6f6aa11fe53b3f1b93a1947 |
from django.test import TestCase
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.urls import reverse
from splinter import Browser
from estudios_socioeconomicos.models import Estudio
from perfiles_usuario.utils import ADMINISTRADOR_GROUP, CAPTURISTA_GROUP, DIRECTIVO_GROUP, \
SERVICIOS_ESCOLARES_GROUP
from perfiles_usuario.models import Capturista
class TestBaseViews(StaticLiveServerTestCase):
"""Integration test suite for testing the views in the app: base.
Test the url for home and the basefiles like robots.txt and humans.txt
Attributes
----------
browser : Browser
Driver to navigate through websites and to run integration tests.
"""
def setUp(self):
"""Initialize the browser, before running the tests.
"""
self.browser = Browser('chrome')
def tearDown(self):
"""At the end of tests, close the browser
"""
self.browser.driver.close()
self.browser.quit()
def test_robots(self):
"""Test for url 'base:base_files(robots.txt)'.
Visit the url of robots.txt and check it loads the file
"""
self.browser.visit(self.live_server_url + reverse('base_files',
kwargs={'filename': 'robots.txt'}))
self.assertTrue(self.browser.is_text_present('robotstxt'))
def test_humans(self):
"""Test for url 'base:base_files(humans.txt)'.
Visit the url of humans.txt and check it loads the file
"""
self.browser.visit(self.live_server_url + reverse('base_files',
kwargs={'filename': 'humans.txt'}))
self.assertTrue(self.browser.is_text_present('humanstxt'))
def test_access_to_help(self):
""" Test that help is accesible via de help button
"""
test_username = 'thelma'
test_password = 'junipero'
self.thelma = get_user_model().objects.create_user(
username=test_username, email='juan@pablo.com', password=test_password,
first_name='Thelma', last_name='Thelmapellido')
administrators = Group.objects.get_or_create(name=ADMINISTRADOR_GROUP)[0]
administrators.user_set.add(self.thelma)
administrators.save()
self.browser.visit(self.live_server_url + reverse('tosp_auth:login'))
self.browser.fill('username', test_username)
self.browser.fill('password', test_password)
self.browser.find_by_id('login-submit').click()
self.browser.find_by_id('my-account-btn').click()
self.browser.find_by_id('help_button').click()
self.assertTrue(self.browser.is_text_present('Página de ayuda'))
class TestHelp(TestCase):
""" Suite to test that the help page can be accessed.
"""
def setUp(self):
""" Create the necessary elements
"""
self.username = 'Eugenio420'
self.password = 'pugnotpug'
self.user = get_user_model().objects.create_user(
username=self.username,
password=self.password)
self.client.login(username=self.username, password=self.password)
def test_help(self):
""" Test for url 'base:ayuda'.
Visits the url of help.html and checks if it loads the correct template.
"""
response = self.client.get(reverse('ayuda'))
self.assertEqual(200, response.status_code)
self.assertTemplateUsed(response, 'base/help.html')
class TestRedirects(TestCase):
""" Suite to test the redirection from base to the corresponding dashboards.
"""
def setUp(self):
self.username = 'Eugenio420'
self.password = 'pugnotpug'
self.user = get_user_model().objects.create_user(
username=self.username,
password=self.password)
def test_redirect_to_login(self):
""" Test that an unauthenticated user gets redirected to login.
We check that the login_url in settings works properly by redirecting
to the login url.
"""
response = self.client.get(reverse('home'))
self.assertRedirects(response, reverse('tosp_auth:login') + '?next=/')
def create_group(self, group_name):
""" Utility function to create a group and add the user to it.
We receive the name of the group, create it, and bound it to the
user.
Parameters:
-----------
group_name : str
The name of the group.
"""
group = Group.objects.get_or_create(name=group_name)[0]
group.user_set.add(self.user)
group.save()
def test_redirect_admin(self):
""" Test that the admin is redirected to its dashboard.
We test that a user who has the admin group is redirected to its dashboard.
"""
self.create_group(ADMINISTRADOR_GROUP)
self.client.login(username=self.username, password=self.password)
response = self.client.get(reverse('home'))
self.assertRedirects(response, reverse('administracion:main_estudios',
kwargs={'status_study': Estudio.REVISION}))
def test_redirect_capturista(self):
""" Test that the capturista is redirected to its dashboard.
"""
self.capturista = Capturista.objects.create(user=self.user)
self.create_group(CAPTURISTA_GROUP)
self.client.login(username=self.username, password=self.password)
response = self.client.get(reverse('home'))
self.assertRedirects(response, reverse('captura:estudios'))
def test_redirect_directivo(self):
""" Test that a directivo is redirected to its dashboard.
"""
self.create_group(DIRECTIVO_GROUP)
self.client.login(username=self.username, password=self.password)
response = self.client.get(reverse('home'))
self.assertRedirects(response, reverse('indicadores:all'))
def test_redirect_servicios_escolares(self):
""" Test that servicios escolares is redirected to its dashboard.
"""
self.create_group(SERVICIOS_ESCOLARES_GROUP)
self.client.login(username=self.username, password=self.password)
response = self.client.get(reverse('home'))
self.assertRedirects(response, reverse('becas:services'))
def test_redirect_login(self):
""" Test that a logged user gets redirected to home.
"""
self.create_group(CAPTURISTA_GROUP)
self.capturista = Capturista.objects.create(user=self.user)
self.create_group(CAPTURISTA_GROUP)
self.client.login(username=self.username, password=self.password)
response = self.client.get(reverse('home'))
self.assertRedirects(response, reverse('captura:estudios'))
response = self.client.get(reverse('tosp_auth:login'))
self.assertRedirects(response, reverse('home'), target_status_code=302)
| erikiado/jp2_online | base/test_views.py | Python | mit | 7,173 | [
"VisIt"
] | 64ceb590a99b9eae4b0c5994033fe3d6a6d0eec51ede7b081b85ed1e8875216a |
from ase import Atoms, Atom
from gpaw import GPAW
a = 4. # Size of unit cell (Angstrom)
c = a / 2
# Hydrogen atom:
atom = Atoms('H',
positions=[(c, c, c)],
magmoms=[1],
cell=(a, a, a))
# gpaw calculator:
calc = GPAW(h=0.18, nbands=1, xc='PBE', txt='H.out')
atom.set_calculator(calc)
e1 = atom.get_potential_energy()
calc.write('H.gpw')
# Hydrogen molecule:
d = 0.74 # Experimental bond length
molecule = Atoms('H2',
positions=([c - d / 2, c, c],
[c + d / 2, c, c]),
cell=(a, a, a))
calc.set(txt='H2.out')
molecule.set_calculator(calc)
e2 = molecule.get_potential_energy()
calc.write('H2.gpw')
print 'hydrogen atom energy: %5.2f eV' % e1
print 'hydrogen molecule energy: %5.2f eV' % e2
print 'atomization energy: %5.2f eV' % (2 * e1 - e2)
| qsnake/gpaw | doc/tutorials/atomization/atomize.py | Python | gpl-3.0 | 857 | [
"ASE",
"GPAW"
] | fb5b44415202b083fd69ccf6aa683dbad50d82e324832795121c2d1a56965730 |
#
# Copyright (c) 2015 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/scancode-toolkit/
# The ScanCode software is licensed under the Apache License version 2.0.
# Data generated with ScanCode require an acknowledgment.
# ScanCode is a trademark of nexB Inc.
#
# You may not use this software except in compliance with the License.
# You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#
# When you publish or redistribute any data created with ScanCode or any ScanCode
# derivative work, you must accompany this data with the following acknowledgment:
#
# Generated with ScanCode and provided on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, either express or implied. No content created from
# ScanCode should be considered or used as legal advice. Consult an Attorney
# for any legal advice.
# ScanCode is a free software code scanning tool from nexB Inc. and others.
# Visit https://github.com/nexB/scancode-toolkit/ for support and download.
from __future__ import absolute_import, print_function, unicode_literals
import os
from unittest.case import skipIf
from unittest.case import expectedFailure
from commoncode.testcase import FileBasedTesting
from commoncode.system import on_windows
from typecode.contenttype import get_filetype
from typecode.contenttype import get_type
from typecode.contenttype import get_pygments_lexer
from typecode.contenttype import is_standard_include
# aliases for testing
get_mimetype_python = lambda l: get_type(l).mimetype_python
get_filetype_pygment = lambda l: get_type(l).filetype_pygment
get_filetype_file = lambda l: get_type(l).filetype_file
get_mimetype_file = lambda l: get_type(l).mimetype_file
is_text = lambda l: get_type(l).is_text
is_archive = lambda l: get_type(l).is_archive
is_media = lambda l: get_type(l).is_media
is_winexe = lambda l: get_type(l).is_winexe
is_source = lambda l: get_type(l).is_source
is_special = lambda l: get_type(l).is_special
is_pdf = lambda l: get_type(l).is_pdf
is_pdf_with_text = lambda l: get_type(l).is_pdf_with_text
is_binary = lambda l: get_type(l).is_binary
is_c_source = lambda l: get_type(l).is_c_source
is_stripped_elf = lambda l: get_type(l).is_stripped_elf
is_elf = lambda l: get_type(l).is_elf
elf_type = lambda l: get_type(l).elf_type
get_link_target = lambda l: get_type(l).link_target
is_link = lambda l: get_type(l).is_link
is_broken_link = lambda l: get_type(l).is_broken_link
size = lambda l: get_type(l).size
class TestContentType(FileBasedTesting):
test_data_dir = os.path.join(os.path.dirname(__file__), 'data')
def test_size(self):
test_dir = self.get_test_loc('contenttype/size')
result = size(test_dir)
assert 18 == result
def test_filetype_file_on_unicode_file_name(self):
test_zip = self.extract_test_zip('contenttype/unicode/unicode.zip')
test_dir = os.path.join(test_zip, 'a')
f = os.listdir(test_dir)[0]
test_file = os.path.join(test_dir, f)
assert os.path.exists(test_file)
expected = 'PNG image data, 16 x 12, 8-bit/color RGBA, interlaced'
if on_windows:
# FIXME: this is a very short png file though
expected = 'Non-ISO extended-ASCII text'
assert expected == get_filetype_file(test_file)
expected = 'image/png'
if on_windows:
# FIXME: this is a very short png file though
expected = 'text/plain'
assert expected == get_mimetype_file(test_file)
@expectedFailure
def test_filetype_file_on_unicode_file_name2(self):
test_dir = self.get_test_loc('contenttype/unicode/')
f = [f for f in os.listdir(test_dir) if f.startswith('g')][0]
test_file = os.path.join(test_dir, f)
assert os.path.exists(test_file)
expected = 'PNG image data, 16 x 12, 8-bit/color RGBA, interlaced'
if on_windows:
# FIXME: this is a very short png file though
expected = 'Non-ISO extended-ASCII text'
assert expected == get_filetype_file(test_file)
expected = 'image/png'
if on_windows:
# FIXME: this is a very short png file though
expected = 'text/plain'
assert expected == get_mimetype_file(test_file)
@skipIf(on_windows, 'Windows does not have (well supported) links.')
def test_symbolink_links(self):
test_dir = self.extract_test_tar('contenttype/links/links.tar.gz', verbatim=True)
assert is_link(os.path.join(test_dir, 'prunedirs/targets/simlink_to_dir'))
assert is_link(os.path.join(test_dir, 'prunedirs/targets/simlink_to_file'))
assert not is_broken_link(os.path.join(test_dir, 'prunedirs/targets/simlink_to_dir'))
assert not is_broken_link(os.path.join(test_dir, 'prunedirs/targets/simlink_to_file'))
assert '../sources/subdir' == get_link_target(os.path.join(test_dir, 'prunedirs/targets/simlink_to_dir'))
assert '../sources/a.txt' == get_link_target(os.path.join(test_dir, 'prunedirs/targets/simlink_to_file'))
assert is_link(os.path.join(test_dir, 'prunedirs/targets/simlink_to_missing_file'))
assert is_link(os.path.join(test_dir, 'prunedirs/targets/simlink_to_missing_dir'))
assert is_broken_link(os.path.join(test_dir, 'prunedirs/targets/simlink_to_missing_file'))
assert is_broken_link(os.path.join(test_dir, 'prunedirs/targets/simlink_to_missing_dir'))
assert '../sources/temp.txt' == get_link_target(os.path.join(test_dir, 'prunedirs/targets/simlink_to_missing_file'))
assert '../sources/tempdir' == get_link_target(os.path.join(test_dir, 'prunedirs/targets/simlink_to_missing_dir'))
@skipIf(not on_windows, 'Hangs for now, for mysterious reasons.')
@skipIf(on_windows, 'Windows does not have fifos.')
def test_contenttype_fifo(self):
test_dir = self.get_temp_dir()
myfifo = os.path.join(test_dir, 'myfifo')
import subprocess
if subprocess.call(['mkfifo', myfifo]) != 0:
self.fail('Unable to create fifo')
assert os.path.exists(myfifo)
assert is_special(myfifo)
assert 'FIFO pipe' == get_filetype(myfifo)
def test_directory(self):
assert not is_binary(self.get_test_loc('contenttype'))
def test_archive_gnu_tar(self):
assert is_binary(self.get_test_loc('contenttype/archive/e.tar'))
assert is_archive(self.get_test_loc('contenttype/archive/e.tar'))
assert 'posix tar archive (gnu)' == get_filetype(self.get_test_loc('contenttype/archive/e.tar'))
def test_archive_gz(self):
assert is_binary(self.get_test_loc('contenttype/archive/file_4.26-1.diff.gz'))
assert is_archive(self.get_test_loc('contenttype/archive/file_4.26-1.diff.gz'))
assert get_filetype(self.get_test_loc('contenttype/archive/file_4.26-1.diff.gz')).startswith('gzip compressed data')
@skipIf(on_windows, 'fails because of libmagic bug on windows.')
def test_archive_squashfs_crashing(self):
test_file = self.get_test_loc('contenttype/archive/crashing-squashfs')
assert get_filetype_file(test_file).startswith('Squashfs filesystem, little endian, version 4.0')
@skipIf(on_windows, 'fails because of libmagic bug on windows.')
def test_archive_squashfs_gz(self):
test_file = self.get_test_loc('contenttype/archive/sqfs-gz.sqs')
assert get_filetype_file(test_file).startswith('Squashfs filesystem, little endian, version 4.0')
@skipIf(on_windows, 'fails because of libmagic bug on windows.')
def test_archive_squashfs_lzo(self):
test_file = self.get_test_loc('contenttype/archive/sqfs-lzo.sqs')
assert get_filetype_file(test_file).startswith('Squashfs filesystem, little endian, version 4.0')
@skipIf(on_windows, 'fails because of libmagic bug on windows.')
def test_archive_squashfs_xz(self):
test_file = self.get_test_loc('contenttype/archive/sqfs-xz.sqs')
assert get_filetype_file(test_file).startswith('Squashfs filesystem, little endian, version 4.0')
def test_archive_tar_bz2(self):
assert is_binary(self.get_test_loc('contenttype/archive/e.tar.bz2'))
assert is_archive(self.get_test_loc('contenttype/archive/e.tar.bz2'))
assert 'bzip2 compressed data, block size = 900k' == get_filetype(self.get_test_loc('contenttype/archive/e.tar.bz2'))
def test_archive_tar_gz_1(self):
assert not is_source(self.get_test_loc('contenttype/archive/a.tar.gz'))
assert not is_text(self.get_test_loc('contenttype/archive/a.tar.gz'))
assert '' == get_filetype_pygment(self.get_test_loc('contenttype/archive/a.tar.gz'))
assert 'application/x-gzip' == get_mimetype_file(self.get_test_loc('contenttype/archive/a.tar.gz'))
assert get_filetype(self.get_test_loc('contenttype/archive/a.tar.gz')).startswith('gzip compressed data')
def test_archive_tar_gz_3(self):
assert is_binary(self.get_test_loc('contenttype/archive/e.tar.gz'))
assert is_archive(self.get_test_loc('contenttype/archive/e.tar.gz'))
assert get_filetype(self.get_test_loc('contenttype/archive/e.tar.gz')).startswith('gzip compressed data')
def test_archive_tar_posix(self):
assert is_binary(self.get_test_loc('contenttype/archive/posixnotgnu.tar'))
assert is_archive(self.get_test_loc('contenttype/archive/posixnotgnu.tar'))
assert 'posix tar archive' == get_filetype(self.get_test_loc('contenttype/archive/posixnotgnu.tar'))
def test_config_eclipse_data(self):
assert is_binary(self.get_test_loc('contenttype/config/eclipse_configuration_3u.cfs'))
assert 'data' == get_filetype(self.get_test_loc('contenttype/config/eclipse_configuration_3u.cfs'))
def test_binary_data(self):
assert is_binary(self.get_test_loc('contenttype/binary/data.fdt'))
assert 'data' == get_filetype(self.get_test_loc('contenttype/binary/data.fdt'))
def test_binary_data_2(self):
assert 'data' == get_filetype(self.get_test_loc('contenttype/binary/dbase.fdt'))
def test_binary_java_serialized_data(self):
assert is_binary(self.get_test_loc('contenttype/binary/jruby_time_zone_TimeOfDay.dat'))
assert 'java serialization data, version 5' == get_filetype(self.get_test_loc('contenttype/binary/jruby_time_zone_TimeOfDay.dat'))
def test_binary_random_data(self):
assert 'data' == get_filetype(self.get_test_loc('contenttype/binary-random/binary_random_0'))
assert 'data' == get_filetype(self.get_test_loc('contenttype/binary-random/binary_random_1'))
assert 'data' == get_filetype(self.get_test_loc('contenttype/binary-random/binary_random_2'))
assert 'data' == get_filetype(self.get_test_loc('contenttype/binary-random/binary_random_3'))
assert 'data' == get_filetype(self.get_test_loc('contenttype/binary-random/binary_random_4'))
assert 'data' == get_filetype(self.get_test_loc('contenttype/binary-random/binary_random_5'))
assert 'data' == get_filetype(self.get_test_loc('contenttype/binary-random/binary_random_6'))
assert 'data' == get_filetype(self.get_test_loc('contenttype/binary-random/binary_random_7'))
assert 'data' == get_filetype(self.get_test_loc('contenttype/binary-random/binary_random_8'))
def test_build_ant_build_xml(self):
assert not is_binary(self.get_test_loc('contenttype/build/build.xml'))
assert 'xml language text' == get_filetype(self.get_test_loc('contenttype/build/build.xml'))
def test_build_makefile(self):
assert is_source(self.get_test_loc('contenttype/build/Makefile'))
assert is_text(self.get_test_loc('contenttype/build/Makefile'))
assert 'Makefile' == get_filetype_pygment(self.get_test_loc('contenttype/build/Makefile'))
assert 'ASCII text' == get_filetype_file(self.get_test_loc('contenttype/build/Makefile'))
assert 'makefile language text' == get_filetype(self.get_test_loc('contenttype/build/Makefile'))
assert 'text/plain' == get_mimetype_file(self.get_test_loc('contenttype/build/Makefile'))
def test_build_makefile_2(self):
assert is_source(self.get_test_loc('contenttype/build/Makefile.inc'))
assert is_text(self.get_test_loc('contenttype/build/Makefile.inc'))
assert 'text/x-makefile' == get_mimetype_file(self.get_test_loc('contenttype/build/Makefile.inc'))
assert 'ASCII text' == get_filetype_file(self.get_test_loc('contenttype/build/Makefile'))
@expectedFailure
def test_build_makefile_inc_is_not_povray(self):
assert 'Makefile' == get_filetype_pygment(self.get_test_loc('contenttype/build/Makefile.inc'))
assert 'makefile language text' == get_filetype(self.get_test_loc('contenttype/build/Makefile.inc'))
def test_build_ide_makefile(self):
assert 'makefile language text' == get_filetype(self.get_test_loc('contenttype/build/documentation.dsp'))
def test_build_java_maven_pom(self):
assert not is_source(self.get_test_loc('contenttype/build/pom.pom'))
assert is_source(self.get_test_loc('contenttype/build/pom.xml'))
assert 'xml language text' == get_filetype(self.get_test_loc('contenttype/build/pom.xml'))
def test_certificate_rsa_eclipse(self):
assert is_binary(self.get_test_loc('contenttype/certificate/ECLIPSE.RSA'))
assert 'data' == get_filetype(self.get_test_loc('contenttype/certificate/ECLIPSE.RSA'))
def test_certificate(self):
assert is_binary(self.get_test_loc('contenttype/certificate/CERTIFICATE'))
assert 'data' == get_filetype(self.get_test_loc('contenttype/certificate/CERTIFICATE'))
def test_code_assembly(self):
assert 'C source, ASCII text, with CRLF line terminators' == get_filetype_file(self.get_test_loc('contenttype/code/assembly/bcopy.s'))
assert 'GAS' == get_filetype_pygment(self.get_test_loc('contenttype/code/assembly/bcopy.s'))
assert 'text/x-c' == get_mimetype_file(self.get_test_loc('contenttype/code/assembly/bcopy.s'))
def test_code_c_1(self):
assert 'c language text' == get_filetype(self.get_test_loc('contenttype/code/c/c_code.c'))
def test_code_c_2(self):
assert is_source(self.get_test_loc('contenttype/code/c/main.c'))
assert is_text(self.get_test_loc('contenttype/code/c/main.c'))
assert 'C' == get_filetype_pygment(self.get_test_loc('contenttype/code/c/main.c'))
assert 'c language text' == get_filetype(self.get_test_loc('contenttype/code/c/main.c'))
assert 'C source, ASCII text' == get_filetype_file(self.get_test_loc('contenttype/code/c/main.c'))
assert 'text/x-c' == get_mimetype_file(self.get_test_loc('contenttype/code/c/main.c'))
def test_code_c_3(self):
assert is_source(self.get_test_loc('contenttype/code/c/cpu.c'))
assert is_text(self.get_test_loc('contenttype/code/c/cpu.c'))
assert 'C' == get_filetype_pygment(self.get_test_loc('contenttype/code/c/cpu.c'))
assert 'c language text' == get_filetype(self.get_test_loc('contenttype/code/c/cpu.c'))
assert 'text/x-c' == get_mimetype_file(self.get_test_loc('contenttype/code/c/cpu.c'))
def test_code_c_4(self):
assert is_source(self.get_test_loc('contenttype/code/c/mm.c'))
assert is_text(self.get_test_loc('contenttype/code/c/mm.c'))
assert 'C' == get_filetype_pygment(self.get_test_loc('contenttype/code/c/mm.c'))
assert 'c language text' == get_filetype(self.get_test_loc('contenttype/code/c/mm.c'))
assert 'text/x-c' == get_mimetype_file(self.get_test_loc('contenttype/code/c/mm.c'))
def test_code_c_5(self):
assert is_source(self.get_test_loc('contenttype/code/c/pci.c'))
assert is_text(self.get_test_loc('contenttype/code/c/pci.c'))
assert 'C source, ASCII text' == get_filetype_file(self.get_test_loc('contenttype/code/c/pci.c'))
assert 'C' == get_filetype_pygment(self.get_test_loc('contenttype/code/c/pci.c'))
assert 'c language text' == get_filetype(self.get_test_loc('contenttype/code/c/pci.c'))
assert 'text/x-c' == get_mimetype_file(self.get_test_loc('contenttype/code/c/pci.c'))
def test_code_c_6(self):
assert is_source(self.get_test_loc('contenttype/code/c/pci_v3.c'))
assert is_text(self.get_test_loc('contenttype/code/c/pci_v3.c'))
assert 'C source, ASCII text' == get_filetype_file(self.get_test_loc('contenttype/code/c/pci_v3.c'))
assert 'C' == get_filetype_pygment(self.get_test_loc('contenttype/code/c/pci_v3.c'))
assert 'c language text' == get_filetype(self.get_test_loc('contenttype/code/c/pci_v3.c'))
assert 'text/x-c' == get_mimetype_file(self.get_test_loc('contenttype/code/c/pci_v3.c'))
def test_code_c_7(self):
assert 'c language text' == get_filetype(self.get_test_loc('contenttype/code/c/some.c'))
def test_code_c_include(self):
assert 'c language text' == get_filetype(self.get_test_loc('contenttype/code/c/resource.h'))
assert is_source(self.get_test_loc('contenttype/code/c/netdb.h'))
def test_code_c_include_mixed_case(self):
assert 'c++ language text' == get_filetype(self.get_test_loc('contenttype/code/c/TEST.H'))
assert 'c language text' == get_filetype(self.get_test_loc('contenttype/code/c/TEST_LOWERCASE.h'))
def test_code_c_mixed_case(self):
assert 'c++ language text' == get_filetype(self.get_test_loc('contenttype/code/c/SIMPLE.C'))
def test_code_cpp_1(self):
assert is_source(self.get_test_loc('contenttype/code/cpp/stacktrace.cpp'))
assert is_text(self.get_test_loc('contenttype/code/cpp/stacktrace.cpp'))
assert 'C++' == get_filetype_pygment(self.get_test_loc('contenttype/code/cpp/stacktrace.cpp'))
assert 'c++ language text' == get_filetype(self.get_test_loc('contenttype/code/cpp/stacktrace.cpp'))
assert 'text/x-c' == get_mimetype_file(self.get_test_loc('contenttype/code/cpp/stacktrace.cpp'))
def test_code_cpp_non_ascii(self):
assert is_source(self.get_test_loc('contenttype/code/cpp/non_ascii.cpp'))
assert is_text(self.get_test_loc('contenttype/code/cpp/non_ascii.cpp'))
assert 'application/octet-stream' == get_mimetype_file(self.get_test_loc('contenttype/code/cpp/non_ascii.cpp'))
assert 'C++' == get_filetype_pygment(self.get_test_loc('contenttype/code/cpp/non_ascii.cpp'))
assert 'c++ language text' == get_filetype(self.get_test_loc('contenttype/code/cpp/non_ascii.cpp'))
def test_code_cpp_stdafx(self):
assert 'c++ language text' == get_filetype(self.get_test_loc('contenttype/code/cpp/StdAfx.cpp'))
def test_code_cpp_mixed_case(self):
assert 'c++ language text' == get_filetype(self.get_test_loc('contenttype/code/cpp/string.CPP'))
assert 'c++ language text' == get_filetype(self.get_test_loc('contenttype/code/cpp/string.CPP'))
def test_code_groff(self):
assert not is_special(self.get_test_loc(u'contenttype/code/groff/example.ms'))
assert is_text(self.get_test_loc(u'contenttype/code/groff/example.ms'))
assert 'Groff' == get_filetype_pygment(self.get_test_loc(u'contenttype/code/groff/example.ms'))
assert 'groff language text' == get_filetype(self.get_test_loc(u'contenttype/code/groff/example.ms'))
assert 'text/troff' == get_mimetype_python(self.get_test_loc(u'contenttype/code/groff/example.ms'))
assert 'text/troff' == get_mimetype_file(self.get_test_loc(u'contenttype/code/groff/example.ms'))
assert get_filetype_file(self.get_test_loc(u'contenttype/code/groff/example.ms')).startswith('troff or preprocessor input')
def test_code_java_1(self):
assert not is_binary(self.get_test_loc('contenttype/code/java/contenttype.java'))
assert 'Java' == get_pygments_lexer(self.get_test_loc('contenttype/code/java/contenttype.java')).name
def test_code_java_non_ascii(self):
assert is_source(self.get_test_loc('contenttype/code/java/ChartTiming1.java'))
assert is_text(self.get_test_loc('contenttype/code/java/ChartTiming1.java'))
# FIXME: incorrect
assert 'application/octet-stream' == get_mimetype_file(self.get_test_loc('contenttype/code/java/ChartTiming1.java'))
assert 'Java' == get_filetype_pygment(self.get_test_loc('contenttype/code/java/ChartTiming1.java'))
assert 'java language text' == get_filetype(self.get_test_loc('contenttype/code/java/ChartTiming1.java'))
def test_code_java_3(self):
assert 'java language text' == get_filetype(self.get_test_loc('contenttype/code/java/Appender.java'))
def test_code_java_jad(self):
# FIXME: should this be Java code?
assert 'python language text' == get_filetype(self.get_test_loc('contenttype/code/java/CommonViewerSiteFactory.jad'))
def test_code_java_mixed_case(self):
# FIXME: incorrect type
assert 'python language text' == get_filetype(self.get_test_loc('contenttype/code/java/Logger.JAVA'))
def test_code_js(self):
assert not is_media(self.get_test_loc('contenttype/code/js/a.js'))
def test_code_python_1(self):
assert not is_binary(self.get_test_loc('contenttype/code/python/contenttype.py'))
assert 'Python' == get_pygments_lexer(self.get_test_loc('contenttype/code/python/contenttype.py')).name
def test_code_python_2(self):
assert is_source(self.get_test_loc('contenttype/code/python/extract.py'))
assert is_text(self.get_test_loc('contenttype/code/python/extract.py'))
assert 'Python' == get_filetype_pygment(self.get_test_loc('contenttype/code/python/extract.py'))
assert 'python language text' == get_filetype(self.get_test_loc('contenttype/code/python/extract.py'))
assert 'text/x-python' == get_mimetype_file(self.get_test_loc('contenttype/code/python/extract.py'))
assert get_filetype_file(self.get_test_loc('contenttype/code/python/extract.py')).startswith('Python script')
def test_code_python_3(self):
assert 'python language text' == get_filetype(self.get_test_loc('contenttype/code/python/__init__.py'))
def test_code_resource(self):
assert 'c language text' == get_filetype(self.get_test_loc('contenttype/code/c/CcccDevStudioAddIn.rc2'))
def test_code_scala(self):
assert 'scala language text' == get_filetype(self.get_test_loc('contenttype/code/scala/Applicative.scala'))
def test_compiled_elf_exe(self):
assert is_binary(self.get_test_loc('contenttype/compiled/linux/i686-shash'))
assert 'elf 32-bit lsb executable, intel 80386, version 1 (sysv), dynamically linked, interpreter /lib/ld-linux.so.2, for gnu/linux 2.6.4, not stripped' == get_filetype(self.get_test_loc(u'contenttype/compiled/linux/i686-shash'))
assert is_binary(self.get_test_loc('contenttype/compiled/linux/x86_64-shash'))
assert 'elf 64-bit lsb executable, x86-64, version 1 (sysv), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for gnu/linux 2.6.9, not stripped' == get_filetype(self.get_test_loc(u'contenttype/compiled/linux/x86_64-shash'))
def test_compiled_elf_so(self):
assert not is_special(self.get_test_loc(u'contenttype/compiled/linux/libssl.so.0.9.7'))
assert not is_text(self.get_test_loc(u'contenttype/compiled/linux/libssl.so.0.9.7'))
assert '' == get_filetype_pygment(self.get_test_loc(u'contenttype/compiled/linux/libssl.so.0.9.7'))
assert 'application/x-sharedlib' == get_mimetype_file(self.get_test_loc(u'contenttype/compiled/linux/libssl.so.0.9.7'))
assert 'elf 32-bit lsb shared object, intel 80386, version 1 (sysv), dynamically linked, stripped' == get_filetype(self.get_test_loc(u'contenttype/compiled/linux/libssl.so.0.9.7'))
assert 'ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, stripped' == get_filetype_file(self.get_test_loc(u'contenttype/compiled/linux/libssl.so.0.9.7'))
def test_compiled_elf_so_2(self):
assert not is_source(self.get_test_loc('contenttype/compiled/linux/libnetsnmpagent.so.5'))
def test_compiled_flash(self):
assert is_binary(self.get_test_loc('contenttype/compiled/flash/a.swf'))
assert is_binary(self.get_test_loc('contenttype/compiled/flash/b.swf'))
def test_compiled_flash_swc(self):
assert is_binary(self.get_test_loc('contenttype/compiled/flash/flash-haloclassic.swc.incr'))
assert 'data' == get_filetype(self.get_test_loc('contenttype/compiled/flash/flash-haloclassic.swc.incr'))
def test_compiled_java(self):
assert 'compiled java class data, version 46.0 (java 1.2)' == get_filetype(self.get_test_loc('contenttype/compiled/java/CommonViewerSiteFactory.class'))
assert is_binary(self.get_test_loc('contenttype/compiled/java/old.class'))
assert 'compiled java class data, version 46.0 (java 1.2)' == get_filetype(self.get_test_loc('contenttype/compiled/java/old.class'))
def test_compiled_python_1(self):
test_dir = self.extract_test_zip('contenttype/compiled/python/compiled.zip')
assert 'python 2.5 byte-compiled' == get_filetype(os.path.join(test_dir, 'command.pyc'))
assert not is_source(os.path.join(test_dir, 'command.pyc'))
assert not is_text(os.path.join(test_dir, 'command.pyc'))
assert 'application/octet-stream' == get_mimetype_file(os.path.join(test_dir, 'command.pyc'))
assert '' == get_filetype_pygment(os.path.join(test_dir, 'command.pyc'))
def test_compiled_python_2(self):
test_dir = self.extract_test_zip('contenttype/compiled/python/compiled.zip')
assert is_binary(os.path.join(test_dir, 'contenttype.pyc'))
assert get_pygments_lexer(os.path.join(test_dir, 'contenttype.pyc')) is None
def test_compiled_python_3(self):
test_dir = self.extract_test_zip('contenttype/compiled/python/compiled.zip')
assert is_binary(os.path.join(test_dir, 'contenttype.pyo'))
assert get_pygments_lexer(os.path.join(test_dir, 'contenttype.pyo')) is None
def test_compiled_python_4(self):
test_dir = self.extract_test_zip('contenttype/compiled/python/compiled.zip')
assert 'python 2.5 byte-compiled' == get_filetype(os.path.join(test_dir, 'extract.pyc'))
assert not is_source(os.path.join(test_dir, 'extract.pyc'))
assert not is_text(os.path.join(test_dir, 'extract.pyc'))
assert 'application/octet-stream' == get_mimetype_file(os.path.join(test_dir, 'extract.pyc'))
assert '' == get_filetype_pygment(os.path.join(test_dir, 'extract.pyc'))
def test_compiled_win_dll(self):
assert is_winexe(self.get_test_loc(u'contenttype/compiled/win/zlib1.dll'))
assert is_binary(self.get_test_loc('contenttype/compiled/win/zlib1.dll'))
def test_compiled_win_exe(self):
assert is_winexe(self.get_test_loc(u'contenttype/compiled/win/file.exe'))
assert is_binary(self.get_test_loc('contenttype/compiled/win/file.exe'))
def test_config_conf(self):
assert 'ascii text, with crlf line terminators' == get_filetype(self.get_test_loc('contenttype/config/config.conf'))
def test_config_linux_conf(self):
assert 'linux make config build file (old)' == get_filetype(self.get_test_loc('contenttype/config/defconfig-ar531x-jffs2'))
def test_config_linux_conf_2(self):
assert not is_source(self.get_test_loc('contenttype/config/defconfig-ar531x-jffs2'))
assert is_text(self.get_test_loc('contenttype/config/defconfig-ar531x-jffs2'))
assert '' == get_filetype_pygment(self.get_test_loc('contenttype/config/defconfig-ar531x-jffs2'))
assert 'linux make config build file (old)' == get_filetype(self.get_test_loc('contenttype/config/defconfig-ar531x-jffs2'))
assert 'text/plain' == get_mimetype_file(self.get_test_loc('contenttype/config/defconfig-ar531x-jffs2'))
def test_config_text_3(self):
assert 'ascii text, with crlf line terminators' == get_filetype(self.get_test_loc('contenttype/config/wrapper.conf'))
assert 'ascii text, with crlf line terminators' == get_filetype(self.get_test_loc('contenttype/config/wrapper.conf'))
def test_debug_win_pdb(self):
assert is_binary(self.get_test_loc('contenttype/debug/QTMovieWin.pdb'))
assert 'msvc program database ver \\004' == get_filetype(self.get_test_loc('contenttype/debug/QTMovieWin.pdb'))
def test_doc_html(self):
assert not is_binary(self.get_test_loc('contenttype/doc/html/contenttype.html'))
assert 'HTML' == get_pygments_lexer(self.get_test_loc('contenttype/doc/html/contenttype.html')).name
assert not is_binary(self.get_test_loc('contenttype/doc/html/a.htm'))
def test_doc_html_2(self):
assert is_source(self.get_test_loc('contenttype/doc/html/allclasses-frame.html'))
assert is_text(self.get_test_loc('contenttype/doc/html/allclasses-frame.html'))
assert 'HTML' == get_filetype_pygment(self.get_test_loc('contenttype/doc/html/allclasses-frame.html'))
assert 'html language text' == get_filetype(self.get_test_loc('contenttype/doc/html/allclasses-frame.html'))
assert 'text/html' == get_mimetype_file(self.get_test_loc('contenttype/doc/html/allclasses-frame.html'))
assert 'HTML document, ASCII text' == get_filetype_file(self.get_test_loc('contenttype/doc/html/allclasses-frame.html'))
def test_doc_html_3(self):
assert is_source(self.get_test_loc('contenttype/doc/html/Label.html'))
assert is_text(self.get_test_loc('contenttype/doc/html/Label.html'))
assert 'HTML' == get_filetype_pygment(self.get_test_loc('contenttype/doc/html/Label.html'))
assert 'html language text' == get_filetype(self.get_test_loc('contenttype/doc/html/Label.html'))
assert 'text/html' == get_mimetype_file(self.get_test_loc('contenttype/doc/html/Label.html'))
assert 'HTML document, ASCII text, with very long lines' == get_filetype_file(self.get_test_loc('contenttype/doc/html/Label.html'))
@expectedFailure
def test_doc_office_are_archives(self):
assert is_archive(self.get_test_loc('contenttype/doc/office/document'))
assert is_archive(self.get_test_loc('contenttype/doc/office/document.doc'))
assert is_archive(self.get_test_loc('contenttype/doc/office/word.docx'))
assert is_archive(self.get_test_loc('contenttype/doc/office/excel.xlsx'))
assert is_archive(self.get_test_loc('contenttype/doc/office/power.pptx'))
def test_doc_office_excel(self):
assert 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' == get_mimetype_file(self.get_test_loc('contenttype/doc/office/excel.xlsx'))
assert 'application/vnd.ms-excel' == get_mimetype_file(self.get_test_loc('contenttype/doc/office/excel.xls'))
def test_doc_office_powerpoint(self):
assert 'application/vnd.openxmlformats-officedocument.presentationml.presentation' == get_mimetype_file(self.get_test_loc('contenttype/doc/office/power.pptx'))
assert 'application/vnd.ms-powerpoint' == get_mimetype_file(self.get_test_loc('contenttype/doc/office/power.ppt'))
def test_doc_office_visio(self):
assert 'application/vnd.ms-office' == get_mimetype_file(self.get_test_loc('contenttype/doc/office/Glitch-ERD.vsd'))
assert not is_text(self.get_test_loc('contenttype/doc/office/Glitch-ERD.vsd'))
assert is_binary(self.get_test_loc('contenttype/doc/office/Glitch-ERD.vsd'))
def test_doc_office_word(self):
assert 'microsoft word 2007+' == get_filetype(self.get_test_loc('contenttype/doc/office/document'))
assert 'microsoft word 2007+' == get_filetype(self.get_test_loc('contenttype/doc/office/document.doc'))
assert not is_special(self.get_test_loc('contenttype/doc/office/word.doc'))
assert '' == get_filetype_pygment(self.get_test_loc('contenttype/doc/office/word.doc'))
assert 'application/msword' == get_mimetype_file(self.get_test_loc('contenttype/doc/office/word.doc'))
assert get_filetype(self.get_test_loc('contenttype/doc/office/word.doc')).startswith('composite document file v2 document')
assert get_filetype_file(self.get_test_loc('contenttype/doc/office/word.doc')).startswith('Composite Document File V2 Document')
assert 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' == get_mimetype_file(self.get_test_loc('contenttype/doc/office/word.docx'))
def test_doc_pdf_1(self):
assert is_pdf(self.get_test_loc('contenttype/doc/pdf/a.pdf'))
assert is_pdf_with_text(self.get_test_loc('contenttype/doc/pdf/a.pdf'))
assert 'pdf document, version 1.2' == get_filetype(self.get_test_loc('contenttype/doc/pdf/a.pdf'))
assert not is_media(self.get_test_loc('contenttype/doc/pdf/a.pdf'))
assert is_binary(self.get_test_loc('contenttype/doc/pdf/a.pdf'))
def test_doc_pdf_2(self):
assert not is_pdf_with_text(self.get_test_loc('contenttype/doc/pdf/notpdf.pdf'))
def test_doc_pdf_3(self):
assert is_pdf(self.get_test_loc('contenttype/doc/pdf/pdf.pdf'))
assert is_pdf_with_text(self.get_test_loc('contenttype/doc/pdf/pdf.pdf'))
assert 'pdf document, version 1.4' == get_filetype(self.get_test_loc('contenttype/doc/pdf/pdf.pdf'))
def test_doc_postscript_1(self):
assert is_text(self.get_test_loc('contenttype/doc/postscript/doc.ps'))
assert not is_binary(self.get_test_loc('contenttype/doc/postscript/doc.ps'))
def test_doc_postscript_2(self):
assert not is_binary(self.get_test_loc('contenttype/doc/postscript/a.ps'))
assert not is_media(self.get_test_loc('contenttype/doc/postscript/a.ps'))
def test_doc_postscript_eps(self):
assert is_binary(self.get_test_loc('contenttype/doc/postscript/Image1.eps'))
assert 'application/octet-stream' == get_mimetype_file(self.get_test_loc('contenttype/doc/postscript/Image1.eps'))
assert get_filetype_file(self.get_test_loc('contenttype/doc/postscript/Image1.eps')).startswith('DOS EPS Binary File Postscript')
def test_doc_xml(self):
assert not is_binary(self.get_test_loc('contenttype/doc/xml/simple.xml'))
assert 'xml language text' == get_filetype(self.get_test_loc('contenttype/doc/xml/simple.xml'))
assert not is_binary(self.get_test_loc('contenttype/doc/xml/some.xml'))
assert 'xml language text' == get_filetype(self.get_test_loc('contenttype/doc/xml/some.xml'))
assert not is_binary(self.get_test_loc('contenttype/doc/xml/somespring.xml'))
assert 'xml language text' == get_filetype(self.get_test_loc('contenttype/doc/xml/somespring.xml'))
def test_media_audio_aif(self):
assert is_media(self.get_test_loc('contenttype/media/a.aif'))
assert is_binary(self.get_test_loc('contenttype/media/a.aif'))
assert is_media(self.get_test_loc('contenttype/media/a.aiff'))
assert is_binary(self.get_test_loc('contenttype/media/a.aiff'))
def test_media_audio_au(self):
assert is_media(self.get_test_loc('contenttype/media/a.au'))
assert is_binary(self.get_test_loc('contenttype/media/a.au'))
def test_media_audio_flac(self):
assert is_media(self.get_test_loc('contenttype/media/a.flac'))
assert is_binary(self.get_test_loc('contenttype/media/a.flac'))
def test_media_audio_mp3(self):
assert is_media(self.get_test_loc('contenttype/media/a.mp3'))
assert is_binary(self.get_test_loc('contenttype/media/a.mp3'))
def test_media_audio_wav(self):
assert is_media(self.get_test_loc('contenttype/media/a.wav'))
assert is_binary(self.get_test_loc('contenttype/media/a.wav'))
def test_media_image_bmp_1(self):
assert is_media(self.get_test_loc('contenttype/media/Image1.bmp'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.bmp'))
def test_media_image_bmp_2(self):
assert 'pc bitmap, windows 3.x format, 400 x 32 x 4' == get_filetype(self.get_test_loc('contenttype/media/TBarLrge.bmp'))
assert 'pc bitmap, windows 3.x format, 210 x 16 x 4' == get_filetype(self.get_test_loc('contenttype/media/TBarMedm.bmp'))
def test_media_image_dib(self):
assert is_media(self.get_test_loc('contenttype/media/Image1.dib'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.dib'))
def test_media_image_gif(self):
assert is_media(self.get_test_loc('contenttype/media/Image1.gif'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.gif'))
def test_media_image_ico(self):
assert is_media(self.get_test_loc('contenttype/media/Image1.ico'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.ico'))
def test_media_image_iff(self):
assert is_media(self.get_test_loc('contenttype/media/Image1.iff'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.iff'))
def test_media_image_img(self):
# FIXME: .img files are more complex
assert is_binary(self.get_test_loc('contenttype/media/Image1.img'))
assert get_filetype_file(self.get_test_loc('contenttype/media/Image1.img')).startswith('GEM Image data')
assert 'application/octet-stream' == get_mimetype_file(self.get_test_loc('contenttype/media/Image1.img'))
assert not get_mimetype_python(self.get_test_loc('contenttype/media/Image1.img'))
assert is_media(self.get_test_loc('contenttype/media/Image1.img'))
def test_media_image_jif(self):
assert is_media(self.get_test_loc('contenttype/media/Image1.jif'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.jif'))
def test_media_image_jpeg(self):
assert is_media(self.get_test_loc('contenttype/media/Image1.jpeg'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.jpeg'))
assert is_media(self.get_test_loc('contenttype/media/Image1.jpg'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.jpg'))
def test_media_image_pbm_ppm(self):
assert is_media(self.get_test_loc('contenttype/media/Image1.pbm'))
assert not is_binary(self.get_test_loc('contenttype/media/Image1.pbm'))
assert not is_binary(self.get_test_loc('contenttype/media/Image1.ppm'))
# this is text
assert is_media(self.get_test_loc('contenttype/media/Image1.ppm'))
def test_media_image_pcx(self):
assert is_media(self.get_test_loc('contenttype/media/Image1.pcx'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.pcx'))
def test_media_image_photoshop(self):
assert is_media(self.get_test_loc('contenttype/media/Image1.psd'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.psd'))
def test_media_image_png(self):
assert is_media(self.get_test_loc('contenttype/media/a.png'))
assert is_binary(self.get_test_loc('contenttype/media/a.png'))
def test_media_image_psp(self):
assert is_media(self.get_test_loc('contenttype/media/Image1.psp'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.psp'))
def test_media_image_ras(self):
assert is_media(self.get_test_loc('contenttype/media/Image1.ras'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.ras'))
def test_media_image_svg(self):
assert not is_binary(self.get_test_loc('contenttype/media/drawing.svg'))
assert is_media(self.get_test_loc('contenttype/media/drawing.svg'))
assert is_media(self.get_test_loc('contenttype/media/drawing.svg'))
def test_media_image_tgg(self):
assert is_media(self.get_test_loc('contenttype/media/Image1.tga'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.tga'))
def test_media_image_tif(self):
assert is_media(self.get_test_loc('contenttype/media/Image1.tif'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.tif'))
def test_media_image_windows_metafile(self):
assert 'application/octet-stream' == get_mimetype_file(self.get_test_loc('contenttype/media/Image1.emf'))
assert not get_mimetype_python(self.get_test_loc('contenttype/media/Image1.emf'))
assert get_filetype_file(self.get_test_loc('contenttype/media/Image1.emf')).startswith('Windows Enhanced Metafile')
assert is_media(self.get_test_loc('contenttype/media/Image1.emf'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.emf'))
def test_media_video_mpeg(self):
assert is_media(self.get_test_loc('contenttype/media/a4.mp4'))
assert is_binary(self.get_test_loc('contenttype/media/a4.mp4'))
assert is_media(self.get_test_loc('contenttype/media/a4.mpg'))
assert is_binary(self.get_test_loc('contenttype/media/a4.mpg'))
assert is_media(self.get_test_loc('contenttype/media/a.mp2'))
assert is_binary(self.get_test_loc('contenttype/media/a.mp2'))
def test_media_video_msft(self):
assert is_media(self.get_test_loc('contenttype/media/a.avi'))
assert is_binary(self.get_test_loc('contenttype/media/a.avi'))
assert is_media(self.get_test_loc('contenttype/media/Image1.wmf'))
assert is_binary(self.get_test_loc('contenttype/media/Image1.wmf'))
assert is_media(self.get_test_loc('contenttype/media/mov.wvm.wmv'))
assert is_binary(self.get_test_loc('contenttype/media/mov.wvm.wmv'))
assert is_media(self.get_test_loc('contenttype/media/Movie.wmv'))
assert is_binary(self.get_test_loc('contenttype/media/Movie.wmv'))
assert is_media(self.get_test_loc('contenttype/media/Movie_0001.wmv'))
assert is_binary(self.get_test_loc('contenttype/media/Movie_0001.wmv'))
assert is_media(self.get_test_loc('contenttype/media/Movie_0002.wmv'))
assert is_binary(self.get_test_loc('contenttype/media/Movie_0002.wmv'))
def test_media_video_ogg(self):
assert is_media(self.get_test_loc('contenttype/media/a.ogg'))
assert is_binary(self.get_test_loc('contenttype/media/a.ogg'))
assert is_media(self.get_test_loc('contenttype/media/a.theo.ogg'))
assert is_binary(self.get_test_loc('contenttype/media/a.theo.ogg'))
def test_package_debian(self):
assert 'debian binary package (format 2.0)' == get_filetype(self.get_test_loc('contenttype/package/wget-el_0.5.0-8_all.deb'))
def test_package_java_jar(self):
assert is_binary(self.get_test_loc('contenttype/package/ant-jsch-1.7.0.jar'))
assert is_archive(self.get_test_loc('contenttype/package/ant-jsch-1.7.0.jar'))
assert 'java archive data (jar)' == get_filetype(self.get_test_loc('contenttype/package/ant-jsch-1.7.0.jar'))
def test_package_java_jar_as_zip(self):
assert is_binary(self.get_test_loc('contenttype/package/ant.zip'))
assert is_archive(self.get_test_loc('contenttype/package/ant.zip'))
assert 'java archive data (jar)' == get_filetype(self.get_test_loc('contenttype/package/ant.zip'))
def test_package_java_war(self):
assert is_binary(self.get_test_loc('contenttype/package/c.war'))
assert is_archive(self.get_test_loc('contenttype/package/c.war'))
assert 'zip archive data, at least v1.0 to extract' == get_filetype(self.get_test_loc('contenttype/package/c.war'))
def test_package_python_egg(self):
assert is_binary(self.get_test_loc('contenttype/package/TicketImport-0.7a-py2.5.egg'))
assert is_archive(self.get_test_loc('contenttype/package/TicketImport-0.7a-py2.5.egg'))
assert 'zip archive data, at least v2.0 to extract' == get_filetype(self.get_test_loc('contenttype/package/TicketImport-0.7a-py2.5.egg'))
def test_package_rpm(self):
assert 'rpm v3.0 bin i386/x86_64' == get_filetype(self.get_test_loc('contenttype/package/wget-1.11.4-3.fc11.i586.rpm'))
def test_package_rubygem(self):
assert 'posix tar archive' == get_filetype(self.get_test_loc('contenttype/package/rubygems-update-1.4.1.gem'))
def test_script_bash(self):
assert 'bash language text' == get_filetype(self.get_test_loc('contenttype/script/test.sh'))
def test_script_bash_makelinks(self):
assert is_source(self.get_test_loc('contenttype/script/makelinks'))
def test_script_windows_bat(self):
assert 'batchfile language text' == get_filetype(self.get_test_loc('contenttype/script/build_w32vc.bat'))
assert 'batchfile language text' == get_filetype(self.get_test_loc('contenttype/script/zip_src.bat'))
def test_script_install(self):
assert 'ascii text' == get_filetype(self.get_test_loc('contenttype/script/install'))
def test_text_crashing(self):
assert 'ASCII text' == get_filetype_file(self.get_test_loc('contenttype/text/crashing-a.txt'))
assert 'ASCII text' == get_filetype_file(self.get_test_loc('contenttype/text/crashing-z.txt'))
def test_text(self):
assert not is_binary(self.get_test_loc('contenttype/text/x11-xconsortium_text.txt'))
assert not is_archive(self.get_test_loc('contenttype/text/x11-xconsortium_text.txt'))
def test_text_license_copying(self):
assert 'ascii text' in get_filetype(self.get_test_loc('contenttype/text/COPYING'))
assert not is_source(self.get_test_loc('contenttype/text/COPYING'))
assert is_text(self.get_test_loc('contenttype/text/COPYING'))
assert '' == get_filetype_pygment(self.get_test_loc('contenttype/text/COPYING'))
assert 'text/plain' == get_mimetype_file(self.get_test_loc('contenttype/text/COPYING'))
def test_text_license_credits(self):
# FIXME
assert 'css+lasso language text' == get_filetype(self.get_test_loc('contenttype/text/CREDITS'))
assert is_text(self.get_test_loc('contenttype/text/CREDITS'))
# FIXME: incorrect
assert is_source(self.get_test_loc('contenttype/text/CREDITS'))
# FIXME: incorrect
assert 'CSS+Lasso' == get_filetype_pygment(self.get_test_loc('contenttype/text/CREDITS'))
assert 'ISO-8859 text' == get_filetype_file(self.get_test_loc('contenttype/text/CREDITS'))
assert 'text/plain' == get_mimetype_file(self.get_test_loc('contenttype/text/CREDITS'))
def test_text_license_gpl(self):
assert not is_source(self.get_test_loc('contenttype/text/GPL.txt'))
def test_text_log(self):
assert not is_source(self.get_test_loc('contenttype/text/windowserver.log'))
assert is_text(self.get_test_loc('contenttype/text/windowserver.log'))
assert '' == get_filetype_pygment(self.get_test_loc('contenttype/text/windowserver.log'))
assert 'ascii text' == get_filetype(self.get_test_loc('contenttype/text/windowserver.log'))
assert 'ASCII text' == get_filetype_file(self.get_test_loc('contenttype/text/windowserver.log'))
assert 'text/plain' == get_mimetype_file(self.get_test_loc('contenttype/text/windowserver.log'))
def test_is_standard_include(self):
assert is_standard_include('<built-in>')
assert is_standard_include('/usr/lib/this.h')
assert is_standard_include('/usr/include/this.h')
def test_text_iso_text_changelog_is_not_iso_cdrom(self):
assert 'Non-ISO extended-ASCII text' == get_filetype_file(self.get_test_loc('contenttype/text/ChangeLog'))
@expectedFailure
def test_text_rsync_file_is_not_octet_stream(self):
# this is a libmagic bug: http://bugs.gw.com/view.php?id=473
assert 'data' != get_filetype_file(self.get_test_loc('contenttype/text/wildtest.txt'))
assert 'octet' not in get_mimetype_file(self.get_test_loc('contenttype/text/wildtest.txt'))
@expectedFailure
def test_rgb_stream_is_binary(self):
# this is a binaryornot bug: https://github.com/audreyr/binaryornot/issues/10
assert 'data' == get_filetype_file(self.get_test_loc('contenttype/binary/pixelstream.rgb'))
assert 'application/octet-stream' == get_mimetype_file(self.get_test_loc('contenttype/binary/pixelstream.rgb'))
assert is_binary(self.get_test_loc('contenttype/binary/pixelstream.rgb'))
| vinodpanicker/scancode-toolkit | tests/typecode/test_contenttype.py | Python | apache-2.0 | 48,662 | [
"VisIt"
] | 29803ff867a9729ddf18fbf407e0bf6a7cfcac10ac1983001df1eb476ec5e78c |
# coding: utf-8
from __future__ import division, unicode_literals, print_function
import math
import os
import subprocess
import tempfile
import logging
import numpy as np
from monty.dev import requires
from monty.json import jsanitize
from monty.os import cd
from monty.os.path import which
from scipy.constants import e, m_e
from scipy.spatial import distance
from pymatgen.core.lattice import Lattice
from pymatgen.core.units import Energy, Length
from pymatgen.electronic_structure.bandstructure import \
BandStructureSymmLine, Kpoint
from pymatgen.electronic_structure.core import Orbital
from pymatgen.electronic_structure.dos import Dos, Spin, CompleteDos
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
from pymatgen.symmetry.bandstructure import HighSymmKpath
"""
This module provides classes to run and analyze boltztrap on pymatgen band
structure objects. Boltztrap is a software interpolating band structures and
computing materials properties from this band structure using Boltzmann
semi-classical transport theory.
Boltztrap has been developed by Georg Madsen.
http://www.icams.de/content/research/software-development/boltztrap/
You need version 1.2.3 or higher
References are::
Madsen, G. K. H., and Singh, D. J. (2006).
BoltzTraP. A code for calculating band-structure dependent quantities.
Computer Physics Communications, 175, 67-71
"""
__author__ = "Geoffroy Hautier, Zachary Gibbs, Francesco Ricci, Anubhav Jain"
__copyright__ = "Copyright 2013, The Materials Project"
__version__ = "1.1"
__maintainer__ = "Geoffroy Hautier"
__email__ = "geoffroy@uclouvain.be"
__status__ = "Development"
__date__ = "August 23, 2013"
class BoltztrapRunner(object):
"""
This class is used to run Boltztrap on a band structure object.
Args:
bs:
A band structure object
nelec:
the number of electrons
dos_type:
two options for the band structure integration: "HISTO"
(histogram) or "TETRA" using the tetrahedon method. TETRA
typically gives better results (especially for DOSes)
but takes more time
energy_grid:
the energy steps used for the integration (eV)
lpfac:
the number of interpolation points in the real space. By
default 10 gives 10 time more points in the real space than
the number of kpoints given in reciprocal space
run_type:
type of boltztrap usage. by default
- BOLTZ: (default) compute transport coefficients
- BANDS: interpolate all bands contained in the energy range
specified in energy_span_around_fermi variable, along specified
k-points
- DOS: compute total and partial dos (custom BoltzTraP code
needed!)
- FERMI: compute fermi surface or more correctly to
get certain bands interpolated
band_nb:
indicates a band number. Used for Fermi Surface interpolation
(run_type="FERMI")
spin:
specific spin component (1: up, -1: down) of the band selected
in FERMI mode (mandatory).
cond_band:
if a conduction band is specified in FERMI mode,
set this variable as True
tauref:
reference relaxation time. Only set to a value different than
zero if we want to model beyond the constant relaxation time.
tauexp:
exponent for the energy in the non-constant relaxation time
approach
tauen:
reference energy for the non-constant relaxation time approach
soc:
results from spin-orbit coupling (soc) computations give
typically non-polarized (no spin up or down) results but single
electron occupations. If the band structure comes from a soc
computation, you should set soc to True (default False)
doping:
the fixed doping levels you want to compute. Boltztrap provides
both transport values depending on electron chemical potential
(fermi energy) and for a series of fixed carrier
concentrations. By default, this is set to 1e16 to 1e22 in
increments of factors of 10.
energy_span_around_fermi:
usually the interpolation is not needed on the entire energy
range but on a specific range around the fermi level.
This energy gives this range in eV. by default it is 1.5 eV.
If DOS or BANDS type are selected, this range is automatically
set to cover the entire energy range.
scissor:
scissor to apply to the band gap (eV). This applies a scissor
operation moving the band edges without changing the band
shape. This is useful to correct the often underestimated band
gap in DFT. Default is 0.0 (no scissor)
kpt_line:
list of fractional coordinates of kpoints as arrays or list of
Kpoint objects for BANDS mode calculation (standard path of
high symmetry k-points is automatically set as default)
tmax:
Maximum temperature (K) for calculation (default=1300)
tgrid:
Temperature interval for calculation (default=50)
symprec: 1e-3 is the default in pymatgen. If the kmesh has been
generated using a different symprec, it has to be specified
to avoid a "factorization error" in BoltzTraP calculation.
"""
@requires(which('x_trans'),
"BoltztrapRunner requires the executables 'x_trans' to be in "
"the path. Please download the Boltztrap at http://"
"www.icams.de/content/research/software-development/boltztrap/ "
"and follow the instructions in the README to compile "
"Bolztrap accordingly. Then add x_trans to your path")
def __init__(self, bs, nelec, dos_type="HISTO", energy_grid=0.005,
lpfac=10, run_type="BOLTZ", band_nb=None, tauref=0, tauexp=0,
tauen=0, soc=False, doping=None, energy_span_around_fermi=1.5,
scissor=0.0, kpt_line=None, spin=None, cond_band=False,
tmax=1300, tgrid=50, symprec=1e-3):
self.lpfac = lpfac
self._bs = bs
self._nelec = nelec
self.dos_type = dos_type
self.energy_grid = energy_grid
self.error = []
self.run_type = run_type
self.band_nb = band_nb
self.spin = spin
self.cond_band = cond_band
self.tauref = tauref
self.tauexp = tauexp
self.tauen = tauen
self.soc = soc
self.kpt_line = kpt_line
if doping:
self.doping = doping
else:
self.doping = []
for d in [1e16, 1e17, 1e18, 1e19, 1e20, 1e21]:
self.doping.extend([1 * d, 2.5 * d, 5 * d, 7.5 * d])
self.doping.append(1e22)
self.energy_span_around_fermi = energy_span_around_fermi
self.scissor = scissor
self.tmax = tmax
self.tgrid = tgrid
self._symprec = symprec
if self.run_type in ("DOS", "BANDS"):
self._auto_set_energy_range()
def _auto_set_energy_range(self):
"""
automatically determine the energy range as min/max eigenvalue
minus/plus the buffer_in_ev
"""
emins = [min([e_k[0] for e_k in self._bs.bands[Spin.up]])]
emaxs = [max([e_k[0] for e_k in self._bs.bands[Spin.up]])]
if self._bs.is_spin_polarized:
emins.append(min([e_k[0] for e_k in
self._bs.bands[Spin.down]]))
emaxs.append(max([e_k[0] for e_k in
self._bs.bands[Spin.down]]))
min_eigenval = Energy(min(emins) - self._bs.efermi, "eV"). \
to("Ry")
max_eigenval = Energy(max(emaxs) - self._bs.efermi, "eV"). \
to("Ry")
# set energy range to buffer around min/max EV
# buffer does not increase CPU time but will help get equal
# energies for spin up/down for band structure
const = Energy(2, "eV").to("Ry")
self._ll = min_eigenval - const
self._hl = max_eigenval + const
en_range = Energy(max((abs(self._ll), abs(self._hl))),
"Ry").to("eV")
self.energy_span_around_fermi = en_range * 1.01
print("energy_span_around_fermi = ",
self.energy_span_around_fermi)
@property
def bs(self):
return self._bs
@property
def nelec(self):
return self._nelec
def write_energy(self, output_file):
with open(output_file, 'w') as f:
f.write("test\n")
f.write("{}\n".format(len(self._bs.kpoints)))
if self.run_type == "FERMI":
sign = -1.0 if self.cond_band else 1.0
for i in range(len(self._bs.kpoints)):
eigs = []
eigs.append(Energy(
self._bs.bands[Spin(self.spin)][self.band_nb][i] -
self._bs.efermi, "eV").to("Ry"))
f.write("%12.8f %12.8f %12.8f %d\n"
% (self._bs.kpoints[i].frac_coords[0],
self._bs.kpoints[i].frac_coords[1],
self._bs.kpoints[i].frac_coords[2],
len(eigs)))
for j in range(len(eigs)):
f.write("%18.8f\n" % (sign * float(eigs[j])))
else:
for i, kpt in enumerate(self._bs.kpoints):
eigs = []
if self.run_type == "DOS":
spin_lst = [self.spin]
else:
spin_lst = self._bs.bands
for spin in spin_lst:
# use 90% of bottom bands since highest eigenvalues
# are usually incorrect
# ask Geoffroy Hautier for more details
nb_bands = int(math.floor(self._bs.nb_bands * 0.9))
for j in range(nb_bands):
eigs.append(
Energy(self._bs.bands[Spin(spin)][j][i] -
self._bs.efermi, "eV").to("Ry"))
eigs.sort()
if self.run_type == "DOS" and self._bs.is_spin_polarized:
eigs.insert(0, self._ll)
eigs.append(self._hl)
f.write("%12.8f %12.8f %12.8f %d\n"
% (kpt.frac_coords[0],
kpt.frac_coords[1],
kpt.frac_coords[2],
len(eigs)))
for j in range(len(eigs)):
f.write("%18.8f\n" % (float(eigs[j])))
def write_struct(self, output_file):
sym = SpacegroupAnalyzer(self._bs.structure, symprec=self._symprec)
with open(output_file, 'w') as f:
f.write("{} {}\n".format(self._bs.structure.composition.formula,
sym.get_space_group_symbol()))
f.write("{}\n".format("\n".join(
[" ".join(["%.5f" % Length(i, "ang").to("bohr") for i in row])
for row in self._bs.structure.lattice.matrix])))
ops = sym.get_symmetry_dataset()['rotations']
f.write("{}\n".format(len(ops)))
for c in ops:
for row in c:
f.write("{}\n".format(" ".join(str(i) for i in row)))
def write_def(self, output_file):
# This function is useless in std version of BoltzTraP code
# because x_trans script overwrite BoltzTraP.def
with open(output_file, 'w') as f:
so = ""
if self._bs.is_spin_polarized or self.soc:
so = "so"
f.write("5, 'boltztrap.intrans', 'old', 'formatted',0\n" +
"6,'boltztrap.outputtrans', 'unknown', "
"'formatted',0\n" +
"20,'boltztrap.struct', 'old', 'formatted',0\n"
+ "10,'boltztrap.energy" + so + "', 'old', "
"'formatted',0\n" +
"48,'boltztrap.engre', 'unknown', "
"'unformatted',0\n" +
"49,'boltztrap.transdos', 'unknown', "
"'formatted',0\n" +
"50,'boltztrap.sigxx', 'unknown', 'formatted',"
"0\n" +
"51,'boltztrap.sigxxx', 'unknown', 'formatted',"
"0\n" +
"21,'boltztrap.trace', 'unknown', "
"'formatted',0\n" +
"22,'boltztrap.condtens', 'unknown', "
"'formatted',0\n" +
"24,'boltztrap.halltens', 'unknown', "
"'formatted',0\n" +
"30,'boltztrap_BZ.cube', 'unknown', "
"'formatted',0\n")
def write_proj(self, output_file_proj, output_file_def):
# This function is useless in std version of BoltzTraP code
# because x_trans script overwrite BoltzTraP.def
for oi, o in enumerate(Orbital):
for site_nb in range(0, len(self._bs.structure.sites)):
if oi < len(self._bs.projections[Spin.up][0][0]):
with open(output_file_proj + "_" + str(site_nb) + "_" + str(
o),
'w') as f:
f.write(self._bs.structure.composition.formula + "\n")
f.write(str(len(self._bs.kpoints)) + "\n")
for i in range(len(self._bs.kpoints)):
tmp_proj = []
for j in range(
int(math.floor(self._bs.nb_bands * 0.9))):
tmp_proj.append(
self._bs.projections[Spin(self.spin)][j][
i][oi][site_nb])
# TODO deal with the sorting going on at
# the energy level!!!
# tmp_proj.sort()
if self.run_type == "DOS" and \
self._bs.is_spin_polarized:
tmp_proj.insert(0, self._ll)
tmp_proj.append(self._hl)
f.write("%12.8f %12.8f %12.8f %d\n"
% (self._bs.kpoints[i].frac_coords[0],
self._bs.kpoints[i].frac_coords[1],
self._bs.kpoints[i].frac_coords[2],
len(tmp_proj)))
for j in range(len(tmp_proj)):
f.write("%18.8f\n" % float(tmp_proj[j]))
with open(output_file_def, 'w') as f:
so = ""
if self._bs.is_spin_polarized:
so = "so"
f.write("5, 'boltztrap.intrans', 'old', 'formatted',0\n" +
"6,'boltztrap.outputtrans', 'unknown', "
"'formatted',0\n" +
"20,'boltztrap.struct', 'old', 'formatted',0\n"
+ "10,'boltztrap.energy" + so + "', 'old', "
"'formatted',0\n" +
"48,'boltztrap.engre', 'unknown', "
"'unformatted',0\n" +
"49,'boltztrap.transdos', 'unknown', "
"'formatted',0\n" +
"50,'boltztrap.sigxx', 'unknown', 'formatted',"
"0\n" +
"51,'boltztrap.sigxxx', 'unknown', 'formatted',"
"0\n" +
"21,'boltztrap.trace', 'unknown', "
"'formatted',0\n" +
"22,'boltztrap.condtens', 'unknown', "
"'formatted',0\n" +
"24,'boltztrap.halltens', 'unknown', "
"'formatted',0\n" +
"30,'boltztrap_BZ.cube', 'unknown', "
"'formatted',0\n")
i = 1000
for oi, o in enumerate(Orbital):
for site_nb in range(0, len(self._bs.structure.sites)):
if oi < len(self._bs.projections[Spin.up][0][0]):
f.write(str(i) + ",\'" + "boltztrap.proj_" + str(
site_nb) + "_" + str(o.name) +
"\' \'old\', \'formatted\',0\n")
i += 1
def write_intrans(self, output_file):
setgap = 1 if self.scissor > 0.0001 else 0
if self.run_type == "BOLTZ" or self.run_type == "DOS":
with open(output_file, 'w') as fout:
fout.write("GENE # use generic interface\n")
fout.write(
"1 0 %d %f # iskip (not presently used) idebug "
"setgap shiftgap \n"
% (setgap, Energy(self.scissor, "eV").to("Ry")))
fout.write(
"0.0 %f %f %6.1f # Fermilevel (Ry),energygrid,energy "
"span around Fermilevel, number of electrons\n"
% (Energy(self.energy_grid, "eV").to("Ry"),
Energy(self.energy_span_around_fermi, "eV").to("Ry"),
self._nelec))
fout.write(
"CALC # CALC (calculate expansion "
"coeff), NOCALC read from file\n")
fout.write(
"%d # lpfac, number of latt-points "
"per k-point\n" % self.lpfac)
fout.write(
"%s # run mode (only BOLTZ is "
"supported)\n" % self.run_type)
fout.write(
".15 # (efcut) energy range of "
"chemical potential\n")
fout.write(
"{} {} # Tmax, temperature grid\n". \
format(self.tmax, self.tgrid))
fout.write(
"-1. # energyrange of bands given DOS output sig_xxx and "
"dos_xxx (xxx is band number)\n")
fout.write(self.dos_type + "\n") # e.g., HISTO or TETRA
fout.write("{} {} {} 0 0 0\n".format(
self.tauref, self.tauexp, self.tauen))
fout.write("{}\n".format(2 * len(self.doping)))
for d in self.doping:
fout.write(str(d) + "\n")
for d in self.doping:
fout.write(str(-d) + "\n")
elif self.run_type == "FERMI":
with open(output_file, 'w') as fout:
fout.write("GENE # use generic interface\n")
fout.write(
"1 0 0 0.0 # iskip (not presently used) idebug "
"setgap shiftgap \n")
fout.write(
"0.0 %f 0.1 %6.1f # Fermilevel (Ry),energygrid,"
"energy span around Fermilevel, "
"number of electrons\n"
% (Energy(self.energy_grid, "eV").to("Ry"), self._nelec))
fout.write(
"CALC # CALC (calculate expansion "
"coeff), NOCALC read from file\n")
fout.write(
"%d # lpfac, number of latt-points "
"per k-point\n" % self.lpfac)
fout.write(
"FERMI # run mode (only BOLTZ is "
"supported)\n")
fout.write(str(1) +
" # actual band selected: " +
str(self.band_nb + 1) + " spin: " + str(self.spin))
elif self.run_type == "BANDS":
if self.kpt_line is None:
kpath = HighSymmKpath(self._bs.structure)
self.kpt_line = [Kpoint(k, self._bs.structure.lattice) for k
in
kpath.get_kpoints(coords_are_cartesian=False)[
0]]
self.kpt_line = [kp.frac_coords for kp in self.kpt_line]
elif type(self.kpt_line[0]) == Kpoint:
self.kpt_line = [kp.frac_coords for kp in self.kpt_line]
with open(output_file, 'w') as fout:
fout.write("GENE # use generic interface\n")
fout.write(
"1 0 %d %f # iskip (not presently used) idebug "
"setgap shiftgap \n"
% (setgap, Energy(self.scissor, "eV").to("Ry")))
fout.write(
"0.0 %f %f %6.1f # Fermilevel (Ry),energygrid,energy "
"span around Fermilevel, "
"number of electrons\n"
% (Energy(self.energy_grid, "eV").to("Ry"),
Energy(self.energy_span_around_fermi, "eV").to("Ry"),
self._nelec))
fout.write(
"CALC # CALC (calculate expansion "
"coeff), NOCALC read from file\n")
fout.write(
"%d # lpfac, number of latt-points "
"per k-point\n" % self.lpfac)
fout.write(
"BANDS # run mode (only BOLTZ is "
"supported)\n")
fout.write("P " + str(len(self.kpt_line)) + "\n")
for kp in self.kpt_line:
fout.writelines([str(k) + " " for k in kp])
fout.write('\n')
def write_input(self, output_dir):
if self._bs.is_spin_polarized or self.soc:
self.write_energy(os.path.join(output_dir, "boltztrap.energyso"))
else:
self.write_energy(os.path.join(output_dir, "boltztrap.energy"))
self.write_struct(os.path.join(output_dir, "boltztrap.struct"))
self.write_intrans(os.path.join(output_dir, "boltztrap.intrans"))
self.write_def(os.path.join(output_dir, "BoltzTraP.def"))
if len(self.bs.projections) != 0 and self.run_type == "DOS":
self.write_proj(os.path.join(output_dir, "boltztrap.proj"),
os.path.join(output_dir, "BoltzTraP.def"))
def run(self, path_dir=None, convergence=True, write_input=True,
clear_dir=False, max_lpfac=150, min_egrid=0.00005):
"""
Write inputs (optional), run BoltzTraP, and ensure
convergence (optional)
Args:
path_dir (str): directory in which to run BoltzTraP
convergence (bool): whether to check convergence and make
corrections if needed
write_input: (bool) whether to write input files before the run
(required for convergence mode)
clear_dir: (bool) whether to remove all files in the path_dir
before starting
max_lpfac: (float) maximum lpfac value to try before reducing egrid
in convergence mode
min_egrid: (float) minimum egrid value to try before giving up in
convergence mode
Returns:
"""
# TODO: consider making this a part of custodian rather than pymatgen
# A lot of this functionality (scratch dirs, handlers, monitors)
# is built into custodian framework
if convergence and not write_input:
raise ValueError("Convergence mode requires write_input to be "
"true")
if self.run_type in ("BANDS", "DOS", "FERMI"):
convergence = False
if self.lpfac > max_lpfac:
max_lpfac = self.lpfac
if self.run_type == "BANDS" and self.bs.is_spin_polarized:
print("Reminder: for run_type " + str(
self.run_type) + ", spin component are not separated! "
"(you have a spin polarized band structure)")
if self.run_type in ("FERMI", "DOS") and self.spin is None:
if self.bs.is_spin_polarized:
raise BoltztrapError(
"Spin parameter must be specified for spin polarized "
"band structures!")
else:
self.spin = 1
dir_bz_name = "boltztrap"
if path_dir is None:
temp_dir = tempfile.mkdtemp()
path_dir = os.path.join(temp_dir, dir_bz_name)
else:
path_dir = os.path.abspath(
os.path.join(path_dir, dir_bz_name))
if not os.path.exists(path_dir):
os.mkdir(path_dir)
elif clear_dir:
for c in os.listdir(path_dir):
os.remove(os.path.join(path_dir, c))
FORMAT = "%(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT,
filename=os.path.join(path_dir, "../boltztrap.out"))
with cd(path_dir):
lpfac_start = self.lpfac
converged = False
while self.energy_grid >= min_egrid and not converged:
self.lpfac = lpfac_start
logging.info("lpfac, energy_grid: {} {}".format(self.lpfac, self.energy_grid))
while self.lpfac <= max_lpfac and not converged:
if write_input:
self.write_input(path_dir)
bt_exe = ["x_trans", "BoltzTraP"]
if self._bs.is_spin_polarized or self.soc:
bt_exe.append("-so")
p = subprocess.Popen(bt_exe, stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
p.wait()
for c in p.communicate():
logging.info(c.decode())
if "error in factorization" in c.decode():
raise BoltztrapError("error in factorization")
warning = ""
with open(os.path.join(path_dir,
dir_bz_name + ".outputtrans")) as f:
for l in f:
if "Option unknown" in l:
raise BoltztrapError(
"DOS mode needs a custom version of "
"BoltzTraP code is needed")
if "WARNING" in l:
warning = l
break
if "Error - Fermi level was not found" in l:
warning = l
break
if not warning and convergence:
# check convergence for warning
analyzer = BoltztrapAnalyzer.from_files(path_dir)
for doping in ['n', 'p']:
for c in analyzer.mu_doping[doping]:
if len(analyzer.mu_doping[doping][c]) != len(
analyzer.doping[doping]):
warning = "length of mu_doping array is " \
"incorrect"
break
if doping == 'p' and \
sorted(
analyzer.mu_doping[doping][
c], reverse=True) != \
analyzer.mu_doping[doping][c]:
warning = "sorting of mu_doping array " \
"incorrect for p-type"
break
# ensure n-type doping sorted correctly
if doping == 'n' and sorted(
analyzer.mu_doping[doping][c]) != \
analyzer.mu_doping[doping][c]:
warning = "sorting of mu_doping array " \
"incorrect for n-type"
break
if warning:
self.lpfac += 10
logging.warn("Warning detected: {}! Increase lpfac to "
"{}".format(warning, self.lpfac))
else:
converged = True
if not converged:
self.energy_grid /= 10
logging.info("Could not converge with max lpfac; "
"Decrease egrid to {}".format(self.energy_grid))
if not converged:
raise BoltztrapError(
"Doping convergence not reached with lpfac=" + str(
self.lpfac) + ", energy_grid=" + str(self.energy_grid))
return path_dir
class BoltztrapError(Exception):
"""
Exception class for boltztrap.
Raised when the boltztrap gives an error
"""
def __init__(self, msg):
self.msg = msg
logging.error(self.msg)
def __str__(self):
return "BoltztrapError : " + self.msg
class BoltztrapAnalyzer(object):
"""
Class used to store all the data from a boltztrap run
"""
def __init__(self, gap=None, mu_steps=None, cond=None, seebeck=None,
kappa=None, hall=None, doping=None,
mu_doping=None, seebeck_doping=None, cond_doping=None,
kappa_doping=None,
hall_doping=None, intrans=None, dos=None, dos_partial=None,
carrier_conc=None, vol=None, warning=None,
bz_bands=None, bz_kpoints=None, fermi_surface_data=None):
"""
Constructor taking directly all the data generated by Boltztrap. You
won't probably use it directly but instead use the from_files and
from_dict methods.
Args:
gap: The gap after interpolation in eV
mu_steps: The steps of electron chemical potential (or Fermi
level) in eV.
cond: The electronic conductivity tensor divided by a constant
relaxation time (sigma/tau) at different temperature and
fermi levels.
The format is {temperature: [array of 3x3 tensors at each
fermi level in mu_steps]}. The units are 1/(Ohm*m*s).
seebeck: The Seebeck tensor at different temperatures and fermi
levels. The format is {temperature: [array of 3x3 tensors at
each fermi level in mu_steps]}. The units are V/K
kappa: The electronic thermal conductivity tensor divided by a
constant relaxation time (kappa/tau) at different temperature
and fermi levels. The format is {temperature: [array of 3x3
tensors at each fermi level in mu_steps]}
The units are W/(m*K*s)
hall: The hall tensor at different temperature and fermi levels
The format is {temperature: [array of 27 coefficients list at
each fermi level in mu_steps]}
The units are m^3/C
doping: The different doping levels that have been given to
Boltztrap. The format is {'p':[],'n':[]} with an array of
doping levels. The units are cm^-3
mu_doping: Gives the electron chemical potential (or Fermi level)
for a given set of doping.
Format is {'p':{temperature: [fermi levels],'n':{temperature:
[fermi levels]}}
the fermi level array is ordered according to the doping
levels in doping units for doping are in cm^-3 and for Fermi
level in eV
seebeck_doping: The Seebeck tensor at different temperatures and
doping levels. The format is {'p': {temperature: [Seebeck
tensors]}, 'n':{temperature: [Seebeck tensors]}}
The [Seebeck tensors] array is ordered according to the
doping levels in doping units for doping are in cm^-3 and for
Seebeck in V/K
cond_doping: The electronic conductivity tensor divided by a
constant relaxation time (sigma/tau) at different
temperatures and doping levels
The format is {'p':{temperature: [conductivity tensors]},
'n':{temperature: [conductivity tensors]}}
The [conductivity tensors] array is ordered according to the
doping levels in doping units for doping are in cm^-3 and for
conductivity in 1/(Ohm*m*s)
kappa_doping: The thermal conductivity tensor divided by a constant
relaxation time (kappa/tau) at different temperatures and
doping levels.
The format is {'p':{temperature: [thermal conductivity
tensors]},'n':{temperature: [thermal conductivity tensors]}}
The [thermal conductivity tensors] array is ordered according
to the doping levels in doping units for doping are in cm^-3
and for thermal conductivity in W/(m*K*s)
hall_doping: The Hall tensor at different temperatures and doping
levels.
The format is {'p':{temperature: [Hall tensors]},
'n':{temperature: [Hall tensors]}}
The [Hall tensors] array is ordered according to the doping
levels in doping and each Hall tensor is represented by a 27
coefficients list.
The units are m^3/C
intrans: a dictionary of inputs e.g. {"scissor": 0.0}
carrier_conc: The concentration of carriers in electron (or hole)
per unit cell
dos: The dos computed by Boltztrap given as a pymatgen Dos object
dos_partial: Data for the partial DOS projected on sites and
orbitals
vol: Volume of the unit cell in angstrom cube (A^3)
warning: string if BoltzTraP outputted a warning, else None
bz_bands: Data for interpolated bands on a k-point line
(run_type=BANDS)
bz_kpoints: k-point in reciprocal coordinates for interpolated
bands (run_type=BANDS)
fermi_surface_data: energy values in a 3D grid imported from the
output .cube file.
"""
self.gap = gap
self.mu_steps = mu_steps
self._cond = cond
self._seebeck = seebeck
self._kappa = kappa
self._hall = hall
self.warning = warning
self.doping = doping
self.mu_doping = mu_doping
self._seebeck_doping = seebeck_doping
self._cond_doping = cond_doping
self._kappa_doping = kappa_doping
self._hall_doping = hall_doping
self.intrans = intrans
self._carrier_conc = carrier_conc
self.dos = dos
self.vol = vol
self._dos_partial = dos_partial
self._bz_bands = bz_bands
self._bz_kpoints = bz_kpoints
self.fermi_surface_data = fermi_surface_data
def get_symm_bands(self, structure, efermi, kpt_line=None,
labels_dict=None):
"""
Function useful to read bands from Boltztrap output and get a
BandStructureSymmLine object comparable with that one from a DFT
calculation (if the same kpt_line is provided). Default kpt_line
and labels_dict is the standard path of high symmetry k-point for
the specified structure. They could be extracted from the
BandStructureSymmLine object that you want to compare with. efermi
variable must be specified to create the BandStructureSymmLine
object (usually it comes from DFT or Boltztrap calc)
"""
try:
if kpt_line is None:
kpath = HighSymmKpath(structure)
kpt_line = [Kpoint(k, structure.lattice.reciprocal_lattice) for
k in
kpath.get_kpoints(coords_are_cartesian=False)[0]]
labels_dict = {l: k for k, l in zip(
*kpath.get_kpoints(coords_are_cartesian=False)) if l}
kpt_line = [kp.frac_coords for kp in kpt_line]
elif type(kpt_line[0]) == Kpoint:
kpt_line = [kp.frac_coords for kp in kpt_line]
labels_dict = {k: labels_dict[k].frac_coords for k in
labels_dict}
idx_list = []
# kpt_dense=np.array([kp for kp in self._bz_kpoints])
for i, kp in enumerate(kpt_line):
w = []
prec = 1e-05
while len(w) == 0:
w = np.where(np.all(
np.abs(kp - self._bz_kpoints) < [prec] * 3,
axis=1))[0]
prec *= 10
# print( prec )
idx_list.append([i, w[0]])
# if len(w)>0:
# idx_list.append([i,w[0]])
# else:
# w=np.where(np.all(np.abs(kp.frac_coords-self._bz_kpoints)
# <[1e-04,1e-04,1e-04],axis=1))[0]
# idx_list.append([i,w[0]])
idx_list = np.array(idx_list)
# print( idx_list.shape )
bands_dict = {Spin.up: (self._bz_bands * Energy(1, "Ry").to(
"eV") + efermi).T[:, idx_list[:, 1]].tolist()}
# bz_kpoints = bz_kpoints[idx_list[:,1]].tolist()
sbs = BandStructureSymmLine(kpt_line, bands_dict,
structure.lattice.reciprocal_lattice,
efermi,
labels_dict=labels_dict)
return sbs
except:
raise BoltztrapError(
"Bands are not in output of BoltzTraP.\nBolztrapRunner must "
"be run with run_type=BANDS")
@staticmethod
def check_acc_bzt_bands(sbs_bz, sbs_ref, warn_thr=(0.03, 0.03)):
"""
Compare sbs_bz BandStructureSymmLine calculated with boltztrap with
the sbs_ref BandStructureSymmLine as reference (from MP for
instance), computing correlation and energy difference for eight bands
around the gap (semiconductors) or fermi level (metals).
warn_thr is a threshold to get a warning in the accuracy of Boltztap
interpolated bands.
Return a dictionary with these keys:
- "N": the index of the band compared; inside each there are:
- "Corr": correlation coefficient for the 8 compared bands
- "Dist": energy distance for the 8 compared bands
- "branch_name": energy distance for that branch
- "avg_corr": average of correlation coefficient over the 8 bands
- "avg_dist": average of energy distance over the 8 bands
- "nb_list": list of indexes of the 8 compared bands
- "acc_thr": list of two float corresponing to the two warning
thresholds in input
- "acc_err": list of two bools:
True if the avg_corr > warn_thr[0], and
True if the avg_dist > warn_thr[1]
See also compare_sym_bands function doc
"""
if not sbs_ref.is_metal() and not sbs_bz.is_metal():
vbm_idx = sbs_bz.get_vbm()['band_index'][Spin.up][-1]
cbm_idx = sbs_bz.get_cbm()['band_index'][Spin.up][0]
nb_list = range(vbm_idx - 3, cbm_idx + 4)
else:
bnd_around_efermi = []
delta = 0
spin = sbs_bz.bands.keys()[0]
while len(bnd_around_efermi) < 8 and delta < 100:
delta += 0.1
bnd_around_efermi = []
for nb in range(len(sbs_bz.bands[spin])):
for kp in range(len(sbs_bz.bands[spin][nb])):
if abs(sbs_bz.bands[spin][nb][
kp] - sbs_bz.efermi) < delta:
bnd_around_efermi.append(nb)
break
if len(bnd_around_efermi) < 8:
print("Warning! check performed on " + str(
len(bnd_around_efermi)))
nb_list = bnd_around_efermi
else:
nb_list = bnd_around_efermi[:8]
# print(nb_list)
bcheck = compare_sym_bands(sbs_bz, sbs_ref, nb_list)
# print(bcheck)
acc_err = [False, False]
avg_corr = sum([item[1]['Corr'] for item in bcheck.iteritems()]) / 8
avg_distance = sum([item[1]['Dist'] for item in bcheck.iteritems()]) / 8
if avg_corr > warn_thr[0]: acc_err[0] = True
if avg_distance > warn_thr[0]: acc_err[1] = True
bcheck['avg_corr'] = avg_corr
bcheck['avg_distance'] = avg_distance
bcheck['acc_err'] = acc_err
bcheck['acc_thr'] = warn_thr
bcheck['nb_list'] = nb_list
if True in acc_err:
print("Warning! some bands around gap are not accurate")
return bcheck
def get_seebeck(self, output='eigs', doping_levels=True):
"""
Gives the seebeck coefficient (microV/K) in either a
full 3x3 tensor form, as 3 eigenvalues, or as the average value
(trace/3.0) If doping_levels=True, the results are given at
different p and n doping
levels (given by self.doping), otherwise it is given as a series
of electron chemical potential values
Args:
output (string): the type of output. 'tensor' give the full
3x3 tensor, 'eigs' its 3 eigenvalues and
'average' the average of the three eigenvalues
doping_levels (boolean): True for the results to be given at
different doping levels, False for results
at different electron chemical potentials
Returns:
If doping_levels=True, a dictionary {temp:{'p':[],'n':[]}}.
The 'p' links to Seebeck at p-type doping
and 'n' to the Seebeck at n-type doping. Otherwise, returns a
{temp:[]} dictionary
The result contains either the sorted three eigenvalues of
the symmetric
Seebeck tensor (output='eigs') or a full tensor (3x3 array) (
output='tensor') or as an average
(output='average').
units are microV/K
"""
return BoltztrapAnalyzer._format_to_output(self._seebeck,
self._seebeck_doping,
output,
doping_levels, 1e6)
def get_conductivity(self, output='eigs', doping_levels=True,
relaxation_time=1e-14):
"""
Gives the conductivity (1/Ohm*m) in either a full 3x3 tensor
form, as 3 eigenvalues, or as the average value
(trace/3.0) If doping_levels=True, the results are given at
different p and n doping
levels (given by self.doping), otherwise it is given as a series
of electron chemical potential values
Args:
output (string): the type of output. 'tensor' give the full
3x3 tensor, 'eigs' its 3 eigenvalues and
'average' the average of the three eigenvalues
doping_levels (boolean): True for the results to be given at
different doping levels, False for results
at different electron chemical potentials
relaxation_time (float): constant relaxation time in secs
Returns:
If doping_levels=True, a dictionary {temp:{'p':[],'n':[]}}.
The 'p' links to conductivity
at p-type doping and 'n' to the conductivity at n-type
doping. Otherwise,
returns a {temp:[]} dictionary. The result contains either
the sorted three eigenvalues of the symmetric
conductivity tensor (format='eigs') or a full tensor (3x3
array) (output='tensor') or as an average
(output='average').
The result includes a given constant relaxation time
units are 1/Ohm*m
"""
return BoltztrapAnalyzer._format_to_output(self._cond,
self._cond_doping, output,
doping_levels,
relaxation_time)
def get_power_factor(self, output='eigs', doping_levels=True,
relaxation_time=1e-14):
"""
Gives the power factor (Seebeck^2 * conductivity) in units
microW/(m*K^2) in either a full 3x3 tensor form,
as 3 eigenvalues, or as the average value (trace/3.0) If
doping_levels=True, the results are given at
different p and n doping levels (given by self.doping), otherwise it
is given as a series of
electron chemical potential values
Args:
output (string): the type of output. 'tensor' give the full 3x3
tensor, 'eigs' its 3 eigenvalues and
'average' the average of the three eigenvalues
doping_levels (boolean): True for the results to be given at
different doping levels, False for results
at different electron chemical potentials
relaxation_time (float): constant relaxation time in secs
Returns:
If doping_levels=True, a dictionnary {temp:{'p':[],'n':[]}}. The
'p' links to power factor
at p-type doping and 'n' to the conductivity at n-type doping.
Otherwise,
returns a {temp:[]} dictionary. The result contains either the
sorted three eigenvalues of the symmetric
power factor tensor (format='eigs') or a full tensor (3x3 array) (
output='tensor') or as an average
(output='average').
The result includes a given constant relaxation time
units are microW/(m K^2)
"""
result = None
result_doping = None
if doping_levels:
result_doping = {doping: {t: [] for t in
self._seebeck_doping[doping]} for
doping in self._seebeck_doping}
for doping in result_doping:
for t in result_doping[doping]:
for i in range(len(self.doping[doping])):
full_tensor = np.dot(self._cond_doping[doping][t][i],
np.dot(
self._seebeck_doping[doping][
t][i],
self._seebeck_doping[doping][
t][i]))
result_doping[doping][t].append(full_tensor)
else:
result = {t: [] for t in self._seebeck}
for t in result:
for i in range(len(self.mu_steps)):
full_tensor = np.dot(self._cond[t][i],
np.dot(self._seebeck[t][i],
self._seebeck[t][i]))
result[t].append(full_tensor)
return BoltztrapAnalyzer._format_to_output(result, result_doping,
output, doping_levels,
multi=1e6 * relaxation_time)
def get_thermal_conductivity(self, output='eigs', doping_levels=True,
k_el=True, relaxation_time=1e-14):
"""
Gives the electronic part of the thermal conductivity in either a
full 3x3 tensor form,
as 3 eigenvalues, or as the average value (trace/3.0) If
doping_levels=True, the results are given at
different p and n doping levels (given by self.doping), otherwise it
is given as a series of
electron chemical potential values
Args:
output (string): the type of output. 'tensor' give the full 3x3
tensor, 'eigs' its 3 eigenvalues and
'average' the average of the three eigenvalues
doping_levels (boolean): True for the results to be given at
different doping levels, False for results
at different electron chemical potentials
k_el (boolean): True for k_0-PF*T, False for k_0
relaxation_time (float): constant relaxation time in secs
Returns:
If doping_levels=True, a dictionary {temp:{'p':[],'n':[]}}. The
'p' links to thermal conductivity
at p-type doping and 'n' to the thermal conductivity at n-type
doping. Otherwise,
returns a {temp:[]} dictionary. The result contains either the
sorted three eigenvalues of the symmetric
conductivity tensor (format='eigs') or a full tensor (3x3 array) (
output='tensor') or as an average
(output='average').
The result includes a given constant relaxation time
units are W/mK
"""
result = None
result_doping = None
if doping_levels:
result_doping = {doping: {t: [] for t in
self._seebeck_doping[doping]} for
doping in self._seebeck_doping}
for doping in result_doping:
for t in result_doping[doping]:
for i in range(len(self.doping[doping])):
if k_el:
pf_tensor = np.dot(self._cond_doping[doping][t][i],
np.dot(
self._seebeck_doping[doping][
t][i],
self._seebeck_doping[doping][
t][i]))
result_doping[doping][t].append((
self._kappa_doping[doping][t][
i] - pf_tensor * t))
else:
result_doping[doping][t].append((
self._kappa_doping[doping][t][i]))
else:
result = {t: [] for t in self._seebeck}
for t in result:
for i in range(len(self.mu_steps)):
if k_el:
pf_tensor = np.dot(self._cond[t][i],
np.dot(self._seebeck[t][i],
self._seebeck[t][i]))
result[t].append((self._kappa[t][i] - pf_tensor * t))
else:
result[t].append((self._kappa[t][i]))
return BoltztrapAnalyzer._format_to_output(result, result_doping,
output, doping_levels,
multi=relaxation_time)
def get_zt(self, output='eigs', doping_levels=True, relaxation_time=1e-14,
kl=1.0):
"""
Gives the ZT coefficient (S^2*cond*T/thermal cond) in either a full
3x3 tensor form,
as 3 eigenvalues, or as the average value (trace/3.0) If
doping_levels=True, the results are given at
different p and n doping levels (given by self.doping), otherwise it
is given as a series of
electron chemical potential values. We assume a constant relaxation
time and a constant
lattice thermal conductivity
Args:
output (string): the type of output. 'tensor' give the full 3x3
tensor, 'eigs' its 3 eigenvalues and
'average' the average of the three eigenvalues
doping_levels (boolean): True for the results to be given at
different doping levels, False for results
at different electron chemical potentials
relaxation_time (float): constant relaxation time in secs
k_l (float): lattice thermal cond in W/(m*K)
Returns:
If doping_levels=True, a dictionary {temp:{'p':[],'n':[]}}. The
'p' links to ZT
at p-type doping and 'n' to the ZT at n-type doping. Otherwise,
returns a {temp:[]} dictionary. The result contains either the
sorted three eigenvalues of the symmetric
ZT tensor (format='eigs') or a full tensor (3x3 array) (
output='tensor') or as an average
(output='average').
The result includes a given constant relaxation time and lattice
thermal conductivity
"""
result = None
result_doping = None
if doping_levels:
result_doping = {doping: {t: [] for t in
self._seebeck_doping[doping]} for
doping in self._seebeck_doping}
for doping in result_doping:
for t in result_doping[doping]:
for i in range(len(self.doping[doping])):
pf_tensor = np.dot(self._cond_doping[doping][t][i],
np.dot(
self._seebeck_doping[doping][t][
i],
self._seebeck_doping[doping][t][
i]))
thermal_conduct = (self._kappa_doping[doping][t][i]
- pf_tensor * t) * relaxation_time
result_doping[doping][t].append(
np.dot(pf_tensor * relaxation_time * t,
np.linalg.inv(
thermal_conduct + kl * np.eye(3, 3))))
else:
result = {t: [] for t in self._seebeck}
for t in result:
for i in range(len(self.mu_steps)):
pf_tensor = np.dot(self._cond[t][i],
np.dot(self._seebeck[t][i],
self._seebeck[t][i]))
thermal_conduct = (self._kappa[t][i]
- pf_tensor * t) * relaxation_time
result[t].append(np.dot(pf_tensor * relaxation_time * t,
np.linalg.inv(
thermal_conduct + kl *
np.eye(3, 3))))
return BoltztrapAnalyzer._format_to_output(result, result_doping,
output, doping_levels)
def get_average_eff_mass(self, output='eigs', doping_levels=True):
"""
Gives the average effective mass tensor. We call it average because
it takes into account all the bands
and regions in the Brillouin zone. This is different than the standard
textbook effective mass which relates
often to only one (parabolic) band.
The average effective mass tensor is defined as the integrated
average of the second derivative of E(k)
This effective mass tensor takes into account:
-non-parabolicity
-multiple extrema
-multiple bands
For more information about it. See:
Hautier, G., Miglio, A., Waroquiers, D., Rignanese, G., & Gonze,
X. (2014).
How Does Chemistry Influence Electron Effective Mass in Oxides?
A High-Throughput Computational Analysis. Chemistry of Materials,
26(19), 5447–5458. doi:10.1021/cm404079a
or
Hautier, G., Miglio, A., Ceder, G., Rignanese, G.-M., & Gonze,
X. (2013).
Identification and design principles of low hole effective mass
p-type transparent conducting oxides.
Nature Communications, 4, 2292. doi:10.1038/ncomms3292
Depending on the value of output, we have either the full 3x3
effective mass tensor,
its 3 eigenvalues or an average
Args:
output (string): 'eigs' for eigenvalues, 'tensor' for the full
tensor and 'average' for an average (trace/3)
doping_levels (boolean): True for the results to be given at
different doping levels, False for results
at different electron chemical potentials
Returns:
If doping_levels=True,a dictionary {'p':{temp:[]},'n':{temp:[]}}
with an array of effective mass tensor, eigenvalues of average
value (depending on output) for each temperature and for each
doping level.
The 'p' links to hole effective mass tensor and 'n' to electron
effective mass tensor.
"""
result = None
result_doping = None
conc = self.get_carrier_concentration()
if doping_levels:
result_doping = {doping: {t: [] for t in self._cond_doping[doping]}
for
doping in self.doping}
for doping in result_doping:
for temp in result_doping[doping]:
for i in range(len(self.doping[doping])):
result_doping[doping][temp].append(np.linalg.inv(
np.array(self._cond_doping[doping][temp][i])) * \
self.doping[doping][
i] * 10 ** 6 * e ** 2 / m_e)
else:
result = {t: [] for t in self._seebeck}
for temp in result:
for i in range(len(self.mu_steps)):
try:
cond_inv = np.linalg.inv(np.array(self._cond[temp][i]))
except np.linalg.LinAlgError:
pass
result[temp].append(cond_inv * \
conc[temp][i] * 10 ** 6 * e ** 2 / m_e)
return BoltztrapAnalyzer._format_to_output(result, result_doping,
output, doping_levels)
def get_extreme(self, target_prop, maximize=True, min_temp=None,
max_temp=None, min_doping=None, max_doping=None,
isotropy_tolerance=0.05, use_average=True):
"""
This method takes in eigenvalues over a range of carriers,
temperatures, and doping levels, and tells you what is the "best"
value that can be achieved for the given target_property. Note that
this method searches the doping dict only, not the full mu dict.
Args:
target_prop: target property, i.e. "seebeck", "power factor",
"conductivity", "kappa", or "zt"
maximize: True to maximize, False to minimize (e.g. kappa)
min_temp: minimum temperature allowed
max_temp: maximum temperature allowed
min_doping: minimum doping allowed (e.g., 1E18)
max_doping: maximum doping allowed (e.g., 1E20)
isotropy_tolerance: tolerance for isotropic (0.05 = 5%)
use_average: True for avg of eigenval, False for max eigenval
Returns:
A dictionary with keys {"p", "n", "best"} with sub-keys:
{"value", "temperature", "doping", "isotropic"}
"""
def is_isotropic(x, isotropy_tolerance):
"""
Internal method to tell you if 3-vector "x" is isotropic
Args:
x: the vector to determine isotropy for
isotropy_tolerance: tolerance, e.g. 0.05 is 5%
"""
if len(x) != 3:
raise ValueError("Invalid input to is_isotropic!")
st = sorted(x)
return bool(all([st[0], st[1], st[2]]) and \
(abs((st[1] - st[0]) / st[1]) <= isotropy_tolerance) and \
(abs((st[2] - st[0])) / st[2] <= isotropy_tolerance) and \
(abs((st[2] - st[1]) / st[2]) <= isotropy_tolerance))
if target_prop.lower() == "seebeck":
d = self.get_seebeck(output="eigs", doping_levels=True)
elif target_prop.lower() == "power factor":
d = self.get_power_factor(output="eigs", doping_levels=True)
elif target_prop.lower() == "conductivity":
d = self.get_conductivity(output="eigs", doping_levels=True)
elif target_prop.lower() == "kappa":
d = self.get_thermal_conductivity(output="eigs",
doping_levels=True)
elif target_prop.lower() == "zt":
d = self.get_zt(output="eigs", doping_levels=True)
else:
raise ValueError("Target property: {} not recognized!".
format(target_prop))
absval = True # take the absolute value of properties
x_val = None
x_temp = None
x_doping = None
x_isotropic = None
output = {}
min_temp = min_temp or 0
max_temp = max_temp or float('inf')
min_doping = min_doping or 0
max_doping = max_doping or float('inf')
for pn in ('p', 'n'):
for t in d[pn]: # temperatures
if min_temp <= float(t) <= max_temp:
for didx, evs in enumerate(d[pn][t]):
doping_lvl = self.doping[pn][didx]
if min_doping <= doping_lvl <= max_doping:
isotropic = is_isotropic(evs, isotropy_tolerance)
if absval:
evs = [abs(x) for x in evs]
if use_average:
val = float(sum(evs)) / len(evs)
else:
val = max(evs)
if x_val is None or (val > x_val and maximize) \
or (val < x_val and not maximize):
x_val = val
x_temp = t
x_doping = doping_lvl
x_isotropic = isotropic
output[pn] = {'value': x_val, 'temperature': x_temp,
'doping': x_doping, 'isotropic': x_isotropic}
x_val = None
if maximize:
max_type = 'p' if output['p']['value'] >= \
output['n']['value'] else 'n'
else:
max_type = 'p' if output['p']['value'] <= \
output['n']['value'] else 'n'
output['best'] = output[max_type]
output['best']['carrier_type'] = max_type
return output
@staticmethod
def _format_to_output(tensor, tensor_doping, output, doping_levels,
multi=1.0):
if doping_levels:
full_tensor = tensor_doping
result = {doping: {t: [] for t in tensor_doping[doping]} for doping
in tensor_doping}
for doping in full_tensor:
for temp in full_tensor[doping]:
for i in range(len(full_tensor[doping][temp])):
if output in ['eig', 'eigs']:
result[doping][temp].append(sorted(
np.linalg.eigh(full_tensor[doping][temp][i])[
0] * multi))
elif output == 'tensor':
result[doping][temp].append(
np.array(full_tensor[doping][temp][i]) * multi)
elif output == 'average':
result[doping][temp].append(
(full_tensor[doping][temp][i][0][0] \
+ full_tensor[doping][temp][i][1][1] \
+ full_tensor[doping][temp][i][2][
2]) * multi / 3.0)
else:
raise ValueError("Unknown output format: "
"{}".format(output))
else:
full_tensor = tensor
result = {t: [] for t in tensor}
for temp in full_tensor:
for i in range(len(tensor[temp])):
if output in ['eig', 'eigs']:
result[temp].append(sorted(
np.linalg.eigh(full_tensor[temp][i])[0] * multi))
elif output == 'tensor':
result[temp].append(
np.array(full_tensor[temp][i]) * multi)
elif output == 'average':
result[temp].append((full_tensor[temp][i][0][0]
+ full_tensor[temp][i][1][1]
+ full_tensor[temp][i][2][
2]) * multi / 3.0)
else:
raise ValueError("Unknown output format: {}".
format(output))
return result
def get_complete_dos(self, structure, analyzer_for_second_spin=None):
"""
Gives a CompleteDos object with the DOS from the interpolated
projected band structure
Args:
the structure (necessary to identify sites for projection)
analyzer_for_second_spin must be specified to have a
CompleteDos with both Spin components
Returns:
a CompleteDos object
Example of use in case of spin polarized case:
BoltztrapRunner(bs=bs,nelec=10,run_type="DOS",spin=1).run(path_dir='dos_up/')
an_up=BoltztrapAnalyzer.from_files("dos_up/boltztrap/",dos_spin=1)
BoltztrapRunner(bs=bs,nelec=10,run_type="DOS",spin=-1).run(path_dir='dos_dw/')
an_dw=BoltztrapAnalyzer.from_files("dos_dw/boltztrap/",dos_spin=-1)
cdos=an_up.get_complete_dos(bs.structure,an_dw)
"""
pdoss = {}
spin_1 = list(self.dos.densities.keys())[0]
if analyzer_for_second_spin:
if not np.all(self.dos.energies ==
analyzer_for_second_spin.dos.energies):
raise BoltztrapError(
"Dos merging error: energies of the two dos are different")
spin_2 = list(analyzer_for_second_spin.dos.densities.keys())[0]
if spin_1 == spin_2:
raise BoltztrapError(
"Dos merging error: spin component are the same")
for s in self._dos_partial:
if structure.sites[int(s)] not in pdoss:
pdoss[structure.sites[int(s)]] = {}
for o in self._dos_partial[s]:
if Orbital[o] not in pdoss[structure.sites[int(s)]]:
pdoss[structure.sites[int(s)]][Orbital[o]] = {}
pdoss[structure.sites[int(s)]][Orbital[o]][
spin_1] = self._dos_partial[s][o]
if analyzer_for_second_spin:
pdoss[structure.sites[int(s)]][Orbital[o]][
spin_2] = analyzer_for_second_spin._dos_partial[s][o]
if analyzer_for_second_spin:
tdos = Dos(self.dos.efermi, self.dos.energies,
{spin_1: self.dos.densities[spin_1],
spin_2: analyzer_for_second_spin.dos.densities[
spin_2]})
else:
tdos = self.dos
return CompleteDos(structure, total_dos=tdos, pdoss=pdoss)
def get_mu_bounds(self, temp=300):
return min(self.mu_doping['p'][temp]), max(self.mu_doping['n'][temp])
def get_carrier_concentration(self):
"""
gives the carrier concentration (in cm^-3)
Returns
a dictionary {temp:[]} with an array of carrier concentration
(in cm^-3) at each temperature
The array relates to each step of electron chemical potential
"""
return {temp: [1e24 * i / self.vol for i in self._carrier_conc[temp]]
for temp in self._carrier_conc}
def get_hall_carrier_concentration(self):
"""
gives the Hall carrier concentration (in cm^-3). This is the trace of
the Hall tensor (see Boltztrap source code) Hall carrier concentration
are not always exactly the same than carrier concentration.
Returns
a dictionary {temp:[]} with an array of Hall carrier concentration
(in cm^-3) at each temperature The array relates to each step of
electron chemical potential
"""
result = {temp: [] for temp in self._hall}
for temp in self._hall:
for i in self._hall[temp]:
trace = (i[1][2][0] + i[2][0][1] + i[0][1][2]) / 3.0
if trace != 0.0:
result[temp].append(1e-6 / (trace * e))
else:
result[temp].append(0.0)
return result
@staticmethod
def parse_outputtrans(path_dir):
"""
Parses .outputtrans file
Args:
path_dir: dir containing boltztrap.outputtrans
Returns:
tuple - (run_type, warning, efermi, gap, doping_levels)
"""
run_type = None
warning = None
efermi = None
gap = None
doping_levels = []
with open(os.path.join(path_dir, "boltztrap.outputtrans"), 'r') \
as f:
for line in f:
if "WARNING" in line:
warning = line
elif "Calc type:" in line:
run_type = line.split()[-1]
elif line.startswith("VBM"):
efermi = Energy(line.split()[1], "Ry").to("eV")
elif line.startswith("Egap:"):
gap = Energy(float(line.split()[1]), "Ry").to("eV")
elif line.startswith("Doping level number"):
doping_levels.append(float(line.split()[6]))
return run_type, warning, efermi, gap, doping_levels
@staticmethod
def parse_transdos(path_dir, efermi, dos_spin=1, trim_dos=False):
"""
Parses .transdos (total DOS) and .transdos_x_y (partial DOS) files
Args:
path_dir: (str) dir containing DOS files
efermi: (float) Fermi energy
dos_spin: (int) -1 for spin down, +1 for spin up
trim_dos: (bool) whether to post-process / trim DOS
Returns:
tuple - (DOS, dict of partial DOS)
"""
data_dos = {'total': [], 'partial': {}}
# parse the total DOS data
## format is energy, DOS, integrated DOS
with open(os.path.join(path_dir, "boltztrap.transdos"), 'r') as f:
count_series = 0 # TODO: why is count_series needed?
for line in f:
if line.lstrip().startswith("#"):
count_series += 1
if count_series > 1:
break
else:
data_dos['total'].append(
[Energy(float(line.split()[0]), "Ry").to("eV"),
float(line.split()[1])])
total_elec = float(line.split()[2])
lw_l = 0
hg_l = -len(data_dos['total'])
if trim_dos:
# Francesco knows what this does
# It has something to do with a trick of adding fake energies
# at the endpoints of the DOS, and then re-trimming it. This is
# to get the same energy scale for up and down spin DOS.
tmp_data = np.array(data_dos['total'])
tmp_den = np.trim_zeros(tmp_data[:, 1], 'f')[1:]
lw_l = len(tmp_data[:, 1]) - len(tmp_den)
tmp_ene = tmp_data[lw_l:, 0]
tmp_den = np.trim_zeros(tmp_den, 'b')[:-1]
hg_l = len(tmp_ene) - len(tmp_den)
tmp_ene = tmp_ene[:-hg_l]
tmp_data = np.vstack((tmp_ene, tmp_den)).T
data_dos['total'] = tmp_data.tolist()
# parse partial DOS data
for file_name in os.listdir(path_dir):
if file_name.endswith(
"transdos") and file_name != 'boltztrap.transdos':
tokens = file_name.split(".")[1].split("_")
site = tokens[1]
orb = '_'.join(tokens[2:])
with open(os.path.join(path_dir, file_name), 'r') as f:
for line in f:
if not line.lstrip().startswith(" #"):
if site not in data_dos['partial']:
data_dos['partial'][site] = {}
if orb not in data_dos['partial'][site]:
data_dos['partial'][site][orb] = []
data_dos['partial'][site][orb].append(
float(line.split()[1]))
data_dos['partial'][site][orb] = data_dos['partial'][site][
orb][lw_l:-hg_l]
dos_full = {'energy': [], 'density': []}
for t in data_dos['total']:
dos_full['energy'].append(t[0])
dos_full['density'].append(t[1])
dos = Dos(efermi, dos_full['energy'],
{Spin(dos_spin): dos_full['density']})
dos_partial = data_dos['partial'] # TODO: make this real DOS object?
return dos, dos_partial
@staticmethod
def parse_intrans(path_dir):
"""
Parses boltztrap.intrans mainly to extract the value of scissor applied to the bands or some other inputs
Args:
path_dir: (str) dir containing the boltztrap.intrans file
Returns:
intrans (dict): a dictionary containing various inputs that had been used in the Boltztrap run.
"""
intrans = {}
with open(os.path.join(path_dir, "boltztrap.intrans"), 'r') as f:
for line in f:
if "iskip" in line:
intrans["scissor"] = Energy(float(line.split(" ")[3]),
"Ry").to("eV")
if "HISTO" in line or "TETRA" in line:
intrans["dos_type"] = line[:-1]
return intrans
@staticmethod
def parse_struct(path_dir):
"""
Parses boltztrap.struct file (only the volume)
Args:
path_dir: (str) dir containing the boltztrap.struct file
Returns:
(float) volume
"""
with open(os.path.join(path_dir, "boltztrap.struct"), 'r') as f:
tokens = f.readlines()
return Lattice([[Length(float(tokens[i].split()[j]), "bohr").
to("ang") for j in range(3)] for i in
range(1, 4)]).volume
@staticmethod
def parse_cond_and_hall(path_dir, doping_levels=None):
"""
Parses the conductivity and Hall tensors
Args:
path_dir: Path containing .condtens / .halltens files
doping_levels: ([float]) - doping lvls, parse outtrans to get this
Returns:
mu_steps, cond, seebeck, kappa, hall, pn_doping_levels,
mu_doping, seebeck_doping, cond_doping, kappa_doping,
hall_doping, carrier_conc
"""
# Step 1: parse raw data but do not convert to final format
t_steps = set()
mu_steps = set()
data_full = []
data_hall = []
data_doping_full = []
data_doping_hall = []
doping_levels = doping_levels or []
# parse the full conductivity/Seebeck/kappa0/etc data
## also initialize t_steps and mu_steps
with open(os.path.join(path_dir, "boltztrap.condtens"), 'r') as f:
for line in f:
if not line.startswith("#"):
mu_steps.add(float(line.split()[0]))
t_steps.add(int(float(line.split()[1])))
data_full.append([float(c) for c in line.split()])
# parse the full Hall tensor
with open(os.path.join(path_dir, "boltztrap.halltens"), 'r') as f:
for line in f:
if not line.startswith("#"):
data_hall.append([float(c) for c in line.split()])
if len(doping_levels) != 0:
# parse doping levels version of full cond. tensor, etc.
with open(
os.path.join(path_dir, "boltztrap.condtens_fixdoping"),
'r') as f:
for line in f:
if not line.startswith("#") and len(line) > 2:
data_doping_full.append([float(c)
for c in line.split()])
# parse doping levels version of full hall tensor
with open(
os.path.join(path_dir, "boltztrap.halltens_fixdoping"),
'r') as f:
for line in f:
if not line.startswith("#") and len(line) > 2:
data_doping_hall.append(
[float(c) for c in line.split()])
# Step 2: convert raw data to final format
# sort t and mu_steps (b/c they are sets not lists)
# and convert to correct energy
t_steps = sorted([t for t in t_steps])
mu_steps = sorted([Energy(m, "Ry").to("eV") for m in mu_steps])
# initialize output variables - could use defaultdict instead
# I am leaving things like this for clarity
cond = {t: [] for t in t_steps}
seebeck = {t: [] for t in t_steps}
kappa = {t: [] for t in t_steps}
hall = {t: [] for t in t_steps}
carrier_conc = {t: [] for t in t_steps}
dos_full = {'energy': [], 'density': []}
mu_doping = {'p': {t: [] for t in t_steps},
'n': {t: [] for t in t_steps}}
seebeck_doping = {'p': {t: [] for t in t_steps},
'n': {t: [] for t in t_steps}}
cond_doping = {'p': {t: [] for t in t_steps},
'n': {t: [] for t in t_steps}}
kappa_doping = {'p': {t: [] for t in t_steps},
'n': {t: [] for t in t_steps}}
hall_doping = {'p': {t: [] for t in t_steps},
'n': {t: [] for t in t_steps}}
# process doping levels
pn_doping_levels = {'p': [], 'n': []}
for d in doping_levels:
if d > 0:
pn_doping_levels['p'].append(d)
else:
pn_doping_levels['n'].append(-d)
# process raw conductivity data, etc.
for d in data_full:
temp, doping = d[1], d[2]
carrier_conc[temp].append(doping)
cond[temp].append(np.reshape(d[3:12], (3, 3)).tolist())
seebeck[temp].append(np.reshape(d[12:21], (3, 3)).tolist())
kappa[temp].append(np.reshape(d[21:30], (3, 3)).tolist())
# process raw Hall data
for d in data_hall:
temp, doping = d[1], d[2]
hall_tens = [np.reshape(d[3:12], (3, 3)).tolist(),
np.reshape(d[12:21], (3, 3)).tolist(),
np.reshape(d[21:30], (3, 3)).tolist()]
hall[temp].append(hall_tens)
# process doping conductivity data, etc.
for d in data_doping_full:
temp, doping, mu = d[0], d[1], d[-1]
pn = 'p' if doping > 0 else 'n'
mu_doping[pn][temp].append(Energy(mu, "Ry").to("eV"))
cond_doping[pn][temp].append(
np.reshape(d[2:11], (3, 3)).tolist())
seebeck_doping[pn][temp].append(
np.reshape(d[11:20], (3, 3)).tolist())
kappa_doping[pn][temp].append(
np.reshape(d[20:29], (3, 3)).tolist())
# process doping Hall data
for d in data_doping_hall:
temp, doping, mu = d[0], d[1], d[-1]
pn = 'p' if doping > 0 else 'n'
hall_tens = [np.reshape(d[2:11], (3, 3)).tolist(),
np.reshape(d[11:20], (3, 3)).tolist(),
np.reshape(d[20:29], (3, 3)).tolist()]
hall_doping[pn][temp].append(hall_tens)
return mu_steps, cond, seebeck, kappa, hall, pn_doping_levels, \
mu_doping, seebeck_doping, cond_doping, kappa_doping, \
hall_doping, carrier_conc
@staticmethod
def from_files(path_dir, dos_spin=1):
"""
get a BoltztrapAnalyzer object from a set of files
Args:
path_dir: directory where the boltztrap files are
dos_spin: in DOS mode, set to 1 for spin up and -1 for spin down
Returns:
a BoltztrapAnalyzer object
"""
run_type, warning, efermi, gap, doping_levels = \
BoltztrapAnalyzer.parse_outputtrans(path_dir)
vol = BoltztrapAnalyzer.parse_struct(path_dir)
intrans = BoltztrapAnalyzer.parse_intrans(path_dir)
if run_type == "BOLTZ":
dos, pdos = BoltztrapAnalyzer.parse_transdos(
path_dir, efermi, dos_spin=dos_spin, trim_dos=False)
mu_steps, cond, seebeck, kappa, hall, pn_doping_levels, mu_doping, \
seebeck_doping, cond_doping, kappa_doping, hall_doping, \
carrier_conc = BoltztrapAnalyzer. \
parse_cond_and_hall(path_dir, doping_levels)
return BoltztrapAnalyzer(
gap, mu_steps, cond, seebeck, kappa, hall, pn_doping_levels,
mu_doping, seebeck_doping, cond_doping, kappa_doping,
hall_doping, intrans, dos, pdos, carrier_conc, vol, warning)
elif run_type == "DOS":
trim = True if intrans["dos_type"] == "HISTO" else False
dos, pdos = BoltztrapAnalyzer.parse_transdos(
path_dir, efermi, dos_spin=dos_spin, trim_dos=trim)
return BoltztrapAnalyzer(gap=gap, dos=dos, dos_partial=pdos,
warning=warning, vol=vol)
elif run_type == "BANDS":
bz_kpoints = np.loadtxt(
os.path.join(path_dir, "boltztrap_band.dat"))[:, -3:]
bz_bands = np.loadtxt(
os.path.join(path_dir, "boltztrap_band.dat"))[:, 1:-6]
return BoltztrapAnalyzer(bz_bands=bz_bands, bz_kpoints=bz_kpoints,
warning=warning, vol=vol)
elif run_type == "FERMI":
"""
"""
if os.path.exists(os.path.join(path_dir, 'boltztrap_BZ.cube')):
fs_data = read_cube_file(
os.path.join(path_dir, 'boltztrap_BZ.cube'))
elif os.path.exists(os.path.join(path_dir, 'fort.30')):
fs_data = read_cube_file(os.path.join(path_dir, 'fort.30'))
else:
raise BoltztrapError("No data file found for fermi surface")
return BoltztrapAnalyzer(fermi_surface_data=fs_data)
else:
raise ValueError("Run type: {} not recognized!".format(run_type))
def as_dict(self):
results = {'gap': self.gap,
'mu_steps': self.mu_steps,
'scissor': self.intrans["scissor"],
'cond': self._cond,
'seebeck': self._seebeck,
'kappa': self._kappa,
'hall': self._hall,
'doping': self.doping,
'mu_doping': self.mu_doping,
'seebeck_doping': self._seebeck_doping,
'cond_doping': self._cond_doping,
'kappa_doping': self._kappa_doping,
'hall_doping': self._hall_doping,
'dos': self.dos.as_dict(),
'dos_partial': self._dos_partial,
'carrier_conc': self._carrier_conc,
'vol': self.vol,
'warning': self.warning}
return jsanitize(results)
@staticmethod
def from_dict(data):
def _make_float_array(a):
res = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
for i in range(3):
for j in range(3):
res[i][j] = float(a[i][j])
return res
def _make_float_hall(a):
return [i for i in a[:27]]
gap = data.get('gap')
mu_steps = [float(d) for d in data['mu_steps']] if \
'mu_steps' in data else None
cond = {int(d): [_make_float_array(v) for v in data['cond'][d]]
for d in data['cond']} if 'cond' in data else None
seebeck = {int(d): [_make_float_array(v) for v in data['seebeck'][d]]
for d in data['seebeck']} if 'seebeck' in data else None
kappa = {int(d): [_make_float_array(v) for v in data['kappa'][d]]
for d in data['kappa']} if 'kappa' in data else None
hall = {int(d): [_make_float_hall(v) for v in data['hall'][d]]
for d in data['hall']} if 'hall' in data else None
doping = {'p': [float(d) for d in data['doping']['p']],
'n': [float(d) for d in data['doping']['n']]} if \
'doping' in data else None
mu_doping = {'p': {int(d): [
float(v) for v in data['mu_doping']['p'][d]] for d in
data['mu_doping']['p']}, 'n':
{int(d): [float(v) for v in data['mu_doping']['n'][d]]
for d in data['mu_doping'][
'n']}} if 'mu_doping' in data else None
seebeck_doping = {'p': {int(d): [
_make_float_array(v) for v in data['seebeck_doping']['p'][d]]
for d in data['seebeck_doping']['p']}, 'n':
{int(d): [_make_float_array(v) for v in
data['seebeck_doping']['n'][d]] for d in
data['seebeck_doping'][
'n']}} if 'seebeck_doping' in data \
else None
cond_doping = {'p': {int(d): [_make_float_array(v)
for v in data['cond_doping']['p'][d]]
for d in data['cond_doping']['p']}, 'n':
{int(d): [_make_float_array(v) for v in
data['cond_doping']['n'][d]] for
d in data['cond_doping'][
'n']}} if 'cond_doping' in data else None
kappa_doping = {'p': {int(d): [_make_float_array(v)
for v in data['kappa_doping']['p'][d]]
for d in data['kappa_doping']['p']},
'n': {int(d): [_make_float_array(v) for v in
data['kappa_doping']['n'][d]]
for d in data['kappa_doping']['n']}} \
if 'kappa_doping' in data else None
hall_doping = {'p': {int(d): [_make_float_hall(v) for v in
data['hall_doping']['p'][d]] for d in
data['hall_doping']['p']}, 'n':
{int(d): [_make_float_hall(v) for v in
data['hall_doping']['n'][d]] for d in
data['hall_doping'][
'n']}} if "hall_doping" in data else None
dos = Dos.from_dict(data['dos']) if 'dos' in data else None
dos_partial = data.get('dos_partial')
carrier_conc = data.get('carrier_conc')
vol = data.get('vol')
warning = data.get('warning')
return BoltztrapAnalyzer(gap, mu_steps, cond, seebeck, kappa, hall,
doping, mu_doping, seebeck_doping,
cond_doping, kappa_doping, hall_doping, dos,
dos_partial, carrier_conc, vol, warning)
def read_cube_file(filename):
with open(filename, 'rt') as f:
natoms = 0
count_line = 0
for line in f:
line = line.rstrip("\n")
if count_line == 0 and "CUBE" not in line:
raise ValueError("CUBE file format not recognized")
if count_line == 2:
tokens = line.split()
natoms = int(tokens[0])
if count_line == 3:
tokens = line.split()
n1 = int(tokens[0])
elif count_line == 4:
tokens = line.split()
n2 = int(tokens[0])
elif count_line == 5:
tokens = line.split()
n3 = int(tokens[0])
elif count_line > 5:
break
count_line += 1
energy_data = np.loadtxt(filename, skiprows=natoms + 6).reshape(n1, n2, n3)
energy_data /= Energy(1, "eV").to("Ry")
return energy_data
def compare_sym_bands(bands_obj, bands_ref_obj, nb=None):
"""
Compute the mean of correlation between bzt and vasp bandstructure on
sym line, for all bands and locally (for each branches) the difference
squared (%) if nb is specified.
"""
nkpt = len(bands_obj.kpoints)
if bands_ref_obj.is_spin_polarized:
nbands = min(bands_obj.nb_bands, 2 * bands_ref_obj.nb_bands)
else:
# TODO: why is this needed? Shouldn't pmg take care of nb_bands?
nbands = min(len(bands_obj.bands[Spin.up]),
len(bands_ref_obj.bands[Spin.up]))
# print(nbands)
arr_bands = np.array(bands_obj.bands[Spin.up][:nbands])
# arr_bands_lavg = (arr_bands-np.mean(arr_bands,axis=1).reshape(nbands,1))
if bands_ref_obj.is_spin_polarized:
arr_bands_ref_up = np.array(bands_ref_obj.bands[Spin.up])
arr_bands_ref_dw = np.array(bands_ref_obj.bands[Spin.down])
# print(arr_bands_ref_up.shape)
arr_bands_ref = np.vstack((arr_bands_ref_up, arr_bands_ref_dw))
arr_bands_ref = np.sort(arr_bands_ref, axis=0)[:nbands]
# print(arr_bands_ref.shape)
else:
arr_bands_ref = np.array(bands_ref_obj.bands[Spin.up][:nbands])
# arr_bands_ref_lavg =
# (arr_bands_ref-np.mean(arr_bands_ref,axis=1).reshape(nbands,1))
# err = np.sum((arr_bands_lavg-arr_bands_ref_lavg)**2,axis=1)/nkpt
corr = np.array(
[distance.correlation(arr_bands[idx], arr_bands_ref[idx]) for idx in
range(nbands)])
if type(nb) == int: nb = [nb]
bcheck = {}
if max(nb) < nbands:
branches = [[s['start_index'], s['end_index'], s['name']] for s in
bands_ref_obj.branches]
if not bands_obj.is_metal() and not bands_ref_obj.is_metal():
zero_ref = bands_ref_obj.get_vbm()['energy']
zero = bands_obj.get_vbm()['energy']
if not zero:
vbm = bands_ref_obj.get_vbm()['band_index'][Spin.up][-1]
zero = max(arr_bands[vbm])
else:
zero_ref = 0 # bands_ref_obj.efermi
zero = 0 # bands_obj.efermi
print(zero, zero_ref)
for nbi in nb:
bcheck[nbi] = {}
bcheck[nbi]['Dist'] = np.mean(abs(arr_bands[nbi] - zero
- arr_bands_ref[nbi] + zero_ref))
bcheck[nbi]['Corr'] = corr[nbi]
for start, end, name in branches:
# werr.append((sum((arr_bands_corr[nb][start:end+1] -
# arr_bands_ref_corr[nb][start:end+1])**2)/(end+1-start)*100,name))
bcheck[nbi][name] = np.mean(abs(arr_bands[nbi][start:end + 1]
- zero
- arr_bands_ref[nbi][
start:end + 1] + zero_ref))
else:
bcheck = "No nb given"
return bcheck
| tallakahath/pymatgen | pymatgen/electronic_structure/boltztrap.py | Python | mit | 94,779 | [
"BoltzTrap",
"VASP",
"pymatgen"
] | 2ae547e44f95beb9f2d5f95e66fc9b9c81fac71c90f9c3fcbfd35feddded2d01 |
import sys
from string import Template
from collections import namedtuple
from pycparser import c_parser, c_ast, parse_file
Func = namedtuple('Func', ('name', 'type', 'args'))
Arg = namedtuple('Arg', ('name', 'type'))
Type = namedtuple('Type', ('ptr', 'name', 'array'))
class FuncDeclVisitor(c_ast.NodeVisitor):
def __init__(self):
self.funcs = []
self.reset()
def reset(self):
self.name = None
self.ptr = ''
self.type = None
self.inargs = False
self.args = []
self.argname = None
self.array = False
def visit_Typedef(self, node):
# Prevent func decls in typedefs from being visited
pass
def visit_FuncDecl(self, node):
self.visit(node.type)
if node.args:
self.inargs = True
self.visit(node.args)
self.funcs.append(Func(self.name, self.type, self.args))
self.reset()
def visit_PtrDecl(self, node):
self.ptr += '*'
self.visit(node.type)
def visit_TypeDecl(self, node):
if node.type.__class__.__name__ == 'Struct':
return
if self.inargs:
self.argname = node.declname
else:
self.name = node.declname
self.visit(node.type)
def visit_ArrayDecl(self, node):
self.array = True
self.visit(node.type)
def visit_IdentifierType(self, node):
type_ = Type(self.ptr, ' '.join(node.names), self.array)
if self.inargs:
self.args.append(Arg(self.argname, type_))
else:
self.type = type_
self.ptr = ''
self.array = False
def cgo_func_wrappers(filename):
ast = parse_file(filename, use_cpp=True)
v = FuncDeclVisitor()
v.visit(ast)
funcnames = {}
threadsafe = []
for func in v.funcs:
funcnames[func.name] = func
for func in v.funcs:
if not func.name.endswith('_r'):
if func.name + '_r' in funcnames:
threadsafe.append(funcnames[func.name + '_r'])
else:
threadsafe.append(func)
print("""
package geos
// Created mechanically from C API header - DO NOT EDIT
/*
#include <geos_c.h>
*/
import "C"
import (
"unsafe"
)\
""")
typemap = {
"unsigned char": "uchar",
"unsigned int": "uint",
}
identmap = {
"type": "_type",
}
for func in threadsafe:
def gotype(ctype):
type_ = "C." + typemap.get(ctype.name, ctype.name)
if ctype.ptr:
type_ = ctype.ptr + type_
if ctype.array:
type_ = '[]' + type_
return type_
def goident(arg, inbody=True):
def voidptr(ctype):
return ctype.ptr and ctype.name == 'void'
ident = identmap.get(arg.name, arg.name)
if arg.type.array and inbody:
ident = '&' + ident + '[0]'
if voidptr(arg.type) and inbody:
ident = 'unsafe.Pointer(' + ident + ')'
return ident
# Go function signature
gosig = "func $name($parameters)"
if func.type.name != "void":
gosig += " $result"
gosig += " {"
t = Template(gosig)
params = ", ".join([goident(p, inbody=False) + " " + gotype(p.type) for p in func.args if p.type.name != 'GEOSContextHandle_t'])
result = gotype(func.type)
func_name = "c" + func.name
if func_name.endswith('_r'):
func_name = func_name[:-2]
print(t.substitute(name=func_name, parameters=params, result=result))
# Go function body
gobody = """\
\t${return_stmt}C.$name($args)
}
"""
if func.name.endswith("_r") and func.name != "initGEOS_r":
gobody = """\
\t${handle_lock}.Lock()
\tdefer ${handle_lock}.Unlock()
""" + gobody
t = Template(gobody)
args = ", ".join([goident(p) for p in func.args])
return_stmt = 'return ' if func.type.name != 'void' else ''
print(t.substitute(return_stmt=return_stmt, name=func.name, args=args, handle_lock='handlemu'))
if __name__ == "__main__":
cgo_func_wrappers(sys.argv[1])
#from pycparser.c_generator import CGenerator
#ast = parse_file(sys.argv[1], use_cpp=True)
#print(CGenerator().visit(ast))
| helmi03/gogeos | geos/geoscapi.py | Python | mit | 4,354 | [
"VisIt"
] | 32dc88b1ef39e6a73f5b5fe269b61e4e006a91d0f212d4b194d626e4ed48886c |
#
# Copyright 2014-2015, 2020 Lars Pastewka (U. Freiburg)
# 2014 James Kermode (Warwick U.)
#
# matscipy - Materials science with Python at the atomic-scale
# https://github.com/libAtoms/matscipy
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# ======================================================================
# matscipy - Python materials science tools
# https://github.com/libAtoms/matscipy
#
# Copyright (2014) James Kermode, King's College London
# Lars Pastewka, Karlsruhe Institute of Technology
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ======================================================================
import unittest
import numpy as np
import matscipytest
import matscipy.contact_mechanics.Hertz as Hertz
###
class TestHertz(matscipytest.MatSciPyTestCase):
def test_Hertz_centerline_stress(self):
z = np.linspace(0.0, 5.0, 101)
for nu in [ 0.3, 0.5 ]:
srr1, szz1 = Hertz.centerline_stress(z, poisson=nu)
stt2, srr2, szz2, srz2 = Hertz.stress(np.zeros_like(z), z, poisson=nu)
self.assertTrue(np.max(np.abs(srr1-srr2)) < 1e-6)
self.assertTrue(np.max(np.abs(srr1-stt2)) < 1e-6)
self.assertTrue(np.max(np.abs(szz1-szz2)) < 1e-6)
def test_Hertz_surface_stress(self):
r = np.linspace(0.0, 5.0, 101)
for nu in [ 0.3, 0.5 ]:
pzz1, srr1, stt1 = Hertz.surface_stress(r, poisson=nu)
stt2, srr2, szz2, srz2 = Hertz.stress(r, np.zeros_like(r), poisson=nu)
self.assertTrue(np.max(np.abs(pzz1+szz2)) < 1e-6)
self.assertTrue(np.max(np.abs(srr1-srr2)) < 1e-6)
self.assertTrue(np.max(np.abs(stt1-stt2)) < 1e-6)
def test_Hertz_subsurface_stress(self):
nx = 51 # Grid size
a = 32. # Contact radius
y = np.linspace(0, 3*a, nx)
z = np.linspace(0, 3*a, nx)
y, z = np.meshgrid(y, z)
x = np.zeros_like(y)
# nu: Poisson
for nu in [0.3, 0.5]:
sxx, syy, szz, syz, sxz, sxy = \
Hertz.stress_Cartesian(x/a, y/a, z/a, poisson=nu)
r_sq = (x**2 + y**2)/a**2
stt2, srr2, szz2, srz2 = \
Hertz.stress(np.sqrt(r_sq), z/a, poisson=nu)
self.assertTrue(np.max(np.abs(sxx-stt2)) < 1e-12)
self.assertTrue(np.max(np.abs(syy-srr2)) < 1e-12)
self.assertTrue(np.max(np.abs(szz-szz2)) < 1e-12)
self.assertTrue(np.max(np.abs(syz-srz2)) < 1e-12)
###
if __name__ == '__main__':
unittest.main()
| libAtoms/matscipy | tests/test_hertz.py | Python | lgpl-2.1 | 3,746 | [
"Matscipy"
] | de087a97904d896a55d97104910151d15df69a3f91d4bda7789717eb450e9740 |
import pathlib
import platform
import numpy as np
import pytest
import vtk
import pyvista
from pyvista import PolyData, RectilinearGrid, UniformGrid, StructuredGrid, MultiBlock
from pyvista import examples as ex
skip_mac = pytest.mark.skipif(platform.system() == 'Darwin', reason="Flaky Mac tests")
@pytest.fixture()
def vtk_multi():
return vtk.vtkMultiBlockDataSet()
@pytest.fixture()
def pyvista_multi():
return pyvista.MultiBlock
def multi_from_datasets(*datasets):
"""Return pyvista multiblock composed of any number of datasets."""
return MultiBlock([*datasets])
def test_multi_block_init_vtk():
multi = vtk.vtkMultiBlockDataSet()
multi.SetBlock(0, vtk.vtkRectilinearGrid())
multi.SetBlock(1, vtk.vtkStructuredGrid())
multi = MultiBlock(multi)
assert isinstance(multi, MultiBlock)
assert multi.n_blocks == 2
assert isinstance(multi.GetBlock(0), RectilinearGrid)
assert isinstance(multi.GetBlock(1), StructuredGrid)
multi = vtk.vtkMultiBlockDataSet()
multi.SetBlock(0, vtk.vtkRectilinearGrid())
multi.SetBlock(1, vtk.vtkStructuredGrid())
multi = MultiBlock(multi, deep=True)
assert isinstance(multi, MultiBlock)
assert multi.n_blocks == 2
assert isinstance(multi.GetBlock(0), RectilinearGrid)
assert isinstance(multi.GetBlock(1), StructuredGrid)
# Test nested structure
multi = vtk.vtkMultiBlockDataSet()
multi.SetBlock(0, vtk.vtkRectilinearGrid())
multi.SetBlock(1, vtk.vtkImageData())
nested = vtk.vtkMultiBlockDataSet()
nested.SetBlock(0, vtk.vtkUnstructuredGrid())
nested.SetBlock(1, vtk.vtkStructuredGrid())
multi.SetBlock(2, nested)
# Wrap the nested structure
multi = MultiBlock(multi)
assert isinstance(multi, MultiBlock)
assert multi.n_blocks == 3
assert isinstance(multi.GetBlock(0), RectilinearGrid)
assert isinstance(multi.GetBlock(1), UniformGrid)
assert isinstance(multi.GetBlock(2), MultiBlock)
def test_multi_block_init_dict(rectilinear, airplane):
data = {'grid': rectilinear, 'poly': airplane}
multi = MultiBlock(data)
assert isinstance(multi, MultiBlock)
assert multi.n_blocks == 2
# Note that dictionaries do not maintain order
assert isinstance(multi.GetBlock(0), (RectilinearGrid, PolyData))
assert multi.get_block_name(0) in ['grid','poly']
assert isinstance(multi.GetBlock(1), (RectilinearGrid, PolyData))
assert multi.get_block_name(1) in ['grid','poly']
def test_multi_block_keys(rectilinear, airplane):
data = {'grid': rectilinear, 'poly': airplane}
multi = MultiBlock(data)
assert len(multi.keys()) == 2
assert 'grid' in multi.keys()
assert 'poly' in multi.keys()
def test_multi_block_init_list(rectilinear, airplane):
data = [rectilinear, airplane]
multi = MultiBlock(data)
assert isinstance(multi, MultiBlock)
assert multi.n_blocks == 2
assert isinstance(multi.GetBlock(0), RectilinearGrid)
assert isinstance(multi.GetBlock(1), PolyData)
def test_multi_block_append(ant, sphere, uniform, airplane, rectilinear):
"""This puts all of the example data objects into a a MultiBlock container"""
multi = MultiBlock()
# Add and test examples
datasets = (ant, sphere, uniform, airplane, rectilinear)
for i, dataset in enumerate(datasets):
multi.append(dataset)
assert multi.n_blocks == i + 1
assert isinstance(multi[i], type(dataset))
assert multi.bounds is not None
# Now overwrite a block
multi[4] = pyvista.Sphere()
assert isinstance(multi[4], PolyData)
multi[4] = vtk.vtkUnstructuredGrid()
assert isinstance(multi[4], pyvista.UnstructuredGrid)
def test_multi_block_set_get_ers():
"""This puts all of the example data objects into a a MultiBlock container"""
multi = MultiBlock()
# Set the number of blocks
multi.n_blocks = 6
assert multi.GetNumberOfBlocks() == 6 # Check that VTK side registered it
assert multi.n_blocks == 6 # Check pyvista side registered it
# Add data to the MultiBlock
data = ex.load_rectilinear()
multi[1, 'rect'] = data
# Make sure number of blocks is constant
assert multi.n_blocks == 6
# Check content
assert isinstance(multi[1], RectilinearGrid)
for i in [0,2,3,4,5]:
assert multi[i] is None
# Check the bounds
assert multi.bounds == list(data.bounds)
multi[5] = ex.load_uniform()
multi.set_block_name(5, 'uni')
multi.set_block_name(5, None) # Make sure it doesn't get overwritten
assert isinstance(multi.get(5), UniformGrid)
# Test get by name
assert isinstance(multi['uni'], UniformGrid)
assert isinstance(multi['rect'], RectilinearGrid)
# Test the del operator
del multi[0]
assert multi.n_blocks == 5
# Make sure the rect grid was moved up
assert isinstance(multi[0], RectilinearGrid)
assert multi.get_block_name(0) == 'rect'
assert multi.get_block_name(2) == None
# test del by name
del multi['uni']
assert multi.n_blocks == 4
# test the pop operator
pop = multi.pop(0)
assert isinstance(pop, RectilinearGrid)
assert multi.n_blocks == 3
assert multi.get_block_name(10) is None
with pytest.raises(KeyError):
_ = multi.get_index_by_name('foo')
# allow Sequence but not Iterable in setitem
with pytest.raises(TypeError):
multi[{1, 'foo'}] = data
def test_multi_block_clean(rectilinear, uniform, ant):
# now test a clean of the null values
multi = MultiBlock()
multi[1, 'rect'] = rectilinear
multi[2, 'empty'] = PolyData()
multi[3, 'mempty'] = MultiBlock()
multi[5, 'uni'] = uniform
# perform the clean to remove all Null elements
multi.clean()
assert multi.n_blocks == 2
assert multi.GetNumberOfBlocks() == 2
assert isinstance(multi[0], RectilinearGrid)
assert isinstance(multi[1], UniformGrid)
assert multi.get_block_name(0) == 'rect'
assert multi.get_block_name(1) == 'uni'
# Test a nested data struct
foo = MultiBlock()
foo[3] = ant
assert foo.n_blocks == 4
multi = MultiBlock()
multi[1, 'rect'] = rectilinear
multi[5, 'multi'] = foo
# perform the clean to remove all Null elements
assert multi.n_blocks == 6
multi.clean()
assert multi.n_blocks == 2
assert multi.GetNumberOfBlocks() == 2
assert isinstance(multi[0], RectilinearGrid)
assert isinstance(multi[1], MultiBlock)
assert multi.get_block_name(0) == 'rect'
assert multi.get_block_name(1) == 'multi'
assert foo.n_blocks == 1
def test_multi_block_repr(ant, sphere, uniform, airplane):
multi = multi_from_datasets(ant, sphere, uniform, airplane, None)
# Now check everything
assert multi.n_blocks == 5
assert multi._repr_html_() is not None
assert repr(multi) is not None
assert str(multi) is not None
@pytest.mark.parametrize('binary', [True, False])
@pytest.mark.parametrize('extension', pyvista.core.composite.MultiBlock._WRITERS)
@pytest.mark.parametrize('use_pathlib', [True, False])
def test_multi_block_io(extension, binary, tmpdir, use_pathlib, ant,
sphere, uniform, airplane, globe):
filename = str(tmpdir.mkdir("tmpdir").join(f'tmp.{extension}'))
if use_pathlib:
pathlib.Path(filename)
multi = multi_from_datasets(ant, sphere, uniform, airplane, globe)
# Now check everything
assert multi.n_blocks == 5
# Save it out
multi.save(filename, binary)
foo = MultiBlock(filename)
assert foo.n_blocks == multi.n_blocks
foo = pyvista.read(filename)
assert foo.n_blocks == multi.n_blocks
@skip_mac # fails due to download examples
@pytest.mark.parametrize('binary', [True, False])
@pytest.mark.parametrize('extension', ['vtm', 'vtmb'])
def test_ensight_multi_block_io(extension, binary, tmpdir, ant,
sphere, uniform, airplane, globe):
filename = str(tmpdir.mkdir("tmpdir").join('tmp.%s' % extension))
# multi = ex.load_bfs() # .case file
multi = ex.download_backward_facing_step() # .case file
# Now check everything
assert multi.n_blocks == 4
array_names = ['v2', 'nut', 'k', 'nuTilda', 'p', 'omega', 'f', 'epsilon', 'U']
for block in multi:
assert block.array_names == array_names
# Save it out
multi.save(filename, binary)
foo = MultiBlock(filename)
assert foo.n_blocks == multi.n_blocks
for block in foo:
assert block.array_names == array_names
foo = pyvista.read(filename)
assert foo.n_blocks == multi.n_blocks
for block in foo:
assert block.array_names == array_names
def test_invalid_arg():
with pytest.raises(TypeError):
pyvista.MultiBlock(np.empty(10))
with pytest.raises(ValueError):
pyvista.MultiBlock(np.empty(10), np.empty(10))
def test_multi_io_erros(tmpdir):
fdir = tmpdir.mkdir("tmpdir")
multi = MultiBlock()
# Check saving with bad extension
bad_ext_name = str(fdir.join('tmp.npy'))
with pytest.raises(ValueError):
multi.save(bad_ext_name)
arr = np.random.rand(10, 10)
np.save(bad_ext_name, arr)
# Load non existing file
with pytest.raises(FileNotFoundError):
_ = MultiBlock('foo.vtm')
# Load bad extension
with pytest.raises(IOError):
_ = MultiBlock(bad_ext_name)
def test_extract_geometry(ant, sphere, uniform, airplane, globe):
multi = multi_from_datasets(ant, sphere, uniform)
nested = multi_from_datasets(airplane, globe)
multi.append(nested)
# Now check everything
assert multi.n_blocks == 4
# Now apply the geometry filter to combine a plethora of data blocks
geom = multi.extract_geometry()
assert isinstance(geom, PolyData)
def test_combine_filter(ant, sphere, uniform, airplane, globe):
multi = multi_from_datasets(ant, sphere, uniform)
nested = multi_from_datasets(airplane, globe)
multi.append(nested)
# Now check everything
assert multi.n_blocks == 4
# Now apply the append filter to combine a plethora of data blocks
geom = multi.combine()
assert isinstance(geom, pyvista.UnstructuredGrid)
def test_multi_block_copy(ant, sphere, uniform, airplane, globe):
multi = multi_from_datasets(ant, sphere, uniform, airplane, globe)
# Now check everything
multi_copy = multi.copy()
assert multi.n_blocks == 5 == multi_copy.n_blocks
assert id(multi[0]) != id(multi_copy[0])
assert id(multi[-1]) != id(multi_copy[-1])
for i in range(multi_copy.n_blocks):
assert pyvista.is_pyvista_dataset(multi_copy.GetBlock(i))
# Now check shallow
multi_copy = multi.copy(deep=False)
assert multi.n_blocks == 5 == multi_copy.n_blocks
assert id(multi[0]) == id(multi_copy[0])
assert id(multi[-1]) == id(multi_copy[-1])
for i in range(multi_copy.n_blocks):
assert pyvista.is_pyvista_dataset(multi_copy.GetBlock(i))
def test_multi_block_negative_index(ant, sphere, uniform, airplane, globe):
multi = multi_from_datasets(ant, sphere, uniform, airplane, globe)
# Now check everything
assert id(multi[-1]) == id(multi[4])
assert id(multi[-2]) == id(multi[3])
assert id(multi[-3]) == id(multi[2])
assert id(multi[-4]) == id(multi[1])
assert id(multi[-5]) == id(multi[0])
with pytest.raises(IndexError):
_ = multi[-6]
def test_multi_slice_index(ant, sphere, uniform, airplane, globe):
multi = multi_from_datasets(ant, sphere, uniform, airplane, globe)
# Now check everything
sub = multi[0:3]
assert len(sub) == 3
for i in range(3):
assert id(sub[i]) == id(multi[i])
assert sub.get_block_name(i) == multi.get_block_name(i)
sub = multi[0:-1]
assert len(sub) == len(multi) == multi.n_blocks
for i in range(multi.n_blocks):
assert id(sub[i]) == id(multi[i])
assert sub.get_block_name(i) == multi.get_block_name(i)
sub = multi[0:-1:2]
assert len(sub) == 3
for i in range(3):
j = i*2
assert id(sub[i]) == id(multi[j])
assert sub.get_block_name(i) == multi.get_block_name(j)
def test_multi_block_list_index(ant, sphere, uniform, airplane, globe):
multi = multi_from_datasets(ant, sphere, uniform, airplane, globe)
# Now check everything
indices = [0, 3, 4]
sub = multi[indices]
assert len(sub) == len(indices)
for i, j in enumerate(indices):
assert id(sub[i]) == id(multi[j])
assert sub.get_block_name(i) == multi.get_block_name(j)
# check list of key names
multi = MultiBlock()
multi["foo"] = pyvista.Sphere()
multi["goo"] = pyvista.Box()
multi["soo"] = pyvista.Cone()
indices = ["goo", "foo"]
sub = multi[indices]
assert len(sub) == len(indices)
assert isinstance(sub["foo"], PolyData)
def test_multi_block_volume(ant, airplane, sphere, uniform):
multi = multi_from_datasets(ant, sphere, uniform, airplane, None)
assert multi.volume
def test_multi_block_length(ant, sphere, uniform, airplane):
multi = multi_from_datasets(ant, sphere, uniform, airplane, None)
assert multi.length
def test_multi_block_save_lines(tmpdir):
radius = 1
xr = np.random.random(10)
yr = np.random.random(10)
x = radius * np.sin(yr) * np.cos(xr)
y = radius * np.sin(yr) * np.sin(xr)
z = radius * np.cos(yr)
xyz = np.stack((x, y, z), axis=1)
poly = pyvista.lines_from_points(xyz, close=False)
blocks = pyvista.MultiBlock()
for _ in range(2):
blocks.append(poly)
path = tmpdir.mkdir("tmpdir")
line_filename = str(path.join('lines.vtk'))
block_filename = str(path.join('blocks.vtmb'))
poly.save(line_filename)
blocks.save(block_filename)
poly_load = pyvista.read(line_filename)
assert np.allclose(poly_load.points, poly.points)
blocks_load = pyvista.read(block_filename)
assert np.allclose(blocks_load[0].points, blocks[0].points)
def test_multi_block_data_range():
volume = pyvista.Wavelet()
a = volume.slice_along_axis(5,'x')
with pytest.raises(ValueError):
a.get_data_range('foo')
mi, ma = a.get_data_range(volume.active_scalars_name)
assert mi is not None
assert ma is not None
# Test on a nested MultiBlock
b = volume.slice_along_axis(5,'y')
slices = pyvista.MultiBlock([a,b])
with pytest.raises(ValueError):
slices.get_data_range('foo')
mi, ma = slices.get_data_range(volume.active_scalars_name)
assert mi is not None
assert ma is not None
| akaszynski/vtkInterface | tests/test_composite.py | Python | mit | 14,505 | [
"VTK"
] | 0fbe3a9a1efd85a8bafd5a118902b9f3cbcccff9c7bfcecb5906b3c654296a4c |
# Copyright(c) 2014, The LIMIX developers (Christoph Lippert, Paolo Francesco Casale, Oliver Stegle)
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
"""preprocessing functions"""
import scipy as SP
import scipy.special as special
import scipy.stats as st
import pdb
def variance_K(K, verbose=False):
"""estimate the variance explained by K"""
c = SP.sum((SP.eye(len(K)) - (1.0 / len(K)) * SP.ones(K.shape)) * SP.array(K))
scalar = (len(K) - 1) / c
return 1.0/scalar
def scale_K(K, verbose=False,trace_method=True):
"""scale covariance K such that it explains unit variance
trace_method: standardize to unit trace (deafault: True)
"""
if trace_method:
scalar=1.0/(K.diagonal().mean())
else:
c = SP.sum((SP.eye(len(K)) - (1.0 / len(K)) * SP.ones(K.shape)) * SP.array(K))
scalar = (len(K) - 1) / c
if verbose:
print(('Kinship scaled by: %0.4f' % scalar))
K = K * scalar
return K
def standardize(Y,in_place=False):
"""
standardize Y in a way that is robust to missing values
in_place: create a copy or carry out inplace opreations?
"""
if in_place:
YY = Y
else:
YY = Y.copy()
for i in range(YY.shape[1]):
Iok = ~SP.isnan(YY[:,i])
Ym = YY[Iok,i].mean()
YY[:,i]-=Ym
Ys = YY[Iok,i].std()
YY[:,i]/=Ys
return YY
def rankStandardizeNormal(X):
"""
Gaussianize X: [samples x phenotypes]
- each phentoype is converted to ranks and transformed back to normal using the inverse CDF
"""
Is = X.argsort(axis=0)
RV = SP.zeros_like(X)
rank = SP.zeros_like(X)
for i in range(X.shape[1]):
x = X[:,i]
i_nan = SP.isnan(x)
if 0:
Is = x.argsort()
rank = SP.zeros_like(x)
rank[Is] = SP.arange(X.shape[0])
#add one to ensure nothing = 0
rank +=1
else:
rank = st.rankdata(x[~i_nan])
#devide by (N+1) which yields uniform [0,1]
rank /= ((~i_nan).sum()+1)
#apply inverse gaussian cdf
RV[~i_nan,i] = SP.sqrt(2) * special.erfinv(2*rank-1)
RV[i_nan,i] = x[i_nan]
return RV
def boxcox(X):
"""
Gaussianize X using the Box-Cox transformation: [samples x phenotypes]
- each phentoype is brought to a positive schale, by first subtracting the minimum value and adding 1.
- Then each phenotype transformed by the boxcox transformation
"""
X_transformed = SP.zeros_like(X)
maxlog = SP.zeros(X.shape[1])
for i in range(X.shape[1]):
i_nan = SP.isnan(X[:,i])
values = X[~i_nan,i]
X_transformed[i_nan,i] = X[i_nan,i]
X_transformed[~i_nan,i], maxlog[i] = st.boxcox(values-values.min()+1.0)
return X_transformed, maxlog
| PMBio/limix | limix/deprecated/utils/preprocess.py | Python | apache-2.0 | 3,121 | [
"Gaussian"
] | 24c8f8b91c950876996189504dd0339083aa2d06f57e5aa5bd94940c2988a121 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) 2012 Michael Hull.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------
""" Object-models for morphology representations.
"""
docs = """
Dual-Represention of morphologies
-----------------------------------
In morphforge, as in many other tools, morphologies are represented as a tree of joined conical frustra (cylinders with different radii ends).
.. figure:: /img_srcs/new_morphology_original.svg
:align: center
Figure 1A shows a projection of an original neuron morphology,
In figure 1B, the morphology is approximated as a set of conical frustra. At every joining point of multiple frustra, the radii are the same.
There are 2 ways of considering these sets of frustra:
* **TreeBased:** As a tree of *Sections* (Figure 1C).
* **VertexBased:** As a set of vertices and a set of connections between them.
Underneath, these two representations contain the same information, but the different object model representations have strengths for different tasks.
In morphforge, they are represented as two different classes: :py:class:`~.core.tree.MorphologyTree` and :py:class:`~.core.array.MorphologyArray`.
* **TreeBased:** (:py:class:`~.core.tree.MorphologyTree`) is arguably more intuitive to read. It is also what the :py:mod:`morphforge.simulation` layer handles.
* **VertexBased:** (:py:class:`~.core.array.MorphologyArray`) is more efficient in speed & memory size for large morphologies.
For more information about the representations, see the documentation for the submodules :py:mod:`~.core.tree` and :py:mod:`~.core.array`
Converting between representations
-----------------------------------
In general, you will only need to use one of the two representations, depending on what your are doing. However, :py:class:`~.core.tree.MorphologyTree` and :py:class:`~.core.array.MorphologyArray` objects can be converted to each type using the methods "to_array()" and "to_tree()".
.. code-block:: python
# Load a MorphArray object and convert
# it to MorphTree object
morph_array = MorphArray.fromSWC(...)
morph_tree = morph_array.to_array()
# Vice-Versa
morph_tree2 = MorphTree.fromSWC(...)
morph_array = morph_tree2.to_array()
# Trying to convert an object to its own
# type returns the original object:
morph_tree3 = morph_tree2.to_tree()
assert morph_tree3 is morphtree2
"""
from morphforge.morphology.core.tree import MorphologyTree, Section, Region
from morphforge.morphology.core.tree import MorphLocation
from morphforge.morphology.core.tree import MorphPath
from morphforge.morphology.core.array import MorphologyArray
__all__ = [
'MorphologyTree',
'Section',
'Region',
'MorphLocation',
'MorphologyArray',
'MorphPath',
]
| mikehulluk/morphforge | src/morphforge/morphology/core/__init__.py | Python | bsd-2-clause | 4,204 | [
"NEURON"
] | 3d528feefcc65563ef50f3863b6a2af1a876b8866d68f745be79fb535c2536e0 |
# -*- coding: utf-8 -*-
"""
End-to-end tests for the Account Settings page.
"""
from unittest import skip
from nose.plugins.attrib import attr
from bok_choy.web_app_test import WebAppTest
from bok_choy.page_object import XSS_INJECTION
from ...pages.lms.account_settings import AccountSettingsPage
from ...pages.lms.auto_auth import AutoAuthPage
from ...pages.lms.dashboard import DashboardPage
from ..helpers import EventsTestMixin
class AccountSettingsTestMixin(EventsTestMixin, WebAppTest):
"""
Mixin with helper methods to test the account settings page.
"""
CHANGE_INITIATED_EVENT_NAME = u"edx.user.settings.change_initiated"
USER_SETTINGS_CHANGED_EVENT_NAME = 'edx.user.settings.changed'
ACCOUNT_SETTINGS_REFERER = u"/account/settings"
def visit_account_settings_page(self):
"""
Visit the account settings page for the current user, and store the page instance
as self.account_settings_page.
"""
# pylint: disable=attribute-defined-outside-init
self.account_settings_page = AccountSettingsPage(self.browser)
self.account_settings_page.visit()
self.account_settings_page.wait_for_ajax()
def log_in_as_unique_user(self, email=None, full_name=None):
"""
Create a unique user and return the account's username and id.
"""
username = "test_{uuid}".format(uuid=self.unique_id[0:6])
auto_auth_page = AutoAuthPage(self.browser, username=username, email=email, full_name=full_name).visit()
user_id = auto_auth_page.get_user_id()
return username, user_id
def settings_changed_event_filter(self, event):
"""Filter out any events that are not "settings changed" events."""
return event['event_type'] == self.USER_SETTINGS_CHANGED_EVENT_NAME
def expected_settings_changed_event(self, setting, old, new, table=None):
"""A dictionary representing the expected fields in a "settings changed" event."""
return {
'username': self.username,
'referer': self.get_settings_page_url(),
'event': {
'user_id': self.user_id,
'setting': setting,
'old': old,
'new': new,
'truncated': [],
'table': table or 'auth_userprofile'
}
}
def settings_change_initiated_event_filter(self, event):
"""Filter out any events that are not "settings change initiated" events."""
return event['event_type'] == self.CHANGE_INITIATED_EVENT_NAME
def expected_settings_change_initiated_event(self, setting, old, new, username=None, user_id=None):
"""A dictionary representing the expected fields in a "settings change initiated" event."""
return {
'username': username or self.username,
'referer': self.get_settings_page_url(),
'event': {
'user_id': user_id or self.user_id,
'setting': setting,
'old': old,
'new': new,
}
}
def get_settings_page_url(self):
"""The absolute URL of the account settings page given the test context."""
return self.relative_path_to_absolute_uri(self.ACCOUNT_SETTINGS_REFERER)
def assert_no_setting_changed_event(self):
"""Assert no setting changed event has been emitted thus far."""
self.assert_no_matching_events_were_emitted({'event_type': self.USER_SETTINGS_CHANGED_EVENT_NAME})
@attr('shard_8')
class DashboardMenuTest(AccountSettingsTestMixin, WebAppTest):
"""
Tests that the dashboard menu works correctly with the account settings page.
"""
def test_link_on_dashboard_works(self):
"""
Scenario: Verify that the "Account" link works from the dashboard.
Given that I am a registered user
And I visit my dashboard
And I click on "Account" in the top drop down
Then I should see my account settings page
"""
self.log_in_as_unique_user()
dashboard_page = DashboardPage(self.browser)
dashboard_page.visit()
dashboard_page.click_username_dropdown()
self.assertIn('Account', dashboard_page.username_dropdown_link_text)
dashboard_page.click_account_settings_link()
@attr('shard_8')
class AccountSettingsPageTest(AccountSettingsTestMixin, WebAppTest):
"""
Tests that verify behaviour of the Account Settings page.
"""
SUCCESS_MESSAGE = 'Your changes have been saved.'
def setUp(self):
"""
Initialize account and pages.
"""
super(AccountSettingsPageTest, self).setUp()
self.full_name = XSS_INJECTION
self.username, self.user_id = self.log_in_as_unique_user(full_name=self.full_name)
self.visit_account_settings_page()
def test_page_view_event(self):
"""
Scenario: An event should be recorded when the "Account Settings"
page is viewed.
Given that I am a registered user
And I visit my account settings page
Then a page view analytics event should be recorded
"""
actual_events = self.wait_for_events(
event_filter={'event_type': 'edx.user.settings.viewed'}, number_of_matches=1)
self.assert_events_match(
[
{
'event': {
'user_id': self.user_id,
'page': 'account',
'visibility': None
}
}
],
actual_events
)
def test_all_sections_and_fields_are_present(self):
"""
Scenario: Verify that all sections and fields are present on the page.
"""
expected_sections_structure = [
{
'title': 'Basic Account Information',
'fields': [
'Username',
'Full Name',
'Email Address',
'Password',
'Language',
'Country or Region'
]
},
{
'title': 'Additional Information',
'fields': [
'Education Completed',
'Gender',
'Year of Birth',
'Preferred Language',
]
}
]
self.assertEqual(self.account_settings_page.sections_structure(), expected_sections_structure)
def _test_readonly_field(self, field_id, title, value):
"""
Test behavior of a readonly field.
"""
self.assertEqual(self.account_settings_page.title_for_field(field_id), title)
self.assertEqual(self.account_settings_page.value_for_readonly_field(field_id), value)
def _test_text_field(
self, field_id, title, initial_value, new_invalid_value, new_valid_values, success_message=SUCCESS_MESSAGE,
assert_after_reload=True
):
"""
Test behaviour of a text field.
"""
self.assertEqual(self.account_settings_page.title_for_field(field_id), title)
self.assertEqual(self.account_settings_page.value_for_text_field(field_id), initial_value)
self.assertEqual(
self.account_settings_page.value_for_text_field(field_id, new_invalid_value), new_invalid_value
)
self.account_settings_page.wait_for_indicator(field_id, 'validation-error')
self.browser.refresh()
self.assertNotEqual(self.account_settings_page.value_for_text_field(field_id), new_invalid_value)
for new_value in new_valid_values:
self.assertEqual(self.account_settings_page.value_for_text_field(field_id, new_value), new_value)
self.account_settings_page.wait_for_message(field_id, success_message)
if assert_after_reload:
self.browser.refresh()
self.assertEqual(self.account_settings_page.value_for_text_field(field_id), new_value)
def _test_dropdown_field(
self, field_id, title, initial_value, new_values, success_message=SUCCESS_MESSAGE, reloads_on_save=False
):
"""
Test behaviour of a dropdown field.
"""
self.assertEqual(self.account_settings_page.title_for_field(field_id), title)
self.assertEqual(self.account_settings_page.value_for_dropdown_field(field_id), initial_value)
for new_value in new_values:
self.assertEqual(self.account_settings_page.value_for_dropdown_field(field_id, new_value), new_value)
# An XHR request is made when changing the field
self.account_settings_page.wait_for_ajax()
if reloads_on_save:
self.account_settings_page.wait_for_loading_indicator()
else:
self.browser.refresh()
self.account_settings_page.wait_for_page()
self.assertEqual(self.account_settings_page.value_for_dropdown_field(field_id), new_value)
def _test_link_field(self, field_id, title, link_title, field_type, success_message):
"""
Test behaviour a link field.
"""
self.assertEqual(self.account_settings_page.title_for_field(field_id), title)
self.assertEqual(self.account_settings_page.link_title_for_link_field(field_id), link_title)
self.account_settings_page.click_on_link_in_link_field(field_id, field_type=field_type)
self.account_settings_page.wait_for_message(field_id, success_message)
def test_username_field(self):
"""
Test behaviour of "Username" field.
"""
self._test_readonly_field('username', 'Username', self.username)
def test_full_name_field(self):
"""
Test behaviour of "Full Name" field.
"""
self._test_text_field(
u'name',
u'Full Name',
self.full_name,
u'@',
[u'another name', self.full_name],
)
actual_events = self.wait_for_events(event_filter=self.settings_changed_event_filter, number_of_matches=2)
self.assert_events_match(
[
self.expected_settings_changed_event('name', self.full_name, 'another name'),
self.expected_settings_changed_event('name', 'another name', self.full_name),
],
actual_events
)
def test_email_field(self):
"""
Test behaviour of "Email" field.
"""
email = u"test@example.com"
username, user_id = self.log_in_as_unique_user(email=email)
self.visit_account_settings_page()
self._test_text_field(
u'email',
u'Email Address',
email,
u'test@example.com' + XSS_INJECTION,
[u'me@here.com', u'you@there.com'],
success_message='Click the link in the message to update your email address.',
assert_after_reload=False
)
actual_events = self.wait_for_events(
event_filter=self.settings_change_initiated_event_filter, number_of_matches=2)
self.assert_events_match(
[
self.expected_settings_change_initiated_event(
'email', email, 'me@here.com', username=username, user_id=user_id),
# NOTE the first email change was never confirmed, so old has not changed.
self.expected_settings_change_initiated_event(
'email', email, 'you@there.com', username=username, user_id=user_id),
],
actual_events
)
# Email is not saved until user confirms, so no events should have been
# emitted.
self.assert_no_setting_changed_event()
def test_password_field(self):
"""
Test behaviour of "Password" field.
"""
self._test_link_field(
u'password',
u'Password',
u'Reset Your Password',
u'button',
success_message='Click the link in the message to reset your password.',
)
event_filter = self.expected_settings_change_initiated_event('password', None, None)
self.wait_for_events(event_filter=event_filter, number_of_matches=1)
# Like email, since the user has not confirmed their password change,
# the field has not yet changed, so no events will have been emitted.
self.assert_no_setting_changed_event()
@skip(
'On bokchoy test servers, language changes take a few reloads to fully realize '
'which means we can no longer reliably match the strings in the html in other tests.'
)
def test_language_field(self):
"""
Test behaviour of "Language" field.
"""
self._test_dropdown_field(
u'pref-lang',
u'Language',
u'English',
[u'Dummy Language (Esperanto)', u'English'],
reloads_on_save=True,
)
def test_education_completed_field(self):
"""
Test behaviour of "Education Completed" field.
"""
self._test_dropdown_field(
u'level_of_education',
u'Education Completed',
u'',
[u'Bachelor\'s degree', u''],
)
actual_events = self.wait_for_events(event_filter=self.settings_changed_event_filter, number_of_matches=2)
self.assert_events_match(
[
self.expected_settings_changed_event('level_of_education', None, 'b'),
self.expected_settings_changed_event('level_of_education', 'b', None),
],
actual_events
)
def test_gender_field(self):
"""
Test behaviour of "Gender" field.
"""
self._test_dropdown_field(
u'gender',
u'Gender',
u'',
[u'Female', u''],
)
actual_events = self.wait_for_events(event_filter=self.settings_changed_event_filter, number_of_matches=2)
self.assert_events_match(
[
self.expected_settings_changed_event('gender', None, 'f'),
self.expected_settings_changed_event('gender', 'f', None),
],
actual_events
)
def test_year_of_birth_field(self):
"""
Test behaviour of "Year of Birth" field.
"""
# Note that when we clear the year_of_birth here we're firing an event.
self.assertEqual(self.account_settings_page.value_for_dropdown_field('year_of_birth', ''), '')
expected_events = [
self.expected_settings_changed_event('year_of_birth', None, 1980),
self.expected_settings_changed_event('year_of_birth', 1980, None),
]
with self.assert_events_match_during(self.settings_changed_event_filter, expected_events):
self._test_dropdown_field(
u'year_of_birth',
u'Year of Birth',
u'',
[u'1980', u''],
)
def test_country_field(self):
"""
Test behaviour of "Country or Region" field.
"""
self._test_dropdown_field(
u'country',
u'Country or Region',
u'',
[u'Pakistan', u'Palau'],
)
def test_preferred_language_field(self):
"""
Test behaviour of "Preferred Language" field.
"""
self._test_dropdown_field(
u'language_proficiencies',
u'Preferred Language',
u'',
[u'Pushto', u''],
)
actual_events = self.wait_for_events(event_filter=self.settings_changed_event_filter, number_of_matches=2)
self.assert_events_match(
[
self.expected_settings_changed_event(
'language_proficiencies', [], [{'code': 'ps'}], table='student_languageproficiency'),
self.expected_settings_changed_event(
'language_proficiencies', [{'code': 'ps'}], [], table='student_languageproficiency'),
],
actual_events
)
def test_linked_accounts(self):
"""
Test that fields for third party auth providers exist.
Currently there is no way to test the whole authentication process
because that would require accounts with the providers.
"""
providers = (
['auth-oa2-facebook', 'Facebook', 'Link Your Account'],
['auth-oa2-google-oauth2', 'Google', 'Link Your Account'],
)
# switch to "Linked Accounts" tab
self.account_settings_page.switch_account_settings_tabs('accounts-tab')
for field_id, title, link_title in providers:
self.assertEqual(self.account_settings_page.title_for_field(field_id), title)
self.assertEqual(self.account_settings_page.link_title_for_link_field(field_id), link_title)
@attr('a11y')
class AccountSettingsA11yTest(AccountSettingsTestMixin, WebAppTest):
"""
Class to test account settings accessibility.
"""
def test_account_settings_a11y(self):
"""
Test the accessibility of the account settings page.
"""
self.log_in_as_unique_user()
self.visit_account_settings_page()
self.account_settings_page.a11y_audit.config.set_rules({
'ignore': [
'link-href', # TODO: AC-233
],
})
self.account_settings_page.a11y_audit.check_for_accessibility_errors()
| ampax/edx-platform | common/test/acceptance/tests/lms/test_account_settings.py | Python | agpl-3.0 | 17,618 | [
"VisIt"
] | 01c1df48038ea9bcee359cfd4be958d1dc19ba5fd51bfdb029d0e905841d57d0 |
"""
Unit tests for various types of character variable.
"""
import os
import tempfile
import unittest
import cdlparser
import numpy as np
import netCDF4 as nc4
#---------------------------------------------------------------------------------------------------
class TestCharVars(unittest.TestCase) :
#---------------------------------------------------------------------------------------------------
def setUp(self) :
cdltext = r"""netcdf charvars {
dimensions:
nreg = 3 ;
namelen = 10 ;
rec = 2 ;
code = 3 ;
codelen = 4 ;
variables:
char letter ;
int regcodes(nreg) ;
regcodes:long_name = "region codes" ;
char regions(nreg, namelen) ;
regions:long_name = "region names" ;
char digits(namelen) ;
digits:long_name = "decimal digits" ;
int sampleid(rec) ;
sampleid:long_name = "sample id" ;
char dna_code(rec, code, codelen) ;
dna_code:long_name = "DNA code" ;
// global attributes
:comment = "a cast of unholy characters" ;
data:
regcodes = 1, 2, 3 ;
regions = "Europe", "Americas", "Asia" ;
digits = "0123456789" ;
letter = "X" ;
sampleid = 1, 2 ;
dna_code = "ACTG", "ACGG", "ATGC", "CTGA", "GCTA", "TGCA";
}"""
parser = cdlparser.CDL3Parser()
self.tmpfile = tempfile.mkstemp(suffix='.nc')[1]
self.dataset = parser.parse_text(cdltext, ncfile=self.tmpfile)
def tearDown(self) :
if os.path.exists(self.tmpfile) : os.remove(self.tmpfile)
def test_scalar_variables(self) :
var = self.dataset.variables['letter']
self.assertTrue(var[:] == b"X")
def test_non_scalar_variables(self) :
var = self.dataset.variables['regcodes']
self.assertTrue(var.long_name == "region codes")
self.assertTrue(var.shape == (3,))
data = var[:]
expected = np.array([1,2,3], dtype=np.int32)
expected.shape = (3,)
self.assertTrue(np.array_equal(data, expected))
var = self.dataset.variables['regions']
self.assertTrue(var.long_name == "region names")
self.assertTrue(var.shape == (3,10))
data = var[:]
data = nc4.chartostring(data)
self.assertTrue(data[0].startswith(b"Europe"))
self.assertTrue(data[1].startswith(b"Americas"))
self.assertTrue(data[2].startswith(b"Asia"))
var = self.dataset.variables['digits']
self.assertTrue(var.long_name == "decimal digits")
self.assertTrue(var.shape == (10,))
data = var[:]
data = nc4.chartostring(data)
self.assertTrue(data == b"0123456789")
var = self.dataset.variables['dna_code']
self.assertTrue(var.long_name == "DNA code")
self.assertTrue(var.shape == (2,3,4))
data = var[:]
sample = nc4.chartostring(data[0])
self.assertTrue(sample[0] == b"ACTG")
self.assertTrue(sample[1] == b"ACGG")
self.assertTrue(sample[2] == b"ATGC")
sample = nc4.chartostring(data[1])
self.assertTrue(sample[0] == b"CTGA")
self.assertTrue(sample[1] == b"GCTA")
self.assertTrue(sample[2] == b"TGCA")
#---------------------------------------------------------------------------------------------------
if __name__ == '__main__':
#---------------------------------------------------------------------------------------------------
unittest.main()
| ocehugo/cdlparser | test/test_charvars.py | Python | bsd-3-clause | 3,532 | [
"NetCDF"
] | 79ce99ba03bda1f0fd12b310c3dc20b0fa0aa492131f942fe31bd17f8b039daa |
#
# @BEGIN LICENSE
#
# Psi4: an open-source quantum chemistry software package
#
# Copyright (c) 2007-2017 The Psi4 Developers.
#
# The copyrights for code used from other parties are included in
# the corresponding files.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# @END LICENSE
#
r"""File for accessory procedures in the chem module.
Credit for the libmints vector3 class to Justin M. Turney and
incremental improvements by other psi4 developers.
"""
from __future__ import absolute_import
from __future__ import print_function
import math
import copy
from .exceptions import *
ZERO = 1.0E-14
def norm(v):
"""Compute the magnitude of vector *v*."""
return math.sqrt(sum(v[i] * v[i] for i in range(len(v))))
def add(v, u):
"""Compute sum of vectors *v* and *u*."""
return [u[i] + v[i] for i in range(len(v))]
def sub(v, u):
"""Compute difference of vectors *v* - *u*."""
return [v[i] - u[i] for i in range(len(v))]
def dot(v, u):
"""Compute dot product of vectors *v* and *u*."""
return sum(u[i] * v[i] for i in range(len(v)))
def scale(v, d):
"""Compute by-element scale by *d* of vector *v*."""
return [d * v[i] for i in range(len(v))]
def naivemult(v, u):
"""Compute by-element multiplication of vectors *v* and *u*."""
if len(u) != len(v):
raise ValidationError('naivemult() only defined for vectors of same length \n')
return [u[i] * v[i] for i in range(len(v))]
def normalize(v):
"""Compute normalized vector *v*."""
vmag = norm(v)
return [v[i] / vmag for i in range(len(v))]
def distance(v, u):
"""Compute the distance between points defined by vectors *v* and *u*."""
return norm(sub(v, u))
def cross(v, u):
"""Compute cross product of length 3 vectors *v* and *u*."""
if len(u) != 3 or len(v) != 3:
raise ValidationError('cross() only defined for vectors of length 3\n')
return [v[1] * u[2] - v[2] * u[1],
v[2] * u[0] - v[0] * u[2],
v[0] * u[1] - v[1] * u[0]]
def rotate(v, theta, axis):
"""Rotate length 3 vector *v* about *axis* by *theta* radians."""
if len(v) != 3 or len(axis) != 3:
raise ValidationError('rotate() only defined for vectors of length 3\n')
unitaxis = normalize(copy.deepcopy(axis))
# split into parallel and perpendicular components along axis
parallel = scale(axis, dot(v, axis) / dot(axis, axis))
perpendicular = sub(v, parallel)
# form unit vector perpendicular to parallel and perpendicular
third_axis = perp_unit(axis, perpendicular)
third_axis = scale(third_axis, norm(perpendicular))
result = add(parallel, add(scale(perpendicular, math.cos(theta)), scale(third_axis, math.sin(theta))))
for item in range(len(result)):
if math.fabs(result[item]) < ZERO:
result[item] = 0.0
return result
def perp_unit(u, v):
"""Compute unit vector perpendicular to length 3 vectors *u* and *v*."""
if len(u) != 3 or len(v) != 3:
raise ValidationError('perp_unit() only defined for vectors of length 3\n')
# try cross product
result = cross(u, v)
resultdotresult = dot(result, result)
if resultdotresult < 1.E-16:
# cross product is too small to normalize
# find the largest of this and v
dotprodt = dot(u, u)
dotprodv = dot(v, v)
if dotprodt < dotprodv:
d = copy.deepcopy(v)
dotprodd = dotprodv
else:
d = copy.deepcopy(u)
dotprodd = dotprodt
# see if d is big enough
if dotprodd < 1.e-16:
# choose an arbitrary vector, since the biggest vector is small
result = [1.0, 0.0, 0.0]
return result
else:
# choose a vector perpendicular to d
# choose it in one of the planes xy, xz, yz
# choose the plane to be that which contains the two largest components of d
absd = [math.fabs(d[0]), math.fabs(d[1]), math.fabs(d[2])]
if (absd[1] - absd[0]) > 1.0e-12:
#if absd[0] < absd[1]:
axis0 = 1
if (absd[2] - absd[0]) > 1.0e-12:
#if absd[0] < absd[2]:
axis1 = 2
else:
axis1 = 0
else:
axis0 = 0
if (absd[2] - absd[1]) > 1.0e-12:
#if absd[1] < absd[2]:
axis1 = 2
else:
axis1 = 1
result = [0.0, 0.0, 0.0]
# do the pi/2 rotation in the plane
result[axis0] = d[axis1]
result[axis1] = -1.0 * d[axis0]
result = normalize(result)
return result
else:
# normalize the cross product and return the result
result = scale(result, 1.0 / math.sqrt(resultdotresult))
return result
def determinant(mat):
"""Given 3x3 matrix *mat*, compute the determinat
"""
if len(mat) != 3 or len(mat[0]) != 3 or len(mat[1]) != 3 or len(mat[2]) != 3:
raise ValidationError('determinant() only defined for arrays of dimension 3x3\n')
det = mat[0][0] * mat[1][1] * mat[2][2] - mat[0][2] * mat[1][1] * mat[2][0] + \
mat[0][1] * mat[1][2] * mat[2][0] - mat[0][1] * mat[1][0] * mat[2][2] + \
mat[0][2] * mat[1][0] * mat[2][1] - mat[0][0] * mat[1][2] * mat[2][1]
return det
def diagonalize3x3symmat(M):
"""Given an real symmetric 3x3 matrix *M*, compute the eigenvalues
"""
if len(M) != 3 or len(M[0]) != 3 or len(M[1]) != 3 or len(M[2]) != 3:
raise ValidationError('diagonalize3x3symmat() only defined for arrays of dimension 3x3\n')
A = copy.deepcopy(M) # Symmetric input matrix
Q = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] # Storage buffer for eigenvectors
w = [A[0][0], A[1][1], A[2][2]] # Storage buffer for eigenvalues
# sd, so # Sums of diagonal resp. off-diagonal elements
# s, c, t # sin(phi), cos(phi), tan(phi) and temporary storage
# g, h, z, theta # More temporary storage
# Calculate SQR(tr(A))
sd = 0.0
for i in range(3):
sd += math.fabs(w[i])
sd = sd * sd
# Main iteration loop
for nIter in range(50):
# Test for convergence
so = 0.0
for p in range(3):
for q in range(p + 1, 3):
so += math.fabs(A[p][q])
if so == 0.0:
return w, Q # return eval, evec
if nIter < 4:
thresh = 0.2 * so / (3 * 3)
else:
thresh = 0.0
# Do sweep
for p in range(3):
for q in range(p + 1, 3):
g = 100.0 * math.fabs(A[p][q])
if nIter > 4 and (math.fabs(w[p]) + g == math.fabs(w[p])) and \
(math.fabs(w[q]) + g == math.fabs(w[q])):
A[p][q] = 0.0
elif math.fabs(A[p][q]) > thresh:
# Calculate Jacobi transformation
h = w[q] - w[p]
if math.fabs(h) + g == math.fabs(h):
t = A[p][q] / h
else:
theta = 0.5 * h / A[p][q]
if theta < 0.0:
t = -1.0 / (math.sqrt(1.0 + theta * theta) - theta)
else:
t = 1.0 / (math.sqrt(1.0 + theta * theta) + theta)
c = 1.0 / math.sqrt(1.0 + t * t)
s = t * c
z = t * A[p][q]
# Apply Jacobi transformation
A[p][q] = 0.0
w[p] -= z
w[q] += z
for r in range(p):
t = A[r][p]
A[r][p] = c * t - s * A[r][q]
A[r][q] = s * t + c * A[r][q]
for r in range(p + 1, q):
t = A[p][r]
A[p][r] = c * t - s * A[r][q]
A[r][q] = s * t + c * A[r][q]
for r in range(q + 1, 3):
t = A[p][r]
A[p][r] = c * t - s * A[q][r]
A[q][r] = s * t + c * A[q][r]
# Update eigenvectors
for r in range(3):
t = Q[r][p]
Q[r][p] = c * t - s * Q[r][q]
Q[r][q] = s * t + c * Q[r][q]
return None
def zero(m, n):
""" Create zero matrix"""
new_matrix = [[0 for row in range(n)] for col in range(m)]
return new_matrix
def identity(m):
"""Create identity matrix"""
new_matrix = zero(m, m)
for i in range(m):
new_matrix[i][i] = 1.0
return new_matrix
def show(matrix):
""" Print out matrix"""
for col in matrix:
print(col)
def mscale(matrix, d):
"""Return *matrix* scaled by scalar *d*"""
for i in range(len(matrix)):
for j in range(len(matrix[0])):
matrix[i][j] *= d
return matrix
def mult(matrix1, matrix2):
""" Matrix multiplication"""
if len(matrix1[0]) != len(matrix2):
# Check matrix dimensions
raise ValidationError('Matrices must be m*n and n*p to multiply!')
else:
# Multiply if correct dimensions
try:
new_matrix = zero(len(matrix1), len(matrix2[0]))
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
new_matrix[i][j] += matrix1[i][k] * matrix2[k][j]
except TypeError:
new_matrix = zero(len(matrix1), 1)
for i in range(len(matrix1)):
for k in range(len(matrix2)):
new_matrix[i][0] += matrix1[i][k] * matrix2[k]
return new_matrix
def transpose(matrix):
"""Return matrix transpose"""
if len(matrix[0]) != len(matrix):
# Check matrix dimensions
raise ValidationError('Matrices must be square.')
tmat = [list(i) for i in zip(*matrix)]
return tmat
def matadd(matrix1, matrix2, fac1=1.0, fac2=1.0):
"""Matrix addition"""
if (len(matrix1[0]) != len(matrix2[0])) or (len(matrix1) != len(matrix2)):
raise ValidationError('Matrices must be same dimension to add.')
new_matrix = zero(len(matrix1), len(matrix1[0]))
for i in range(len(matrix1)):
for j in range(len(matrix1[0])):
new_matrix[i][j] = fac1 * matrix1[i][j] + fac2 * matrix2[i][j]
return new_matrix
| kratman/psi4public | psi4/driver/qcdb/vecutil.py | Python | gpl-2.0 | 11,265 | [
"Psi4"
] | 27c54433e34b555e7250bcc2b30afe3fb88ef0f0c0423a766d3a6b9d6912d1b9 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# --- BEGIN_HEADER ---
#
# rmvgridres - remove vgrid resource
# Copyright (C) 2003-2015 The MiG Project lead by Brian Vinter
#
# This file is part of MiG.
#
# MiG is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# MiG 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# -- END_HEADER ---
#
"""Remove a resource from a given vgrid"""
import shared.returnvalues as returnvalues
from shared.functional import validate_input_and_cert, REJECT_UNSET
from shared.handlers import correct_handler
from shared.init import initialize_main_variables
from shared.vgrid import init_vgrid_script_add_rem, vgrid_is_owner, \
vgrid_is_resource, vgrid_remove_resources
def signature():
"""Signature of the main function"""
defaults = {'vgrid_name': REJECT_UNSET,
'unique_resource_name': REJECT_UNSET}
return ['text', defaults]
def main(client_id, user_arguments_dict):
"""Main function used by front end"""
(configuration, logger, output_objects, op_name) = \
initialize_main_variables(client_id, op_header=False)
defaults = signature()[1]
output_objects.append({'object_type': 'header', 'text'
: 'Remove %s Resource' % \
configuration.site_vgrid_label})
(validate_status, accepted) = validate_input_and_cert(
user_arguments_dict,
defaults,
output_objects,
client_id,
configuration,
allow_rejects=False,
)
if not validate_status:
return (accepted, returnvalues.CLIENT_ERROR)
if not correct_handler('POST'):
output_objects.append(
{'object_type': 'error_text', 'text'
: 'Only accepting POST requests to prevent unintended updates'})
return (output_objects, returnvalues.CLIENT_ERROR)
vgrid_name = accepted['vgrid_name'][-1]
unique_resource_name = accepted['unique_resource_name'][-1].lower()
# Validity of user and vgrid names is checked in this init function so
# no need to worry about illegal directory traversal through variables
(ret_val, msg, ret_variables) = \
init_vgrid_script_add_rem(vgrid_name, client_id,
unique_resource_name, 'resource',
configuration)
if not ret_val:
output_objects.append({'object_type': 'error_text', 'text'
: msg})
return (output_objects, returnvalues.CLIENT_ERROR)
elif msg:
# In case of warnings, msg is non-empty while ret_val remains True
output_objects.append({'object_type': 'warning', 'text': msg})
if not vgrid_is_owner(vgrid_name, client_id, configuration):
output_objects.append({'object_type': 'error_text', 'text'
: '''You must be an owner of the %s to
remove a resource!''' % configuration.site_vgrid_label
})
return (output_objects, returnvalues.CLIENT_ERROR)
# don't remove if not a participant
if not vgrid_is_resource(vgrid_name, unique_resource_name, configuration):
output_objects.append({'object_type': 'error_text', 'text'
: '%s is not a resource in %s or a parent %s.'
% (unique_resource_name, vgrid_name,
configuration.site_vgrid_label)})
return (output_objects, returnvalues.CLIENT_ERROR)
# remove
(rm_status, rm_msg) = vgrid_remove_resources(configuration, vgrid_name,
[unique_resource_name])
if not rm_status:
output_objects.append({'object_type': 'error_text', 'text'
: rm_msg})
output_objects.append({'object_type': 'error_text', 'text'
: '''%(res_name)s might be listed as a resource
of this %(_label)s because it is a resource of a parent %(_label)s. Removal
must be performed from the most significant %(_label)s possible.''' % \
{'res_name': unique_resource_name,
'_label': configuration.site_vgrid_label}})
return (output_objects, returnvalues.SYSTEM_ERROR)
output_objects.append({'object_type': 'text', 'text'
: 'Resource %s successfully removed from %s %s!'
% (unique_resource_name, vgrid_name,
configuration.site_vgrid_label)})
output_objects.append({'object_type': 'link', 'destination':
'adminvgrid.py?vgrid_name=%s' % vgrid_name, 'text':
'Back to administration for %s' % vgrid_name})
return (output_objects, returnvalues.OK)
| heromod/migrid | mig/shared/functionality/rmvgridres.py | Python | gpl-2.0 | 5,374 | [
"Brian"
] | b60dcdecd5b6bac35c236c07b9c260b2f97bf87cb9fa46523f3edfb0ed85461c |
# coding: utf-8
import constance
from django.conf import settings
from hub.models import ConfigurationFile, PerUserSetting
from hub.utils.i18n import I18nUtils
def external_service_tokens(request):
out = {}
if settings.GOOGLE_ANALYTICS_TOKEN:
out['google_analytics_token'] = settings.GOOGLE_ANALYTICS_TOKEN
if settings.RAVEN_JS_DSN:
out['raven_js_dsn'] = settings.RAVEN_JS_DSN
if settings.RAVEN_FRONTEND_ENV:
out['raven_env'] = settings.RAVEN_FRONTEND_ENV
try:
intercom_setting = PerUserSetting.objects.get(name='INTERCOM_APP_ID')
except PerUserSetting.DoesNotExist:
pass
else:
out['intercom_app_id'] = intercom_setting.get_for_user(request.user)
return out
def email(request):
out = {}
# 'kpi_protocol' used in the activation_email.txt template
out['kpi_protocol'] = request.META.get('wsgi.url_scheme', 'http')
return out
def sitewide_messages(request):
"""
required in the context for any pages that need to display
custom text in django templates
"""
if request.path_info.endswith("accounts/register/"):
sitewide_message = I18nUtils.get_sitewide_message()
if sitewide_message is not None:
return {"welcome_message": sitewide_message}
return {}
class CombinedConfig:
'''
An object that gets its attributes from both a dictionary (`extra_config`)
AND a django-constance LazyConfig object
'''
def __init__(self, constance_config, extra_config):
'''
constance_config: LazyConfig object
extra_config: dictionary
'''
self.constance_config = constance_config
self.extra_config = extra_config
def __getattr__(self, key):
try:
return self.extra_config[key]
except KeyError:
return getattr(self.constance_config, key)
def config(request):
'''
Merges django-constance configuration field names and values with
slugs and URLs for each hub.ConfigurationFile. Example use in a template:
Please visit our <a href="{{ config.SUPPORT_URL }}">help page</a>.
<img src="{{ config.logo }}">
'''
conf_files = {f.slug: f.url for f in ConfigurationFile.objects.all()}
return {'config': CombinedConfig(constance.config, conf_files)}
| onaio/kpi | kpi/context_processors.py | Python | agpl-3.0 | 2,327 | [
"VisIt"
] | 220034a87fe870f55179f628294e277de39b547be55f9561453b679968b97b13 |
""" Based on
https://greentreesnakes.readthedocs.io
"""
import ast
class AstTransformer(ast.NodeTransformer):
pass
def apply_transformers(tree):
tree = AstTransformer().visit(tree)
# Add lineno & col_offset to possibly modified nodes
ast.fix_missing_locations(tree)
return tree
| avanov/solo | solo/import_hooks/hooks.py | Python | mit | 302 | [
"VisIt"
] | 0c26aa058dbfb8323a7d318ea71cdf4fce063f02353c12f67a6e9bc3ceae9f23 |
import numpy as np
from scipy.ndimage.filters import gaussian_filter, gaussian_laplace
import itertools as itt
import math
from math import sqrt, hypot, log
from numpy import arccos
from ..util import img_as_float
from .peak import peak_local_max
from ._hessian_det_appx import _hessian_matrix_det
from ..transform import integral_image
from .._shared.utils import assert_nD
# This basic blob detection algorithm is based on:
# http://www.cs.utah.edu/~jfishbau/advimproc/project1/ (04.04.2013)
# Theory behind: http://en.wikipedia.org/wiki/Blob_detection (04.04.2013)
def _blob_overlap(blob1, blob2):
"""Finds the overlapping area fraction between two blobs.
Returns a float representing fraction of overlapped area.
Parameters
----------
blob1 : sequence
A sequence of ``(y,x,sigma)``, where ``x,y`` are coordinates of blob
and sigma is the standard deviation of the Gaussian kernel which
detected the blob.
blob2 : sequence
A sequence of ``(y,x,sigma)``, where ``x,y`` are coordinates of blob
and sigma is the standard deviation of the Gaussian kernel which
detected the blob.
Returns
-------
f : float
Fraction of overlapped area.
"""
root2 = sqrt(2)
# extent of the blob is given by sqrt(2)*scale
r1 = blob1[2] * root2
r2 = blob2[2] * root2
d = hypot(blob1[0] - blob2[0], blob1[1] - blob2[1])
if d > r1 + r2:
return 0
# one blob is inside the other, the smaller blob must die
if d <= abs(r1 - r2):
return 1
ratio1 = (d ** 2 + r1 ** 2 - r2 ** 2) / (2 * d * r1)
ratio1 = np.clip(ratio1, -1, 1)
acos1 = arccos(ratio1)
ratio2 = (d ** 2 + r2 ** 2 - r1 ** 2) / (2 * d * r2)
ratio2 = np.clip(ratio2, -1, 1)
acos2 = arccos(ratio2)
a = -d + r2 + r1
b = d - r2 + r1
c = d + r2 - r1
d = d + r2 + r1
area = r1 ** 2 * acos1 + r2 ** 2 * acos2 - 0.5 * sqrt(abs(a * b * c * d))
return area / (math.pi * (min(r1, r2) ** 2))
def _prune_blobs(blobs_array, overlap):
"""Eliminated blobs with area overlap.
Parameters
----------
blobs_array : ndarray
A 2d array with each row representing 3 values, ``(y,x,sigma)``
where ``(y,x)`` are coordinates of the blob and ``sigma`` is the
standard deviation of the Gaussian kernel which detected the blob.
overlap : float
A value between 0 and 1. If the fraction of area overlapping for 2
blobs is greater than `overlap` the smaller blob is eliminated.
Returns
-------
A : ndarray
`array` with overlapping blobs removed.
"""
# iterating again might eliminate more blobs, but one iteration suffices
# for most cases
for blob1, blob2 in itt.combinations(blobs_array, 2):
if _blob_overlap(blob1, blob2) > overlap:
if blob1[2] > blob2[2]:
blob2[2] = -1
else:
blob1[2] = -1
# return blobs_array[blobs_array[:, 2] > 0]
return np.array([b for b in blobs_array if b[2] > 0])
def blob_dog(image, min_sigma=1, max_sigma=50, sigma_ratio=1.6, threshold=2.0,
overlap=.5,):
"""Finds blobs in the given grayscale image.
Blobs are found using the Difference of Gaussian (DoG) method [1]_.
For each blob found, the method returns its coordinates and the standard
deviation of the Gaussian kernel that detected the blob.
Parameters
----------
image : ndarray
Input grayscale image, blobs are assumed to be light on dark
background (white on black).
min_sigma : float, optional
The minimum standard deviation for Gaussian Kernel. Keep this low to
detect smaller blobs.
max_sigma : float, optional
The maximum standard deviation for Gaussian Kernel. Keep this high to
detect larger blobs.
sigma_ratio : float, optional
The ratio between the standard deviation of Gaussian Kernels used for
computing the Difference of Gaussians
threshold : float, optional.
The absolute lower bound for scale space maxima. Local maxima smaller
than thresh are ignored. Reduce this to detect blobs with less
intensities.
overlap : float, optional
A value between 0 and 1. If the area of two blobs overlaps by a
fraction greater than `threshold`, the smaller blob is eliminated.
Returns
-------
A : (n, 3) ndarray
A 2d array with each row representing 3 values, ``(y,x,sigma)``
where ``(y,x)`` are coordinates of the blob and ``sigma`` is the
standard deviation of the Gaussian kernel which detected the blob.
References
----------
.. [1] http://en.wikipedia.org/wiki/Blob_detection#The_difference_of_Gaussians_approach
Examples
--------
>>> from skimage import data, feature
>>> feature.blob_dog(data.coins(), threshold=.5, max_sigma=40)
array([[ 45. , 336. , 16.777216],
[ 52. , 155. , 16.777216],
[ 52. , 216. , 16.777216],
[ 54. , 42. , 16.777216],
[ 54. , 276. , 10.48576 ],
[ 58. , 100. , 10.48576 ],
[ 120. , 272. , 16.777216],
[ 124. , 337. , 10.48576 ],
[ 125. , 45. , 16.777216],
[ 125. , 208. , 10.48576 ],
[ 127. , 102. , 10.48576 ],
[ 128. , 154. , 10.48576 ],
[ 185. , 347. , 16.777216],
[ 193. , 213. , 16.777216],
[ 194. , 277. , 16.777216],
[ 195. , 102. , 16.777216],
[ 196. , 43. , 10.48576 ],
[ 198. , 155. , 10.48576 ],
[ 260. , 46. , 16.777216],
[ 261. , 173. , 16.777216],
[ 263. , 245. , 16.777216],
[ 263. , 302. , 16.777216],
[ 267. , 115. , 10.48576 ],
[ 267. , 359. , 16.777216]])
Notes
-----
The radius of each blob is approximately :math:`\sqrt{2}sigma`.
"""
assert_nD(image, 2)
image = img_as_float(image)
# k such that min_sigma*(sigma_ratio**k) > max_sigma
k = int(log(float(max_sigma) / min_sigma, sigma_ratio)) + 1
# a geometric progression of standard deviations for gaussian kernels
sigma_list = np.array([min_sigma * (sigma_ratio ** i)
for i in range(k + 1)])
gaussian_images = [gaussian_filter(image, s) for s in sigma_list]
# computing difference between two successive Gaussian blurred images
# multiplying with standard deviation provides scale invariance
dog_images = [(gaussian_images[i] - gaussian_images[i + 1])
* sigma_list[i] for i in range(k)]
image_cube = np.dstack(dog_images)
# local_maxima = get_local_maxima(image_cube, threshold)
local_maxima = peak_local_max(image_cube, threshold_abs=threshold,
footprint=np.ones((3, 3, 3)),
threshold_rel=0.0,
exclude_border=False)
# Convert local_maxima to float64
lm = local_maxima.astype(np.float64)
# Convert the last index to its corresponding scale value
lm[:, 2] = sigma_list[local_maxima[:, 2]]
local_maxima = lm
return _prune_blobs(local_maxima, overlap)
def blob_log(image, min_sigma=1, max_sigma=50, num_sigma=10, threshold=.2,
overlap=.5, log_scale=False):
"""Finds blobs in the given grayscale image.
Blobs are found using the Laplacian of Gaussian (LoG) method [1]_.
For each blob found, the method returns its coordinates and the standard
deviation of the Gaussian kernel that detected the blob.
Parameters
----------
image : ndarray
Input grayscale image, blobs are assumed to be light on dark
background (white on black).
min_sigma : float, optional
The minimum standard deviation for Gaussian Kernel. Keep this low to
detect smaller blobs.
max_sigma : float, optional
The maximum standard deviation for Gaussian Kernel. Keep this high to
detect larger blobs.
num_sigma : int, optional
The number of intermediate values of standard deviations to consider
between `min_sigma` and `max_sigma`.
threshold : float, optional.
The absolute lower bound for scale space maxima. Local maxima smaller
than thresh are ignored. Reduce this to detect blobs with less
intensities.
overlap : float, optional
A value between 0 and 1. If the area of two blobs overlaps by a
fraction greater than `threshold`, the smaller blob is eliminated.
log_scale : bool, optional
If set intermediate values of standard deviations are interpolated
using a logarithmic scale to the base `10`. If not, linear
interpolation is used.
Returns
-------
A : (n, 3) ndarray
A 2d array with each row representing 3 values, ``(y,x,sigma)``
where ``(y,x)`` are coordinates of the blob and ``sigma`` is the
standard deviation of the Gaussian kernel which detected the blob.
References
----------
.. [1] http://en.wikipedia.org/wiki/Blob_detection#The_Laplacian_of_Gaussian
Examples
--------
>>> from skimage import data, feature, exposure
>>> img = data.coins()
>>> img = exposure.equalize_hist(img) # improves detection
>>> feature.blob_log(img, threshold = .3)
array([[ 113. , 323. , 1. ],
[ 121. , 272. , 17.33333333],
[ 124. , 336. , 11.88888889],
[ 126. , 46. , 11.88888889],
[ 126. , 208. , 11.88888889],
[ 127. , 102. , 11.88888889],
[ 128. , 154. , 11.88888889],
[ 185. , 344. , 17.33333333],
[ 194. , 213. , 17.33333333],
[ 194. , 276. , 17.33333333],
[ 197. , 44. , 11.88888889],
[ 198. , 103. , 11.88888889],
[ 198. , 155. , 11.88888889],
[ 260. , 174. , 17.33333333],
[ 263. , 244. , 17.33333333],
[ 263. , 302. , 17.33333333],
[ 266. , 115. , 11.88888889]])
Notes
-----
The radius of each blob is approximately :math:`\sqrt{2}sigma`.
"""
assert_nD(image, 2)
image = img_as_float(image)
if log_scale:
start, stop = log(min_sigma, 10), log(max_sigma, 10)
sigma_list = np.logspace(start, stop, num_sigma)
else:
sigma_list = np.linspace(min_sigma, max_sigma, num_sigma)
# computing gaussian laplace
# s**2 provides scale invariance
gl_images = [-gaussian_laplace(image, s) * s ** 2 for s in sigma_list]
image_cube = np.dstack(gl_images)
local_maxima = peak_local_max(image_cube, threshold_abs=threshold,
footprint=np.ones((3, 3, 3)),
threshold_rel=0.0,
exclude_border=False)
# Convert local_maxima to float64
lm = local_maxima.astype(np.float64)
# Convert the last index to its corresponding scale value
lm[:, 2] = sigma_list[local_maxima[:, 2]]
local_maxima = lm
return _prune_blobs(local_maxima, overlap)
def blob_doh(image, min_sigma=1, max_sigma=30, num_sigma=10, threshold=0.01,
overlap=.5, log_scale=False):
"""Finds blobs in the given grayscale image.
Blobs are found using the Determinant of Hessian method [1]_. For each blob
found, the method returns its coordinates and the standard deviation
of the Gaussian Kernel used for the Hessian matrix whose determinant
detected the blob. Determinant of Hessians is approximated using [2]_.
Parameters
----------
image : ndarray
Input grayscale image.Blobs can either be light on dark or vice versa.
min_sigma : float, optional
The minimum standard deviation for Gaussian Kernel used to compute
Hessian matrix. Keep this low to detect smaller blobs.
max_sigma : float, optional
The maximum standard deviation for Gaussian Kernel used to compute
Hessian matrix. Keep this high to detect larger blobs.
num_sigma : int, optional
The number of intermediate values of standard deviations to consider
between `min_sigma` and `max_sigma`.
threshold : float, optional.
The absolute lower bound for scale space maxima. Local maxima smaller
than thresh are ignored. Reduce this to detect less prominent blobs.
overlap : float, optional
A value between 0 and 1. If the area of two blobs overlaps by a
fraction greater than `threshold`, the smaller blob is eliminated.
log_scale : bool, optional
If set intermediate values of standard deviations are interpolated
using a logarithmic scale to the base `10`. If not, linear
interpolation is used.
Returns
-------
A : (n, 3) ndarray
A 2d array with each row representing 3 values, ``(y,x,sigma)``
where ``(y,x)`` are coordinates of the blob and ``sigma`` is the
standard deviation of the Gaussian kernel of the Hessian Matrix whose
determinant detected the blob.
References
----------
.. [1] http://en.wikipedia.org/wiki/Blob_detection#The_determinant_of_the_Hessian
.. [2] Herbert Bay, Andreas Ess, Tinne Tuytelaars, Luc Van Gool,
"SURF: Speeded Up Robust Features"
ftp://ftp.vision.ee.ethz.ch/publications/articles/eth_biwi_00517.pdf
Examples
--------
>>> from skimage import data, feature
>>> img = data.coins()
>>> feature.blob_doh(img)
array([[ 121. , 271. , 30. ],
[ 123. , 44. , 23.55555556],
[ 123. , 205. , 20.33333333],
[ 124. , 336. , 20.33333333],
[ 126. , 101. , 20.33333333],
[ 126. , 153. , 20.33333333],
[ 156. , 302. , 30. ],
[ 185. , 348. , 30. ],
[ 192. , 212. , 23.55555556],
[ 193. , 275. , 23.55555556],
[ 195. , 100. , 23.55555556],
[ 197. , 44. , 20.33333333],
[ 197. , 153. , 20.33333333],
[ 260. , 173. , 30. ],
[ 262. , 243. , 23.55555556],
[ 265. , 113. , 23.55555556],
[ 270. , 363. , 30. ]])
Notes
-----
The radius of each blob is approximately `sigma`.
Computation of Determinant of Hessians is independent of the standard
deviation. Therefore detecting larger blobs won't take more time. In
methods line :py:meth:`blob_dog` and :py:meth:`blob_log` the computation
of Gaussians for larger `sigma` takes more time. The downside is that
this method can't be used for detecting blobs of radius less than `3px`
due to the box filters used in the approximation of Hessian Determinant.
"""
assert_nD(image, 2)
image = img_as_float(image)
image = integral_image(image)
if log_scale:
start, stop = log(min_sigma, 10), log(max_sigma, 10)
sigma_list = np.logspace(start, stop, num_sigma)
else:
sigma_list = np.linspace(min_sigma, max_sigma, num_sigma)
hessian_images = [_hessian_matrix_det(image, s) for s in sigma_list]
image_cube = np.dstack(hessian_images)
local_maxima = peak_local_max(image_cube, threshold_abs=threshold,
footprint=np.ones((3, 3, 3)),
threshold_rel=0.0,
exclude_border=False)
# Convert local_maxima to float64
lm = local_maxima.astype(np.float64)
# Convert the last index to its corresponding scale value
lm[:, 2] = sigma_list[local_maxima[:, 2]]
local_maxima = lm
return _prune_blobs(local_maxima, overlap)
| bennlich/scikit-image | skimage/feature/blob.py | Python | bsd-3-clause | 16,627 | [
"Gaussian"
] | 8cdee2a64ac99a47a54d25c8628f29c2afd0d716d90112c2552e7f81817a7859 |
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2016 - 2017, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program 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 Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""
Test the noise tolerance of Layer 2 in isolation.
Perform an experiment to see if L2 eventually recognizes an object.
Test with various noise levels and with various column counts and synapse
sample sizes.
"""
from collections import defaultdict
import json
import math
import random
import os
import time
import matplotlib.pyplot as plt
import numpy as np
from htmresearch.algorithms.column_pooler import ColumnPooler
from htmresearch.frameworks.layers.sensor_placement import greedySensorPositions
L4_CELL_COUNT = 8*1024
def createRandomObjectDescriptions(numObjects,
numLocationsPerObject,
featurePool=("A", "B", "C")):
"""
Returns {"Object 1": [(0, "C"), (1, "B"), (2, "C"), ...],
"Object 2": [(0, "C"), (1, "A"), (2, "B"), ...]}
"""
return dict(("Object %d" % i,
zip(xrange(numLocationsPerObject),
[random.choice(featurePool)
for _ in xrange(numLocationsPerObject)]))
for i in xrange(1, numObjects + 1))
def noisy(pattern, noiseLevel, totalNumCells):
"""
Generate a noisy copy of a pattern.
Given number of active bits w = len(pattern),
deactivate noiseLevel*w cells, and activate noiseLevel*w other cells.
@param pattern (set)
A set of active indices
@param noiseLevel (float)
The percentage of the bits to shuffle
@param totalNumCells (int)
The number of cells in the SDR, active and inactive
@return (numpy array)
A noisy list of active indices
"""
n = int(noiseLevel * len(pattern))
noised = set(pattern)
noised.difference_update(random.sample(noised, n))
for _ in xrange(n):
while True:
v = random.randint(0, totalNumCells - 1)
if v not in pattern and v not in noised:
noised.add(v)
break
return np.array(sorted(noised), dtype="uint32")
def doExperiment(numColumns, l2Overrides, objectDescriptions, noiseMu,
noiseSigma, numInitialTraversals, noiseEverywhere):
"""
Touch every point on an object 'numInitialTraversals' times, then evaluate
whether it has inferred the object by touching every point once more and
checking the number of correctly active and incorrectly active cells.
@param numColumns (int)
The number of sensors to use
@param l2Overrides (dict)
Parameters for the ColumnPooler
@param objectDescriptions (dict)
A mapping of object names to their feature-locations.
See 'createRandomObjectDescriptions'.
@param noiseMu (float)
The average amount of noise in a feedforward input. The noise level for each
column's input is determined once per touch. It is a gaussian distribution
with mean 'noiseMu' and sigma 'noiseSigma'.
@param noiseSigma (float)
The sigma for the gaussian distribution of noise levels. If the noiseSigma is
0, then the noise level will always be 'noiseMu'.
@param numInitialTraversals (int)
The number of times to traverse the object before testing whether the object
has been inferred.
@param noiseEverywhere (bool)
If true, add noise to every column's input, and record accuracy of every
column. If false, add noise to one column's input, and only record accuracy
of that column.
"""
# For each column, keep a mapping from feature-location names to their SDRs
layer4sdr = lambda : np.array(sorted(random.sample(xrange(L4_CELL_COUNT),
40)), dtype="uint32")
featureLocationSDRs = [defaultdict(layer4sdr) for _ in xrange(numColumns)]
params = {"inputWidth": L4_CELL_COUNT,
"lateralInputWidths": [4096]*(numColumns-1),
"seed": random.randint(0, 1024)}
params.update(l2Overrides)
l2Columns = [ColumnPooler(**params)
for _ in xrange(numColumns)]
# Learn the objects
objectL2Representations = {}
for objectName, featureLocations in objectDescriptions.iteritems():
for featureLocationName in featureLocations:
# Touch it enough times for the distal synapses to reach the
# connected permanence, and then once more.
for _ in xrange(4):
allLateralInputs = [l2.getActiveCells() for l2 in l2Columns]
for columnNumber, l2 in enumerate(l2Columns):
feedforwardInput = featureLocationSDRs[columnNumber][featureLocationName]
lateralInputs = [lateralInput
for i, lateralInput in enumerate(allLateralInputs)
if i != columnNumber]
l2.compute(feedforwardInput, lateralInputs, learn=True)
objectL2Representations[objectName] = [set(l2.getActiveCells())
for l2 in l2Columns]
for l2 in l2Columns:
l2.reset()
results = []
# Try to infer the objects
for objectName, featureLocations in objectDescriptions.iteritems():
for l2 in l2Columns:
l2.reset()
sensorPositionsIterator = greedySensorPositions(numColumns, len(featureLocations))
# Touch each location at least numInitialTouches times, and then touch it
# once more, testing it. For each traversal, touch each point on the object
# ~once. Not once per sensor -- just once. So we translate the "number of
# traversals" into a "number of touches" according to the number of sensors.
numTouchesPerTraversal = len(featureLocations) / float(numColumns)
numInitialTouches = int(math.ceil(numInitialTraversals * numTouchesPerTraversal))
if noiseEverywhere:
numTestTouches = int(math.ceil(1 * numTouchesPerTraversal))
else:
numTestTouches = len(featureLocations)
for touch in xrange(numInitialTouches + numTestTouches):
sensorPositions = next(sensorPositionsIterator)
# Give the system a few timesteps to settle, allowing lateral connections
# to cause cells to be inhibited.
for _ in xrange(3):
allLateralInputs = [l2.getActiveCells() for l2 in l2Columns]
for columnNumber, l2 in enumerate(l2Columns):
position = sensorPositions[columnNumber]
featureLocationName = featureLocations[position]
feedforwardInput = featureLocationSDRs[columnNumber][featureLocationName]
if noiseEverywhere or columnNumber == 0:
noiseLevel = random.gauss(noiseMu, noiseSigma)
noiseLevel = max(0.0, min(1.0, noiseLevel))
feedforwardInput = noisy(feedforwardInput, noiseLevel, L4_CELL_COUNT)
lateralInputs = [lateralInput
for i, lateralInput in enumerate(allLateralInputs)
if i != columnNumber]
l2.compute(feedforwardInput, lateralInputs, learn=False)
if touch >= numInitialTouches:
if noiseEverywhere:
for columnNumber, l2 in enumerate(l2Columns):
activeCells = set(l2.getActiveCells())
correctCells = objectL2Representations[objectName][columnNumber]
results.append((len(activeCells & correctCells),
len(activeCells - correctCells)))
else:
activeCells = set(l2Columns[0].getActiveCells())
correctCells = objectL2Representations[objectName][0]
results.append((len(activeCells & correctCells),
len(activeCells - correctCells)))
return results
def plotSuccessRate_varyNumColumns(noiseSigma, noiseEverywhere):
"""
Run and plot the experiment, varying the number of cortical columns.
"""
#
# Run the experiment
#
noiseLevels = [x * 0.01 for x in xrange(0, 101, 5)]
l2Overrides = {"sampleSizeDistal": 20}
columnCounts = [1, 2, 3, 4]
results = defaultdict(list)
for trial in xrange(1):
print "trial", trial
objectDescriptions = createRandomObjectDescriptions(10, 10)
for numColumns in columnCounts:
print "numColumns", numColumns
for noiseLevel in noiseLevels:
r = doExperiment(numColumns, l2Overrides, objectDescriptions,
noiseLevel, noiseSigma, numInitialTraversals=6,
noiseEverywhere=noiseEverywhere)
results[(numColumns, noiseLevel)].extend(r)
#
# Plot it
#
numCorrectActiveThreshold = 30
numIncorrectActiveThreshold = 10
plt.figure()
colors = dict(zip(columnCounts,
('r', 'k', 'g', 'b')))
markers = dict(zip(columnCounts,
('o', '*', 'D', 'x')))
for numColumns in columnCounts:
y = []
for noiseLevel in noiseLevels:
trials = results[(numColumns, noiseLevel)]
numPassed = len([True for numCorrect, numIncorrect in trials
if numCorrect >= numCorrectActiveThreshold
and numIncorrect <= numIncorrectActiveThreshold])
y.append(numPassed / float(len(trials)))
plt.plot(noiseLevels, y,
color=colors[numColumns],
marker=markers[numColumns])
lgnd = plt.legend(["%d columns" % numColumns
for numColumns in columnCounts],
bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)
plt.xlabel("Mean feedforward noise level")
plt.xticks([0.01 * n for n in xrange(0, 101, 10)])
plt.ylabel("Success rate")
plt.yticks([0.0, 0.2, 0.4, 0.6, 0.8, 1.0])
plt.title("Inference with normally distributed noise (stdev=%.2f)" % noiseSigma)
plotPath = os.path.join("plots",
"successRate_varyColumnCount_sigma%.2f_%s.pdf"
% (noiseSigma, time.strftime("%Y%m%d-%H%M%S")))
plt.savefig(plotPath, bbox_extra_artists=(lgnd,), bbox_inches="tight")
print "Saved file %s" % plotPath
def plotSuccessRate_varyDistalSampleSize(noiseSigma, noiseEverywhere):
"""
Run and plot the experiment, varying the distal sample size.
"""
#
# Run the experiment
#
noiseLevels = [x * 0.01 for x in xrange(0, 101, 5)]
noiseSigma = 0.1
sampleSizes = [13, 20, 30, 40]
numColumns = 3
results = defaultdict(list)
for trial in xrange(1):
print "trial", trial
objectDescriptions = createRandomObjectDescriptions(10, 10)
for sampleSizeDistal in sampleSizes:
print "sampleSizeDistal", sampleSizeDistal
l2Overrides = {"sampleSizeDistal": sampleSizeDistal}
for noiseLevel in noiseLevels:
r = doExperiment(numColumns, l2Overrides, objectDescriptions,
noiseLevel, noiseSigma, numInitialTraversals=6,
noiseEverywhere=noiseEverywhere)
results[(sampleSizeDistal, noiseLevel)].extend(r)
#
# Plot it
#
numCorrectActiveThreshold = 30
numIncorrectActiveThreshold = 10
plt.figure()
colorList = dict(zip(sampleSizes,
('r', 'k', 'g', 'b')))
markerList = dict(zip(sampleSizes,
('o', '*', 'D', 'x')))
for sampleSizeDistal in sampleSizes:
y = []
for noiseLevel in noiseLevels:
trials = results[(sampleSizeDistal, noiseLevel)]
numPassed = len([True for numCorrect, numIncorrect in trials
if numCorrect >= numCorrectActiveThreshold
and numIncorrect <= numIncorrectActiveThreshold])
y.append(numPassed / float(len(trials)))
plt.plot(noiseLevels, y,
color=colorList[sampleSizeDistal],
marker=markerList[sampleSizeDistal])
lgnd = plt.legend(["Distal sample size %d" % sampleSizeDistal
for sampleSizeDistal in sampleSizes],
bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)
plt.xlabel("Mean feedforward noise level")
plt.xticks([0.01 * n for n in xrange(0, 101, 10)])
plt.ylabel("Success rate")
plt.yticks([0.0, 0.2, 0.4, 0.6, 0.8, 1.0])
plt.title("Inference with normally distributed noise (stdev=0.1)")
plotPath = os.path.join("plots",
"successRate_varyDistalSampleSize_sigma%.2f_%s.pdf"
% (noiseSigma, time.strftime("%Y%m%d-%H%M%S")))
plt.savefig(plotPath, bbox_extra_artists=(lgnd,), bbox_inches="tight")
print "Saved file %s" % plotPath
def plotSuccessRate_varyProximalSampleSize(noiseSigma, noiseEverywhere):
"""
Run and plot the experiment, varying the proximal sample size.
"""
#
# Run the experiment
#
noiseLevels = [x * 0.01 for x in xrange(0, 101, 5)]
noiseSigma = 0.1
sampleSizes = [13, 20, 30, 40]
numColumns = 3
results = defaultdict(list)
for trial in xrange(1):
print "trial", trial
objectDescriptions = createRandomObjectDescriptions(10, 10)
for sampleSizeProximal in sampleSizes:
print "sampleSizeProximal", sampleSizeProximal
l2Overrides = {"sampleSizeProximal": sampleSizeProximal}
for noiseLevel in noiseLevels:
r = doExperiment(numColumns, l2Overrides, objectDescriptions,
noiseLevel, noiseSigma, numInitialTraversals=6,
noiseEverywhere=noiseEverywhere)
results[(sampleSizeProximal, noiseLevel)].extend(r)
#
# Plot it
#
numCorrectActiveThreshold = 30
numIncorrectActiveThreshold = 10
plt.figure()
colorList = dict(zip(sampleSizes,
('r', 'k', 'g', 'b')))
markerList = dict(zip(sampleSizes,
('o', '*', 'D', 'x')))
for sampleSizeProximal in sampleSizes:
y = []
for noiseLevel in noiseLevels:
trials = results[(sampleSizeProximal, noiseLevel)]
numPassed = len([True for numCorrect, numIncorrect in trials
if numCorrect >= numCorrectActiveThreshold
and numIncorrect <= numIncorrectActiveThreshold])
y.append(numPassed / float(len(trials)))
plt.plot(noiseLevels, y,
color=colorList[sampleSizeProximal],
marker=markerList[sampleSizeProximal])
lgnd = plt.legend(["Proximal sample size %d" % sampleSizeProximal
for sampleSizeProximal in sampleSizes],
bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0)
plt.xlabel("Mean feedforward noise level")
plt.xticks([0.01 * n for n in xrange(0, 101, 10)])
plt.ylabel("Success rate")
plt.yticks([0.0, 0.2, 0.4, 0.6, 0.8, 1.0])
plt.title("Inference with normally distributed noise (stdev=0.1)")
plotPath = os.path.join("plots",
"successRate_varyProximalSampleSize_sigma%.2f_%s.pdf"
% (noiseSigma, time.strftime("%Y%m%d-%H%M%S")))
plt.savefig(plotPath, bbox_extra_artists=(lgnd,), bbox_inches="tight")
print "Saved file %s" % plotPath
def logCellActivity_varyNumColumns(noiseSigma, noiseEverywhere):
"""
Run the experiment, varying the column counts, and save each
[# correctly active cells, # incorrectly active cells]
pair to a JSON file that can be visualized.
"""
noiseLevels = [0.30, 0.40, 0.45, 0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90]
l2Overrides = {"sampleSizeDistal": 20}
columnCounts = [1, 2, 3, 4, 5]
results = defaultdict(list)
for trial in xrange(1):
print "trial", trial
objectDescriptions = createRandomObjectDescriptions(10, 10)
for numColumns in columnCounts:
print "numColumns", numColumns
for noiseLevel in noiseLevels:
r = doExperiment(numColumns, l2Overrides, objectDescriptions,
noiseLevel, noiseSigma, numInitialTraversals=6,
noiseEverywhere=noiseEverywhere)
results[(numColumns, noiseLevel)].extend(r)
d = []
for (numColumns, noiseLevel), cellCounts in results.iteritems():
d.append({"numColumns": numColumns,
"noiseLevel": noiseLevel,
"results": cellCounts})
filename = os.path.join("plots",
"varyColumns_sigma%.2f_%s.json"
% (noiseSigma, time.strftime("%Y%m%d-%H%M%S")))
with open(filename, "w") as fout:
json.dump(d, fout)
print "Wrote to", filename
print "Visualize this file at: http://numenta.github.io/nupic.research/visualizations/grid-of-scatterplots/L2-columns-with-noise.html"
if __name__ == "__main__":
# Plot the accuracy of inference when noise is added, varying the number of
# cortical columns. We find that when noise is applied at a constant equal
# rate for each column, the accuracy only improves slightly with more cortical
# columns.
plotSuccessRate_varyNumColumns(noiseSigma=0.0, noiseEverywhere=True)
# Change noise to a Gaussian random variable that is independently applied to
# different columns. We find that the accuracy now improves with more cortical
# columns. This means that noisy sensors benefit from having lateral input
# from non-noisy sensors. The sensors that happen to have high noise levels
# take advantage of the sensors that happen to have low noise levels, so the
# array as a whole can partially guard itself from noise.
plotSuccessRate_varyNumColumns(noiseSigma=0.1, noiseEverywhere=True)
plotSuccessRate_varyNumColumns(noiseSigma=0.2, noiseEverywhere=True)
# Plot the accuracy of inference when noise is added, varying the ratio of the
# proximal threshold to the proximal synapse sample size. We find that this
# ratio does more than any other parameter to determine at what noise level
# the accuracy drop-off occurs.
plotSuccessRate_varyProximalSampleSize(noiseSigma=0.1, noiseEverywhere=True)
# Plot the accuracy of inference when noise is added, varying the ratio of the
# distal segment activation threshold to the distal synapse sample size. We
# find that increasing this ratio provides additional noise tolerance on top
# of the noise tolerance provided by proximal connections.
plotSuccessRate_varyDistalSampleSize(noiseSigma=0.1, noiseEverywhere=True)
# Observe the impact of columns without noisy input on columns with noisy
# input. Add constant noise to one column's input, and don't add noise for the
# other columns. Observe what happens as more non-noisy columns are added. We
# find that the lateral input from other columns can help correctly active
# cells inhibit cells that shouldn't be active, but it doesn't help increase
# the number of correctly active cells. So the accuracy of inference is
# improved, but the confidence of the inference isn't.
logCellActivity_varyNumColumns(noiseSigma=0.0, noiseEverywhere=False)
| marionleborgne/nupic.research | projects/l2_pooling/noise_tolerance_l2.py | Python | agpl-3.0 | 19,191 | [
"Gaussian"
] | bb63a60ae88babdceb829a1c8e24ef8978e9a973ab8fa01edc5385132da35cd5 |
# Copyright (c) 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
This script is intended for use as a GYP_GENERATOR. It takes as input (by way of
the generator flag config_path) the path of a json file that dictates the files
and targets to search for. The following keys are supported:
files: list of paths (relative) of the files to search for.
targets: list of targets to search for. The target names are unqualified.
The following is output:
error: only supplied if there is an error.
targets: the set of targets passed in via targets that either directly or
indirectly depend upon the set of paths supplied in files.
build_targets: minimal set of targets that directly depend on the changed
files and need to be built. The expectation is this set of targets is passed
into a build step.
status: outputs one of three values: none of the supplied files were found,
one of the include files changed so that it should be assumed everything
changed (in this case targets and build_targets are not output) or at
least one file was found.
invalid_targets: list of supplied targets thare were not found.
If the generator flag analyzer_output_path is specified, output is written
there. Otherwise output is written to stdout.
"""
import gyp.common
import gyp.ninja_syntax as ninja_syntax
import json
import os
import posixpath
import sys
debug = False
found_dependency_string = 'Found dependency'
no_dependency_string = 'No dependencies'
# Status when it should be assumed that everything has changed.
all_changed_string = 'Found dependency (all)'
# MatchStatus is used indicate if and how a target depends upon the supplied
# sources.
# The target's sources contain one of the supplied paths.
MATCH_STATUS_MATCHES = 1
# The target has a dependency on another target that contains one of the
# supplied paths.
MATCH_STATUS_MATCHES_BY_DEPENDENCY = 2
# The target's sources weren't in the supplied paths and none of the target's
# dependencies depend upon a target that matched.
MATCH_STATUS_DOESNT_MATCH = 3
# The target doesn't contain the source, but the dependent targets have not yet
# been visited to determine a more specific status yet.
MATCH_STATUS_TBD = 4
generator_supports_multiple_toolsets = True
generator_wants_static_library_dependencies_adjusted = False
generator_default_variables = {
}
for dirname in ['INTERMEDIATE_DIR', 'SHARED_INTERMEDIATE_DIR', 'PRODUCT_DIR',
'LIB_DIR', 'SHARED_LIB_DIR']:
generator_default_variables[dirname] = '!!!'
for unused in ['RULE_INPUT_PATH', 'RULE_INPUT_ROOT', 'RULE_INPUT_NAME',
'RULE_INPUT_DIRNAME', 'RULE_INPUT_EXT',
'EXECUTABLE_PREFIX', 'EXECUTABLE_SUFFIX',
'STATIC_LIB_PREFIX', 'STATIC_LIB_SUFFIX',
'SHARED_LIB_PREFIX', 'SHARED_LIB_SUFFIX',
'CONFIGURATION_NAME']:
generator_default_variables[unused] = ''
def _ToGypPath(path):
"""Converts a path to the format used by gyp."""
if os.sep == '\\' and os.altsep == '/':
return path.replace('\\', '/')
return path
def _ResolveParent(path, base_path_components):
"""Resolves |path|, which starts with at least one '../'. Returns an empty
string if the path shouldn't be considered. See _AddSources() for a
description of |base_path_components|."""
depth = 0
while path.startswith('../'):
depth += 1
path = path[3:]
# Relative includes may go outside the source tree. For example, an action may
# have inputs in /usr/include, which are not in the source tree.
if depth > len(base_path_components):
return ''
if depth == len(base_path_components):
return path
return '/'.join(base_path_components[0:len(base_path_components) - depth]) + \
'/' + path
def _AddSources(sources, base_path, base_path_components, result):
"""Extracts valid sources from |sources| and adds them to |result|. Each
source file is relative to |base_path|, but may contain '..'. To make
resolving '..' easier |base_path_components| contains each of the
directories in |base_path|. Additionally each source may contain variables.
Such sources are ignored as it is assumed dependencies on them are expressed
and tracked in some other means."""
# NOTE: gyp paths are always posix style.
for source in sources:
if not len(source) or source.startswith('!!!') or source.startswith('$'):
continue
# variable expansion may lead to //.
org_source = source
source = source[0] + source[1:].replace('//', '/')
if source.startswith('../'):
source = _ResolveParent(source, base_path_components)
if len(source):
result.append(source)
continue
result.append(base_path + source)
if debug:
print 'AddSource', org_source, result[len(result) - 1]
def _ExtractSourcesFromAction(action, base_path, base_path_components,
results):
if 'inputs' in action:
_AddSources(action['inputs'], base_path, base_path_components, results)
def _ToLocalPath(toplevel_dir, path):
"""Converts |path| to a path relative to |toplevel_dir|."""
if path == toplevel_dir:
return ''
if path.startswith(toplevel_dir + '/'):
return path[len(toplevel_dir) + len('/'):]
return path
def _ExtractSources(target, target_dict, toplevel_dir):
# |target| is either absolute or relative and in the format of the OS. Gyp
# source paths are always posix. Convert |target| to a posix path relative to
# |toplevel_dir_|. This is done to make it easy to build source paths.
base_path = posixpath.dirname(_ToLocalPath(toplevel_dir, _ToGypPath(target)))
base_path_components = base_path.split('/')
# Add a trailing '/' so that _AddSources() can easily build paths.
if len(base_path):
base_path += '/'
if debug:
print 'ExtractSources', target, base_path
results = []
if 'sources' in target_dict:
_AddSources(target_dict['sources'], base_path, base_path_components,
results)
# Include the inputs from any actions. Any changes to these affect the
# resulting output.
if 'actions' in target_dict:
for action in target_dict['actions']:
_ExtractSourcesFromAction(action, base_path, base_path_components,
results)
if 'rules' in target_dict:
for rule in target_dict['rules']:
_ExtractSourcesFromAction(rule, base_path, base_path_components, results)
return results
class Target(object):
"""Holds information about a particular target:
deps: set of Targets this Target depends upon. This is not recursive, only the
direct dependent Targets.
match_status: one of the MatchStatus values.
back_deps: set of Targets that have a dependency on this Target.
visited: used during iteration to indicate whether we've visited this target.
This is used for two iterations, once in building the set of Targets and
again in _GetBuildTargets().
name: fully qualified name of the target.
requires_build: True if the target type is such that it needs to be built.
See _DoesTargetTypeRequireBuild for details.
added_to_compile_targets: used when determining if the target was added to the
set of targets that needs to be built.
in_roots: true if this target is a descendant of one of the root nodes.
is_executable: true if the type of target is executable."""
def __init__(self, name):
self.deps = set()
self.match_status = MATCH_STATUS_TBD
self.back_deps = set()
self.name = name
# TODO(sky): I don't like hanging this off Target. This state is specific
# to certain functions and should be isolated there.
self.visited = False
self.requires_build = False
self.added_to_compile_targets = False
self.in_roots = False
self.is_executable = False
class Config(object):
"""Details what we're looking for
files: set of files to search for
targets: see file description for details."""
def __init__(self):
self.files = []
self.targets = set()
def Init(self, params):
"""Initializes Config. This is a separate method as it raises an exception
if there is a parse error."""
generator_flags = params.get('generator_flags', {})
config_path = generator_flags.get('config_path', None)
if not config_path:
return
try:
f = open(config_path, 'r')
config = json.load(f)
f.close()
except IOError:
raise Exception('Unable to open file ' + config_path)
except ValueError as e:
raise Exception('Unable to parse config file ' + config_path + str(e))
if not isinstance(config, dict):
raise Exception('config_path must be a JSON file containing a dictionary')
self.files = config.get('files', [])
self.targets = set(config.get('targets', []))
def _WasBuildFileModified(build_file, data, files, toplevel_dir):
"""Returns true if the build file |build_file| is either in |files| or
one of the files included by |build_file| is in |files|. |toplevel_dir| is
the root of the source tree."""
if _ToLocalPath(toplevel_dir, _ToGypPath(build_file)) in files:
if debug:
print 'gyp file modified', build_file
return True
# First element of included_files is the file itself.
if len(data[build_file]['included_files']) <= 1:
return False
for include_file in data[build_file]['included_files'][1:]:
# |included_files| are relative to the directory of the |build_file|.
rel_include_file = \
_ToGypPath(gyp.common.UnrelativePath(include_file, build_file))
if _ToLocalPath(toplevel_dir, rel_include_file) in files:
if debug:
print 'included gyp file modified, gyp_file=', build_file, \
'included file=', rel_include_file
return True
return False
def _GetOrCreateTargetByName(targets, target_name):
"""Creates or returns the Target at targets[target_name]. If there is no
Target for |target_name| one is created. Returns a tuple of whether a new
Target was created and the Target."""
if target_name in targets:
return False, targets[target_name]
target = Target(target_name)
targets[target_name] = target
return True, target
def _DoesTargetTypeRequireBuild(target_dict):
"""Returns true if the target type is such that it needs to be built."""
# If a 'none' target has rules or actions we assume it requires a build.
return target_dict['type'] != 'none' or \
target_dict.get('actions') or target_dict.get('rules')
def _GenerateTargets(data, target_list, target_dicts, toplevel_dir, files,
build_files):
"""Returns a tuple of the following:
. A dictionary mapping from fully qualified name to Target.
. A list of the targets that have a source file in |files|.
. Set of root Targets reachable from the the files |build_files|.
This sets the |match_status| of the targets that contain any of the source
files in |files| to MATCH_STATUS_MATCHES.
|toplevel_dir| is the root of the source tree."""
# Maps from target name to Target.
targets = {}
# Targets that matched.
matching_targets = []
# Queue of targets to visit.
targets_to_visit = target_list[:]
# Maps from build file to a boolean indicating whether the build file is in
# |files|.
build_file_in_files = {}
# Root targets across all files.
roots = set()
# Set of Targets in |build_files|.
build_file_targets = set()
while len(targets_to_visit) > 0:
target_name = targets_to_visit.pop()
created_target, target = _GetOrCreateTargetByName(targets, target_name)
if created_target:
roots.add(target)
elif target.visited:
continue
target.visited = True
target.requires_build = _DoesTargetTypeRequireBuild(
target_dicts[target_name])
target.is_executable = target_dicts[target_name]['type'] == 'executable'
build_file = gyp.common.ParseQualifiedTarget(target_name)[0]
if not build_file in build_file_in_files:
build_file_in_files[build_file] = \
_WasBuildFileModified(build_file, data, files, toplevel_dir)
if build_file in build_files:
build_file_targets.add(target)
# If a build file (or any of its included files) is modified we assume all
# targets in the file are modified.
if build_file_in_files[build_file]:
print 'matching target from modified build file', target_name
target.match_status = MATCH_STATUS_MATCHES
matching_targets.append(target)
else:
sources = _ExtractSources(target_name, target_dicts[target_name],
toplevel_dir)
for source in sources:
if source in files:
print 'target', target_name, 'matches', source
target.match_status = MATCH_STATUS_MATCHES
matching_targets.append(target)
break
# Add dependencies to visit as well as updating back pointers for deps.
for dep in target_dicts[target_name].get('dependencies', []):
targets_to_visit.append(dep)
created_dep_target, dep_target = _GetOrCreateTargetByName(targets, dep)
if not created_dep_target:
roots.discard(dep_target)
target.deps.add(dep_target)
dep_target.back_deps.add(target)
return targets, matching_targets, roots & build_file_targets
def _GetUnqualifiedToTargetMapping(all_targets, to_find):
"""Returns a mapping (dictionary) from unqualified name to Target for all the
Targets in |to_find|."""
result = {}
if not to_find:
return result
to_find = set(to_find)
for target_name in all_targets.keys():
extracted = gyp.common.ParseQualifiedTarget(target_name)
if len(extracted) > 1 and extracted[1] in to_find:
to_find.remove(extracted[1])
result[extracted[1]] = all_targets[target_name]
if not to_find:
return result
return result
def _DoesTargetDependOn(target):
"""Returns true if |target| or any of its dependencies matches the supplied
set of paths. This updates |matches| of the Targets as it recurses.
target: the Target to look for."""
if target.match_status == MATCH_STATUS_DOESNT_MATCH:
return False
if target.match_status == MATCH_STATUS_MATCHES or \
target.match_status == MATCH_STATUS_MATCHES_BY_DEPENDENCY:
return True
for dep in target.deps:
if _DoesTargetDependOn(dep):
target.match_status = MATCH_STATUS_MATCHES_BY_DEPENDENCY
return True
target.match_status = MATCH_STATUS_DOESNT_MATCH
return False
def _GetTargetsDependingOn(possible_targets):
"""Returns the list of Targets in |possible_targets| that depend (either
directly on indirectly) on the matched targets.
possible_targets: targets to search from."""
found = []
for target in possible_targets:
if _DoesTargetDependOn(target):
found.append(target)
return found
def _AddBuildTargets(target, roots, add_if_no_ancestor, result):
"""Recurses through all targets that depend on |target|, adding all targets
that need to be built (and are in |roots|) to |result|.
roots: set of root targets.
add_if_no_ancestor: If true and there are no ancestors of |target| then add
|target| to |result|. |target| must still be in |roots|.
result: targets that need to be built are added here."""
if target.visited:
return
target.visited = True
target.in_roots = not target.back_deps and target in roots
for back_dep_target in target.back_deps:
_AddBuildTargets(back_dep_target, roots, False, result)
target.added_to_compile_targets |= back_dep_target.added_to_compile_targets
target.in_roots |= back_dep_target.in_roots
# Always add 'executable' targets. Even though they may be built by other
# targets that depend upon them it makes detection of what is going to be
# built easier.
if target.in_roots and \
(target.is_executable or
(not target.added_to_compile_targets and
(add_if_no_ancestor or target.requires_build))):
result.add(target)
target.added_to_compile_targets = True
def _GetBuildTargets(matching_targets, roots):
"""Returns the set of Targets that require a build.
matching_targets: targets that changed and need to be built.
roots: set of root targets in the build files to search from."""
result = set()
for target in matching_targets:
_AddBuildTargets(target, roots, True, result)
return result
def _WriteOutput(params, **values):
"""Writes the output, either to stdout or a file is specified."""
if 'error' in values:
print 'Error:', values['error']
if 'status' in values:
print values['status']
if 'targets' in values:
values['targets'].sort()
print 'Supplied targets that depend on changed files:'
for target in values['targets']:
print '\t', target
if 'invalid_targets' in values:
values['invalid_targets'].sort()
print 'The following targets were not found:'
for target in values['invalid_targets']:
print '\t', target
if 'build_targets' in values:
values['build_targets'].sort()
print 'Targets that require a build:'
for target in values['build_targets']:
print '\t', target
output_path = params.get('generator_flags', {}).get(
'analyzer_output_path', None)
if not output_path:
print json.dumps(values)
return
try:
f = open(output_path, 'w')
f.write(json.dumps(values) + '\n')
f.close()
except IOError as e:
print 'Error writing to output file', output_path, str(e)
def _WasGypIncludeFileModified(params, files):
"""Returns true if one of the files in |files| is in the set of included
files."""
if params['options'].includes:
for include in params['options'].includes:
if _ToGypPath(include) in files:
print 'Include file modified, assuming all changed', include
return True
return False
def _NamesNotIn(names, mapping):
"""Returns a list of the values in |names| that are not in |mapping|."""
return [name for name in names if name not in mapping]
def _LookupTargets(names, mapping):
"""Returns a list of the mapping[name] for each value in |names| that is in
|mapping|."""
return [mapping[name] for name in names if name in mapping]
def CalculateVariables(default_variables, params):
"""Calculate additional variables for use in the build (called by gyp)."""
flavor = gyp.common.GetFlavor(params)
if flavor == 'mac':
default_variables.setdefault('OS', 'mac')
elif flavor == 'win':
default_variables.setdefault('OS', 'win')
# Copy additional generator configuration data from VS, which is shared
# by the Windows Ninja generator.
import gyp.generator.msvs as msvs_generator
generator_additional_non_configuration_keys = getattr(msvs_generator,
'generator_additional_non_configuration_keys', [])
generator_additional_path_sections = getattr(msvs_generator,
'generator_additional_path_sections', [])
gyp.msvs_emulation.CalculateCommonVariables(default_variables, params)
else:
operating_system = flavor
if flavor == 'android':
operating_system = 'linux' # Keep this legacy behavior for now.
default_variables.setdefault('OS', operating_system)
def GenerateOutput(target_list, target_dicts, data, params):
"""Called by gyp as the final stage. Outputs results."""
config = Config()
try:
config.Init(params)
if not config.files:
raise Exception('Must specify files to analyze via config_path generator '
'flag')
toplevel_dir = _ToGypPath(os.path.abspath(params['options'].toplevel_dir))
if debug:
print 'toplevel_dir', toplevel_dir
if _WasGypIncludeFileModified(params, config.files):
result_dict = { 'status': all_changed_string,
'targets': list(config.targets) }
_WriteOutput(params, **result_dict)
return
all_targets, matching_targets, roots = _GenerateTargets(
data, target_list, target_dicts, toplevel_dir, frozenset(config.files),
params['build_files'])
unqualified_mapping = _GetUnqualifiedToTargetMapping(all_targets,
config.targets)
invalid_targets = None
if len(unqualified_mapping) != len(config.targets):
invalid_targets = _NamesNotIn(config.targets, unqualified_mapping)
if matching_targets:
search_targets = _LookupTargets(config.targets, unqualified_mapping)
matched_search_targets = _GetTargetsDependingOn(search_targets)
# Reset the visited status for _GetBuildTargets.
for target in all_targets.values():
target.visited = False
build_targets = _GetBuildTargets(matching_targets, roots)
matched_search_targets = [gyp.common.ParseQualifiedTarget(target.name)[1]
for target in matched_search_targets]
build_targets = [gyp.common.ParseQualifiedTarget(target.name)[1]
for target in build_targets]
else:
matched_search_targets = []
build_targets = []
result_dict = { 'targets': matched_search_targets,
'status': found_dependency_string if matching_targets else
no_dependency_string,
'build_targets': build_targets}
if invalid_targets:
result_dict['invalid_targets'] = invalid_targets
_WriteOutput(params, **result_dict)
except Exception as e:
_WriteOutput(params, error=str(e))
| pyokagan/gyp | pylib/gyp/generator/analyzer.py | Python | bsd-3-clause | 21,402 | [
"VisIt"
] | 6c41bfac26a1d3189e94c4d8476d2fd49d99ca3a73b09c2b124799cda54278ea |
#!/usr/bin/python3
from Bio import SearchIO
import os
# fetch files in current working directory
files = [f for f in os.listdir('.') if os.path.isfile(f)]
#print(files)
def convert_to_tab():
for f in files:
if f.endswith('.xml'):
# print(f)
# print(f.replace('.xml', '.xml.tab')
print("converting ", f, " to ", f.replace('.xml', '.xml.tab'))
SearchIO.convert(f, 'blast-xml', f.replace('.xml', '.xml.tab'), 'blast-tab', fields="qseqid sseqid pident description length mismatch gapopen qstart qend sstart send evalue bitscore"
print("converted ", f, " to ", f.replace('.xml', '.xml.tab'))
print("finished")
convert_to_tab
exit
| manasb/genomics | 469/FASTA/RESULTS/23_NOV_2015/TESTING/xml-to-tab.py | Python | gpl-3.0 | 649 | [
"BLAST"
] | c266f6a9250de28b1d9e96c3eaae2dff8d3bd051ea489b48dc225679a40ef404 |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import unicode_literals
import unittest
from pymatgen.command_line.aconvasp_caller import get_num_division_kpoints, \
get_minkowski_red, get_vasp_kpoint_file_sym
from pymatgen.core.composition import Composition
from pymatgen.core.structure import Lattice, Structure
from pymatgen.core.periodic_table import Element
from monty.os.path import which
aconvasp_present = which('aconvasp')
aconvasp_present = False # disable aconvasp testing for now.
@unittest.skipIf(not aconvasp_present, "aconvasp not present.")
class AconvaspCallerTest(unittest.TestCase):
def setUp(self):
self.si = Element("Si")
coords = list()
coords.append([0, 0, 0])
coords.append([0.75, 0.5, 0.75])
self.lattice = Lattice([[3.8401979337, 0.00, 0.00],
[1.9200989668, 3.3257101909, 0.00],
[0.00, -2.2171384943, 3.1355090603]])
self.struct = Structure(self.lattice, [self.si, self.si], coords)
def test_get_num_division_kpoints(self):
self.assertListEqual(get_num_division_kpoints(self.struct, 500),
[6, 7, 6])
def test_get_minkowski_red(self):
new_struct = get_minkowski_red(self.struct)
self.assertAlmostEqual(new_struct.lattice.a, 3.840198)
self.assertAlmostEqual(new_struct.lattice.alpha, 60.0)
self.assertEqual(new_struct.species_and_occu[0], Composition("Si"))
self.assertEqual(new_struct.frac_coords[1][0], 0.25)
def test_get_vasp_kpoint_file_sym(self):
self.assertEqual(get_vasp_kpoint_file_sym(self.struct).split("\n")[0],
"FCC (face-centered cubic) G-X-W-K-G-L-U-W-L-K U-X")
if __name__ == '__main__':
unittest.main()
| matk86/pymatgen | pymatgen/command_line/tests/test_aconvasp_caller.py | Python | mit | 1,881 | [
"pymatgen"
] | d78697b9c7ce740516d34c883b51cb9440707794a60dfc372efb57978782d4e1 |
#!/usr/bin/env python
import pysam
import argparse, sys
import math, time, re
from collections import Counter
from argparse import RawTextHelpFormatter
__author__ = "Colby Chiang (cc2qe@virginia.edu)"
__version__ = "$Revision: 0.0.1 $"
__date__ = "$Date: 2015-09-28 11:31 $"
# --------------------------------------
# define functions
def get_args():
parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter, description="\
vcf_modify_header.py\n\
author: " + __author__ + "\n\
version: " + __version__ + "\n\
description: Add or remove lines from the header")
parser.add_argument('-i', '--id', dest='vcf_id', metavar='STR', type=str, required=False, help='field id')
parser.add_argument('-c', '--category', dest='category', metavar='STR', type=str, help='INFO, FORMAT, FILTER')
parser.add_argument('-t', '--type', dest='type', metavar='STR', type=str, required=False, help='Number, String, Float, Integer')
parser.add_argument('-n', '--number', dest='number', metavar='STR', type=str, required=False, help='integer, A, R, G, or .')
parser.add_argument('-d', '--description', dest='description', metavar='STR', type=str, required=False, help='description')
parser.add_argument(metavar='vcf', dest='input_vcf', nargs='?', type=argparse.FileType('r'), default=None, help='VCF input (default: stdin)')
# parse the arguments
args = parser.parse_args()
# if no input, check if part of pipe and if so, read stdin.
if args.input_vcf == None:
if sys.stdin.isatty():
parser.print_help()
exit(1)
else:
args.input_vcf = sys.stdin
# send back the user input
return args
class Vcf(object):
def __init__(self):
self.file_format = 'VCFv4.2'
# self.fasta = fasta
self.reference = ''
self.sample_list = []
self.info_list = []
self.format_list = []
self.filter_list = []
self.alt_list = []
self.add_format('GT', 1, 'String', 'Genotype')
def add_header(self, header):
for line in header:
if line.split('=')[0] == '##fileformat':
self.file_format = line.rstrip().split('=')[1]
elif line.split('=')[0] == '##reference':
self.reference = line.rstrip().split('=')[1]
elif line.split('=')[0] == '##INFO':
a = line[line.find('<')+1:line.find('>')]
r = re.compile(r'(?:[^,\"]|\"[^\"]*\")+')
self.add_info(*[b.split('=')[1] for b in r.findall(a)])
elif line.split('=')[0] == '##ALT':
a = line[line.find('<')+1:line.find('>')]
r = re.compile(r'(?:[^,\"]|\"[^\"]*\")+')
self.add_alt(*[b.split('=')[1] for b in r.findall(a)])
elif line.split('=')[0] == '##FORMAT':
a = line[line.find('<')+1:line.find('>')]
r = re.compile(r'(?:[^,\"]|\"[^\"]*\")+')
self.add_format(*[b.split('=')[1] for b in r.findall(a)])
elif line.split('=')[0] == '##FILTER':
a = line[line.find('<')+1:-2]
r = re.compile(r'(?:[^,\"]|\"[^\"]*\")+')
self.add_filter(*[b.split('=')[1] for b in r.findall(a)])
elif line[0] == '#' and line[1] != '#':
self.sample_list = line.rstrip().split('\t')[9:]
# return the VCF header
def get_header(self, include_samples=True):
if include_samples:
header = '\n'.join(['##fileformat=' + self.file_format,
'##fileDate=' + time.strftime('%Y%m%d'),
'##reference=' + self.reference] + \
[f.hstring for f in self.filter_list] + \
[i.hstring for i in self.info_list] + \
[a.hstring for a in self.alt_list] + \
[f.hstring for f in self.format_list] + \
['\t'.join([
'#CHROM',
'POS',
'ID',
'REF',
'ALT',
'QUAL',
'FILTER',
'INFO',
'FORMAT'] + \
self.sample_list
)])
else:
header = '\n'.join(['##fileformat=' + self.file_format,
'##fileDate=' + time.strftime('%Y%m%d'),
'##reference=' + self.reference] + \
[f.hstring for f in self.filter_list] + \
[i.hstring for i in self.info_list] + \
[a.hstring for a in self.alt_list] + \
[f.hstring for f in self.format_list] + \
['\t'.join([
'#CHROM',
'POS',
'ID',
'REF',
'ALT',
'QUAL',
'FILTER',
'INFO']
)])
return header
def add_info(self, id, number, type, desc):
if id not in [i.id for i in self.info_list]:
inf = self.Info(id, number, type, desc)
self.info_list.append(inf)
def remove_info(self, id):
for i in self.info_list:
if i.id == id:
self.info_list.remove(i)
return
def add_alt(self, id, desc):
if id not in [a.id for a in self.alt_list]:
alt = self.Alt(id, desc)
self.alt_list.append(alt)
def add_format(self, id, number, type, desc):
if id not in [f.id for f in self.format_list]:
fmt = self.Format(id, number, type, desc)
self.format_list.append(fmt)
def add_filter(self, id, desc):
if id not in [f.id for f in self.filter_list]:
filter = self.Filter(id, desc)
self.filter_list.append(filter)
def add_sample(self, name):
self.sample_list.append(name)
# get the VCF column index of a sample
# NOTE: this is zero-based, like python arrays
def sample_to_col(self, sample):
return self.sample_list.index(sample) + 9
class Info(object):
def __init__(self, id, number, type, desc):
self.id = str(id)
self.number = str(number)
self.type = str(type)
self.desc = str(desc)
# strip the double quotes around the string if present
if self.desc.startswith('"') and self.desc.endswith('"'):
self.desc = self.desc[1:-1]
self.hstring = '##INFO=<ID=' + self.id + ',Number=' + self.number + ',Type=' + self.type + ',Description=\"' + self.desc + '\">'
class Alt(object):
def __init__(self, id, desc):
self.id = str(id)
self.desc = str(desc)
# strip the double quotes around the string if present
if self.desc.startswith('"') and self.desc.endswith('"'):
self.desc = self.desc[1:-1]
self.hstring = '##ALT=<ID=' + self.id + ',Description=\"' + self.desc + '\">'
class Format(object):
def __init__(self, id, number, type, desc):
self.id = str(id)
self.number = str(number)
self.type = str(type)
self.desc = str(desc)
# strip the double quotes around the string if present
if self.desc.startswith('"') and self.desc.endswith('"'):
self.desc = self.desc[1:-1]
self.hstring = '##FORMAT=<ID=' + self.id + ',Number=' + self.number + ',Type=' + self.type + ',Description=\"' + self.desc + '\">'
class Filter(object):
def __init__(self, id, desc):
self.id = str(id)
self.desc = str(desc)
# strip the double quotes around the string if present
if self.desc.startswith('"') and self.desc.endswith('"'):
self.desc = self.desc[1:-1]
self.hstring = '##FILTER=<ID=' + self.id + ',Description=\"' + self.desc + '\">'
class Variant(object):
def __init__(self, var_list, vcf):
self.chrom = var_list[0]
self.pos = int(var_list[1])
self.var_id = var_list[2]
self.ref = var_list[3]
self.alt = var_list[4]
if var_list[5] == '.':
self.qual = 0
else:
self.qual = float(var_list[5])
self.filter = var_list[6]
self.sample_list = vcf.sample_list
self.info_list = vcf.info_list
self.info = dict()
self.format_list = vcf.format_list
self.active_formats = list()
self.gts = dict()
# fill in empty sample genotypes
if len(var_list) < 8:
sys.stderr.write('\nError: VCF file must have at least 8 columns\n')
exit(1)
if len(var_list) < 9:
var_list.append("GT")
# make a genotype for each sample at variant
for s in self.sample_list:
try:
s_gt = var_list[vcf.sample_to_col(s)].split(':')[0]
self.gts[s] = Genotype(self, s, s_gt)
# import the existing fmt fields
for j in zip(var_list[8].split(':'), var_list[vcf.sample_to_col(s)].split(':')):
self.gts[s].set_format(j[0], j[1])
except IndexError:
self.gts[s] = Genotype(self, s, './.')
self.info = dict()
i_split = [a.split('=') for a in var_list[7].split(';')] # temp list of split info column
for i in i_split:
if len(i) == 1:
i.append(True)
self.info[i[0]] = i[1]
def set_info(self, field, value):
if field in [i.id for i in self.info_list]:
self.info[field] = value
else:
sys.stderr.write('\nError: invalid INFO field, \"' + field + '\"\n')
exit(1)
def get_info(self, field):
return self.info[field]
def get_info_string(self):
i_list = list()
for info_field in self.info_list:
if info_field.id in self.info.keys():
if info_field.type == 'Flag':
i_list.append(info_field.id)
else:
i_list.append('%s=%s' % (info_field.id, self.info[info_field.id]))
return ';'.join(i_list)
def get_format_string(self):
f_list = list()
for f in self.format_list:
if f.id in self.active_formats:
f_list.append(f.id)
return ':'.join(f_list)
def genotype(self, sample_name):
if sample_name in self.sample_list:
return self.gts[sample_name]
else:
sys.stderr.write('\nError: invalid sample name, \"' + sample_name + '\"\n')
def get_var_string(self):
s = '\t'.join(map(str,[
self.chrom,
self.pos,
self.var_id,
self.ref,
self.alt,
'%0.2f' % self.qual,
self.filter,
self.get_info_string(),
self.get_format_string(),
'\t'.join(self.genotype(s).get_gt_string() for s in self.sample_list)
]))
return s
class Genotype(object):
def __init__(self, variant, sample_name, gt):
self.format = dict()
self.variant = variant
self.set_format('GT', gt)
def set_format(self, field, value):
if field in [i.id for i in self.variant.format_list]:
self.format[field] = value
if field not in self.variant.active_formats:
self.variant.active_formats.append(field)
# sort it to be in the same order as the format_list in header
self.variant.active_formats.sort(key=lambda x: [f.id for f in self.variant.format_list].index(x))
else:
sys.stderr.write('\nError: invalid FORMAT field, \"' + field + '\"\n')
exit(1)
def get_format(self, field):
return self.format[field]
def get_gt_string(self):
g_list = list()
for f in self.variant.active_formats:
if f in self.format:
if type(self.format[f]) == float:
g_list.append('%0.2f' % self.format[f])
else:
g_list.append(self.format[f])
else:
g_list.append('.')
return ':'.join(map(str,g_list))
# primary function
def mod_header(vcf_id,
category,
f_type,
number,
description,
vcf_file):
in_header = True
header = []
breakend_dict = {} # cache to hold unmatched generic breakends for genotyping
vcf = Vcf()
vcf_out = sys.stdout
# read input VCF
for line in vcf_file:
if in_header:
if line[0] == '#':
header.append(line)
if line[1] != '#':
vcf_samples = line.rstrip().split('\t')[9:]
continue
else:
in_header = False
vcf.add_header(header)
if category == 'INFO':
vcf.remove_info(vcf_id)
vcf.add_info(vcf_id, number, f_type, description)
elif category == 'FORMAT':
vcf.add_format(vcf_id, number, f_type, description)
elif category == 'FILTER':
vcf.add_filter(vcf_id, description)
# write the output header
if len(vcf_samples) > 0:
vcf_out.write(vcf.get_header(include_samples=True) + '\n')
else:
vcf_out.write(vcf.get_header(include_samples=False) + '\n')
vcf_out.write(line)
vcf_out.close()
return
# --------------------------------------
# main function
def main():
# parse the command line args
args = get_args()
# call primary function
mod_header(args.vcf_id,
args.category,
args.type,
args.number,
args.description,
args.input_vcf)
# close the files
args.input_vcf.close()
# initialize the script
if __name__ == '__main__':
try:
sys.exit(main())
except IOError, e:
if e.errno != 32: # ignore SIGPIPE
raise
| abelhj/svtools | svtools/bin/svtyper/scripts/vcf_modify_header.py | Python | mit | 14,777 | [
"pysam"
] | cd4d7f0290e1fb6d023fc6dc0e8f7c964f3a276fee26916f9bfc93028dfbf1ae |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the unique domains visited analysis plugin."""
from __future__ import unicode_literals
import unittest
from plaso.analysis import unique_domains_visited
from plaso.lib import definitions
from tests.analysis import test_lib
class UniqueDomainsPluginTest(test_lib.AnalysisPluginTestCase):
"""Tests for the unique domains analysis plugin."""
_TEST_EVENTS = [
{'data_type': 'chrome:history:file_downloaded',
'domain':'firstevent.com',
'path': '/1/index.html',
'timestamp': '2015-01-01 01:00:00',
'timestamp_desc': definitions.TIME_DESCRIPTION_UNKNOWN,
'url': 'https://firstevent.com/1/index.html'},
{'data_type': 'firefox:places:page_visited',
'domain': 'secondevent.net',
'path': '/2/index.html',
'timestamp': '2015-02-02 02:00:00',
'timestamp_desc': definitions.TIME_DESCRIPTION_UNKNOWN,
'url': 'https://secondevent.net/2/index.html'},
{'data_type': 'msiecf:redirected',
'domain': 'thirdevent.org',
'path': '/3/index.html',
'timestamp': '2015-03-03 03:00:00',
'timestamp_desc': definitions.TIME_DESCRIPTION_UNKNOWN,
'url': 'https://thirdevent.org/3/index.html'},
{'data_type': 'safari:history:visit',
'domain': 'fourthevent.co',
'path': '/4/index.html',
'timestamp': '2015-04-04 04:00:00',
'timestamp_desc': definitions.TIME_DESCRIPTION_UNKNOWN,
'url': 'https://fourthevent.co/4/index.html'}]
def testExamineEventAndCompileReport(self):
"""Tests the ExamineEvent and CompileReport functions."""
plugin = unique_domains_visited.UniqueDomainsVisitedPlugin()
storage_writer = self._AnalyzeEvents(self._TEST_EVENTS, plugin)
self.assertEqual(len(storage_writer.analysis_reports), 1)
analysis_report = storage_writer.analysis_reports[0]
report_text = analysis_report.GetString()
for event_dictionary in self._TEST_EVENTS:
domain = event_dictionary.get('domain', '')
self.assertIn(domain, report_text)
if __name__ == '__main__':
unittest.main()
| rgayon/plaso | tests/analysis/unique_domains_visited.py | Python | apache-2.0 | 2,121 | [
"VisIt"
] | 23f5ec5c875e59c6efaa3b17de6d0aea48dcdda7ece8e81bf2710559b6813397 |
import re
import subprocess
from thefuck.utils import replace_command
def match(command, script):
return command.script.startswith('gulp')\
and 'is not in your gulpfile' in command.stdout
def get_gulp_tasks():
proc = subprocess.Popen(['gulp', '--tasks-simple'],
stdout=subprocess.PIPE)
return [line.decode('utf-8')[:-1]
for line in proc.stdout.readlines()]
def get_new_command(command, script):
wrong_task = re.findall(r"Task '(\w+)' is not in your gulpfile",
command.stdout)[0]
return replace_command(command, wrong_task, get_gulp_tasks())
| NguyenHoaiNam/thefuck | thefuck/rules/gulp_not_task.py | Python | mit | 643 | [
"GULP"
] | 4adda2de60ae73e5f96e93eecf20bc826ccd5008d232547eab2bae07490d9b76 |
# Copyright (C) 2010-2019 The ESPResSo project
#
# This file is part of ESPResSo.
#
# ESPResSo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ESPResSo 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import collections.abc
from .script_interface import ScriptInterfaceHelper, script_interface_register, ScriptObjectRegistry
class Shape:
_so_bind_methods = ("calc_distance",)
@script_interface_register
class Cylinder(Shape, ScriptInterfaceHelper):
"""
A cylinder shape.
Attributes
----------
center : (3,) array_like of :obj:`float`
Coordinates of the center of the cylinder.
axis : (3,) array_like of :obj:`float`
Axis of the cylinder.
radius : :obj:`float`
Radius of the cylinder.
length : :obj:`float`
Length of the cylinder.
direction : :obj:`int`
Surface orientation, for +1 the normal points
out of the mantel, for -1 it points inward.
open : :obj:`bool`
cylinder is open or has caps.
"""
_so_name = "Shapes::Cylinder"
@script_interface_register
class Ellipsoid(Shape, ScriptInterfaceHelper):
"""
An ellipsoid.
For now only ellipsoids of revolution are supported.
The symmetry axis is aligned parallel to the x-direction.
Attributes
----------
center : (3,) array_like of :obj:`float`
Coordinates of the center of the ellipsoid.
a : :obj:`float`
Semiaxis along the axis of rotational symmetry.
b : :obj:`float`
Equatorial semiaxes.
direction : :obj:`int`
Surface orientation, for +1 the normal points
out of the mantel, for -1 it points inward.
"""
_so_name = "Shapes::Ellipsoid"
@script_interface_register
class Rhomboid(Shape, ScriptInterfaceHelper):
"""
An parallelepiped.
Attributes
----------
a : (3,) array_like of :obj:`float`
First base vector.
b : (3,) array_like of :obj:`float`
Second base vector.
c : (3,) array_like of :obj:`float`
Third base vector.
corner : (3,) array_like of :obj:`float`
Lower left corner of the rhomboid.
direction : :obj:`int`
Surface orientation, for +1 the normal points
out of the mantel, for -1 it points inward.
"""
_so_name = "Shapes::Rhomboid"
@script_interface_register
class Slitpore(Shape, ScriptInterfaceHelper):
"""
.. figure:: figures/slitpore.png
:alt: Schematic for the Slitpore shape with labeled geometrical parameters.
:align: center
:height: 8.00000cm
Attributes
----------
channel_width : :obj:`float`
lower_smoothing_radius : :obj:`float`
pore_length : :obj:`float`
pore_mouth : :obj:`float`
pore_width : :obj:`float`
upper_smoothing_radius : :obj:`float`
dividing_plane : :obj:`float`
"""
_so_name = "Shapes::Slitpore"
@script_interface_register
class Sphere(Shape, ScriptInterfaceHelper):
"""
A sphere.
Attributes
----------
center : (3,) array_like of :obj:`float`
Center of the sphere
radius : :obj:`float`
Radius of the sphere.
direction : :obj:`int`
Surface orientation, for +1 the normal points
out of the mantel, for -1 it points inward.
"""
_so_name = "Shapes::Sphere"
@script_interface_register
class SpheroCylinder(Shape, ScriptInterfaceHelper):
"""
A cylinder with hemispheres as caps.
Attributes
----------
center : (3,) array_like of :obj:`float`
Coordinates of the center of the cylinder.
axis : (3,) array_like of :obj:`float`
Axis of the cylinder.
radius : :obj:`float`
Radius of the cylinder.
direction : :obj:`int`
Surface orientation, for +1 the normal points
out of the mantel, for -1 it points inward.
length : :obj:`float`
Length of the cylinder (not including the caps).
"""
_so_name = "Shapes::SpheroCylinder"
@script_interface_register
class Torus(Shape, ScriptInterfaceHelper):
"""
A torus shape.
Attributes
----------
center : (3,) array_like of :obj:`float`
Coordinates of the center of the torus.
normal : (3,) array_like of :obj:`float`
Normal axis of the torus.
radius : :obj:`float`
Radius of the torus.
tube_radius : :obj:`float`
Radius of the tube.
direction : :obj:`int`
Surface orientation, for +1 the normal points
out of the mantel, for -1 it points inward.
"""
_so_name = "Shapes::Torus"
@script_interface_register
class Wall(Shape, ScriptInterfaceHelper):
"""
An infinite plane.
Attributes
----------
dist : :obj:`float`
Distance from the origin.
normal : (3,) array_like of :obj:`int`
Normal vector of the plane (needs not to be length 1).
"""
_so_name = "Shapes::Wall"
@script_interface_register
class SimplePore(Shape, ScriptInterfaceHelper):
"""
Two parallel infinite planes, and a cylindrical channel connecting them.
The cylinder and the planes are connected by torus segments with an
adjustable radius.
Attributes
----------
radius: :obj:`float`
The radius of the pore.
length: :obj:`float`
The distance between the planes.
smoothing_radius: :obj:`float`
Radius of the torus segments
axis: (3,) array_like of :obj:`float`
Axis of the cylinder and normal of the planes
center: (3,) array_like of :obj:`float`
Position of the center of the cylinder.
"""
_so_name = "Shapes::SimplePore"
@script_interface_register
class HollowConicalFrustum(Shape, ScriptInterfaceHelper):
"""
Hollow conical frustum shape.
Attributes
----------
r1: :obj:`float`
Radius r1.
r2: :obj:`float`
Radius r2.
length: :obj:`float`
Length of the conical frustum along ``axis``.
axis: (3,) array_like of :obj:`float`
Symmetry axis.
center: (3,) array_like of :obj:`float`
Position of the center.
.. image:: figures/conical_frustum.png
"""
_so_name = "Shapes::HollowConicalFrustum"
@script_interface_register
class Union(Shape, ScriptObjectRegistry):
"""A union of shapes.
This shape represents a union of shapes where the distance to the union
is defined by the smallest distance to any shape contained in the union.
"""
_so_name = "Shapes::Union"
def add(self, shape):
"""
Add a shape to the union.
Parameters
----------
shape : array_like / instance of :class:`espressomd.shapes.Shape`
Shape instance(s) to be added to the union.
"""
def _add(self, shape):
if isinstance(shape, Shape):
self.call_method("add", shape=shape)
else:
raise ValueError("Only shapes can be added.")
if isinstance(shape, collections.abc.Iterable):
for s in shape:
_add(self, s)
else:
_add(self, shape)
def remove(self, shape):
"""
Remove a shape from the union.
Parameters
----------
shape : array_like / instance of :class:`espressomd.shapes.Shape`
Shape instance(s) to be removed from the union.
"""
def _remove(self, shape):
if isinstance(shape, Shape):
self.call_method("remove", shape=shape)
else:
raise ValueError("Only shapes can be removed.")
if isinstance(shape, collections.abc.Iterable):
for s in shape:
_remove(self, s)
else:
_remove(self, shape)
def clear(self):
"""
Remove all shapes from the union.
"""
self.call_method("clear")
def size(self):
"""
Number of shapes contained in the union.
"""
return self.call_method("size")
| KaiSzuttor/espresso | src/python/espressomd/shapes.py | Python | gpl-3.0 | 8,473 | [
"ESPResSo"
] | 22232286522c213d6e525e5f9e4213b7f689e96410b3e66d2e6f0eaecd0ed5a6 |
#!/usr/bin/env python
""" task_setup.py - Version 1.0 2013-12-20
Set up a number of waypoints and a charging station for use with simulated tasks using
SMACH and teer.
Created for the Pi Robot Project: http://www.pirobot.org
Copyright (c) 2013 Patrick Goebel. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.5
This program 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 General Public License for more details at:
http://www.gnu.org/licenses/gpl.html
"""
import rospy
import actionlib
from actionlib import GoalStatus
from geometry_msgs.msg import Pose, Point, Quaternion, Twist
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal, MoveBaseActionFeedback
from tf.transformations import quaternion_from_euler
from visualization_msgs.msg import Marker
from math import pi
from collections import OrderedDict
def setup_task_environment(self):
# How big is the square we want the robot to patrol?
self.square_size = rospy.get_param("~square_size", 1.0) # meters
# Set the low battery threshold (between 0 and 100)
self.low_battery_threshold = rospy.get_param('~low_battery_threshold', 50)
# How many times should we execute the patrol loop
self.n_patrols = rospy.get_param("~n_patrols", 2) # meters
# How long do we have to get to each waypoint?
self.move_base_timeout = rospy.get_param("~move_base_timeout", 60) #seconds
# Initialize the patrol counter
self.patrol_count = 0
# Subscribe to the move_base action server
self.move_base = actionlib.SimpleActionClient("move_base", MoveBaseAction)
rospy.loginfo("Waiting for move_base action server...")
# Wait up to 60 seconds for the action server to become available
self.move_base.wait_for_server(rospy.Duration(60))
rospy.loginfo("Connected to move_base action server")
# Create a list to hold the target quaternions (orientations)
quaternions = list()
# First define the corner orientations as Euler angles
euler_angles = (pi/2, pi, 3*pi/2, 0)
# Then convert the angles to quaternions
for angle in euler_angles:
q_angle = quaternion_from_euler(0, 0, angle, axes='sxyz')
q = Quaternion(*q_angle)
quaternions.append(q)
# Create a list to hold the waypoint poses
self.waypoints = list()
# Append each of the four waypoints to the list. Each waypoint
# is a pose consisting of a position and orientation in the map frame.
self.waypoints.append(Pose(Point(0.0, 0.0, 0.0), quaternions[3]))
self.waypoints.append(Pose(Point(self.square_size, 0.0, 0.0), quaternions[0]))
self.waypoints.append(Pose(Point(self.square_size, self.square_size, 0.0), quaternions[1]))
self.waypoints.append(Pose(Point(0.0, self.square_size, 0.0), quaternions[2]))
# Create a mapping of room names to waypoint locations
room_locations = (('hallway', self.waypoints[0]),
('living_room', self.waypoints[1]),
('kitchen', self.waypoints[2]),
('bathroom', self.waypoints[3]))
# Store the mapping as an ordered dictionary so we can visit the rooms in sequence
self.room_locations = OrderedDict(room_locations)
# Where is the docking station?
self.docking_station_pose = (Pose(Point(0.5, 0.5, 0.0), Quaternion(0.0, 0.0, 0.0, 1.0)))
# Initialize the waypoint visualization markers for RViz
init_waypoint_markers(self)
# Set a visualization marker at each waypoint
for waypoint in self.waypoints:
p = Point()
p = waypoint.position
self.waypoint_markers.points.append(p)
# Set a marker for the docking station
init_docking_station_marker(self)
# Publisher to manually control the robot (e.g. to stop it)
self.cmd_vel_pub = rospy.Publisher('cmd_vel', Twist)
rospy.loginfo("Starting Tasks")
# Publish the waypoint markers
self.marker_pub.publish(self.waypoint_markers)
rospy.sleep(1)
self.marker_pub.publish(self.waypoint_markers)
# Publish the docking station marker
self.docking_station_marker_pub.publish(self.docking_station_marker)
rospy.sleep(1)
def init_waypoint_markers(self):
# Set up our waypoint markers
marker_scale = 0.2
marker_lifetime = 0 # 0 is forever
marker_ns = 'waypoints'
marker_id = 0
marker_color = {'r': 1.0, 'g': 0.7, 'b': 1.0, 'a': 1.0}
# Define a marker publisher.
self.marker_pub = rospy.Publisher('waypoint_markers', Marker)
# Initialize the marker points list.
self.waypoint_markers = Marker()
self.waypoint_markers.ns = marker_ns
self.waypoint_markers.id = marker_id
self.waypoint_markers.type = Marker.CUBE_LIST
self.waypoint_markers.action = Marker.ADD
self.waypoint_markers.lifetime = rospy.Duration(marker_lifetime)
self.waypoint_markers.scale.x = marker_scale
self.waypoint_markers.scale.y = marker_scale
self.waypoint_markers.color.r = marker_color['r']
self.waypoint_markers.color.g = marker_color['g']
self.waypoint_markers.color.b = marker_color['b']
self.waypoint_markers.color.a = marker_color['a']
self.waypoint_markers.header.frame_id = 'odom'
self.waypoint_markers.header.stamp = rospy.Time.now()
self.waypoint_markers.points = list()
def init_docking_station_marker(self):
# Define a marker for the charging station
marker_scale = 0.3
marker_lifetime = 0 # 0 is forever
marker_ns = 'waypoints'
marker_id = 0
marker_color = {'r': 0.7, 'g': 0.7, 'b': 0.0, 'a': 1.0}
self.docking_station_marker_pub = rospy.Publisher('docking_station_marker', Marker)
self.docking_station_marker = Marker()
self.docking_station_marker.ns = marker_ns
self.docking_station_marker.id = marker_id
self.docking_station_marker.type = Marker.CYLINDER
self.docking_station_marker.action = Marker.ADD
self.docking_station_marker.lifetime = rospy.Duration(marker_lifetime)
self.docking_station_marker.scale.x = marker_scale
self.docking_station_marker.scale.y = marker_scale
self.docking_station_marker.scale.z = 0.02
self.docking_station_marker.color.r = marker_color['r']
self.docking_station_marker.color.g = marker_color['g']
self.docking_station_marker.color.b = marker_color['b']
self.docking_station_marker.color.a = marker_color['a']
self.docking_station_marker.header.frame_id = 'odom'
self.docking_station_marker.header.stamp = rospy.Time.now()
self.docking_station_marker.pose = self.docking_station_pose
| peterheim1/robbie_ros | robbie_ai/src/robbie_ai/task_setup.py | Python | bsd-3-clause | 7,076 | [
"VisIt"
] | ee1c765db3bdaab4171f2c30b02614a719dbddf5374ae28f1895c37b70032ca3 |
""" simple hello world job
"""
from DIRAC.Interfaces.API.Job import Job
from DIRAC.Interfaces.API.Dirac import Dirac
from DIRAC.DataManagementSystem.Utilities.DMSHelpers import DMSHelpers
j = Job()
j.setName("helloWorld-test")
j.setExecutable("exe-script.py", "", "Executable.log")
# <-- user settings
j.setCPUTime(172800)
tier1s = DMSHelpers().getTiers(tier=(0, 1))
j.setBannedSites(tier1s)
# user settings -->
# print j.workflow
# submit the job to dirac
result = Dirac().submitJob(j)
print(result)
| DIRACGrid/DIRAC | src/DIRAC/tests/Workflow/Regression/helloWorld.py | Python | gpl-3.0 | 509 | [
"DIRAC"
] | ebd782805b95498a3e98adc38f6770d5cea0f3ab05e4592c2827fc5766865683 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import datetime
import errno
import json
from sqlalchemy import orm
from DIRAC.DataManagementSystem.Client.FTS3Job import FTS3Job
from DIRAC.DataManagementSystem.private import FTS3Utilities
from DIRAC.DataManagementSystem.Utilities.DMSHelpers import DMSHelpers
from DIRAC.DataManagementSystem.Client.DataManager import DataManager
from DIRAC.FrameworkSystem.Client.Logger import gLogger
from DIRAC.Resources.Storage.StorageElement import StorageElement
from DIRAC.Core.Utilities.ReturnValues import returnSingleResult
from DIRAC.Core.Utilities.DErrno import cmpError
from DIRAC import S_OK, S_ERROR
from DIRAC.Core.Utilities.List import breakListIntoChunks
from DIRAC.ResourceStatusSystem.Client.ResourceStatus import ResourceStatus
from DIRAC.DataManagementSystem.Client.FTS3File import FTS3File
from DIRAC.Core.Utilities.JEncode import JSerializable
from DIRAC.RequestManagementSystem.Client.ReqClient import ReqClient
from DIRAC.RequestManagementSystem.Client.Operation import Operation as rmsOperation
from DIRAC.RequestManagementSystem.Client.File import File as rmsFile
from DIRAC.RequestManagementSystem.Client.Request import Request as rmsRequest
from DIRAC.ConfigurationSystem.Client.Helpers.Registry import getVOForGroup
class FTS3Operation(JSerializable):
"""Abstract class to represent an operation to be executed by FTS. It is a
container for FTSFiles, as well as for FTSJobs.
There can be a mapping between one FTS3Operation and one RMS Operation.
The FTS3Operation takes care of generating the appropriate FTSJobs,
and to perform a callback when the work with FTS is over. The actual
generation and callback depends on the subclass.
This class should not be instantiated directly, but rather one of its
subclass
"""
# START states
ALL_STATES = [
"Active", # Default state until FTS has done everything
"Processed", # Interactions with FTS done, but callback not done
"Finished", # Everything was done
"Canceled", # Canceled by the user
"Failed", # I don't know yet
]
FINAL_STATES = ["Finished", "Canceled", "Failed"]
INIT_STATE = "Active"
# END states
_attrToSerialize = [
"operationID",
"username",
"userGroup",
"rmsReqID",
"rmsOpID",
"sourceSEs",
"ftsFiles",
"activity",
"priority",
"ftsJobs",
"creationTime",
"lastUpdate",
"error",
"status",
]
def __init__(
self,
ftsFiles=None,
username=None,
userGroup=None,
rmsReqID=-1,
rmsOpID=0,
sourceSEs=None,
activity=None,
priority=None,
):
"""
:param ftsFiles: list of FTS3Files object that belongs to the operation
:param username: username whose proxy should be used
:param userGroup: group that should be used with username
:param rmsReqID: ID of the Request in the RMS system
:param rmsOpID: ID of the Operation in the RMS system
:param sourceSEs: list of SE to be used as source (if applicable)
:param activity: FTS activity to use
:param priority: FTS priority to use
"""
############################
# persistent attributes
self.username = username
self.userGroup = userGroup
self.rmsReqID = rmsReqID
self.rmsOpID = rmsOpID
if isinstance(sourceSEs, list):
sourceSEs = ",".join(sourceSEs)
self.sourceSEs = sourceSEs
self.ftsFiles = ftsFiles if ftsFiles else []
self.activity = activity
self.priority = priority
self.ftsJobs = []
now = datetime.datetime.utcnow().replace(microsecond=0)
self.creationTime = now
self.lastUpdate = now
self.error = None
self.status = FTS3Operation.INIT_STATE
########################
self.reqClient = None
self.dManager = None
self._log = None
self.fts3Plugin = None
self.init_on_load()
@orm.reconstructor
def init_on_load(self):
"""This method initializes some attributes.
It is called by sqlalchemy (which does not call __init__)
"""
self._vo = None
# Note that in the case of an FTS3Operation created from an RMS
# object, the members here will probably be "wrong" in the sense
# that the VO will not be known by then.
# It does not really matter however, since we do not perform anything
# on an operation created this way, it's just to be then serialized
# in the DB.
self.dManager = DataManager()
self.rssClient = ResourceStatus()
self.fts3Plugin = FTS3Utilities.getFTS3Plugin(vo=self.vo)
opID = getattr(self, "operationID", None)
loggerName = "%s/" % opID if opID else ""
loggerName += "req_%s/op_%s" % (self.rmsReqID, self.rmsOpID)
self._log = gLogger.getSubLogger(loggerName)
@property
def vo(self):
""":returns: return vo of the usergroup"""
if self._vo:
return self._vo
if self.userGroup:
self._vo = getVOForGroup(self.userGroup)
return self._vo
def isTotallyProcessed(self):
"""Returns True if and only if there is nothing
else to be done by FTS for this operation.
All files are successful or definitely failed
"""
if self.status == "Processed":
return True
fileStatuses = set([f.status for f in self.ftsFiles])
# If all the files are in a final state
if fileStatuses <= set(FTS3File.FINAL_STATES):
self.status = "Processed"
return True
return False
def _getFilesToSubmit(self, maxAttemptsPerFile=10):
"""Return the list of FTS3files that can be submitted
Either because they never were submitted, or because
we can make more attempts
:param maxAttemptsPerFile: the maximum number of attempts to be tried for a file
:return: List of FTS3File to submit
"""
toSubmit = []
for ftsFile in self.ftsFiles:
if ftsFile.attempt >= maxAttemptsPerFile:
ftsFile.status = "Defunct"
# The file was never submitted or
# The file failed from the point of view of FTS
# but no more than the maxAttemptsPerFile
elif ftsFile.status in [FTS3File.INIT_STATE] + FTS3File.FTS_FAILED_STATES:
toSubmit.append(ftsFile)
return toSubmit
@staticmethod
def _checkSEAccess(seName, accessType, vo=None):
"""Check the Status of a storage element
:param seName: name of the StorageElement
:param accessType ReadAccess, WriteAccess,CheckAccess,RemoveAccess
:return: S_ERROR if not allowed or error, S_OK() otherwise
"""
# Check that the target is writable
# access = self.rssClient.getStorageElementStatus( seName, accessType )
# if not access["OK"]:
# return access
# if access["Value"][seName][accessType] not in ( "Active", "Degraded" ):
# return S_ERROR( "%s does not have %s in Active or Degraded" % ( seName, accessType ) )
status = StorageElement(seName, vo=vo).getStatus()
if not status["OK"]:
return status
status = status["Value"]
accessType = accessType.replace("Access", "")
if not status[accessType]:
return S_ERROR(errno.EACCES, "%s does not have %s in Active or Degraded" % (seName, accessType))
return S_OK()
def _createNewJob(self, jobType, ftsFiles, targetSE, sourceSE=None):
"""Create a new FTS3Job object
:param jobType: type of job to create (Transfer, Staging, Removal)
:param ftsFiles: list of FTS3File objects the job has to work on
:param targetSE: SE on which to operate
:param sourceSE: source SE, only useful for Transfer jobs
:return: FTS3Job object
"""
newJob = FTS3Job()
newJob.type = jobType
newJob.sourceSE = sourceSE
newJob.targetSE = targetSE
newJob.activity = self.activity
newJob.priority = self.priority
newJob.username = self.username
newJob.userGroup = self.userGroup
newJob.vo = self.vo
newJob.filesToSubmit = ftsFiles
newJob.operationID = getattr(self, "operationID")
newJob.rmsReqID = self.rmsReqID
return newJob
def _callback(self):
"""Actually performs the callback"""
raise NotImplementedError("You should not be using the base class")
def callback(self):
"""Trigger the callback once all the FTS interactions are done
and update the status of the Operation to 'Finished' if successful
"""
self.reqClient = ReqClient()
res = self._callback()
if res["OK"]:
self.status = "Finished"
return res
def prepareNewJobs(self, maxFilesPerJob=100, maxAttemptsPerFile=10):
"""Prepare the new jobs that have to be submitted
:param maxFilesPerJob: maximum number of files assigned to a job
:param maxAttemptsPerFile: maximum number of retry after an fts failure
:return: list of jobs
"""
raise NotImplementedError("You should not be using the base class")
def _updateRmsOperationStatus(self):
"""Update the status of the Files in the rms operation
:return: S_OK with a dict:
* request: rms Request object
* operation: rms Operation object
* ftsFilesByTarget: dict {SE: [ftsFiles that were successful]}
"""
log = self._log.getLocalSubLogger(
"_updateRmsOperationStatus/%s/%s" % (getattr(self, "operationID"), self.rmsReqID)
)
res = self.reqClient.getRequest(self.rmsReqID)
if not res["OK"]:
return res
request = res["Value"]
res = request.getWaiting()
if not res["OK"]:
log.error("Unable to find 'Scheduled' operation in request")
res = self.reqClient.putRequest(request, useFailoverProxy=False, retryMainService=3)
if not res["OK"]:
log.error("Could not put back the request !", res["Message"])
return S_ERROR("Could not find scheduled operation")
operation = res["Value"]
# We index the files of the operation by their IDs
rmsFileIDs = {}
for opFile in operation:
rmsFileIDs[opFile.FileID] = opFile
# Files that failed to transfer
defunctRmsFileIDs = set()
# { SE : [FTS3Files] }
ftsFilesByTarget = {}
for ftsFile in self.ftsFiles:
if ftsFile.status == "Defunct":
log.info(
"File failed to transfer, setting it to failed in RMS", "%s %s" % (ftsFile.lfn, ftsFile.targetSE)
)
defunctRmsFileIDs.add(ftsFile.rmsFileID)
continue
if ftsFile.status == "Canceled":
log.info("File canceled, setting it Failed in RMS", "%s %s" % (ftsFile.lfn, ftsFile.targetSE))
defunctRmsFileIDs.add(ftsFile.rmsFileID)
continue
# SHOULD NEVER HAPPEN !
if ftsFile.status != "Finished":
log.error("Callback called with file in non terminal state", "%s %s" % (ftsFile.lfn, ftsFile.targetSE))
res = self.reqClient.putRequest(request, useFailoverProxy=False, retryMainService=3)
if not res["OK"]:
log.error("Could not put back the request !", res["Message"])
return S_ERROR("Callback called with file in non terminal state")
ftsFilesByTarget.setdefault(ftsFile.targetSE, []).append(ftsFile)
# Now, we set the rmsFile as done in the operation, providing
# that they are not in the defunctFiles.
# We cannot do this in the previous list because in the FTS system,
# each destination is a separate line in the DB but not in the RMS
for ftsFile in self.ftsFiles:
opFile = rmsFileIDs[ftsFile.rmsFileID]
opFile.Status = "Failed" if ftsFile.rmsFileID in defunctRmsFileIDs else "Done"
return S_OK({"request": request, "operation": operation, "ftsFilesByTarget": ftsFilesByTarget})
@classmethod
def fromRMSObjects(cls, rmsReq, rmsOp, username):
"""Construct an FTS3Operation object from the RMS Request and Operation corresponding.
The attributes taken are the OwnerGroup, Request and Operation IDS, sourceSE,
and activity and priority if they are defined in the Argument field of the operation
:param rmsReq: RMS Request object
:param rmsOp: RMS Operation object
:param username: username to which associate the FTS3Operation (normally comes from the Req OwnerDN)
:returns: FTS3Operation object
"""
ftsOp = cls()
ftsOp.username = username
ftsOp.userGroup = rmsReq.OwnerGroup
ftsOp.rmsReqID = rmsReq.RequestID
ftsOp.rmsOpID = rmsOp.OperationID
ftsOp.sourceSEs = rmsOp.SourceSE
try:
argumentDic = json.loads(rmsOp.Arguments)
ftsOp.activity = argumentDic["activity"]
ftsOp.priority = argumentDic["priority"]
except Exception:
pass
return ftsOp
class FTS3TransferOperation(FTS3Operation):
"""Class to be used for a Replication operation"""
def prepareNewJobs(self, maxFilesPerJob=100, maxAttemptsPerFile=10):
log = self._log.getSubLogger("_prepareNewJobs")
filesToSubmit = self._getFilesToSubmit(maxAttemptsPerFile=maxAttemptsPerFile)
log.debug("%s ftsFiles to submit" % len(filesToSubmit))
newJobs = []
# {targetSE : [FTS3Files] }
res = FTS3Utilities.groupFilesByTarget(filesToSubmit)
if not res["OK"]:
return res
filesGroupedByTarget = res["Value"]
for targetSE, ftsFiles in filesGroupedByTarget.items():
res = self._checkSEAccess(targetSE, "WriteAccess", vo=self.vo)
if not res["OK"]:
# If the SE is currently banned, we just skip it
if cmpError(res, errno.EACCES):
log.info("Write access currently not permitted to %s, skipping." % targetSE)
else:
log.error(res)
for ftsFile in ftsFiles:
ftsFile.attempt += 1
continue
sourceSEs = self.sourceSEs.split(",") if self.sourceSEs is not None else []
# { sourceSE : [FTSFiles] }
res = FTS3Utilities.selectUniqueSource(ftsFiles, self.fts3Plugin, allowedSources=sourceSEs)
if not res["OK"]:
return res
uniqueTransfersBySource, failedFiles = res["Value"]
# Treat the errors of the failed files
for ftsFile, errMsg in failedFiles.items():
log.error("Error when selecting random sources", "%s, %s" % (ftsFile.lfn, errMsg))
# If the error is that the file does not exist in the catalog
# fail it !
if cmpError(errMsg, errno.ENOENT):
log.error("The file does not exist, setting it Defunct", "%s" % ftsFile.lfn)
ftsFile.status = "Defunct"
# We don't need to check the source, since it is already filtered by the DataManager
for sourceSE, ftsFiles in uniqueTransfersBySource.items():
if self.__needsMultiHopStaging(sourceSE, targetSE):
log.verbose("Needs multihop staging, max files per job is 1")
maxFilesPerJob = 1
for ftsFilesChunk in breakListIntoChunks(ftsFiles, maxFilesPerJob):
newJob = self._createNewJob("Transfer", ftsFilesChunk, targetSE, sourceSE=sourceSE)
newJobs.append(newJob)
return S_OK(newJobs)
def __needsMultiHopStaging(self, sourceSEName, destSEName):
"""Checks whether transfers between the two SE given as parameters
need a multi hop transfer to stage with a different protocol
than the transfer one.
:param str sourceSEName: source storage element name
:param str destSEName: destination storage element name
:returns: boolean
"""
srcSE = StorageElement(sourceSEName, vo=self.vo)
dstSE = StorageElement(destSEName, vo=self.vo)
srcIsTape = srcSE.getStatus()["Value"].get("TapeSE", True)
if not srcIsTape:
return False
# To know if we will need a multihop staging transfer,
# we check whether we can generate transfer URLs
# for a fake LFN, and see if the protocol we get
# is compatible with staging
tpcProtocols = self.fts3Plugin.selectTPCProtocols(sourceSEName=sourceSEName, destSEName=destSEName)
res = dstSE.generateTransferURLsBetweenSEs("/%s/fakeLFN" % self.vo, srcSE, protocols=tpcProtocols)
# There is an error, but let's ignore it,
# it will be dealt with in the FTS3Job logic
if not res["OK"]:
return False
srcProto, _destProto = res["Value"]["Protocols"]
if srcProto not in srcSE.localStageProtocolList:
return True
return False
def _callback(self):
""" " After a Transfer operation, we have to update the matching Request in the
RMS, and add the registration operation just before the ReplicateAndRegister one
NOTE: we don't use ReqProxy when putting the request back to avoid operational hell
"""
log = self._log.getSubLogger("callback")
# In case there is no Request associated to the Transfer
# we do not do the callback. Not really advised, but there is a feature
# request to use the FTS3 system without RMS
if self.rmsReqID == -1:
return S_OK()
# Now we check the status of the Request.
# in principle, it should be scheduled
res = self.reqClient.getRequestStatus(self.rmsReqID)
if not res["OK"]:
log.error("Could not get request status", res)
return res
status = res["Value"]
# If it is not scheduled, something went wrong
# and we will not modify it
if status != "Scheduled":
# If the Request is in a final state, just leave it,
# and we consider our job done.
# (typically happens when the callback had already been done but not persisted to the FTS3DB)
if status in rmsRequest.FINAL_STATES:
log.warn(
"Request with id %s is not Scheduled (%s), but okay it is in a Final State"
% (self.rmsReqID, status)
)
return S_OK()
# If the Request is not in a final state, then something really wrong is going on,
# and we do not do anything, keep ourselves pending
else:
return S_ERROR("Request with id %s is not Scheduled:%s" % (self.rmsReqID, status))
res = self._updateRmsOperationStatus()
if not res["OK"]:
return res
ftsFilesByTarget = res["Value"]["ftsFilesByTarget"]
request = res["Value"]["request"]
operation = res["Value"]["operation"]
registrationProtocols = DMSHelpers(vo=self.vo).getRegistrationProtocols()
log.info("will create %s 'RegisterReplica' operations" % len(ftsFilesByTarget))
for target, ftsFileList in ftsFilesByTarget.items():
log.info(
"creating 'RegisterReplica' operation for targetSE %s with %s files..." % (target, len(ftsFileList))
)
registerOperation = rmsOperation()
registerOperation.Type = "RegisterReplica"
registerOperation.Status = "Waiting"
registerOperation.TargetSE = target
if operation.Catalog:
registerOperation.Catalog = operation.Catalog
targetSE = StorageElement(target, vo=self.vo)
for ftsFile in ftsFileList:
opFile = rmsFile()
opFile.LFN = ftsFile.lfn
opFile.Checksum = ftsFile.checksum
# TODO: are we really ever going to change type... ?
opFile.ChecksumType = "ADLER32"
opFile.Size = ftsFile.size
res = returnSingleResult(targetSE.getURL(ftsFile.lfn, protocol=registrationProtocols))
# This should never happen !
if not res["OK"]:
log.error("Could not get url", res["Message"])
continue
opFile.PFN = res["Value"]
registerOperation.addFile(opFile)
request.insertBefore(registerOperation, operation)
return self.reqClient.putRequest(request, useFailoverProxy=False, retryMainService=3)
class FTS3StagingOperation(FTS3Operation):
"""Class to be used for a Staging operation"""
def prepareNewJobs(self, maxFilesPerJob=100, maxAttemptsPerFile=10):
log = gLogger.getSubLogger("_prepareNewJobs")
filesToSubmit = self._getFilesToSubmit(maxAttemptsPerFile=maxAttemptsPerFile)
log.debug("%s ftsFiles to submit" % len(filesToSubmit))
newJobs = []
# {targetSE : [FTS3Files] }
filesGroupedByTarget = FTS3Utilities.groupFilesByTarget(filesToSubmit)
for targetSE, ftsFiles in filesGroupedByTarget.items():
res = self._checkSEAccess(targetSE, "ReadAccess", vo=self.vo)
if not res["OK"]:
log.error(res)
continue
for ftsFilesChunk in breakListIntoChunks(ftsFiles, maxFilesPerJob):
newJob = self._createNewJob("Staging", ftsFilesChunk, targetSE, sourceSE=targetSE)
newJobs.append(newJob)
return S_OK(newJobs)
def _callback(self):
""" " After a Staging operation, we have to update the matching Request in the
RMS, and nothing more. If a callback is to be performed, it will be the next
operation in the request, and put by the caller
NOTE: we don't use ReqProxy when putting the request back to avoid operational hell
"""
res = self._updateRmsOperationStatus()
if not res["OK"]:
return res
request = res["Value"]["request"]
return self.reqClient.putRequest(request, useFailoverProxy=False, retryMainService=3)
| ic-hep/DIRAC | src/DIRAC/DataManagementSystem/Client/FTS3Operation.py | Python | gpl-3.0 | 22,972 | [
"DIRAC"
] | 31e922724414d797594691adad16c9e1a497e2194f9fba7596faefa732c4f7d3 |
from numpy import array, matrix, diag, exp, inner, nan_to_num
from numpy.core.umath_tests import inner1d
from numpy import argmin, array
class GKS:
"""Gaussian kernel smoother to transform any clustering method into regression. setN is the list containing numpy arrays which are the weights of clustering centors.
populations is a list of integers of cluster populations. standard_variances is the list of real
numbers meaning the standard variances of the dataset along each dimension. smooth is None or real number.
While set to None, an SSL procedure will be employed. For details, see the responses() method."""
sv_kernel = None
setN = None #:Weights of the clustering centers, after instance initialization, it will be a list data structure.
Y = 1 #:Number of response variables.
percentages = None #:Distribution of the cluster populations.
xdim = None #:Dimension of the explanatory variables.
ydim = None #:Dimension of the response variables.
__global = True
smooth = None #:Smooth parameter.
__S = 0.0
K = 5 #: Number of clustering centers for smooth parameter calculation.
def __init__(self, setN, populations, standard_variances, Y_number, smooth = None, K = 5):
if len(setN[0])!=len(standard_variances):
print('ill GKS initialization')
else:
self.sv_kernel = matrix(diag(array(standard_variances)[:-1*Y_number]**-1.0))
self.setN = []
self.Y = []
for each in setN:
self.setN.append(each[:-1*Y_number])
self.Y.append(each[-1*Y_number:])
self.Y = matrix(self.Y).T
self.percentages = array(populations) / float(sum(populations))
self.setN = array(self.setN)
self.xdim = float(len(setN[0]) - Y_number)
self.ydim = float(Y_number)
self.smooth = smooth
self.K = K
def response_1s(self, point):
dif_vectors = self.setN - point
dif_and_varianced = array(matrix(dif_vectors)*self.sv_kernel)
dif_traces = inner1d(dif_and_varianced , dif_vectors)
weights = exp(-0.5*self.__S*dif_traces)
results = (self.Y*(matrix(self.percentages * weights).T))/(inner(self.percentages, weights))
return array(results.T)[0]
def responses(self, points, prototypes = None):
"""points is a list or array of numpy arrays, and this method returns the regression results
of the dataset points. If the smooth parameter is initialized as None, the prototypes parameter
will be required as a list or array of clustering centers in the form of numpy arrays, which is genertated
by the user chosen clustering method on the same dataset to the one specified by points variable."""
if self.smooth == None:
self.K = min(self.K, prototypes)
accumulated_traces = 0.0
for point in prototypes:
dif_vectors = self.setN - point
dif_and_varianced = array(matrix(dif_vectors)*self.sv_kernel)
dif_traces = inner1d(dif_and_varianced , dif_vectors)
nn_index = argmin(dif_traces)
accumulated_traces += float(dif_traces[nn_index])
for i in range(self.K - 1):
dif_traces[nn_index] = float('inf')
nn_index = argmin(dif_traces)
accumulated_traces += float(dif_traces[nn_index])
self.__S = len(self.setN)*self.xdim/accumulated_traces
if self.__S < 0.0:
self.__S = 0.0
else:
self.__S = len(self.setN)**(-2.0*self.smooth)
results = []
if self.ydim == 1:
for each in points:
results.append(self.response_1s(each)[0])
else:
for each in points:
results.append(self.response_1s(each))
return results
if __name__ == '__main__':
testgks = GKS([array([1, 2, 2,3]), array([2, 3, 1,5])], array([1, 2]), array([1, 2, 3,1]), 2, smooth = -0.4)
print(testgks.response_1s(array([1,2])))
print(testgks.responses([array([1,2]),array([2,0])]))
| sbxzy/pygks | pygks/ae_backup.py | Python | bsd-3-clause | 4,229 | [
"Gaussian"
] | d7f7969fb72b7a605999662a089bf37fb8e2fad6f9f9b49a3d6aaf1a4061e2dc |
#!/usr/bin/env python
"""
The dependencies module determines which descriptions depend on which other
descriptions.
"""
from ctypesgencore.descriptions import *
from ctypesgencore.ctypedescs import *
from ctypesgencore.messages import *
def find_dependencies(data, opts):
"""Visit each description in `data` and figure out which other descriptions
it depends on, putting the results in desc.requirements. Also find errors in
ctypedecls or expressions attached to the description and transfer them to the
description."""
struct_names = {}
enum_names = {}
typedef_names = {}
ident_names = {}
# Start the lookup tables with names from imported modules
for name in opts.other_known_names:
typedef_names[name] = None
ident_names[name] = None
if name.startswith("struct_") or name.startswith("enum_"):
variety = name.split("_")[0]
tag = "_".join(name.split("_")[1:])
struct_names[(variety,tag)] = None
if name.startswith("enum_"):
enum_names[name] = None
def depend(desc, nametable, name):
"""Try to add `name` as a requirement for `desc`, looking `name` up in
`nametable`. Returns True if found."""
if name in nametable:
requirement = nametable[name]
if requirement: desc.add_requirements([requirement])
return True
else:
return False
def find_dependencies_for(desc, kind):
"""Find all the descriptions that `desc` depends on and add them as
dependencies for `desc`. Also collect error messages regarding `desc` and
convert unlocateable descriptions into error messages."""
if kind == "constant": roots = [desc.value]
if kind == "struct": roots = []
if kind == "struct-body": roots = [desc.ctype]
if kind == "enum": roots = []
if kind == "typedef": roots = [desc.ctype]
if kind == "function": roots = desc.argtypes + [desc.restype]
if kind == "variable": roots = [desc.ctype]
if kind == "macro":
if desc.expr: roots = [desc.expr]
else: roots = []
cstructs,cenums,ctypedefs,errors,identifiers = [], [], [], [], []
for root in roots:
s, e, t, errs, i = visit_type_and_collect_info(root)
cstructs.extend(s)
cenums.extend(e)
ctypedefs.extend(t)
errors.extend(errs)
identifiers.extend(i)
unresolvables = []
for cstruct in cstructs:
if kind == "struct" and desc.variety == cstruct.variety and \
desc.tag == cstruct.tag:
continue
if not depend(desc, struct_names, (cstruct.variety, cstruct.tag)):
unresolvables.append("%s \"%s\"" % \
(cstruct.variety, cstruct.tag))
for cenum in cenums:
if kind == "enum" and desc.tag == cenum.tag:
continue
if not depend(desc, enum_names, cenum.tag):
unresolvables.append("enum \"%s\"" % cenum.tag)
for ctypedef in ctypedefs:
if not depend(desc, typedef_names, ctypedef):
unresolvables.append("typedef \"%s\"" % ctypedef)
for ident in identifiers:
if isinstance(desc, MacroDescription) and \
desc.params and ident in desc.params:
continue
if not depend(desc, ident_names, ident):
unresolvables.append("identifier \"%s\"" % ident)
for u in unresolvables:
errors.append(("%s depends on an unknown %s." % \
(desc.casual_name(), u), None))
for err, cls in errors:
err += " %s will not be output" % desc.casual_name()
desc.error(err, cls = cls)
def add_to_lookup_table(desc, kind):
"""Add `desc` to the lookup table so that other descriptions that use
it can find it."""
if kind == "struct":
if (desc.variety, desc.tag) not in struct_names:
struct_names[(desc.variety, desc.tag)] = desc
if kind == "enum":
if desc.tag not in enum_names:
enum_names[desc.tag] = desc
if kind == "typedef":
if desc.name not in typedef_names:
typedef_names[desc.name] = desc
if kind in ("function", "constant", "variable", "macro"):
if desc.name not in ident_names:
ident_names[desc.name] = desc
# Macros are handled differently from everything else because macros can
# call other macros that are referenced after them in the input file, but
# no other type of description can look ahead like that.
for kind, desc in data.output_order:
if kind!="macro":
find_dependencies_for(desc, kind)
add_to_lookup_table(desc, kind)
for kind, desc in data.output_order:
if kind=="macro":
add_to_lookup_table(desc, kind)
for kind, desc in data.output_order:
if kind=="macro":
find_dependencies_for(desc, kind)
| AsherBond/MondocosmOS | grass_trunk/lib/python/ctypes/ctypesgencore/processor/dependencies.py | Python | agpl-3.0 | 5,207 | [
"VisIt"
] | 5764544431e2770a75098e885675fbc6965e5847a6386b3bef7d9fa43758a107 |
# #############################################################################
# MDTraj: A Python Library for Loading, Saving, and Manipulating
# Molecular Dynamics Trajectories.
# Copyright 2012-2014 Stanford University and the Authors
#
# Authors: Matthew Harrigan
# Contributors: Robert T. McGibbon
#
# MDTraj 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 MDTraj. If not, see <http://www.gnu.org/licenses/>.
# #############################################################################
from __future__ import print_function
import re
import ast
import sys
from copy import deepcopy
from collections import namedtuple
from mdtraj.utils.six import PY2
from pyparsing import (Word, ParserElement, MatchFirst,
Keyword, opAssoc, quotedString, alphas, alphanums, infixNotation, Group,
ParseException, OneOrMore)
from astor import code_gen
# this number arises from the current selection language, if the cache size is exceeded, it hurts performance a bit.
ParserElement.enablePackrat(cache_size_limit=304)
__all__ = ['parse_selection']
# ############################################################################
# Globals
# ############################################################################
NUMS = '.0123456789'
THIS_ATOM = ast.Name(id='atom', ctx=ast.Load(), SINGLETON=True)
RE_MODULE = ast.Name(id='re', ctx=ast.Load(), SINGLETON=True)
SELECTION_GLOBALS = {'re': re}
_ParsedSelection = namedtuple('_ParsedSelection', ['expr', 'source', 'astnode'])
# ############################################################################
# Utils
# ############################################################################
class _RewriteNames(ast.NodeTransformer):
def visit_Name(self, node):
if hasattr(node, 'SINGLETON'):
return node
_safe_names = {'None': None, 'True': True, 'False': False}
if node.id in _safe_names:
if sys.version_info >= (3, 4):
return ast.NameConstant(value=_safe_names[node.id], kind=None)
return node
# all other bare names are taken to be string literals. Thus something
# like parse_selection('name CA') properly resolves CA as a string
# literal, not a barename to be loaded from the global scope!
return ast.Str(s=node.id)
def _chain(*attrs):
"""This transforms, for example, ('residue', 'is_protein'), into
Attribute(value=Attribute(value=THIS_ATOM,
attr='residue', ctx=Load()), attr='is_protein', ctx=Load())
"""
left = THIS_ATOM
for attr in attrs:
left = ast.Attribute(value=left, attr=attr, ctx=ast.Load())
return left
def _kw(*tuples):
"""Create a many-to-one dictionary.
_kw((['one', '1'], 'one'))
gives {'one': 'one', '1': 'one'}
"""
dic = dict()
for keys, val in tuples:
for key in keys:
dic[key] = val
return dic
def _check_n_tokens(tokens, n_tokens, name):
if not len(tokens) == n_tokens:
err = "{} take {} values. You gave {}"
err = err.format(name, n_tokens, len(tokens))
raise ParseException(err)
class SelectionKeyword(object):
keyword_aliases = _kw(
# Atom.<attribute>
(('all', 'everything'), ast.Name(id='True', ctx=ast.Load())),
(('none', 'nothing'), ast.Name(id='False', ctx=ast.Load())),
(('backbone', 'is_backbone'), _chain('is_backbone')),
(('sidechain', 'is_sidechain'), _chain('is_sidechain')),
# Atom.residue.<attribute>
(('protein', 'is_protein'), _chain('residue', 'is_protein')),
(('code', 'rescode', 'resc'), _chain('residue', 'code')),
# (('nucleic', 'is_nucleic'), _chain('residue', 'is_nucleic')),
(('water', 'waters', 'is_water'), _chain('residue', 'is_water')),
(('name',), _chain('name')),
(('index',), _chain('index')),
(('n_bonds',), _chain('n_bonds')),
(('residue', 'resSeq'), _chain('residue', 'resSeq')),
(('resname', 'resn'), _chain('residue', 'name')),
(('resid', 'resi'), _chain('residue', 'index')),
(('segment_id','segname',), _chain('segment_id')),
# Atom.residue.chain.<attribute>
(('chainid',), _chain('residue', 'chain', 'index')),
# Atom.element.<attribute>
(('type', 'element', 'symbol'), _chain('element', 'symbol')),
# (('radius',), _chain('element', 'radius')),
(('mass',), _chain('element', 'mass')),
)
def __init__(self, tokens):
# pyparsing constructs the instance while building the parse tree,
# and gives us the set tokens. In this case, the tokens are
self._tokens = tokens
_check_n_tokens(tokens, 1, 'Unary selectors')
assert tokens[0] in self.keyword_aliases
def ast(self):
return self.keyword_aliases[self._tokens[0]]
class Literal(object):
def __init__(self, tokens):
self.token = tokens[0]
_check_n_tokens(tokens, 1, 'literal')
def ast(self):
return ast.parse(self.token, mode='eval').body
class UnaryInfixOperand(object):
n_terms = 1
assoc = 'RIGHT'
keyword_aliases = _kw(
(['not ', '!'], ast.Not()),
)
def __init__(self, tokens):
tokens = tokens[0]
_check_n_tokens(tokens, 2, 'Unary infix operators')
self.op_token, self.value_token = tokens
assert self.op_token in self.keyword_aliases
if isinstance(self.value_token, Literal):
raise ValueError("Cannot use literals as booleans.")
def ast(self):
return ast.UnaryOp(op=self.keyword_aliases[self.op_token],
operand=self.value_token.ast())
class RegexInfixOperand(object):
n_terms = 2
assoc = 'LEFT'
keyword_aliases = {'=~': '=~'}
def __init__(self, tokens):
self.tokens = tokens[0]
_check_n_tokens(self.tokens, 3, 'regex operator')
self.string, op, self.pattern = self.tokens
assert op == '=~'
if isinstance(self.string, Literal):
raise ValueError("Cannot do regex comparison on literal")
def ast(self):
pattern = self.tokens[2].ast()
string = self.tokens[0].ast()
return ast.Compare(
left=ast.Call(func=ast.Attribute(value=RE_MODULE, attr='match',
ctx=ast.Load()),
args=[pattern, string], keywords=[], starargs=None,
kwargs=None),
ops=[ast.IsNot()], comparators=[ast.Name(id='None', ctx=ast.Load())]
)
class BinaryInfixOperand(object):
n_terms = 2
assoc = 'LEFT'
keyword_aliases = _kw(
(['and', '&&'], ast.And()),
(['or', '||'], ast.Or()),
(['<', 'lt'], ast.Lt()),
(['==', 'eq'], ast.Eq()),
(['<=', 'le'], ast.LtE()),
(['!=', 'ne'], ast.NotEq()),
(['>=', 'ge'], ast.GtE()),
(['>', 'gt'], ast.Gt()),
)
def __init__(self, tokens):
tokens = tokens[0]
if len(tokens) % 2 == 1:
self.op_token = tokens[1]
self.comparators = tokens[::2]
else:
err = "Invalid number of infix expressions: {}"
err = err.format(len(tokens))
raise ParseException(err)
assert self.op_token in self.keyword_aliases
# Check for too many literals and not enough keywords
op = self.keyword_aliases[self.op_token]
if isinstance(op, ast.boolop):
if any(isinstance(c, Literal) for c in self.comparators):
raise ValueError("Cannot use literals as truth")
else:
if all(isinstance(c, Literal) for c in self.comparators):
raise ValueError("Cannot compare literals.")
def ast(self):
op = self.keyword_aliases[self.op_token]
if isinstance(op, ast.boolop):
# and and or use one type of AST node
value = ast.BoolOp(op=op, values=[e.ast() for e in self.comparators])
else:
# remaining operators use another
value = ast.Compare(left=self.comparators[0].ast(), ops=[op],
comparators=[e.ast() for e in self.comparators[1:]])
return value
class RangeCondition(object):
def __init__(self, tokens):
tokens = tokens[0]
_check_n_tokens(tokens, 4, 'range condition')
assert tokens[2] == 'to'
self._field, self._from, self._to = tokens[0], tokens[1], tokens[3]
if isinstance(self._field, Literal):
raise ValueError("Can't test literal in range.")
def ast(self):
return ast.Compare(left=self._from.ast(), ops=[ast.LtE(), ast.LtE()],
comparators=[self._field.ast(), self._to.ast()])
class InListCondition(object):
def __init__(self, tokens):
tokens = tokens[0]
self._field = tokens[0]
if len(tokens) == 2:
# Implicit equality
self.implicit_equality = True
elif len(tokens) > 2:
self.implicit_equality = False
else:
raise ValueError("Not enough tokens for `in` condition")
self.compare_to = tokens[1:]
def ast(self):
if self.implicit_equality:
return ast.Compare(left=self._field.ast(), ops=[ast.Eq()],
comparators=[e.ast() for e in self.compare_to])
else:
comparator = ast.List([e.ast() for e in self.compare_to], ast.Load())
return ast.Compare(left=self._field.ast(), ops=[ast.In()],
comparators=[comparator])
class parse_selection(object):
"""Parse an atom selection expression
Parameters
----------
selection_string : str
Selection string, a string in the MDTraj atom selection grammar.
Returns
-------
expr : callable (atom -> bool)
A callable object which accepts an MDTraj.core.topology.Atom object and
returns a boolean value giving whether or not that particular atom
satisfies the selection string.
source : str
Python source code corresponding to the expression ``expr``.
astnode : ast.AST
Python abstract syntax tree node containing the parsed expression
Examples
--------
>>> expr, source, astnode = parse_selection('protein and type CA')
>>> expr
<function __main__.<lambda>>
>>> source
'(atom.residue.is_protein and (atom.element.symbol == CA))'
>>> <_ast.BoolOp at 0x103969d50>
"""
def __init__(self):
self.is_initialized = False
self.expression = None
def _initialize(self):
def keywords(klass):
kws = sorted(klass.keyword_aliases.keys())
return MatchFirst([Keyword(kw) for kw in kws])
def infix(klass):
kws = sorted(klass.keyword_aliases.keys())
return [(kw, klass.n_terms, getattr(opAssoc, klass.assoc), klass)
for kw in kws]
# literals include words made of alphanumerics, numbers,
# or quoted strings but we exclude any of the logical
# operands (e.g. 'or') from being parsed literals
literal = (
~(keywords(BinaryInfixOperand) | keywords(UnaryInfixOperand)) +
(Word(NUMS) | quotedString | Word(alphas, alphanums))
)
literal.setParseAction(Literal)
# These are the other 'root' expressions,
# the selection keywords (resname, resid, mass, etc)
selection_keyword = keywords(SelectionKeyword)
selection_keyword.setParseAction(SelectionKeyword)
base_expression = MatchFirst([selection_keyword, literal])
# range condition matches expressions such as 'mass 1 to 20'
range_condition = Group(
selection_keyword + literal + Keyword('to') + literal
)
range_condition.setParseAction(RangeCondition)
# matches expression such as `resname GLU ASP ARG` and also
# handles implicit equality `resname ALA`
in_list_condition = Group(selection_keyword + OneOrMore(literal))
in_list_condition.setParseAction(InListCondition)
expression = range_condition | in_list_condition | base_expression
logical_expr = infixNotation(
expression,
infix(UnaryInfixOperand) +
infix(BinaryInfixOperand) +
infix(RegexInfixOperand)
)
self.expression = logical_expr
self.is_initialized = True
self.transformer = _RewriteNames()
def __call__(self, selection):
if not self.is_initialized:
self._initialize()
try:
parse_result = self.expression.parseString(selection, parseAll=True)
except ParseException as e:
msg = str(e)
lines = ["%s: %s" % (msg, selection),
" " * (12 + len("%s: " % msg) + e.loc) + "^^^"]
raise ValueError('\n'.join(lines))
# Change __ATOM__ in function bodies. It must bind to the arg
# name specified below (i.e. 'atom')
astnode = self.transformer.visit(deepcopy(parse_result[0].ast()))
# Special check for a single literal
if isinstance(astnode, ast.Num) or isinstance(astnode, ast.Str):
raise ValueError("Cannot use a single literal as a boolean.")
if PY2:
args = [ast.Name(id='atom', ctx=ast.Param())]
signature = ast.arguments(args=args, vararg=None, kwarg=None,
defaults=[])
else:
args = [ast.arg(arg='atom', annotation=None)]
signature = ast.arguments(args=args, vararg=None, kwarg=None,
posonlyargs=[], kwonlyargs=[],
defaults=[], kw_defaults=[])
func = ast.Expression(body=ast.Lambda(signature, astnode))
source = code_gen.to_source(astnode, pretty_source=lambda src: ''.join(src[:-1]))
expr = eval(
compile(ast.fix_missing_locations(func), '<string>', mode='eval'),
SELECTION_GLOBALS)
return _ParsedSelection(expr, source, astnode)
# Create the callable, and use it to overshadow the class. this way there's
# basically just one global instance of the "function", even thought its
# a callable class.
parse_selection = parse_selection()
if __name__ == '__main__':
exp = parse_selection(sys.argv[1])
print(exp.source)
print(ast.dump(exp.astnode))
| mattwthompson/mdtraj | mdtraj/core/selection.py | Python | lgpl-2.1 | 15,049 | [
"MDTraj",
"VisIt"
] | bf9f2b4185a194808ea20bd34c23dcc142f225e53641965f9390238f67b6e0d8 |
# Copyright 2016 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import unicode_literals, absolute_import
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse, HttpResponseNotAllowed, HttpResponseForbidden, Http404
from django.urls import reverse
from django.core.exceptions import PermissionDenied
from django.conf import settings
from ci import models, event, forms
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib import messages
from django.db.models import Prefetch
from datetime import timedelta
import time
import tarfile
from io import BytesIO
from ci import RepositoryStatus, EventsStatus, Permissions, PullRequestEvent, ManualEvent, TimeUtils
from django.utils.html import escape
from django.utils.text import get_valid_filename
from django.views.decorators.cache import never_cache
from ci.client import UpdateRemoteStatus
import os, re
from datetime import datetime
from croniter import croniter
import pytz
import logging, traceback
logger = logging.getLogger('ci')
def get_user_repos_info(request, limit=30, last_modified=None):
"""
Get the information for the main view.
This checks to see if the user has preferred repositories set, and if
so then just shows those.
You can also set the "default" parameter to show all the repositories.
Input:
request: django.http.HttpRequest
limit: int: How many events to show
last_modified: datetime: If not None, then only get information that has occured after this time.
Return:
(repo_info, evs_info, default):
repo_info: list of dicts of repository status
evs_info: list of dicts of event information
default: Whether the default view was enforced
"""
pks = []
default = request.GET.get('default')
if default is None:
default = False
for server in settings.INSTALLED_GITSERVERS:
try:
gitserver = models.GitServer.objects.get(host_type=server["type"], name=server["hostname"])
except models.GitServer.DoesNotExist:
# Probably shouldn't happen in production but it does seem to
# happen during selenium testing
continue
user = gitserver.signed_in_user(request.session)
if user != None:
for repo in user.preferred_repos.filter(user__server=gitserver).all():
pks.append(repo.pk)
else:
default = True
if pks:
repos = RepositoryStatus.filter_repos_status(pks, last_modified=last_modified)
evs_info = EventsStatus.events_filter_by_repo(pks, limit=limit, last_modified=last_modified)
else:
repos = RepositoryStatus.main_repos_status(last_modified=last_modified)
evs_info = EventsStatus.all_events_info(limit=limit, last_modified=last_modified)
return repos, evs_info, default
def sorted_clients(client_q):
clients = [ c for c in client_q.all() ]
clients.sort(key=lambda s: [int(t) if t.isdigit() else t.lower() for t in re.split(r'(\d+)', s.name)])
return clients
def main(request):
"""
Main view. Just shows the status of repos, with open prs, as
well as a short list of recent jobs.
Input:
request: django.http.HttpRequest
Return:
django.http.HttpResponse based object
"""
limit = 30
repos, evs_info, default = get_user_repos_info(request, limit=limit)
return render(request,
'ci/main.html',
{'repos': repos,
'recent_events': evs_info,
'last_request': TimeUtils.get_local_timestamp(),
'event_limit': limit,
'update_interval': settings.HOME_PAGE_UPDATE_INTERVAL,
'default_view': default,
})
def user_repo_settings(request):
"""
Allow the user to change the default view on the main page.
Input:
request: django.http.HttpRequest
Return:
django.http.HttpResponse based object
"""
current_repos = []
all_repos = []
users = {}
for server in settings.INSTALLED_GITSERVERS:
gitserver = models.GitServer.objects.get(host_type=server["type"], name=server["hostname"])
user = gitserver.signed_in_user(request.session)
if user != None:
users[gitserver.pk] = user
for repo in user.preferred_repos.filter(user__server=gitserver).all():
current_repos.append(repo.pk)
q = models.Repository.objects.filter(active=True, user__server=gitserver).order_by('user__name', 'name').all()
for repo in q:
all_repos.append((repo.pk, str(repo)))
if not users:
messages.error(request, "You need to be signed in to set preferences")
return render(request, 'ci/repo_settings.html', {"form": None})
if request.method == "GET":
form = forms.UserRepositorySettingsForm()
form.fields["repositories"].choices = all_repos
form.fields["repositories"].initial = current_repos
else:
form = forms.UserRepositorySettingsForm(request.POST)
form.fields["repositories"].choices = all_repos
if form.is_valid():
for server, user in users.items():
messages.info(request, "Set repository preferences for %s" % user)
user.preferred_repos.clear()
for pk in form.cleaned_data["repositories"]:
repo = models.Repository.objects.get(pk=pk)
user = users[repo.server().pk]
user.preferred_repos.add(repo)
return render(request, 'ci/repo_settings.html', {"form": form})
def view_pr(request, pr_id):
"""
Show the details of a PR
Input:
request: django.http.HttpRequest
pr_id: pk of models.PullRequest
Return:
django.http.HttpResponse based object
"""
pr = get_object_or_404(models.PullRequest.objects.select_related('repository__user'), pk=pr_id)
ev = pr.events.select_related('build_user', 'base__branch__repository__user__server').latest()
allowed = Permissions.is_collaborator(request.session, ev.build_user, ev.base.repo())
current_alt = []
alt_choices = []
default_choices = []
if allowed:
alt_recipes = (models.Recipe.objects
.filter(repository=pr.repository,
build_user=ev.build_user,
current=True,
active=True,
cause=models.Recipe.CAUSE_PULL_REQUEST_ALT,)
.order_by("display_name"))
default_recipes = (models.Recipe.objects
.filter(repository=pr.repository,
build_user=ev.build_user,
current=True,
active=True,
cause=models.Recipe.CAUSE_PULL_REQUEST,)
.order_by("display_name"))
push_recipes = (models.Recipe.objects
.filter(repository=pr.repository,
build_user=ev.build_user,
current=True,
active=True,
cause=models.Recipe.CAUSE_PUSH,)
.order_by("display_name"))
default_recipes = [r for r in default_recipes.all()]
current_alt = [ r.pk for r in pr.alternate_recipes.all() ]
current_default = [j.recipe.filename for j in pr.events.latest("created").jobs.all() ]
push_map = {r.filename: r.branch for r in push_recipes.all()}
alt_choices = []
for r in alt_recipes:
alt_choices.append({"recipe": r,
"selected": r.pk in current_alt,
"push_branch": push_map.get(r.filename),
})
default_choices = []
for r in default_recipes:
default_choices.append({"recipe": r,
"pk": r.pk,
"disabled": r.filename in current_default,
"push_branch": push_map.get(r.filename),
})
if alt_choices and request.method == "POST":
form_choices = [ (r.pk, r.display_name) for r in alt_recipes ]
form = forms.AlternateRecipesForm(request.POST)
form.fields["recipes"].choices = form_choices
form_default_choices = []
for r in default_choices:
if not r["disabled"]:
form_default_choices.append((r["pk"], r["recipe"].display_name))
form.fields["default_recipes"].choices = form_default_choices
if form.is_valid():
pr.alternate_recipes.clear()
for pk in form.cleaned_data["recipes"]:
alt = models.Recipe.objects.get(pk=pk)
pr.alternate_recipes.add(alt)
# do some saves to update the timestamp so that the javascript updater gets activated
pr.save()
pr.events.latest('created').save()
messages.info(request, "Success")
pr_event = PullRequestEvent.PullRequestEvent()
selected_default_recipes = []
if form.cleaned_data["default_recipes"]:
q = models.Recipe.objects.filter(pk__in=form.cleaned_data["default_recipes"])
selected_default_recipes = [r for r in q]
pr_event.create_pr_alternates(pr, default_recipes=selected_default_recipes)
# update the choices so the new form is correct
current_alt = [ r.pk for r in pr.alternate_recipes.all() ]
alt_choices = [ {"recipe": r, "selected": r.pk in current_alt} for r in alt_recipes ]
else:
messages.warning(request, "Invalid form")
logger.warning("Invalid form")
for field, errors in form.errors.items():
logger.warning("Form error in field: %s: %s" % (field, errors))
events = EventsStatus.events_with_head(pr.events)
evs_info = EventsStatus.multiline_events_info(events, events_url=True)
context = { "pr": pr,
"events": evs_info,
"allowed": allowed,
"update_interval": settings.EVENT_PAGE_UPDATE_INTERVAL,
"alt_choices": alt_choices,
"default_choices": default_choices,
}
return render(request, 'ci/pr.html', context)
def view_event(request, event_id):
"""
Show the details of an Event
"""
ev = get_object_or_404(EventsStatus.events_with_head(), pk=event_id)
evs_info = EventsStatus.multiline_events_info([ev])
allowed = Permissions.is_collaborator(request.session, ev.build_user, ev.base.repo())
has_unactivated = ev.jobs.filter(active=False).count() != 0
context = {'event': ev,
'events': evs_info,
'allowed_to_cancel': allowed,
"update_interval": settings.EVENT_PAGE_UPDATE_INTERVAL,
"has_unactivated": has_unactivated,
}
return render(request, 'ci/event.html', context)
def get_job_results(request, job_id):
"""
Just download all the output of the job into a tarball.
"""
job = get_object_or_404(models.Job.objects.select_related('recipe',).prefetch_related('step_results'), pk=job_id)
perms = Permissions.job_permissions(request.session, job)
if not perms['can_see_results']:
return HttpResponseForbidden('Not allowed to see results')
response = HttpResponse(content_type='application/x-gzip')
base_name = 'results_{}_{}'.format(job.pk, get_valid_filename(job.recipe.name))
response['Content-Disposition'] = 'attachment; filename="{}.tar.gz"'.format(base_name)
tar = tarfile.open(fileobj=response, mode='w:gz')
for result in job.step_results.all():
info = tarfile.TarInfo(name='{}/{:02}_{}'.format(base_name, result.position, get_valid_filename(result.name)))
s = BytesIO(result.plain_output().replace('\u2018', "'").replace("\u2019", "'").encode("utf-8", "replace"))
buf = s.getvalue()
info.size = len(buf)
info.mtime = time.time()
tar.addfile(tarinfo=info, fileobj=s)
tar.close()
return response
def view_job(request, job_id):
"""
View the details of a job, along
with any results.
"""
recipe_q = models.Recipe.objects.prefetch_related("depends_on", "auto_authorized", "viewable_by_teams")
q = (models.Job.objects
.select_related('recipe__repository__user__server',
'recipe__build_user__server',
'event__pull_request',
'event__base__branch__repository__user__server',
'event__head__branch__repository__user__server',
'config',
'client',)
.prefetch_related(Prefetch("recipe", queryset=recipe_q),
'step_results',
'changelog'))
job = get_object_or_404(q, pk=job_id)
perms = Permissions.job_permissions(request.session, job)
clients = None
if perms['can_see_client']:
clients = sorted_clients(models.Client.objects.exclude(status=models.Client.DOWN))
perms['job'] = job
perms['clients'] = clients
perms['update_interval'] = settings.JOB_PAGE_UPDATE_INTERVAL
return render(request, 'ci/job.html', perms)
def get_paginated(request, obj_list, obj_per_page=30):
limit = request.GET.get('limit')
if limit:
obj_per_page = min(int(limit), 500)
paginator = Paginator(obj_list, obj_per_page)
page = request.GET.get('page')
try:
objs = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
objs = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
objs = paginator.page(paginator.num_pages)
objs.limit = obj_per_page
copy_get = request.GET.copy()
if copy_get.get('page'):
del copy_get['page']
copy_get['limit'] = obj_per_page
objs.get_params = copy_get.urlencode()
return objs
def do_repo_page(request, repo):
"""
Render the repo page. This has the same layout as the main page but only for single repository.
Input:
request[django.http.HttpRequest]
repo[models.Repository]
"""
limit = 30
repos_status = RepositoryStatus.filter_repos_status([repo.pk])
events_info = EventsStatus.events_filter_by_repo([repo.pk], limit=limit)
params = {
'repo': repo,
'repos_status': repos_status,
'events_info': events_info,
'event_limit': limit,
'last_request': TimeUtils.get_local_timestamp(),
'update_interval': settings.HOME_PAGE_UPDATE_INTERVAL
}
return render(request, 'ci/repo.html', params)
def view_owner_repo(request, owner, repo):
"""
Render the repo page given the owner and repo
Input:
request[django.http.HttpRequest]
owner[str]: The owner of the repository
repo[str]: The name of the repository
"""
repo = get_object_or_404(models.Repository.objects.select_related('user__server'), name=repo, user__name=owner)
return do_repo_page(request, repo)
def view_repo(request, repo_id):
"""
Render the repo page given the internal DB id of the repo
Input:
request[django.http.HttpRequest]
repo_id[int]: The internal DB id of the repo
"""
repo = get_object_or_404(models.Repository.objects.select_related('user__server'), pk=repo_id)
return do_repo_page(request, repo)
def view_client(request, client_id):
"""
View details about a client, along with
some a list of paginated jobs it has run
"""
client = get_object_or_404(models.Client, pk=client_id)
allowed = Permissions.is_allowed_to_see_clients(request.session)
if not allowed:
return render(request, 'ci/client.html', {'client': None, 'allowed': False})
jobs_list = models.Job.objects.filter(client=client).order_by('-last_modified').select_related('config',
'event__pull_request',
'event__base__branch__repository__user',
'event__head__branch__repository__user',
'recipe',
)
jobs = get_paginated(request, jobs_list)
return render(request, 'ci/client.html', {'client': client, 'jobs': jobs, 'allowed': True})
def do_branch_page(request, branch):
"""
Render the branch page given a branch object
Input:
request[django.http.HttpRequest]
branch[models.Branch]
"""
if request.method != "GET":
return HttpResponseNotAllowed(['GET'])
causes = []
if request.GET.get("do_filter", "0") == "0":
causes = [models.Event.PUSH, models.Event.MANUAL, models.Event.RELEASE]
form = forms.BranchEventsForm(initial={"filter_events": causes})
else:
form = forms.BranchEventsForm(request.GET)
if form.is_valid():
causes = [int(c) for c in form.cleaned_data["filter_events"]]
event_list = EventsStatus.get_default_events_query().filter(base__branch=branch, cause__in=causes)
events = get_paginated(request, event_list)
evs_info = EventsStatus.multiline_events_info(events)
return render(request, 'ci/branch.html', {"form": form, 'branch': branch, 'events': evs_info, 'pages': events})
def view_repo_branch(request, owner, repo, branch):
"""
Render the branch page based on owner/repo/branch
Input:
request[django.http.HttpRequest]
owner[str]: Owner of the repository
repo[str]: Name of the repository
branch[str]: Name of the branch
"""
q = models.Branch.objects.select_related("repository__user__server")
branch = get_object_or_404(q, name=branch, repository__name=repo, repository__user__name=owner)
return do_branch_page(request, branch)
def view_branch(request, branch_id):
"""
Render the branch page based on a branch id
Input:
request[django.http.HttpRequest]
branch_id[int]: Internal DB id of the branch
"""
branch = get_object_or_404(models.Branch.objects.select_related("repository__user__server"), pk=int(branch_id))
return do_branch_page(request, branch)
def view_user(request, username):
"""
Render the user page based on username
Input:
request[django.http.HttpRequest]
username[str]: Name of the user
"""
users = models.GitUser.objects.filter(name=username)
if users.count() == 0:
raise Http404('Bad username')
repos = RepositoryStatus.get_user_repos_with_open_prs_status(username)
pr_ids = []
for r in repos:
for pr in r["prs"]:
pr_ids.append(pr["id"])
event_list = EventsStatus.get_single_event_for_open_prs(pr_ids)
evs_info = EventsStatus.multiline_events_info(event_list)
data = {'username': username, 'repos': repos, 'events': evs_info, "update_interval": settings.EVENT_PAGE_UPDATE_INTERVAL,}
return render(request, 'ci/user.html', data)
def pr_list(request):
pr_list = (models.PullRequest.objects
.order_by('-created')
.select_related('repository__user__server')
.order_by('repository__user__name', 'repository__name', 'number'))
prs = get_paginated(request, pr_list)
return render(request, 'ci/prs.html', {'prs': prs})
def branch_list(request):
branch_list = (models.Branch.objects
.exclude(status=models.JobStatus.NOT_STARTED)
.select_related('repository__user__server')
.order_by('repository__user__name', 'repository__name', 'name'))
branches = get_paginated(request, branch_list)
return render(request, 'ci/branches.html', {'branches': branches})
def client_list(request):
allowed = Permissions.is_allowed_to_see_clients(request.session)
if not allowed:
return render(request, 'ci/clients.html', {'clients': None, 'allowed': False})
client_list = clients_info()
data = {'clients': client_list, 'allowed': True, 'update_interval': settings.HOME_PAGE_UPDATE_INTERVAL, }
return render(request, 'ci/clients.html', data)
def manual_cron(request, recipe_id):
allowed = Permissions.is_allowed_to_see_clients(request.session)
if not allowed:
return HttpResponseForbidden('Not allowed to start manual cron runs')
r = get_object_or_404(models.Recipe, pk=recipe_id)
user = r.build_user
branch = r.branch
latest = user.api().last_sha(branch.repository.user.name, branch.repository.name, branch.name)
#likely need to add exception checks for this!
if latest: r.last_scheduled = datetime.now(tz=pytz.UTC); r.save(); mev = ManualEvent.ManualEvent(user, branch, latest, "", recipe=r); mev.force = True; mev.save(update_branch_status=True);
return redirect('ci:cronjobs')
def cronjobs(request):
# TODO: make this check for permission to view cron stuff instead
allowed = Permissions.is_allowed_to_see_clients(request.session)
if not allowed:
return render(request, 'ci/cronjobs.html', {'recipes': None, 'allowed': False})
recipe_list = models.Recipe.objects.filter(active=True, current=True, scheduler__isnull=False, branch__isnull=False).exclude(scheduler="")
local_tz = pytz.timezone('US/Mountain')
for r in recipe_list:
event_list = (EventsStatus
.get_default_events_query()
.filter(jobs__recipe__filename=r.filename, jobs__recipe__cause=r.cause))
events = get_paginated(request, event_list)
evs_info = EventsStatus.multiline_events_info(events)
r.most_recent_event = evs_info[0]['id'] if len(evs_info) > 0 else None
c = croniter(r.scheduler, start_time=r.last_scheduled.astimezone(local_tz))
r.next_run_time = c.get_next(datetime)
# TODO: augment recipes objects with fields that html template will need.
data = {'recipes': recipe_list, 'allowed': True, 'update_interval': settings.HOME_PAGE_UPDATE_INTERVAL, }
return render(request, 'ci/cronjobs.html', data)
def clients_info():
"""
Gets the information on all the currently active clients.
Retruns:
list of dicts containing client information
"""
sclients = sorted_clients(models.Client.objects.exclude(status=models.Client.DOWN))
active_clients = [] # clients that we've seen in <= 60 s
inactive_clients = [] # clients that we've seen in > 60 s
for c in sclients:
d = {'pk': c.pk,
"ip": c.ip,
"name": c.name,
"message": c.status_message,
"status": c.status_str(),
"lastseen": TimeUtils.human_time_str(c.last_seen),
}
if c.unseen_seconds() > 2*7*24*60*60: # 2 weeks
# do it like this so that last_seen doesn't get updated
models.Client.objects.filter(pk=c.pk).update(status=models.Client.DOWN)
elif c.unseen_seconds() > 60:
d["status_class"] = "client_NotSeen"
inactive_clients.append(d)
else:
d["status_class"] = "client_%s" % c.status_slug()
active_clients.append(d)
clients = [] # sort these so that active clients (seen in < 60 s) are first
for d in active_clients:
clients.append(d)
for d in inactive_clients:
clients.append(d)
return clients
def event_list(request):
event_list = EventsStatus.get_default_events_query()
events = get_paginated(request, event_list)
evs_info = EventsStatus.multiline_events_info(events)
return render(request, 'ci/events.html', {'events': evs_info, 'pages': events})
def sha_events(request, owner, repo, sha):
repo = get_object_or_404(models.Repository.objects, name=repo, user__name=owner)
event_q = models.Event.objects.filter(head__branch__repository=repo, head__sha__startswith=sha)
event_list = EventsStatus.get_default_events_query(event_q)
events = get_paginated(request, event_list)
evs_info = EventsStatus.multiline_events_info(events)
return render(request, 'ci/events.html',
{'events': evs_info, 'pages': events, 'sha': sha, 'repo': repo})
def recipe_events(request, recipe_id):
recipe = get_object_or_404(models.Recipe, pk=recipe_id)
event_list = (EventsStatus
.get_default_events_query()
.filter(jobs__recipe__filename=recipe.filename, jobs__recipe__cause=recipe.cause))
total = 0
count = 0
qs = models.Job.objects.filter(recipe__filename=recipe.filename)
for job in qs.all():
if job.status == models.JobStatus.SUCCESS:
total += job.seconds.total_seconds()
count += 1
if count:
total /= count
events = get_paginated(request, event_list)
evs_info = EventsStatus.multiline_events_info(events)
avg = timedelta(seconds=total)
data = {'recipe': recipe,
'events': evs_info,
'average_time': avg,
'pages': events,
}
return render(request, 'ci/recipe_events.html', data)
def recipe_crons(request, recipe_id):
recipe = get_object_or_404(models.Recipe, pk=recipe_id)
event_list = (EventsStatus
.get_default_events_query()
.filter(jobs__recipe__filename=recipe.filename, jobs__recipe__cause=recipe.cause, jobs__recipe__scheduler__isnull=False).exclude(jobs__recipe__scheduler=''))
total = 0
count = 0
qs = models.Job.objects.filter(recipe__filename=recipe.filename)
for job in qs.all():
total += job.seconds.total_seconds() if job.status == models.JobStatus.SUCCESS else 0
count += 1 if job.status == models.JobStatus.SUCCESS else 0
if count:
total /= count
events = get_paginated(request, event_list)
evs_info = EventsStatus.multiline_events_info(events)
avg = timedelta(seconds=total)
data = {'recipe': recipe,
'events': evs_info,
'average_time': avg,
'pages': events,
}
return render(request, 'ci/recipe_events.html', data)
def invalidate_job(request, job, message, same_client=False, client=None, check_ready=True):
"""
Convience function to invalidate a job and show a message to the user.
Input:
request: django.http.HttpRequest
job. models.Job
same_client: bool
"""
job.set_invalidated(message, same_client, client, check_ready)
messages.info(request, 'Job results invalidated for {}'.format(job))
def invalidate_event(request, event_id):
"""
Invalidate all the jobs of an event.
The user must be signed in.
Input:
request: django.http.HttpRequest
event_id. models.Event.pk: PK of the event to be invalidated
Return: django.http.HttpResponse based object
"""
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
ev = get_object_or_404(models.Event, pk=event_id)
allowed = Permissions.is_collaborator(request.session, ev.build_user, ev.base.repo())
if not allowed:
messages.error(request, 'You need to be signed in and be a collaborator to invalidate results.')
return redirect('ci:view_event', event_id=ev.pk)
signed_in_user = ev.base.server().signed_in_user(request.session)
comment = escape(request.POST.get("comment"))
logger.info('Event {}: {} invalidated by {}'.format(ev.pk, ev, signed_in_user))
event_url = reverse("ci:view_event", args=[ev.pk])
message = "Parent <a href='%s'>event</a> invalidated by %s" % (event_url, signed_in_user)
if comment:
message += " with comment: %s" % comment
post_to_pr = request.POST.get("post_to_pr") == "on"
if post_to_pr:
post_event_change_to_pr(request, ev, "invalidated", comment, signed_in_user)
same_client = request.POST.get('same_client') == "on"
for job in ev.jobs.all():
invalidate_job(request, job, message, same_client, check_ready=False)
# Only do this once so that we get the job dependencies setup correctly.
ev.make_jobs_ready()
return redirect('ci:view_event', event_id=ev.pk)
def post_job_change_to_pr(request, job, action, comment, signed_in_user):
"""
Makes a PR comment to notify of a change in job status.
Input:
job: models.Job: Job that has changed
action: str: Describing what happend (like "canceled" or "invalidated")
comment: str: Comment that was entered in by the user
signed_in_user: models.GitUser: the initiating user
"""
if job.event.pull_request and job.event.comments_url:
gapi = job.event.build_user.api()
additional = ""
if comment:
additional = "\n\n%s" % comment
abs_job_url = request.build_absolute_uri(reverse('ci:view_job', args=[job.pk]))
pr_message = "Job [%s](%s) on %s : %s by @%s%s" % (job.unique_name(),
abs_job_url,
job.event.head.short_sha(),
action,
signed_in_user,
additional)
gapi.pr_comment(job.event.comments_url, pr_message)
def invalidate(request, job_id):
"""
Invalidate the results of a Job.
The user must be signed in.
Input:
request: django.http.HttpRequest
job_id: models.Job.pk
"""
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
job = get_object_or_404(models.Job, pk=job_id)
allowed = Permissions.is_collaborator(request.session, job.event.build_user, job.event.base.repo())
if not allowed:
raise PermissionDenied('You are not allowed to invalidate results.')
same_client = request.POST.get('same_client') == 'on'
selected_client = request.POST.get('client_list')
comment = escape(request.POST.get('comment'))
post_to_pr = request.POST.get('post_to_pr') == 'on'
client = None
if selected_client:
try:
client = models.Client.objects.get(pk=int(selected_client))
same_client = True
except:
pass
signed_in_user = job.event.base.server().signed_in_user(request.session)
message = "Invalidated by %s" % signed_in_user
if comment:
message += "\nwith comment: %s" % comment
if post_to_pr:
post_job_change_to_pr(request, job, "invalidated", comment, signed_in_user)
logger.info('Job {}: {} on {} invalidated by {}'.format(job.pk, job, job.recipe.repository, signed_in_user))
invalidate_job(request, job, message, same_client, client)
return redirect('ci:view_job', job_id=job.pk)
def sort_recipes_key(entry):
return str(entry[0].repository)
def view_profile(request, server_type, server_name):
"""
View the recipes that the user owns
"""
server = get_object_or_404(models.GitServer, host_type=server_type, name=server_name)
user = server.signed_in_user(request.session)
if not user:
request.session['source_url'] = request.build_absolute_uri()
return redirect(server.api().sign_in_url())
recipes = (models.Recipe.objects
.filter(build_user=user, current=True)
.order_by('repository__name', 'cause', 'branch__name', 'name')
.select_related('branch', 'repository__user')\
.prefetch_related('build_configs', 'depends_on'))
recipe_data =[]
prev_repo = 0
current_data = []
for recipe in recipes.all():
if recipe.repository.pk != prev_repo:
prev_repo = recipe.repository.pk
if current_data:
recipe_data.append(current_data)
current_data = [recipe]
else:
current_data.append(recipe)
if current_data:
recipe_data.append(current_data)
recipe_data.sort(key=sort_recipes_key)
return render(request, 'ci/profile.html', {
'user': user,
'recipes_by_repo': recipe_data,
})
@csrf_exempt
def manual_branch(request, build_key, branch_id, label=""):
"""
Endpoint for creating a manual event.
"""
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
branch = get_object_or_404(models.Branch, pk=branch_id)
user = get_object_or_404(models.GitUser, build_key=build_key)
reply = 'OK'
try:
logger.info('Running manual with user %s on branch %s' % (user, branch))
latest = user.api().last_sha(branch.repository.user.name, branch.repository.name, branch.name)
force = bool(int(request.POST.get('force', 0)))
update_branch_status = bool(int(request.POST.get('update_branch_status', 1)))
if latest:
mev = ManualEvent.ManualEvent(user, branch, latest, label)
mev.force = force
mev.save(update_branch_status)
reply = 'Success. Scheduled recipes on branch %s for user %s' % (branch, user)
messages.info(request, reply)
logger.info(reply)
else:
reply = "Failed to get latest SHA for %s" % branch
except Exception:
reply = 'Error running manual for user %s on branch %s\nError: %s'\
% (user, branch, traceback.format_exc())
messages.error(request, reply)
logger.info(reply)
next_url = request.POST.get('next', None)
if next_url:
return redirect(next_url)
return HttpResponse(reply)
def set_job_active(request, job, user):
"""
Sets an inactive job to active and check to see if it is ready to run
Returns a bool indicating if it changed the job.
"""
if job.active:
return False
job.active = True
job.event.complete = False
job.set_status(models.JobStatus.NOT_STARTED, calc_event=True) # will save job and event
message = "Activated by %s" % user
models.JobChangeLog.objects.create(job=job, message=message)
messages.info(request, 'Job %s activated' % job)
return True
def activate_event(request, event_id):
"""
Endpoint for activating all jobs on an event
"""
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
ev = get_object_or_404(models.Event, pk=event_id)
jobs = ev.jobs.filter(active=False).order_by('-created')
if jobs.count() == 0:
messages.info(request, 'No jobs to activate')
return redirect('ci:view_event', event_id=ev.pk)
repo = jobs.first().recipe.repository
user = repo.server().signed_in_user(request.session)
if not user:
raise PermissionDenied('You need to be signed in to activate jobs')
collab = Permissions.is_collaborator(request.session, ev.build_user, repo, user=user)
if collab:
activated_jobs = []
for j in jobs.all():
if set_job_active(request, j, user):
activated_jobs.append(j)
for j in activated_jobs:
j.init_pr_status()
ev.make_jobs_ready()
else:
raise PermissionDenied('Activate event: {} is NOT a collaborator on {}'.format(user, repo))
return redirect('ci:view_event', event_id=ev.pk)
def activate_job(request, job_id):
"""
Endpoint for activating a job
"""
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
job = get_object_or_404(models.Job, pk=job_id)
server = job.recipe.repository.server()
user = server.signed_in_user(request.session)
if not user:
raise PermissionDenied('You need to be signed in to activate a job')
collab = Permissions.is_collaborator(request.session, job.event.build_user, job.recipe.repository, user=user)
if collab:
if set_job_active(request, job, user):
job.init_pr_status()
job.event.make_jobs_ready()
else:
raise PermissionDenied('Activate job: {} is NOT a collaborator on {}'.format(user, job.recipe.repository))
return redirect('ci:view_job', job_id=job.pk)
def post_event_change_to_pr(request, ev, action, comment, signed_in_user):
"""
Makes a PR comment to notify of a change in event status.
Input:
event: models.Job: Job that has changed
action: str: Describing what happend (like "canceled" or "invalidated")
comment: str: Comment that was entered in by the user
signed_in_user: models.GitUser: the initiating user
"""
if ev.pull_request and ev.comments_url:
gapi = ev.build_user.api()
additional = ""
if comment:
additional = "\n\n%s" % comment
abs_ev_url = request.build_absolute_uri(reverse('ci:view_event', args=[ev.pk]))
pr_message = "All [jobs](%s) on %s : %s by @%s%s" % (abs_ev_url,
ev.head.short_sha(),
action,
signed_in_user,
additional)
gapi.pr_comment(ev.comments_url, pr_message)
def cancel_event(request, event_id):
"""
Cancel all jobs attached to an event
"""
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
ev = get_object_or_404(models.Event, pk=event_id)
allowed = Permissions.is_collaborator(request.session, ev.build_user, ev.base.repo())
if not allowed:
messages.error(request, 'You are not allowed to cancel this event')
return redirect('ci:view_event', event_id=ev.pk)
signed_in_user = ev.base.server().signed_in_user(request.session)
comment = escape(request.POST.get("comment"))
post_to_pr = request.POST.get("post_to_pr") == "on"
event_url = reverse("ci:view_event", args=[ev.pk])
message = "Parent <a href='%s'>event</a> canceled by %s" % (event_url, signed_in_user)
if comment:
message += " with comment: %s" % comment
if post_to_pr:
post_event_change_to_pr(request, ev, "canceled", comment, signed_in_user)
event.cancel_event(ev, message, True)
logger.info('Event {}: {} canceled by {}'.format(ev.pk, ev, signed_in_user))
messages.info(request, 'Event {} canceled'.format(ev))
return redirect('ci:view_event', event_id=ev.pk)
def set_job_canceled(job, msg=None, status=models.JobStatus.CANCELED):
job.complete = True
job.set_status(status, calc_event=True) # This will save the job
if msg:
models.JobChangeLog.objects.create(job=job, message=msg)
def cancel_job(request, job_id):
if request.method != 'POST':
return HttpResponseNotAllowed(['POST'])
job = get_object_or_404(models.Job, pk=job_id)
allowed = Permissions.is_collaborator(request.session, job.event.build_user, job.event.base.repo())
if not allowed:
return HttpResponseForbidden('Not allowed to cancel this job')
signed_in_user = job.event.base.server().signed_in_user(request.session)
message = "Canceled by %s" % signed_in_user
comment = escape(request.POST.get('comment'))
post_to_pr = request.POST.get('post_to_pr') == 'on'
if post_to_pr:
post_job_change_to_pr(request, job, "canceled", comment, signed_in_user)
if comment:
message += "\nwith comment: %s" % comment
set_job_canceled(job, message)
UpdateRemoteStatus.job_complete(job)
logger.info('Job {}: {} on {} canceled by {}'.format(job.pk, job, job.recipe.repository, signed_in_user))
messages.info(request, 'Job {} canceled'.format(job))
return redirect('ci:view_job', job_id=job.pk)
def mooseframework(request):
"""
This produces a very basic set of status reports for MOOSE, its branches and
its open PRs.
Intended to be included on mooseframework.org
"""
message = ''
data = None
try:
repo = models.Repository.objects.get(
user__name='idaholab',
name='moose',
user__server__host_type=settings.GITSERVER_GITHUB
)
except models.Repository.DoesNotExist:
return HttpResponse('Moose not available')
try:
master = repo.branches.get(name='master')
devel = repo.branches.get(name='devel')
except models.Branch.DoesNotExist:
return HttpResponse('Branches not there')
data = {'master_status': master.status_slug()}
data['master_url'] = request.build_absolute_uri(reverse('ci:view_branch', args=[master.pk,]))
data['devel_status'] = devel.status_slug()
data['devel_url'] = request.build_absolute_uri(reverse('ci:view_branch', args=[devel.pk,]))
prs = models.PullRequest.objects.filter(repository=repo, closed=False).order_by('number')
pr_data = []
for pr in prs:
d = {'number': pr.number,
'url': request.build_absolute_uri(reverse('ci:view_pr', args=[pr.pk,])),
'status': pr.status_slug(),
}
pr_data.append(d)
data['prs'] = pr_data
return render(request,
'ci/mooseframework.html',
{'status': data,
'message': message,
})
def scheduled_events(request):
"""
List schedule events
"""
event_list = EventsStatus.get_default_events_query().filter(cause=models.Event.MANUAL)
events = get_paginated(request, event_list)
evs_info = EventsStatus.multiline_events_info(events)
return render(request, 'ci/scheduled.html', {'events': evs_info, 'pages': events})
def job_info_search(request):
"""
Presents a form to filter jobs by either OS version or modules loaded.
The modules loaded are parsed from the output of jobs and then stored
in the database. This form allows to select which jobs contained the
selected modules.
Input:
request: django.http.HttpRequest
Return: django.http.HttpResponse based object
"""
jobs = []
if request.method == "GET":
form = forms.JobInfoForm(request.GET)
if form.is_valid():
jobs = models.Job.objects.order_by("-created").select_related("event",
"recipe",
'config',
'event__pull_request',
'event__base__branch__repository__user',
'event__head__branch__repository__user')
if form.cleaned_data['os_versions']:
jobs = jobs.filter(operating_system__in=form.cleaned_data['os_versions'])
if form.cleaned_data['modules']:
for mod in form.cleaned_data['modules'].all():
jobs = jobs.filter(loaded_modules__pk=mod.pk)
jobs = get_paginated(request, jobs)
return render(request, 'ci/job_info_search.html', {"form": form, "jobs": jobs})
def get_branch_status(branch):
"""
Returns an SVG image of the status of a branch.
Input:
branch[models.Branch]: Branch to get the image for
"""
if branch.status == models.JobStatus.NOT_STARTED:
raise Http404('Branch not active')
m = { models.JobStatus.SUCCESS: "CIVET-passed-green.svg",
models.JobStatus.FAILED: "CIVET-failed-red.svg",
models.JobStatus.FAILED_OK: "CIVET-failed_but_allowed-orange.svg",
models.JobStatus.RUNNING: "CIVET-running-yellow.svg",
models.JobStatus.CANCELED: "CIVET-canceled-lightgrey.svg",
}
static_file = m[branch.status]
this_dir = os.path.dirname(__file__)
full_path = os.path.join(this_dir, "static", "third_party", "shields.io", static_file)
with open(full_path, "r") as f:
data = f.read()
return HttpResponse(data, content_type="image/svg+xml")
@never_cache
def repo_branch_status(request, owner, repo, branch):
"""
Returns an SVG image of the status of a branch.
This is intended to be used for build status "badges"
Input:
owner[str]: Owner of the repository
repo[str]: Name of the repository
branch[str]: Name of the branch
"""
if request.method != "GET":
return HttpResponseNotAllowed(['GET'])
branch_obj = get_object_or_404(models.Branch.objects, repository__user__name=owner, repository__name=repo, name=branch)
return get_branch_status(branch_obj)
@never_cache
def branch_status(request, branch_id):
"""
Returns an SVG image of the status of a branch.
This is intended to be used for build status "badges"
Input:
branch_id[int]: Id Of the branch to get the status
"""
if request.method != "GET":
return HttpResponseNotAllowed(['GET'])
branch = get_object_or_404(models.Branch.objects, pk=int(branch_id))
return get_branch_status(branch)
| idaholab/civet | ci/views.py | Python | apache-2.0 | 44,683 | [
"MOOSE"
] | 1f613bcae8505a20eafbc90885c6bafc0a08a0a2bc1db853b60bf651870287cb |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# --- BEGIN_HEADER ---
#
# fakecgi - fake a cgi request
# Copyright (C) 2003-2013 The MiG Project lead by Brian Vinter
#
# This file is part of MiG.
#
# MiG is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# MiG 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# -- END_HEADER ---
#
# DO NOT CHANGE THIS SCRIPT TO BE GENERALLY CGI EXECUTABLE!
# It should only be accessible from the command line to avoid
# unauthenticated user access to CGI scripts.
"""This is a simple wrapper to fake actual CGI GET/POST execution of a
script. Some of the MiG cgi scripts may require the provided RUNAS user
to exist for actions to work.
"""
import os
import sys
import subprocess
from shared.useradm import distinguished_name_to_user
def usage():
print 'Usage: %s SCRIPT [METHOD] [QUERY] [RUNAS]' % sys.argv[0]
if len(sys.argv) < 2:
usage()
sys.exit(1)
script = sys.argv[1]
query = ''
method = 'GET'
run_as_dn = '/C=DK/ST=NA/L=NA/O=NBI/OU=NA/CN=Test User/emailAddress=nosuch@bogusdomain.net'
if sys.argv[2:]:
method = sys.argv[2]
if sys.argv[:3]:
query = sys.argv[3]
if sys.argv[:4]:
run_as_dn = sys.argv[4]
run_as_user = distinguished_name_to_user(run_as_dn)
extra_environment = {
'REQUEST_METHOD': method,
'SERVER_PROTOCOL': 'HTTP/1.1',
'GATEWAY_INTERFACE': 'CGI/1.1',
'PATH': '/bin:/usr/bin:/usr/local/bin',
'REMOTE_ADDR': '127.0.0.1',
'SSL_CLIENT_S_DN': run_as_user['distinguished_name'],
'SSL_CLIENT_S_DN_C': run_as_user['country'],
'SSL_CLIENT_S_DN_O': run_as_user['organization'],
'SSL_CLIENT_S_DN_OU': run_as_user['organizational_unit'],
'SSL_CLIENT_S_DN_L': run_as_user['locality'],
'SSL_CLIENT_S_DN_CN': run_as_user['full_name'],
'SSL_CLIENT_I_DN': '/C=DK/ST=Denmark/O=IMADA/OU=MiG/CN=MiGCA',
'SSL_CLIENT_I_DN_C': 'DK',
'SSL_CLIENT_I_DN_ST': 'Denmark',
'SSL_CLIENT_I_DN_O': 'IMADA',
'SSL_CLIENT_I_DN_OU': 'MiGCA',
'SSL_CLIENT_I_DN_CN': 'MiGCA',
}
extra_environment['SCRIPT_FILENAME'] = script
extra_environment['QUERY_STRING'] = query
extra_environment['REQUEST_URI'] = '%s%s' % (script, query)
extra_environment['SCRIPT_URL'] = script
extra_environment['SCRIPT_NAME'] = script
extra_environment['SCRIPT_URI'] = 'https://localhost/cgi-bin/%s'\
% script
os.environ.update(extra_environment)
if not os.path.isabs(script):
script = os.path.abspath(script)
print "Running %s with environment:\n%s" % (script, os.environ)
subprocess.call(script, stdin=open('/dev/null', 'r'))
| heromod/migrid | mig/cgi-bin/fakecgi.py | Python | gpl-2.0 | 3,111 | [
"Brian"
] | e2d3975c7bb6c148c4d4e9c7b1bfa8f1757b5511fd10de3d4659c527e15e5d22 |
# -*- coding: utf-8 -*-
"""methods_utils.py:
"""
__author__ = "Dilawar Singh"
__copyright__ = "Copyright 2013, NCBS Bangalore"
__credits__ = ["NCBS Bangalore", "Bhalla Lab"]
__license__ = "GPL"
__version__ = "1.0.0"
__maintainer__ = "Dilawar Singh"
__email__ = "dilawars@ncbs.res.in"
__status__ = "Development"
import re
objPathPat = re.compile(r'(\/\w+\[\d+\])+?$')
def idPathToObjPath( idPath ):
""" Append a [0] if missing from idPath.
Id-paths do not have [0] at their end. This does not allow one to do
algebra properly.
"""
m = objPathPat.match( idPath )
if m: return idPath
else:
return '{}[0]'.format(idPath)
def main():
p1 = '/cable[0]/comp_[1]/a'
p2 = '/cab[1]/comp/com'
p3 = '/cab[1]/p[2]/c[3]'
p4 = '/ca__b[1]/_p[2]/c[122]'
for p in [p1, p2, p3, p4]:
m = objPathPat.match(p)
if m:
print(m.group(0))
else:
print(("{} is invalid Obj path in moose".format( p )))
if __name__ == '__main__':
main()
| dilawar/moose-core | python/moose/methods_utils.py | Python | gpl-3.0 | 1,096 | [
"MOOSE"
] | c5cf1d662fe78060f1c735f97aaeb8748cfacdfc63ceb7c5888aad6ed7898e88 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.contrib.auth import views as auth_views
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name="home"),
url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name="about"),
# Django Admin
url(r'^admin/', include(admin.site.urls)),
# User management
url('^login/', auth_views.login, name='login'),
url('^logout/', auth_views.logout, name='logout'),
url(r'^users/', include("overdewey.users.urls", namespace="users")),
# Rest
url(r'^api/', include('overdewey.users.api.urls')),
url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
# Your stuff: custom urls includes go here
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
# This allows the error pages to be debugged during development, just visit
# these url in browser to see how these error pages look like.
urlpatterns += [
url(r'^400/$', 'django.views.defaults.bad_request'),
url(r'^403/$', 'django.views.defaults.permission_denied'),
url(r'^404/$', 'django.views.defaults.page_not_found'),
url(r'^500/$', 'django.views.defaults.server_error'),
]
| edanweis/overdewey | config/urls.py | Python | bsd-3-clause | 1,488 | [
"VisIt"
] | ed9dbf261e5cdb24d7e6c31197879bd551b9dd1590e0e91a3be5b1c1b7c4e052 |
import copy
import json
import multiprocessing
import os.path
import random
import shutil
import string
import tempfile
from contextlib import contextmanager
from os import chdir, getcwd, mkdir
from os.path import exists
from subprocess import CalledProcessError, check_call, check_output
import pkgpanda.build.constants
import pkgpanda.build.src_fetchers
from pkgpanda import expand_require as expand_require_exceptions
from pkgpanda import Install, PackageId, Repository
from pkgpanda.actions import add_package_file
from pkgpanda.constants import RESERVED_UNIT_NAMES
from pkgpanda.exceptions import FetchError, PackageError, ValidationError
from pkgpanda.util import (check_forbidden_services, download_atomic,
hash_checkout, load_json, load_string, logger,
make_file, make_tar, rewrite_symlinks, write_json,
write_string)
class BuildError(Exception):
"""An error while building something."""
def __init__(self, msg: str):
self.msg = msg
def __str__(self):
return self.msg
class DockerCmd:
def __init__(self):
self.volumes = dict()
self.environment = dict()
self.container = str()
def run(self, name, cmd):
container_name = "{}-{}".format(
name, ''.join(
random.choice(string.ascii_lowercase) for _ in range(10)
)
)
docker = ["docker", "run", "--name={}".format(container_name)]
for host_path, container_path in self.volumes.items():
docker += ["-v", "{0}:{1}".format(host_path, container_path)]
for k, v in self.environment.items():
docker += ["-e", "{0}={1}".format(k, v)]
docker.append(self.container)
docker += cmd
check_call(docker)
DockerCmd.clean(container_name)
@staticmethod
def clean(name):
"""Cleans up the specified container"""
check_call(["docker", "rm", "-v", name])
def get_variants_from_filesystem(directory, extension):
results = set()
for filename in os.listdir(directory):
# Skip things that don't end in the extension
if not filename.endswith(extension):
continue
variant = filename[:-len(extension)]
# Empty name variant shouldn't have a `.` following it
if variant == '.':
raise BuildError("Invalid filename {}. The \"default\" variant file should be just {}".format(
filename, extension))
# Empty / default variant is represented as 'None'.
if variant == '':
variant = None
else:
# Should be foo. since we've moved the extension.
if variant[-1] != '.':
raise BuildError("Invalid variant filename {}. Expected a '.' separating the "
"variant name and extension '{}'.".format(filename, extension))
variant = variant[:-1]
results.add(variant)
return results
def get_src_fetcher(src_info, cache_dir, working_directory):
try:
kind = src_info['kind']
if kind not in pkgpanda.build.src_fetchers.all_fetchers:
raise ValidationError("No known way to catch src with kind '{}'. Known kinds: {}".format(
kind,
pkgpanda.src_fetchers.all_fetchers.keys()))
args = {
'src_info': src_info,
'cache_dir': cache_dir
}
if src_info['kind'] in ['git_local', 'url', 'url_extract']:
args['working_directory'] = working_directory
return pkgpanda.build.src_fetchers.all_fetchers[kind](**args)
except ValidationError as ex:
raise BuildError("Validation error when fetching sources for package: {}".format(ex))
class TreeInfo:
ALLOWED_TREEINFO_KEYS = {'exclude', 'variants', 'core_package_list', 'bootstrap_package_list'}
def __init__(self, treeinfo_dict):
if treeinfo_dict.keys() > self.ALLOWED_TREEINFO_KEYS:
raise BuildError(
"treeinfo can only include the keys {}. Found {}".format(
self.ALLOWED_TREEINFO_KEYS, treeinfo_dict.keys()))
self.excludes = set(self._get_package_list(treeinfo_dict, 'exclude'))
self.core_package_list = set(self._get_package_list(treeinfo_dict, 'core_package_list', self.excludes))
self.bootstrap_package_list = set(self._get_package_list(
treeinfo_dict,
'bootstrap_package_list',
self.excludes))
# List of mandatory package variants to include in the buildinfo.
self.variants = treeinfo_dict.get('variants', dict())
if not isinstance(self.variants, dict):
raise BuildError("treeinfo variants must be a dictionary of package name to variant name")
@staticmethod
def _get_package_list(treeinfo_dict, key, excludes=None):
"""Return a list of package name strings from treeinfo_dict by key.
If key isn't present in treeinfo_dict, an empty list is returned.
"""
excludes = excludes or list()
package_list = treeinfo_dict.get(key, list())
# Validate package list.
if not isinstance(package_list, list):
raise BuildError("{} must be either null (meaning don't use) or a list of package names.".format(key))
for package_name in package_list:
if not isinstance(package_name, str):
raise BuildError("{} must be a list of strings. Found a {} with the value: {}".format(
key, type(package_name), package_name))
try:
PackageId.validate_name(package_name)
except ValidationError as ex:
raise BuildError("Invalid package name in {}: {}".format(key, package_name)) from ex
if package_name in excludes:
raise BuildError("Package found in both exclude and {}: {}".format(key, package_name))
return package_list
class PackageSet:
def __init__(self, variant, treeinfo, package_store):
self.variant = variant
self.all_packages = self.package_tuples_with_dependencies(
# If core_package_list is empty, default to all non-excluded packages.
treeinfo.core_package_list or (package_store.packages_by_name.keys() - treeinfo.excludes),
treeinfo,
package_store
)
self.validate_package_tuples(self.all_packages, treeinfo, package_store)
if treeinfo.bootstrap_package_list:
self.bootstrap_packages = self.package_tuples_with_dependencies(
treeinfo.bootstrap_package_list,
treeinfo,
package_store
)
self.validate_package_tuples(self.bootstrap_packages, treeinfo, package_store)
else:
self.bootstrap_packages = self.all_packages
# Validate bootstrap packages are a subset of all packages.
for package_name, variant in self.bootstrap_packages:
if (package_name, variant) not in self.all_packages:
raise BuildError("Bootstrap package {} (variant {}) not found in set of all packages".format(
package_name, pkgpanda.util.variant_name(variant)))
@staticmethod
def package_tuples_with_dependencies(package_names, treeinfo, package_store):
package_tuples = set((name, treeinfo.variants.get(name)) for name in set(package_names))
to_visit = list(package_tuples)
while to_visit:
package_tuple = to_visit.pop()
for require in package_store.get_buildinfo(*package_tuple)['requires']:
require_tuple = expand_require(require)
if require_tuple not in package_tuples:
to_visit.append(require_tuple)
package_tuples.add(require_tuple)
return package_tuples
@staticmethod
def validate_package_tuples(package_tuples, treeinfo, package_store):
# Validate that all packages have the variant specified in treeinfo.
for package_name, variant in package_tuples:
treeinfo_variant = treeinfo.variants.get(package_name)
if variant != treeinfo_variant:
raise BuildError(
"package {} is supposed to have variant {} included in the tree according to the treeinfo, "
"but variant {} was found.".format(
package_name,
pkgpanda.util.variant_name(treeinfo_variant),
pkgpanda.util.variant_name(variant),
)
)
# Validate that all needed packages are built and not excluded by treeinfo.
for package_name, variant in package_tuples:
if (package_name, variant) not in package_store.packages:
raise BuildError(
"package {} variant {} is needed (explicitly requested or as a requires) "
"but is not in the set of built packages.".format(
package_name,
pkgpanda.util.variant_name(variant),
)
)
if package_name in treeinfo.excludes:
raise BuildError("package {} is needed (explicitly requested or as a requires) "
"but is excluded according to the treeinfo.json.".format(package_name))
class PackageStore:
def __init__(self, packages_dir, repository_url):
self._builders = {}
self._repository_url = repository_url.rstrip('/') if repository_url is not None else None
self._packages_dir = packages_dir.rstrip('/')
# Load all possible packages, making a dictionary from (name, variant) -> buildinfo
self._packages = dict()
self._packages_by_name = dict()
self._package_folders = dict()
# Load an upstream if one exists
# TODO(cmaloney): Allow upstreams to have upstreams
self._package_cache_dir = self._packages_dir + "/cache/packages"
self._upstream_dir = self._packages_dir + "/cache/upstream/checkout"
self._upstream = None
self._upstream_package_dir = self._upstream_dir + "/packages"
# TODO(cmaloney): Make it so the upstream directory can be kept around
check_call(['rm', '-rf', self._upstream_dir])
upstream_config = self._packages_dir + '/upstream.json'
if os.path.exists(upstream_config):
try:
self._upstream = get_src_fetcher(
load_optional_json(upstream_config),
self._packages_dir + '/cache/upstream',
packages_dir)
self._upstream.checkout_to(self._upstream_dir)
if os.path.exists(self._upstream_package_dir + "/upstream.json"):
raise Exception("Support for upstreams which have upstreams is not currently implemented")
except Exception as ex:
raise BuildError("Error fetching upstream: {}".format(ex))
# Iterate through the packages directory finding all packages. Note this package dir comes
# first, then we ignore duplicate definitions of the same package
package_dirs = [self._packages_dir]
if self._upstream:
package_dirs.append(self._upstream_package_dir)
for directory in package_dirs:
for name in os.listdir(directory):
package_folder = directory + '/' + name
# Ignore files / non-directories
if not os.path.isdir(package_folder):
continue
# If we've already found this package, it means 1+ versions have been defined. Use
# those and ignore everything in the upstreams.
if name in self._packages_by_name:
continue
builder_folder = os.path.join(directory, name, 'docker')
if os.path.exists(builder_folder):
self._builders[name] = builder_folder
# Search the directory for buildinfo.json files, record the variants
for variant in get_variants_from_filesystem(package_folder, 'buildinfo.json'):
# Only adding the default dictionary once we know we have a package.
self._packages_by_name.setdefault(name, dict())
buildinfo = load_buildinfo(package_folder, variant)
self._packages[(name, variant)] = buildinfo
self._packages_by_name[name][variant] = buildinfo
if name in self._package_folders:
assert self._package_folders[name] == package_folder
else:
self._package_folders[name] = package_folder
def get_package_folder(self, name):
return self._package_folders[name]
def get_bootstrap_cache_dir(self):
return self._packages_dir + "/cache/bootstrap"
def get_complete_cache_dir(self):
return self._packages_dir + "/cache/complete"
def get_buildinfo(self, name, variant):
return self._packages[(name, variant)]
def get_last_complete_set(self):
def get_last_complete(variant):
complete_latest = (
self.get_complete_cache_dir() + '/' + pkgpanda.util.variant_prefix(variant) + 'complete.latest.json')
if not os.path.exists(complete_latest):
raise BuildError("No last complete found for variant {}. Expected to find {} to match "
"{}".format(pkgpanda.util.variant_name(variant), complete_latest,
pkgpanda.util.variant_prefix(variant) + 'treeinfo.json'))
return load_json(complete_latest)
result = {}
for variant in self.list_trees():
result[variant] = get_last_complete(variant)
return result
def get_last_build_filename(self, name, variant):
return self.get_package_cache_folder(name) + '/{}latest'.format(pkgpanda.util.variant_prefix(variant))
def get_package_path(self, pkg_id):
return self.get_package_cache_folder(pkg_id.name) + '/{}.tar.xz'.format(pkg_id)
def get_package_cache_folder(self, name):
directory = self._package_cache_dir + '/' + name
check_call(['mkdir', '-p', directory])
return directory
def list_trees(self):
return get_variants_from_filesystem(self._packages_dir, 'treeinfo.json')
def get_package_set(self, variant):
return PackageSet(variant, TreeInfo(load_config_variant(self._packages_dir, variant, 'treeinfo.json')), self)
def get_all_package_sets(self):
return [self.get_package_set(variant) for variant in sorted(self.list_trees(), key=pkgpanda.util.variant_str)]
@property
def packages(self):
return self._packages
@property
def builders(self):
return self._builders.copy()
@property
def packages_by_name(self):
return self._packages_by_name
@property
def packages_dir(self):
return self._packages_dir
def try_fetch_by_id(self, pkg_id: PackageId):
if self._repository_url is None:
return False
# TODO(cmaloney): Use storage providers to download instead of open coding.
pkg_path = "{}.tar.xz".format(pkg_id)
url = self._repository_url + '/packages/{0}/{1}'.format(pkg_id.name, pkg_path)
try:
directory = self.get_package_cache_folder(pkg_id.name)
# TODO(cmaloney): Move to some sort of logging mechanism?
print("Attempting to download", pkg_id, "from", url, "to", directory)
download_atomic(directory + '/' + pkg_path, url, directory)
assert os.path.exists(directory + '/' + pkg_path)
return directory + '/' + pkg_path
except FetchError:
return False
def try_fetch_bootstrap_and_active(self, bootstrap_id):
if self._repository_url is None:
return False
try:
bootstrap_name = '{}.bootstrap.tar.xz'.format(bootstrap_id)
active_name = '{}.active.json'.format(bootstrap_id)
# TODO(cmaloney): Use storage providers to download instead of open coding.
bootstrap_url = self._repository_url + '/bootstrap/' + bootstrap_name
active_url = self._repository_url + '/bootstrap/' + active_name
print("Attempting to download", bootstrap_name, "from", bootstrap_url)
dest_dir = self.get_bootstrap_cache_dir()
# Normalize to no trailing slash for repository_url
download_atomic(dest_dir + '/' + bootstrap_name, bootstrap_url, self._packages_dir)
print("Attempting to download", active_name, "from", active_url)
download_atomic(dest_dir + '/' + active_name, active_url, self._packages_dir)
return True
except FetchError:
return False
def expand_require(require):
try:
return expand_require_exceptions(require)
except ValidationError as ex:
raise BuildError(str(ex)) from ex
def get_docker_id(docker_name):
return check_output(["docker", "inspect", "-f", "{{ .Id }}", docker_name]).decode('utf-8').strip()
def hash_files_in_folder(directory):
"""Given a relative path, hashes all files inside that folder and subfolders
Returns a dictionary from filename to the hash of that file. If that whole
dictionary is hashed, you get a hash of all the contents of the folder.
This is split out from calculating the whole folder hash so that the
behavior in different walking corner cases can be more easily tested.
"""
assert not directory.startswith('/'), \
"For the hash to be reproducible on other machines relative paths must always be used. " \
"Got path: {}".format(directory)
directory = directory.rstrip('/')
file_hash_dict = {}
# TODO(cmaloney): Disallow symlinks as they're hard to hash, people can symlink / copy in their
# build steps if needed.
for root, dirs, filenames in os.walk(directory):
assert not root.startswith('/')
for name in filenames:
path = root + '/' + name
base = path[len(directory) + 1:]
file_hash_dict[base] = pkgpanda.util.sha1(path)
# If the directory has files inside of it, then it'll be picked up implicitly. by the files
# or folders inside of it. If it contains nothing, it wouldn't be picked up but the existence
# is important, so added it with a value for it's hash not-makeable via sha1 (empty string).
if len(filenames) == 0 and len(dirs) == 0:
path = root[len(directory) + 1:]
# Empty path means it is the root directory, in which case we want no entries, not a
# single entry "": ""
if path:
file_hash_dict[root[len(directory) + 1:]] = ""
return file_hash_dict
@contextmanager
def as_cwd(path):
start_dir = getcwd()
chdir(path)
yield
chdir(start_dir)
def hash_folder_abs(directory, work_dir):
assert directory.startswith(work_dir), "directory must be inside work_dir: {} {}".format(directory, work_dir)
assert not work_dir[-1] == '/', "This code assumes no trailing slash on the work_dir"
with as_cwd(work_dir):
return hash_folder(directory[len(work_dir) + 1:])
def hash_folder(directory):
return hash_checkout(hash_files_in_folder(directory))
# Try to read json from the given file. If it is an empty file, then return an
# empty json dictionary.
def load_optional_json(filename):
try:
with open(filename) as f:
text = f.read().strip()
if text:
return json.loads(text)
return {}
except OSError as ex:
raise BuildError("Failed to open JSON file {}: {}".format(filename, ex))
except ValueError as ex:
raise BuildError("Unable to parse json in {}: {}".format(filename, ex))
def load_config_variant(directory, variant, extension):
assert directory[-1] != '/'
return load_optional_json(directory + '/' + pkgpanda.util.variant_prefix(variant) + extension)
def load_buildinfo(path, variant):
buildinfo = load_config_variant(path, variant, 'buildinfo.json')
# Fill in default / guaranteed members so code everywhere doesn't have to guard around it.
buildinfo.setdefault('build_script', 'build')
buildinfo.setdefault('docker', 'dcos/dcos-builder:dcos-builder_dockerdir-latest')
buildinfo.setdefault('environment', dict())
buildinfo.setdefault('requires', list())
buildinfo.setdefault('state_directory', False)
return buildinfo
def make_bootstrap_tarball(package_store, packages, variant):
# Convert filenames to package ids
pkg_ids = list()
for pkg_path in packages:
# Get the package id from the given package path
filename = os.path.basename(pkg_path)
if not filename.endswith(".tar.xz"):
raise BuildError("Packages must be packaged / end with a .tar.xz. Got {}".format(filename))
pkg_id = filename[:-len(".tar.xz")]
pkg_ids.append(pkg_id)
bootstrap_cache_dir = package_store.get_bootstrap_cache_dir()
# Filename is output_name.<sha-1>.{active.json|.bootstrap.tar.xz}
bootstrap_id = hash_checkout(pkg_ids)
latest_name = "{}/{}bootstrap.latest".format(bootstrap_cache_dir, pkgpanda.util.variant_prefix(variant))
output_name = bootstrap_cache_dir + '/' + bootstrap_id + '.'
# bootstrap tarball = <sha1 of packages in tarball>.bootstrap.tar.xz
bootstrap_name = "{}bootstrap.tar.xz".format(output_name)
active_name = "{}active.json".format(output_name)
def mark_latest():
# Ensure latest is always written
write_string(latest_name, bootstrap_id)
print("bootstrap: {}".format(bootstrap_name))
print("active: {}".format(active_name))
print("latest: {}".format(latest_name))
return bootstrap_id
if (os.path.exists(bootstrap_name)):
print("Bootstrap already up to date, not recreating")
return mark_latest()
check_call(['mkdir', '-p', bootstrap_cache_dir])
# Try downloading.
if package_store.try_fetch_bootstrap_and_active(bootstrap_id):
print("Bootstrap already up to date, Not recreating. Downloaded from repository-url.")
return mark_latest()
print("Unable to download from cache. Building.")
print("Creating bootstrap tarball for variant {}".format(variant))
work_dir = tempfile.mkdtemp(prefix='mkpanda_bootstrap_tmp')
def make_abs(path):
return os.path.join(work_dir, path)
pkgpanda_root = make_abs("opt/mesosphere")
repository = Repository(os.path.join(pkgpanda_root, "packages"))
# Fetch all the packages to the root
for pkg_path in packages:
filename = os.path.basename(pkg_path)
pkg_id = filename[:-len(".tar.xz")]
def local_fetcher(id, target):
shutil.unpack_archive(pkg_path, target, "gztar")
repository.add(local_fetcher, pkg_id, False)
# Activate the packages inside the repository.
# Do generate dcos.target.wants inside the root so that we don't
# try messing with /etc/systemd/system.
install = Install(
root=pkgpanda_root,
config_dir=None,
rooted_systemd=True,
manage_systemd=False,
block_systemd=True,
fake_path=True,
skip_systemd_dirs=True,
manage_users=False,
manage_state_dir=False)
install.activate(repository.load_packages(pkg_ids))
# Mark the tarball as a bootstrap tarball/filesystem so that
# dcos-setup.service will fire.
make_file(make_abs("opt/mesosphere/bootstrap"))
# Write out an active.json for the bootstrap tarball
write_json(active_name, pkg_ids)
# Rewrite all the symlinks to point to /opt/mesosphere
rewrite_symlinks(work_dir, work_dir, "/")
make_tar(bootstrap_name, pkgpanda_root)
shutil.rmtree(work_dir)
# Update latest last so that we don't ever use partially-built things.
write_string(latest_name, bootstrap_id)
print("Built bootstrap")
return mark_latest()
def build_tree_variants(package_store, mkbootstrap):
""" Builds all possible tree variants in a given package store
"""
result = dict()
tree_variants = get_variants_from_filesystem(package_store.packages_dir, 'treeinfo.json')
if len(tree_variants) == 0:
raise Exception('No treeinfo.json can be found in {}'.format(package_store.packages_dir))
for variant in tree_variants:
result[variant] = pkgpanda.build.build_tree(package_store, mkbootstrap, variant)
return result
def build_tree(package_store, mkbootstrap, tree_variant):
"""Build packages and bootstrap tarballs for one or all tree variants.
Returns a dict mapping tree variants to bootstrap IDs.
If tree_variant is None, builds all available tree variants.
"""
# TODO(cmaloney): Add support for circular dependencies. They are doable
# long as there is a pre-built version of enough of the packages.
# TODO(cmaloney): Make it so when we're building a treeinfo which has a
# explicit package list we don't build all the other packages.
build_order = list()
visited = set()
built = set()
def visit(pkg_tuple: tuple):
"""Add a package and its requires to the build order.
Raises AssertionError if pkg_tuple is in the set of visited packages.
If the package has any requires, they're recursively visited and added
to the build order depth-first. Then the package itself is added.
"""
# Visit the node for the first (and only) time.
assert pkg_tuple not in visited
visited.add(pkg_tuple)
# Ensure all dependencies are built. Sorted for stability
for require in sorted(package_store.packages[pkg_tuple]['requires']):
require_tuple = expand_require(require)
# If the dependency has already been built, we can move on.
if require_tuple in built:
continue
# If the dependency has not been built but has been visited, then
# there's a cycle in the dependency graph.
if require_tuple in visited:
raise BuildError("Circular dependency. Circular link {0} -> {1}".format(pkg_tuple, require_tuple))
if PackageId.is_id(require_tuple[0]):
raise BuildError("Depending on a specific package id is not supported. Package {} "
"depends on {}".format(pkg_tuple, require_tuple))
if require_tuple not in package_store.packages:
raise BuildError("Package {0} require {1} not buildable from tree.".format(pkg_tuple, require_tuple))
# Add the dependency (after its dependencies, if any) to the build
# order.
visit(require_tuple)
build_order.append(pkg_tuple)
built.add(pkg_tuple)
# Can't compare none to string, so expand none -> "true" / "false", then put
# the string in a field after "" if none, the string if not.
def key_func(elem):
return elem[0], elem[1] is None, elem[1] or ""
def visit_packages(package_tuples):
for pkg_tuple in sorted(package_tuples, key=key_func):
if pkg_tuple in visited:
continue
visit(pkg_tuple)
if tree_variant:
package_sets = [package_store.get_package_set(tree_variant)]
else:
package_sets = package_store.get_all_package_sets()
with logger.scope("resolve package graph"):
# Build all required packages for all tree variants.
for package_set in package_sets:
visit_packages(package_set.all_packages)
built_packages = dict()
for (name, variant) in build_order:
built_packages.setdefault(name, dict())
# Run the build, store the built package path for later use.
# TODO(cmaloney): Only build the requested variants, rather than all variants.
built_packages[name][variant] = build(
package_store,
name,
variant,
True)
# Build bootstrap tarballs for all tree variants.
def make_bootstrap(package_set):
with logger.scope("Making bootstrap variant: {}".format(pkgpanda.util.variant_name(package_set.variant))):
package_paths = list()
for name, pkg_variant in package_set.bootstrap_packages:
package_paths.append(built_packages[name][pkg_variant])
if mkbootstrap:
return make_bootstrap_tarball(
package_store,
list(sorted(package_paths)),
package_set.variant)
# Build bootstraps and and package lists for all variants.
# TODO(cmaloney): Allow distinguishing between "build all" and "build the default one".
complete_cache_dir = package_store.get_complete_cache_dir()
check_call(['mkdir', '-p', complete_cache_dir])
results = {}
for package_set in package_sets:
info = {
'bootstrap': make_bootstrap(package_set),
'packages': sorted(
load_string(package_store.get_last_build_filename(*pkg_tuple))
for pkg_tuple in package_set.all_packages)}
write_json(
complete_cache_dir + '/' + pkgpanda.util.variant_prefix(package_set.variant) + 'complete.latest.json',
info)
results[package_set.variant] = info
return results
def assert_no_duplicate_keys(lhs, rhs):
if len(lhs.keys() & rhs.keys()) != 0:
print("ASSERTION FAILED: Duplicate keys between {} and {}".format(lhs, rhs))
assert len(lhs.keys() & rhs.keys()) == 0
# Find all build variants and build them
def build_package_variants(package_store, name, clean_after_build=True, recursive=False):
# Find the packages dir / root of the packages tree, and create a PackageStore
results = dict()
for variant in package_store.packages_by_name[name].keys():
results[variant] = build(
package_store,
name,
variant,
clean_after_build=clean_after_build,
recursive=recursive)
return results
class IdBuilder():
def __init__(self, buildinfo):
self._start_keys = set(buildinfo.keys())
self._buildinfo = copy.deepcopy(buildinfo)
self._taken = set()
def _check_no_key(self, field):
if field in self._buildinfo:
raise BuildError("Key {} shouldn't be in buildinfo, but was".format(field))
def add(self, field, value):
self._check_no_key(field)
self._buildinfo[field] = value
def has(self, field):
return field in self._buildinfo
def take(self, field):
self._taken.add(field)
return self._buildinfo[field]
def replace(self, taken_field, new_field, new_value):
assert taken_field in self._buildinfo
self._check_no_key(new_field)
del self._buildinfo[taken_field]
self._buildinfo[new_field] = new_value
self._taken.add(new_field)
def update(self, field, new_value):
assert field in self._buildinfo
self._buildinfo[field] = new_value
def get_build_ids(self):
# If any keys are left in the buildinfo, error that there were unused keys
remaining_keys = self._start_keys - self._taken
if remaining_keys:
raise BuildError("ERROR: Unknown keys {} in buildinfo.json".format(remaining_keys))
return self._buildinfo
def build(package_store: PackageStore, name: str, variant, clean_after_build, recursive=False):
msg = "Building package {} variant {}".format(name, pkgpanda.util.variant_name(variant))
with logger.scope(msg):
return _build(package_store, name, variant, clean_after_build, recursive)
def _build(package_store, name, variant, clean_after_build, recursive):
assert isinstance(package_store, PackageStore)
tmpdir = tempfile.TemporaryDirectory(prefix="pkgpanda_repo")
repository = Repository(tmpdir.name)
package_dir = package_store.get_package_folder(name)
def src_abs(name):
return package_dir + '/' + name
def cache_abs(filename):
return package_store.get_package_cache_folder(name) + '/' + filename
# Build pkginfo over time, translating fields from buildinfo.
pkginfo = {}
# Build up the docker command arguments over time, translating fields as needed.
cmd = DockerCmd()
assert (name, variant) in package_store.packages, \
"Programming error: name, variant should have been validated to be valid before calling build()."
builder = IdBuilder(package_store.get_buildinfo(name, variant))
final_buildinfo = dict()
builder.add('name', name)
builder.add('variant', pkgpanda.util.variant_str(variant))
# Convert single_source -> sources
if builder.has('sources'):
if builder.has('single_source'):
raise BuildError('Both sources and single_source cannot be specified at the same time')
sources = builder.take('sources')
elif builder.has('single_source'):
sources = {name: builder.take('single_source')}
builder.replace('single_source', 'sources', sources)
else:
builder.add('sources', {})
sources = dict()
print("NOTICE: No sources specified")
final_buildinfo['sources'] = sources
# Construct the source fetchers, gather the checkout ids from them
checkout_ids = dict()
fetchers = dict()
try:
for src_name, src_info in sorted(sources.items()):
# TODO(cmaloney): Switch to a unified top level cache directory shared by all packages
cache_dir = package_store.get_package_cache_folder(name) + '/' + src_name
check_call(['mkdir', '-p', cache_dir])
fetcher = get_src_fetcher(src_info, cache_dir, package_dir)
fetchers[src_name] = fetcher
checkout_ids[src_name] = fetcher.get_id()
except ValidationError as ex:
raise BuildError("Validation error when fetching sources for package: {}".format(ex))
for src_name, checkout_id in checkout_ids.items():
# NOTE: single_source buildinfo was expanded above so the src_name is
# always correct here.
# Make sure we never accidentally overwrite something which might be
# important. Fields should match if specified (And that should be
# tested at some point). For now disallowing identical saves hassle.
assert_no_duplicate_keys(checkout_id, final_buildinfo['sources'][src_name])
final_buildinfo['sources'][src_name].update(checkout_id)
# Add the sha1 of the buildinfo.json + build file to the build ids
builder.update('sources', checkout_ids)
build_script = src_abs(builder.take('build_script'))
# TODO(cmaloney): Change dest name to build_script_sha1
builder.replace('build_script', 'build', pkgpanda.util.sha1(build_script))
builder.add('pkgpanda_version', pkgpanda.build.constants.version)
extra_dir = src_abs("extra")
# Add the "extra" folder inside the package as an additional source if it
# exists
if os.path.exists(extra_dir):
extra_id = hash_folder_abs(extra_dir, package_dir)
builder.add('extra_source', extra_id)
final_buildinfo['extra_source'] = extra_id
# Figure out the docker name.
docker_name = builder.take('docker')
cmd.container = docker_name
# Add the id of the docker build environment to the build_ids.
try:
docker_id = get_docker_id(docker_name)
except CalledProcessError:
# docker pull the container and try again
check_call(['docker', 'pull', docker_name])
docker_id = get_docker_id(docker_name)
builder.update('docker', docker_id)
# TODO(cmaloney): The environment variables should be generated during build
# not live in buildinfo.json.
pkginfo['environment'] = builder.take('environment')
# Whether pkgpanda should on the host make sure a `/var/lib` state directory is available
pkginfo['state_directory'] = builder.take('state_directory')
if pkginfo['state_directory'] not in [True, False]:
raise BuildError("state_directory in buildinfo.json must be a boolean `true` or `false`")
username = None
if builder.has('username'):
username = builder.take('username')
if not isinstance(username, str):
raise BuildError("username in buildinfo.json must be either not set (no user for this"
" package), or a user name string")
try:
pkgpanda.UserManagement.validate_username(username)
except ValidationError as ex:
raise BuildError("username in buildinfo.json didn't meet the validation rules. {}".format(ex))
pkginfo['username'] = username
group = None
if builder.has('group'):
group = builder.take('group')
if not isinstance(group, str):
raise BuildError("group in buildinfo.json must be either not set (use default group for this user)"
", or group must be a string")
try:
pkgpanda.UserManagement.validate_group_name(group)
except ValidationError as ex:
raise BuildError("group in buildinfo.json didn't meet the validation rules. {}".format(ex))
pkginfo['group'] = group
# Packages need directories inside the fake install root (otherwise docker
# will try making the directories on a readonly filesystem), so build the
# install root now, and make the package directories in it as we go.
install_dir = tempfile.mkdtemp(prefix="pkgpanda-")
active_packages = list()
active_package_ids = set()
active_package_variants = dict()
auto_deps = set()
# Final package has the same requires as the build.
requires = builder.take('requires')
pkginfo['requires'] = requires
if builder.has("sysctl"):
pkginfo["sysctl"] = builder.take("sysctl")
# TODO(cmaloney): Pull generating the full set of requires a function.
to_check = copy.deepcopy(requires)
if type(to_check) != list:
raise BuildError("`requires` in buildinfo.json must be an array of dependencies.")
while to_check:
requires_info = to_check.pop(0)
requires_name, requires_variant = expand_require(requires_info)
if requires_name in active_package_variants:
# TODO(cmaloney): If one package depends on the <default>
# variant of a package and 1+ others depends on a non-<default>
# variant then update the dependency to the non-default variant
# rather than erroring.
if requires_variant != active_package_variants[requires_name]:
# TODO(cmaloney): Make this contain the chains of
# dependencies which contain the conflicting packages.
# a -> b -> c -> d {foo}
# e {bar} -> d {baz}
raise BuildError(
"Dependncy on multiple variants of the same package {}. variants: {} {}".format(
requires_name,
requires_variant,
active_package_variants[requires_name]))
# The variant has package {requires_name, variant} already is a
# dependency, don't process it again / move on to the next.
continue
active_package_variants[requires_name] = requires_variant
# Figure out the last build of the dependency, add that as the
# fully expanded dependency.
requires_last_build = package_store.get_last_build_filename(requires_name, requires_variant)
if not os.path.exists(requires_last_build):
if recursive:
# Build the dependency
build(package_store, requires_name, requires_variant, clean_after_build, recursive)
else:
raise BuildError("No last build file found for dependency {} variant {}. Rebuild "
"the dependency".format(requires_name, requires_variant))
try:
pkg_id_str = load_string(requires_last_build)
auto_deps.add(pkg_id_str)
pkg_buildinfo = package_store.get_buildinfo(requires_name, requires_variant)
pkg_requires = pkg_buildinfo['requires']
pkg_path = repository.package_path(pkg_id_str)
pkg_tar = pkg_id_str + '.tar.xz'
if not os.path.exists(package_store.get_package_cache_folder(requires_name) + '/' + pkg_tar):
raise BuildError(
"The build tarball {} refered to by the last_build file of the dependency {} "
"variant {} doesn't exist. Rebuild the dependency.".format(
pkg_tar,
requires_name,
requires_variant))
active_package_ids.add(pkg_id_str)
# Mount the package into the docker container.
cmd.volumes[pkg_path] = "/opt/mesosphere/packages/{}:ro".format(pkg_id_str)
os.makedirs(os.path.join(install_dir, "packages/{}".format(pkg_id_str)))
# Add the dependencies of the package to the set which will be
# activated.
# TODO(cmaloney): All these 'transitive' dependencies shouldn't
# be available to the package being built, only what depends on
# them directly.
to_check += pkg_requires
except ValidationError as ex:
raise BuildError("validating package needed as dependency {0}: {1}".format(requires_name, ex)) from ex
except PackageError as ex:
raise BuildError("loading package needed as dependency {0}: {1}".format(requires_name, ex)) from ex
# Add requires to the package id, calculate the final package id.
# NOTE: active_packages isn't fully constructed here since we lazily load
# packages not already in the repository.
builder.update('requires', list(active_package_ids))
version_extra = None
if builder.has('version_extra'):
version_extra = builder.take('version_extra')
build_ids = builder.get_build_ids()
version_base = hash_checkout(build_ids)
version = None
if builder.has('version_extra'):
version = "{0}-{1}".format(version_extra, version_base)
else:
version = version_base
pkg_id = PackageId.from_parts(name, version)
# Everything must have been extracted by now. If it wasn't, then we just
# had a hard error that it was set but not used, as well as didn't include
# it in the caluclation of the PackageId.
builder = None
# Save the build_ids. Useful for verify exactly what went into the
# package build hash.
final_buildinfo['build_ids'] = build_ids
final_buildinfo['package_version'] = version
# Save the package name and variant. The variant is used when installing
# packages to validate dependencies.
final_buildinfo['name'] = name
final_buildinfo['variant'] = variant
# If the package is already built, don't do anything.
pkg_path = package_store.get_package_cache_folder(name) + '/{}.tar.xz'.format(pkg_id)
# Done if it exists locally
if exists(pkg_path):
print("Package up to date. Not re-building.")
# TODO(cmaloney): Updating / filling last_build should be moved out of
# the build function.
write_string(package_store.get_last_build_filename(name, variant), str(pkg_id))
return pkg_path
# Try downloading.
dl_path = package_store.try_fetch_by_id(pkg_id)
if dl_path:
print("Package up to date. Not re-building. Downloaded from repository-url.")
# TODO(cmaloney): Updating / filling last_build should be moved out of
# the build function.
write_string(package_store.get_last_build_filename(name, variant), str(pkg_id))
print(dl_path, pkg_path)
assert dl_path == pkg_path
return pkg_path
# Fall out and do the build since it couldn't be downloaded
print("Unable to download from cache. Proceeding to build")
print("Building package {} with buildinfo: {}".format(
pkg_id,
json.dumps(final_buildinfo, indent=2, sort_keys=True)))
# Clean out src, result so later steps can use them freely for building.
def clean():
# Run a docker container to remove src/ and result/
cmd = DockerCmd()
cmd.volumes = {
package_store.get_package_cache_folder(name): "/pkg/:rw",
}
cmd.container = "ubuntu:14.04.4"
cmd.run("package-cleaner", ["rm", "-rf", "/pkg/src", "/pkg/result"])
clean()
# Only fresh builds are allowed which don't overlap existing artifacts.
result_dir = cache_abs("result")
if exists(result_dir):
raise BuildError("result folder must not exist. It will be made when the package is "
"built. {}".format(result_dir))
# 'mkpanda add' all implicit dependencies since we actually need to build.
for dep in auto_deps:
print("Auto-adding dependency: {}".format(dep))
# NOTE: Not using the name pkg_id because that overrides the outer one.
id_obj = PackageId(dep)
add_package_file(repository, package_store.get_package_path(id_obj))
package = repository.load(dep)
active_packages.append(package)
# Checkout all the sources int their respective 'src/' folders.
try:
src_dir = cache_abs('src')
if os.path.exists(src_dir):
raise ValidationError(
"'src' directory already exists, did you have a previous build? " +
"Currently all builds must be from scratch. Support should be " +
"added for re-using a src directory when possible. src={}".format(src_dir))
os.mkdir(src_dir)
for src_name, fetcher in sorted(fetchers.items()):
root = cache_abs('src/' + src_name)
os.mkdir(root)
fetcher.checkout_to(root)
except ValidationError as ex:
raise BuildError("Validation error when fetching sources for package: {}".format(ex))
# Activate the packages so that we have a proper path, environment
# variables.
# TODO(cmaloney): RAII type thing for temproary directory so if we
# don't get all the way through things will be cleaned up?
install = Install(
root=install_dir,
config_dir=None,
rooted_systemd=True,
manage_systemd=False,
block_systemd=True,
fake_path=True,
manage_users=False,
manage_state_dir=False)
install.activate(active_packages)
# Rewrite all the symlinks inside the active path because we will
# be mounting the folder into a docker container, and the absolute
# paths to the packages will change.
# TODO(cmaloney): This isn't very clean, it would be much nicer to
# just run pkgpanda inside the package.
rewrite_symlinks(install_dir, repository.path, "/opt/mesosphere/packages/")
print("Building package in docker")
# TODO(cmaloney): Run as a specific non-root user, make it possible
# for non-root to cleanup afterwards.
# Run the build, prepping the environment as necessary.
mkdir(cache_abs("result"))
# Copy the build info to the resulting tarball
write_json(cache_abs("src/buildinfo.full.json"), final_buildinfo)
write_json(cache_abs("result/buildinfo.full.json"), final_buildinfo)
write_json(cache_abs("result/pkginfo.json"), pkginfo)
# Make the folder for the package we are building. If docker does it, it
# gets auto-created with root permissions and we can't actually delete it.
os.makedirs(os.path.join(install_dir, "packages", str(pkg_id)))
# TOOD(cmaloney): Disallow writing to well known files and directories?
# Source we checked out
cmd.volumes.update({
# TODO(cmaloney): src should be read only...
cache_abs("src"): "/pkg/src:rw",
# The build script
build_script: "/pkg/build:ro",
# Getting the result out
cache_abs("result"): "/opt/mesosphere/packages/{}:rw".format(pkg_id),
install_dir: "/opt/mesosphere:ro"
})
if os.path.exists(extra_dir):
cmd.volumes[extra_dir] = "/pkg/extra:ro"
cmd.environment = {
"PKG_VERSION": version,
"PKG_NAME": name,
"PKG_ID": pkg_id,
"PKG_PATH": "/opt/mesosphere/packages/{}".format(pkg_id),
"PKG_VARIANT": variant if variant is not None else "<default>",
"NUM_CORES": multiprocessing.cpu_count()
}
try:
# TODO(cmaloney): Run a wrapper which sources
# /opt/mesosphere/environment then runs a build. Also should fix
# ownership of /opt/mesosphere/packages/{pkg_id} post build.
cmd.run("package-builder", [
"/bin/bash",
"-o", "nounset",
"-o", "pipefail",
"-o", "errexit",
"/pkg/build"])
except CalledProcessError as ex:
raise BuildError("docker exited non-zero: {}\nCommand: {}".format(ex.returncode, ' '.join(ex.cmd)))
# Clean up the temporary install dir used for dependencies.
# TODO(cmaloney): Move to an RAII wrapper.
check_call(['rm', '-rf', install_dir])
with logger.scope("Build package tarball"):
# Check for forbidden services before packaging the tarball:
try:
check_forbidden_services(cache_abs("result"), RESERVED_UNIT_NAMES)
except ValidationError as ex:
raise BuildError("Package validation failed: {}".format(ex))
# TODO(cmaloney): Updating / filling last_build should be moved out of
# the build function.
write_string(package_store.get_last_build_filename(name, variant), str(pkg_id))
# Bundle the artifacts into the pkgpanda package
tmp_name = pkg_path + "-tmp.tar.xz"
make_tar(tmp_name, cache_abs("result"))
os.rename(tmp_name, pkg_path)
print("Package built.")
if clean_after_build:
clean()
return pkg_path
| BenWhitehead/dcos | pkgpanda/build/__init__.py | Python | apache-2.0 | 50,458 | [
"VisIt"
] | f741cb3f92e6a2ec70e695e10b6971d6175b731ffdfebd6bc795e1d007e09871 |
# -*- coding: utf-8 -*-
import os
import tempfile
from datetime import datetime
import numpy as np
import pytest
from numpy.testing import assert_array_almost_equal
from pysteps.io import import_netcdf_pysteps
from pysteps.io.exporters import _get_geotiff_filename
from pysteps.io.exporters import close_forecast_files
from pysteps.io.exporters import export_forecast_dataset
from pysteps.io.exporters import initialize_forecast_exporter_netcdf
from pysteps.tests.helpers import get_precipitation_fields, get_invalid_mask
def test_get_geotiff_filename():
"""Test the geotif name generator."""
start_date = datetime.strptime("201909082022", "%Y%m%d%H%M")
n_timesteps = 50
timestep = 5
for timestep_index in range(n_timesteps):
file_name = _get_geotiff_filename(
"test/path", start_date, n_timesteps, timestep, timestep_index
)
expected = (
f"test/path_201909082022_" f"{(timestep_index + 1) * timestep:03d}.tif"
)
assert expected == file_name
def test_io_export_netcdf_one_member_one_time_step():
"""
Test the export netcdf.
Also, test that the exported file can be read by the importer.
"""
pytest.importorskip("pyproj")
precip, metadata = get_precipitation_fields(
return_raw=True, metadata=True, source="fmi"
)
precip = precip.squeeze()
invalid_mask = get_invalid_mask(precip)
# save it back to disk
with tempfile.TemporaryDirectory() as outpath:
outfnprefix = "test_netcdf_out"
file_path = os.path.join(outpath, outfnprefix + ".nc")
startdate = metadata["timestamps"][0]
timestep = metadata["accutime"]
n_timesteps = 1
shape = precip.shape
exporter = initialize_forecast_exporter_netcdf(
outpath,
outfnprefix,
startdate,
timestep,
n_timesteps,
shape,
metadata,
n_ens_members=1,
)
export_forecast_dataset(precip[np.newaxis, :], exporter)
close_forecast_files(exporter)
# assert if netcdf file was saved and file size is not zero
assert os.path.exists(file_path) and os.path.getsize(file_path) > 0
# Test that the file can be read by the nowcast_importer
output_file_path = os.path.join(outpath, f"{outfnprefix}.nc")
precip_new, _ = import_netcdf_pysteps(output_file_path)
assert_array_almost_equal(precip, precip_new.data)
assert precip_new.dtype == "single"
precip_new, _ = import_netcdf_pysteps(output_file_path, dtype="double")
assert_array_almost_equal(precip, precip_new.data)
assert precip_new.dtype == "double"
precip_new, _ = import_netcdf_pysteps(output_file_path, fillna=-1000)
new_invalid_mask = precip_new == -1000
assert (new_invalid_mask == invalid_mask).all()
| pySTEPS/pysteps | pysteps/tests/test_exporters.py | Python | bsd-3-clause | 2,913 | [
"NetCDF"
] | d2f128e951c6f222495563cce0f8da2196fd28a9fb8fd8256864581d5e6361d9 |
# $Id$
"""
Introduction
============
``fortune`` is a stripped-down implementation of the classic BSD Unix
``fortune`` command. It combines the capabilities of the ``strfile`` command
(which produces the fortune index file) and the ``fortune`` command (which
displays a random fortune). It reads the traditional ``fortune`` program's
text file format.
Usage
=====
Usage::
fortune [OPTIONS] /path/to/fortunes
OPTIONS
-h, --help Show usage and exit.
-u, --update Update the index file.
-q, --quiet When updating the index file, do so quietly.
-V, --version Show version and exit.
If you omit the path, ``fortune`` looks at the ``FORTUNE_FILE`` environment
variable. If that environment variable isn't set, ``fortune`` aborts.
Fortune Cookie File Format
==========================
A fortune cookie file is a text file full of quotes. The format is simple:
The file consists of paragraphs separated by lines containing a single '%'
character. For example::
A little caution outflanks a large cavalry.
-- Bismarck
%
A little retrospection shows that although many fine, useful software
systems have been designed by committees and built as part of multipart
projects, those software systems that have excited passionate fans are
those that are the products of one or a few designing minds, great
designers. Consider Unix, APL, Pascal, Modula, the Smalltalk interface,
even Fortran; and contrast them with Cobol, PL/I, Algol, MVS/370, and
MS-DOS.
-- Fred Brooks, Jr.
%
A man is not old until regrets take the place of dreams.
-- John Barrymore
The Index File
==============
For efficiency and speed, ``fortune`` uses an index file to store the offsets
and lengths of every fortune in the text fortune file. So, before you can use
``fortune`` to read a random fortune, you have to generate the data file. With
the traditional BSD ``fortune`` program, you used the I{strfile}(8) command
to generate the index. With I{this} fortune program, however, you simply
pass a special argument to the ``fortune`` command::
fortune -u /path/to/fortunes
That command will generate a binary ``/path/to/fortunes.dat`` file that
contains the index. You should run ``fortune -u`` whenever you change the text
fortune file.
Generating a Random Fortune
===========================
Once you have an index file, you can generate a random fortune simply by
running the ``fortune`` utility with the path to your text fortunes file::
fortune /path/to/fortunes
Differences
===========
This version of ``fortune`` does not provide some of the more advanced
capabilities of the original BSD program. For instance, it lacks:
- the ability to mark offensive and inoffensive fortunes
- the ability to separate long and short quotes
- the ability to print all fortunes matching a regular expression
It does, however, provide the most important function: The ability to display
a random quote from a set of quotes.
License and Copyright Info
==========================
Copyright (c) 2008 Brian M. Clapper
This is free software, released under the following BSD-like license:
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- The end-user documentation included with the redistribution, if any,
must include the following acknowlegement:
This product includes software developed by Brian M. Clapper
(bmc@clapper.org, http://www.clapper.org/bmc/). That software is
copyright (c) 2008 Brian M. Clapper.
Alternately, this acknowlegement may appear in the software itself, if
and wherever such third-party acknowlegements normally appear.
THIS SOFTWARE IS PROVIDED B{AS IS} AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BRIAN M.
CLAPPER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
"""
# ---------------------------------------------------------------------------
# Imports
# ---------------------------------------------------------------------------
from __future__ import print_function
import random
import os
import sys
import argparse
try:
import cPickle as pickle
except ImportError:
# Python 3 merged cPickle and pickle under one interface
import pickle
# ---------------------------------------------------------------------------
# Exports
# ---------------------------------------------------------------------------
__all__ = ['main', 'get_random_fortune', 'make_fortune_data_file']
# Info about the module
__version__ = '1.1'
__author__ = 'Brian M. Clapper'
__email__ = 'bmc@clapper.org'
__url__ = 'http://software.clapper.org/fortune/'
__copyright__ = '2008-2015 Brian M. Clapper'
__license__ = 'BSD-style license'
# ---------------------------------------------------------------------------
# Internal Constants
# ---------------------------------------------------------------------------
_PICKLE_PROTOCOL = 2
# ---------------------------------------------------------------------------
# Functions
# ---------------------------------------------------------------------------
def random_int(start, end):
try:
# Use SystemRandom, if it's available, since it's likely to have
# more entropy.
r = random.SystemRandom()
except:
r = random
return r.randint(start, end)
def get_random_fortune(fortune_file):
"""
Get a random fortune from the specified file. Barfs if the corresponding
``.dat`` file isn't present.
:Parameters:
fortune_file : str
path to file containing fortune cookies
:rtype: str
:return: the random fortune
"""
fortune_index_file = fortune_file + '.dat'
if not os.path.exists(fortune_index_file):
raise ValueError('Can\'t find file "{}"'.format(fortune_index_file))
fortuneIndex = open(fortune_index_file, 'rb')
data = pickle.load(fortuneIndex)
fortuneIndex.close()
randomRecord = random_int(0, len(data) - 1)
(start, length) = data[randomRecord]
f = open(fortune_file, 'rU')
f.seek(start)
fortuneCookie = f.read(length)
f.close()
return fortuneCookie[0:-1] # strips trailing newline
def _read_fortunes(fortune_file):
""" Yield fortunes as lists of lines """
result = []
start = None
pos = 0
for line in fortune_file:
if line == "%\n":
if pos == 0: # "%" at top of file. Skip it.
continue
yield (start, pos - start, result)
result = []
start = None
else:
if start == None:
start = pos
result.append(line)
pos += len(line)
if result:
yield (start, pos - start, result)
def make_fortune_data_file(fortune_file, quiet=False):
"""
Create or update the data file for a fortune cookie file.
:Parameters:
fortune_file : str
path to file containing fortune cookies
quiet : bool
If ``True``, don't display progress messages
"""
fortune_index_file = fortune_file + '.dat'
if not quiet:
print('Updating "{}" from "{}"...'.format(
fortune_index_file, fortune_file))
data = []
shortest = sys.maxsize
longest = 0
for start, length, fortune in _read_fortunes(open(fortune_file, 'rU')):
data += [(start, length)]
shortest = min(shortest, length)
longest = max(longest, length)
fortuneIndex = open(fortune_index_file, 'wb')
pickle.dump(data, fortuneIndex, _PICKLE_PROTOCOL)
fortuneIndex.close()
if not quiet:
print('Processed {} fortunes.\nLongest: {}\nShortest: {}'.format(
len(data), longest, shortest))
def main():
"""
Main program.
"""
epilogue = ('If <fortune_file> is omitted, fortune looks at the '
'FORTUNE_FILE environment variable for the path.')
arg_parser = argparse.ArgumentParser(epilog=epilogue)
arg_parser.add_argument('-q', '--quiet', action='store_true', dest='quiet',
help="when updating the index file, don't emit " \
"messages.")
arg_parser.add_argument('-u', '--update', action='store_true', dest='update',
help='Update the index file, instead of printing a '
'fortune.')
arg_parser.add_argument('-V', '--version', action='store_true',
dest='show_version', help='Show version and exit.')
arg_parser.add_argument('fortune_file', help='the file to read/write.',
nargs='?')
args = arg_parser.parse_args()
if args.show_version:
print('fortune, version %s'.format(__version__))
fortune_file = ''
if args.fortune_file:
fortune_file = args.fortune_file
else:
try:
fortune_file = os.environ['FORTUNE_FILE']
except KeyError:
arg_parser.print_help()
try:
if args.update:
make_fortune_data_file(fortune_file)
else:
print(get_random_fortune(fortune_file))
except ValueError as e:
print(e, file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
main()
| spasticVerbalizer/fortune | fortune/__init__.py | Python | bsd-3-clause | 9,974 | [
"Brian"
] | fc951cb3a2682bde57784ae695b1aca1aa4698f39dbaef377d11922cf867ba44 |
# shrunk - Rutgers University URL Shortener
"""Database-level interactions for shrunk. """
import datetime
import random
import string
import pymongo
class DuplicateIdException(Exception):
"""Raised when trying to add a duplicate key to the database."""
pass
class ForbiddenNameException(Exception):
"""Raised when trying to use a forbidden custom short URL."""
pass
class InvalidOperationException(Exception):
"""Raised when performing an invalid operation."""
pass
class ShrunkCursor(object):
"""Easy-to-use wrapper for internal database cursors."""
TIME_DESC = 0
"""Sort by creation time, descending."""
TIME_ASC = 1
"""Sort by creation time, ascending."""
TITLE_ASC = 2
"""Sort by title, alphabetically."""
TITLE_DESC = 3
"""Sort by title, reverse-alphabetically."""
def __init__(self, cursor):
"""Represents the result of a database operation.
:Parameters:
- `cursor`: A MongoDB cursor
"""
self.cursor = cursor
def paginate(self, page, links_per_page):
"""Performs pagination on this cursor.
This pagination assumes that pages are one-indexed; that is, the first
page starts numbering as page 1. Specifying a page number of zero or
less gives the first page; specifying a page number after the last gives
the last page.
:Parameters:
- `page`: An integer. Only show the results that belong on this page
- `links_per_page`: Limit the number of results for each page
:Side Effects:
Calling `get_results` on this cursor will return only the results that
belong on the given page. (All of the other results will be lost.)
:Returns:
A tuple containing the current page number and the last page number.
"""
if self.cursor is None:
return (1, 1)
# Calculate the pagination
count = self.cursor.count()
last_page = self.get_last_page(links_per_page)
page = min(max(page, 1), last_page)
# Apply a skip and limit to the cursor
self.cursor.skip((page-1)*links_per_page).limit(links_per_page)
# Return the new page number and total count
return (page, last_page)
def get_results(self):
"""Gets the results in the cursor in list form.
After calling this function, the cursor will be exhausted and no more
results may be drawn from it.
:Returns:
A list of JSON-compatible dictionaries containing the results from the
database.
"""
if self.cursor is None:
return []
else:
return list(self.cursor)
def get_last_page(self, links_per_page):
"""Calculates the total number of pages of results.
Performs some simple calculation of the total number of pages that will
be shown for the main application's pagination.
:Parameters:
- `links_per_page`: The maximum number of links per page
:Returns:
A nonnegative integer indicating the one-based index number of the
last page. For instance, if `count` is 11 and `links_per_page` is 5,
then this function returns 3.
"""
if not self.cursor:
return 1
count = self.cursor.count()
if count < links_per_page:
return 1
elif count % links_per_page == 0:
# Special case: fills all pages exactly
return count // links_per_page
else:
return (count // links_per_page) + 1
def sort(self, sortby):
"""Sort the results in the cursor.
The cursor can be sorted only if it hasn't been used yet; that is, no
records have been read from it.
:Parameters:
- `sortby`: The direction to sort in. Should be one of TIME_ASC,
TIME_DESC, TITLE_ASC, or TITLE_DESC
:Raises:
- ValueError: if the sorting parameter is invalid
- InvalidOperationException: if the cursor has already been used
before sorting
"""
try:
sortby = int(sortby)
if sortby == ShrunkCursor.TIME_ASC:
self.cursor.sort("timeCreated", pymongo.ASCENDING)
elif sortby == ShrunkCursor.TIME_DESC:
self.cursor.sort("timeCreated", pymongo.DESCENDING)
elif sortby == ShrunkCursor.TITLE_ASC:
self.cursor.sort([("title", pymongo.ASCENDING),
("_id", pymongo.ASCENDING)])
elif sortby == ShrunkCursor.TITLE_DESC:
self.cursor.sort([("title", pymongo.DESCENDING),
("_id", pymongo.DESCENDING)])
else:
raise IndexError("Invalid argument to 'sortby'")
except ValueError:
raise ValueError("'sortby' must be an integer")
except pymongo.errors.InvalidOperation:
raise InvalidOperationException(
"You cannot sort a cursor after use.")
class ShrunkClient(object):
"""A class for database interactions."""
ALPHABET = string.digits + string.ascii_lowercase
"""The alphabet used for encoding short urls."""
URL_MIN = 46656
"""The shortest allowable URL.
This is the value of '1000' in the URL base encoding. Guarantees that all
URLs are at least four characters long.
"""
URL_MAX = 2821109907455
"""The longest allowable URL.
This is the value of 'zzzzzzzz' in the URL base encoding. Guarantees that
all URLs do not exceed eight characters.
"""
RESERVED_WORDS = ["add", "login", "logout", "delete", "admin"]
"""Reserved words that cannot be used as shortened urls."""
def __init__(self, host=None, port=None):
"""Create a new client connection.
This client uses MongoDB. No network traffic occurs until a data method
is called.
:Parameters:
- `host` (optional): the hostname to connect to; defaults to
"localhost"
- `port` (optional): the port to connect to on the server; defaults to
the database default if not present
"""
self._mongo = pymongo.MongoClient(host, port)
def count_links(self, netid=None):
"""Counts the number of created links.
Gives a count on the number of created links for the given NetID. If no
specific user is specified, this returns a global count for all users.
:Parameters:
- `netid` (optional): Specify a NetID to count their links; if None,
finds a global count
:Returns:
A nonnegative integer.
"""
db = self._mongo.shrunk_urls
if netid:
return db.urls.find({"netid": netid}).count()
else:
return db.urls.count()
def create_short_url(self, long_url, short_url=None, netid=None, title=None):
"""Given a long URL, create a new short URL.
Randomly creates a new short URL and updates the Shrunk database.
:Parameters:
- `long_url`: The original URL to shrink.
- `short_url` (optional): A custom name for the short URL. A random
one is generated if none is specified.
- `netid` (optional): The creator of this URL.
- `title` (optional): A descriptive title for this URL.
:Returns:
The shortened URL.
:Raises:
- ForbiddenNameException: if the requested name is a reserved word or
has been banned by an administrator
- DuplicateIdException: if the requested name is already taken
"""
custom_url = short_url is not None
db = self._mongo.shrunk_urls
#Check if url is blocked
base_url = long_url[(long_url.find("://") + 3):] # Strip any protocol
base_url = base_url[: base_url.find("/")] # Strip path
if db.blocked_urls.find_one({"url" : { "$regex" : "%s*" % base_url }}):
raise ForbiddenNameException("That URL is not allowed.")
document = {
"_id" : short_url,
"long_url" : long_url,
"timeCreated" : datetime.datetime.now(),
"visits" : 0
}
if netid is not None:
document["netid"] = netid
if title is not None:
document["title"] = title
if custom_url:
# Attempt to insert the custom URL
if custom_url in ShrunkClient.RESERVED_WORDS:
raise ForbiddenNameException("That name is reserved.")
try:
response = db.urls.insert(document)
except pymongo.errors.DuplicateKeyError:
raise DuplicateIdException("That name already exists.")
else:
# Generate a unique key and update MongoDB
response = None
while response is None:
try:
url = ShrunkClient._generate_unique_key()
while url in ShrunkClient.RESERVED_WORDS:
url = ShrunkClient._generate_unique_key()
document["_id"] = url
response = db.urls.insert(document)
except pymongo.errors.DuplicateKeyError:
continue
return response
def modify_url(self, short_url, **kwargs):
"""Modifies an existing URL.
Edits the values of the url `short_url` and replaces them with the
values specified in the keyword arguments.
:Parameters:
- `short_url`: The ID of the URL to edit.
- `kwargs`: A dictionary of keyword arguments. The URL will take on
all values specified.
"""
db = self._mongo.shrunk_urls
db.urls.update({"_id" : short_url},
{"$set" : kwargs})
def delete_url(self, short_url):
"""Given a short URL, delete it from the database.
This deletes all information associated with the short URL and wipes all
appropriate databases.
:Parameters:
- `short_url`: The shortened URL to dete.
:Returns:
A response in JSON detailing the effect of the database operations.
"""
url_db = self._mongo.shrunk_urls
visit_db = self._mongo.shrunk_visits
if short_url is None:
return {
"urlDataResponse" : {"nRemoved" : 0},
"visitDataResponse" : {"nRemoved" : 0}
}
else:
return {
"urlDataResponse" : url_db.urls.remove({
"_id" : short_url
}),
"visitDataResponse" : visit_db.visits.remove({
"short_url" : short_url
})
}
def delete_user_urls(self, netid):
"""Deletes all URLs associated with a given NetID.
The response, encoded as a JSON-compatible Python dict, will at least
contained an "nRemoved" indicating the number of records removed.
:Parameters:
- `netid`: The NetID of the URLs to delete.
:Returns:
A response in JSON detailing the effect of the database operations.
"""
db = self._mongo.shrunk_urls
if netid is None:
return {"nRemoved" : 0}
else:
return db.urls.remove({"netid" : netid})
def get_url_info(self, short_url):
"""Given a short URL, return information about it.
This returns a dictionary containing the following fields:
- url : The original unshrunk URL
- timeCreated: The time the URL was created, expressed as an ISODate
instance
- netid : If it exists, the creator of the shortened URL
- visits : The number of visits to this URL
:Parameters:
- `short_url`: A shortened URL
"""
db = self._mongo.shrunk_urls
return db.urls.find_one({"_id" : short_url})
def get_long_url(self, short_url):
"""Given a short URL, returns the long URL.
Performs a case-insensitive search for the corresponding long URL.
:Parameters:
- `short_url`: A shortened URL
:Returns:
The long URL, or None if the short URL does not exist.
"""
result = self.get_url_info(short_url.lower())
if result is not None:
return result["long_url"]
else:
return None
def get_visits(self, short_url):
"""Returns all visit information to the given short URL.
:Parameters:
- `short_url`: A shortened URL
:Response:
- A JSON-compatible Python dict containing the database response.
"""
db = self._mongo.shrunk_visits
return db.visits.find({"short_url" : short_url})
def get_num_visits(self, short_url):
"""Given a short URL, return the number of visits.
:Parameters:
- `short_url`: A shortened URL
:Returns:
A nonnegative integer indicating the number of times the URL has been
visited, or None if the URL does not exist in the database.
"""
db = self._mongo.shrunk_urls
try:
# Can be at most one document
[document] = [doc for doc in db.urls.find({"_id" : short_url})]
return document["visits"]
except ValueError:
# There were no values to unpack
return None
def get_all_urls(self, filter_dict=None):
"""Gets all the URLs created.
:Parameters:
- `filter_dict` (optional): Mongo filter to be applied to the query
- `skip` (optional): The number of results to skip
- `limit` (optional): The maximum number of results
:Returns:
A ShrunkCursor containing the results of the operation.
"""
db = self._mongo.shrunk_urls
if not filter_dict:
cursor = db.urls.find(sort=[("timeCreated", pymongo.DESCENDING)])
else:
cursor = db.urls.find(filter_dict,
sort=[("timeCreated", pymongo.DESCENDING)])
return ShrunkCursor(cursor)
def get_urls(self, netid):
"""Gets all the URLs created by the given NetID.
:Parameters:
- `netid`: A Rutgers NetID
:Returns:
A ShrunkCursor containing the results of the operation.
"""
return self.get_all_urls(filter_dict={'netid' : netid})
def search(self, search_string, netid=None):
"""Search for URLs containing the given search string.
Searches for links where the title or URL contain the given search
string. The search is non-case-sensitive.
:Parameters:
- `search_string`: A query string
- `netid` (optional): Search for links only owned by this NetID
:Returns:
A Shrunk cursor containing the results of the search, or None if an
error occurred.
"""
db = self._mongo.shrunk_urls
match = {"$regex" : search_string, "$options" : "i"}
query = {"$or" : [{"long_url" : match}, {"title" : match}, {"netid" : match}]}
if netid is not None:
query["netid"] = netid
cursor = db.urls.find(query)
return ShrunkCursor(cursor)
def visit(self, short_url, source_ip):
"""Visits the given URL and logs visit information.
On visiting a URL, this is guaranteed to perform at least the following
side effects if the URL is valid:
- Increment the hit counter
- Log the visitor
If the URL is invalid, no side effects will occur.
:Returns:
The long URL corresponding to the short URL, or None if no such URL
was found in the database.
"""
db = self._mongo.shrunk_urls
# TODO return type and validation that the URL exists
db.urls.update({"_id" : short_url},
{"$inc" : {"visits" : 1}})
# TODO Do we need the source ip or can we detect it?
db = self._mongo.shrunk_visits
db.visits.insert({
"short_url" : short_url,
"source_ip" : source_ip,
"time" : datetime.datetime.now()
})
def is_blacklisted(self, netid):
"""Determines if a user has been blacklisted.
:Parameters:
- `netid` A Rutgers NetID
:Returns
True if the user is in the blacklist collection; False otherwise.
"""
db = self._mongo.shrunk_users
if db.blacklist.find_one({"netid" : netid}) is None:
return False
return True
def ban_user(self, netid, banned_by):
"""Adds a user to the blacklist collection.
:Parameters:
- `netid`: A Rutgers NetID
- `banned_by`: The NetID of the administrator that banned this person
"""
db = self._mongo.shrunk_users
if not self.is_blacklisted(netid):
return db.blacklist.insert({
'netid' : netid,
'banned_by' : [ banned_by ]
})
else:
update = {'$addToSet' : {'banned_by' : banned_by}}
return db.blacklist.update({'netid' : netid}, update, upsert=False,
multi=False)
def unban_user(self, netid):
"""Removes a user from the blacklist collection.
:Parameters:
- `netid`: A Rutgers NetID
"""
db = self._mongo.shrunk_users
if self.is_blacklisted:
db.blacklist.remove({'netid' : netid})
return True
else:
return False
def is_admin(self, netid):
"""Determine if a user is an administrator.
:Parameters:
- `netid`: A Rutgers NetID.
:Returns:
True if the user is in the administrators collection, False
otherwise.
"""
db = self._mongo.shrunk_users
if db.administrators.find_one({'netid' : netid}) is None:
return False
return True
def add_admin(self, netid, added_by):
"""Adds a user to the administrators collection.
:Parameters:
- `netid`: A Rutgers NetID
- `added_by`: The NetID of the administrator that added this person
"""
db = self._mongo.shrunk_users
if not self.is_admin(netid):
return db.administrators.insert({"netid" : netid, "added_by" :
added_by})
def delete_admin(self, netid):
"""Revokes a user's administrator privileges.
:Parameters:
- `netid`: They NetID of the administrator to remove
"""
db = self._mongo.shrunk_users
return db.administrators.remove({"netid" : netid})
def get_admins(self):
"""Retrieves the list of administrators.
:Returns:
A list of dicts containing information about each administrator.
"""
db = self._mongo.shrunk_users
return list(db.administrators.find())
def is_blocked(self, url):
"""Determines if a URL has been banned.
:Parameters:
- `url`: The url to check
:Returns:
True if the url is in the blocked_urls collection; False otherwise.
"""
db = self._mongo.shrunk_urls
if db.blocked_urls.find_one({'url' : url}) is None:
return False
return True
def get_blocked_links(self):
"""Retrieves the list of blocked links.
:Returns:
A list of dicts containing information about each blocked link.
"""
db = self._mongo.shrunk_urls
return list(db.blocked_urls.find())
def block_link(self, url, blocked_by):
"""Adds a link to the blocked_urls collection.
:Parameters:
- `url`: The url to block
- `blocked_by`: The NetIDs of the administrators blocking the URL
"""
db = self._mongo.shrunk_urls
if not self.is_blocked(url):
res = db.blocked_urls.insert({'url' : url, 'blocked_by' : blocked_by})
# Find any urls that should be deleted
db.urls.remove({"long_url" : { "$regex" : url }})
return res
def allow_link(self, url):
"""Removes a link from the blocked_urls collection.
:Parameters:
- `url`: The url to allow
"""
db = self._mongo.shrunk_urls
return db.blocked_urls.remove({'url' : { '$regex' : url }})
def get_blacklisted_users(self):
"""Retrieves the list of banned users.
:Returns:
A list of dicts containing information about each blacklisted NetID.
"""
db = self._mongo.shrunk_users
return list(db.blacklist.find())
@staticmethod
def _generate_unique_key():
"""Generates a unique key."""
return ShrunkClient._base_encode(
random.randint(ShrunkClient.URL_MIN, ShrunkClient.URL_MAX))
@staticmethod
def _base_encode(integer):
"""Encodes an integer into our arbitrary link alphabet.
Given an integer, convert it to base-36. Letters are case-insensitive;
this function uses uppercase arbitrarily.
:Parameters:
- `integer`: An integer.
:Returns:
A string composed of characters from ShrunkClient.ALPHABET.
"""
length = len(ShrunkClient.ALPHABET)
result = []
while integer != 0:
result.append(ShrunkClient.ALPHABET[integer % length])
integer //= length
return "".join(reversed(result))
| ksuarz/shrunk | shrunk/client.py | Python | mit | 21,781 | [
"VisIt"
] | 61289d1e4f9714fbe1db98ad032f33249d04ef3233f4101c4b1936ac505252d0 |
#!/usr/bin/env python3
import os
import sys
import random
import time
from random import seed, randint
import argparse
import platform
from datetime import datetime
import imp
from time import sleep
# from run_parameter import *
parser = argparse.ArgumentParser(
description="This is a python3 script to\
automatic copy the template file, \
run simulation and analysis")
parser.add_argument("template", help="the name of template file")
parser.add_argument("-n", "--number", type=int, default=20,
help="Number of simulation run")
parser.add_argument("-s", "--steps", type=int, default=8,
help="Simulation steps in unit of million,\
default is 8 million, -1 means test run")
parser.add_argument("-r", "--read", help="Read from config file",
action="store_true")
parser.add_argument("-ws", "--warmSteps", type=int, default=20,
help="Warmup Simulation steps in unit of hundred thousand,\
default is 2 million")
parser.add_argument("-t", "--test", help="test mode",
action="store_true")
parser.add_argument("-c", "--copy",
help="copy the restart file before run",
action="store_true")
parser.add_argument("-o", "--offAuto", help="turn off from Read from \
config file", action="store_true", default=False)
args = parser.parse_args()
# TODO:
# add clean command.
# test analysis, and fullfill missing analysis.
# protein_name = args.template.split('_', 1)[-1].strip('/')
n = args.number
protein_name = args.template.strip('/')
if args.steps == -1: # smallest run for debug.
simulation_steps = 10**5
warm_up_steps = 10**4
n = 1 # also set
elif args.test: # test run
simulation_steps = 50 * 10**3
warm_up_steps = 50 * 10**3
else:
simulation_steps = args.steps * 10**6
warm_up_steps = args.warmSteps * 10**5
config = open('config.py', 'w')
config.write("protein_name = '%s'\nnumber_of_run = %d\nsimulation_steps = %d\n\
warm_up_steps = %d\n" % (protein_name, n, simulation_steps, warm_up_steps))
config.close()
if(not args.offAuto):
exec(open("variables.dat").read())
print(TSTART, TEND)
for i in range(n):
seed(datetime.now())
# simulation set up
if(args.copy):
os.system("cp restart/{}/melt.4000000 1qjp/".format(i))
name = "restart_" + str(i)
os.system("mkdir -p simulation/"+name)
os.system("cp -r "+args.template+"* simulation/"+name)
os.system("cp simulation/"+str(i)+"/restart.4000000 simulation/"+name)
os.chdir("simulation/"+name)
os.system("cp ~/opt/pulling/2xov_pulling_back.in 2xov.in")
os.system( # replace SIMULATION_STEPS with specific steps
"sed -i.bak 's/WARM_UP_STEPS/'" +
str(warm_up_steps) +
"'/g' "+protein_name+".in")
os.system( # replace RANDOM with a radnom number
"sed -i.bak 's/RANDOM/'" +
str(randint(1, 10**6)) +
"'/g' "+protein_name+".in")
os.system( # replace SIMULATION_STEPS with specific steps
"sed -i.bak 's/SIMULATION_STEPS/'" +
str(simulation_steps) +
"'/g' "+protein_name+".in")
if args.steps == -1:
os.system( # replace TEMPERATURE with specific steps
"sed -i.bak 's/Q0/'" +
str(0.5) +
"'/g' fix_qbias_coeff.data")
os.system( # replace TEMPERATURE with specific steps
"sed -i.bak 's/TEMPERATURE/'" +
str(350) +
"'/g' "+protein_name+".in")
if(not args.offAuto):
os.system( # replace SIMULATION_STEPS with specific steps
"sed -i.bak 's/TSTART/'" +
str(TSTART) +
"'/g' "+protein_name+".in")
os.system( # replace SIMULATION_STEPS with specific steps
"sed -i.bak 's/TEND/'" +
str(TEND) +
"'/g' "+protein_name+".in")
# if(platform.system() == 'Darwin'):
# os.system("/Users/weilu/Documents/lammps-9Oct12_modified/src/lmp_serial \
# < "+protein_name+".in")
if(platform.system() == 'Darwin'):
os.system("/Users/weilu/Research/bin/lmp_serial < "+protein_name+".in")
# os.system("/Users/weilu/Research/Build/lammps-9Oct12_modified/src/lmp_serial \
# < "+protein_name+".in")
elif(platform.system() == 'Linux'):
os.system("cp ~/opt/run.slurm run.slurm")
os.system( # replace PROTEIN with pdb name
"sed -i.bak 's/PROTEIN/'" +
protein_name +
"'/g' run.slurm")
os.system("sbatch run.slurm")
sleep(0.2) # Time in seconds.
else:
print("system unkown")
os.chdir("../..")
# print("hello world")
| luwei0917/awsemmd_script | restart.py | Python | mit | 4,735 | [
"LAMMPS"
] | ea76a21132b309f33c911010e8caa5dfd7833727de19b7f553a0edf23910bed2 |
#!/usr/bin/env python
import sys
import os
# Locate MOOSE directory
MOOSE_DIR = os.getenv('MOOSE_DIR', os.path.join(os.getcwd(), 'moose'))
if not os.path.exists(MOOSE_DIR):
MOOSE_DIR = os.path.join(os.getenv('HOME'), 'projects', 'moose')
if not os.path.exists(MOOSE_DIR):
raise Exception('Failed to locate MOOSE, specify the MOOSE_DIR environment variable.')
# Append MOOSE python directory
MOOSE_PYTHON_DIR = os.path.join(MOOSE_DIR, 'python')
if MOOSE_PYTHON_DIR not in sys.path:
sys.path.append(MOOSE_PYTHON_DIR)
import MooseDocs
MooseDocs.MOOSE_DIR = MOOSE_DIR
if __name__ == '__main__':
sys.exit(MooseDocs.moosedocs())
| katyhuff/moose | docs/moosedocs.py | Python | lgpl-2.1 | 642 | [
"MOOSE"
] | b53f4e3cd720fad917adf1ba2340c3bd5de54bf2f3e97602b6d62ec7147dc1f3 |
# Orca
#
# Copyright 2005-2008 Sun Microsystems Inc.
#
# 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., Franklin Street, Fifth Floor,
# Boston MA 02110-1301 USA.
"""Provides the default implementation for bookmarks in Orca."""
import pickle
import os
import rolenames
import speech
import settings
import orca_state
from orca_i18n import _
class Bookmarks:
"""Represents a default bookmark handler."""
def __init__(self, script):
self._script = script
self._bookmarks = {}
self._saveObservers = []
self._loadObservers = []
self._loadBookmarks()
self._currentbookmarkindex = None
def addSaveObserver(self, observer):
self._saveObservers.append(observer)
def addLoadObserver(self, observer):
self._loadObservers.append(observer)
def goToBookmark(self, inputEvent, index=None):
""" Go to the bookmark indexed by inputEvent.hw_code """
# establish the _bookmarks index
index = index or inputEvent.hw_code
try:
context = self._script.getFlatReviewContext()
context_info = self._bookmarks[index]
context.setCurrent(context_info['line'], context_info['zone'], \
context_info['word'], context_info['char'])
self._bookmarks[index] = context_info
except KeyError:
self._script.systemBeep()
return
self._script.flatReviewContext = context
self._script.reviewCurrentItem(inputEvent)
# update the currentbookmark
self._currentbookmarkindex = index
def addBookmark(self, inputEvent):
""" Add an in-page accessible object bookmark for this key. """
context = self._script.getFlatReviewContext()
self._bookmarks[inputEvent.hw_code] = self._contextToBookmark(context)
# Translators: this announces that a bookmark has been entered.
# Orca allows users to tell it to remember a particular spot in an
# application window and provides keystrokes for the user to jump to
# those spots. These spots are known as 'bookmarks'.
#
utterances = [_('bookmark entered')]
utterances.extend(
self._script.speechGenerator.generateSpeech(
context.getCurrentAccessible()))
speech.speak(utterances)
def bookmarkCurrentWhereAmI(self, inputEvent):
""" Report "Where am I" information for this bookmark relative to the
current pointer location."""
try:
context = self._bookmarkToContext( \
self._bookmarks[inputEvent.hw_code])
except KeyError:
self._script.systemBeep()
return
obj = context.getCurrentAccessible()
cur_obj = orca_state.locusOfFocus
# Are they the same object?
if self._script.utilities.isSameObject(cur_obj, obj):
# Translators: this announces that the current object is the same
# object pointed to by the bookmark.
#
self._script.presentMessage(_('bookmark is current object'))
return
# Are their parents the same?
elif self._script.utilities.isSameObject(cur_obj.parent, obj.parent):
# Translators: this announces that the current object's parent and
# the parent of the object pointed to by the bookmark are the same.
#
self._script.presentMessage(
_('bookmark and current object have same parent'))
return
# Do they share a common ancestor?
# bookmark's ancestors
bookmark_ancestors = []
p = obj.parent
while p:
bookmark_ancestors.append(p)
p = p.parent
# look at current object's ancestors to compare to bookmark's ancestors
p = cur_obj.parent
while p:
if bookmark_ancestors.count(p) > 0:
rolename = rolenames.getSpeechForRoleName(p)
# Translators: this announces that the bookmark and the current
# object share a common ancestor
#
self._script.presentMessage(_('shared ancestor %s') % rolename)
return
p = p.parent
# Translators: This announces that a comparison between the bookmark
# and the current object can not be determined.
#
self._script.presentMessage(_('comparison unknown'))
def saveBookmarks(self, inputEvent):
""" Save the bookmarks for this script. """
try:
self.saveBookmarksToDisk(self._bookmarks)
# Translators: this announces that a bookmark has been saved to
# disk
#
self._script.presentMessage(_('bookmarks saved'))
except IOError:
# Translators: this announces that a bookmark could not be saved to
# disk
#
self._script.presentMessage(_('bookmarks could not be saved'))
# Notify the observers
for o in self._saveObservers:
o()
def goToNextBookmark(self, inputEvent):
""" Go to the next bookmark location. If no bookmark has yet to be
selected, the first bookmark will be used. """
# get the hardware keys that have registered bookmarks
hwkeys = self._bookmarks.keys()
hwkeys.sort()
# no bookmarks have been entered
if len(hwkeys) == 0:
self._script.systemBeep()
return
# only 1 bookmark or we are just starting out
elif len(hwkeys) == 1 or self._currentbookmarkindex is None:
self.goToBookmark(None, index=hwkeys[0])
return
# find current bookmark hw_code in our sorted list.
# Go to next one if possible
try:
index = hwkeys.index(self._currentbookmarkindex)
self.goToBookmark(None, index=hwkeys[index+1])
except (ValueError, KeyError, IndexError):
self.goToBookmark(None, index=hwkeys[0])
def goToPrevBookmark(self, inputEvent):
# get the hardware keys that have registered bookmarks
hwkeys = self._bookmarks.keys()
hwkeys.sort()
# no bookmarks have been entered
if len(hwkeys) == 0:
self._script.systemBeep()
return
# only 1 bookmark or we are just starting out
elif len(hwkeys) == 1 or self._currentbookmarkindex is None:
self.goToBookmark(None, index=hwkeys[0])
return
# find current bookmark hw_code in our sorted list.
# Go to previous one if possible
try:
index = hwkeys.index(self._currentbookmarkindex)
self.goToBookmark(None, index=hwkeys[index-1])
except (ValueError, KeyError, IndexError):
self.goToBookmark(None, index=hwkeys[0])
def _loadBookmarks(self):
""" Load this scripts saved bookmarks."""
self._bookmarks = self.readBookmarksFromDisk() or {}
# notify the observers
for o in self._loadObservers:
o()
def readBookmarksFromDisk(self, filename=None):
""" Read saved bookmarks from disk. Currently an unpickled object
that represents a bookmark """
filename = filename or self._script.name.split(' ')[0]
orcaDir = settings.userPrefsDir
orcaBookmarksDir = os.path.join(orcaDir, "bookmarks")
try:
inputFile = open( os.path.join( orcaBookmarksDir, \
'%s.pkl' %filename), "r")
bookmarks = pickle.load(inputFile)
inputFile.close()
return bookmarks
except (IOError, EOFError, OSError):
return None
def saveBookmarksToDisk(self, bookmarksObj, filename=None):
""" Write bookmarks to disk. bookmarksObj must be a pickleable
object. """
filename = filename or self._script.name.split(' ')[0]
orcaDir = settings.userPrefsDir
orcaBookmarksDir = os.path.join(orcaDir, "bookmarks")
# create directory if it does not exist. correct place??
try:
os.stat(orcaBookmarksDir)
except OSError:
os.mkdir(orcaBookmarksDir)
output = open( os.path.join( orcaBookmarksDir, \
'%s.pkl' %filename), "w", os.O_CREAT)
pickle.dump(bookmarksObj, output)
output.close()
def _contextToBookmark(self, context):
"""Converts a flat_review.Context object into a bookmark."""
context_info = {}
context_info['zone'] = context.zoneIndex
context_info['char'] = context.charIndex
context_info['word'] = context.wordIndex
context_info['line'] = context.lineIndex
return context_info
def _bookmarkToContext(self, bookmark):
"""Converts a bookmark into a flat_review.Context object."""
context = self._script.getFlatReviewContext()
context.setCurrent(bookmark['line'], bookmark['zone'], \
bookmark['word'], bookmark['char'])
return context
| Alberto-Beralix/Beralix | i386-squashfs-root/usr/share/pyshared/orca/bookmarks.py | Python | gpl-3.0 | 9,803 | [
"ORCA"
] | 946f59ba062c4a4a38d582862008fba42d7a71039637c52dd8d828d95c51921b |
#!/usr/bin/env python
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import ticker, gridspec
import QM_parser.util.util as u
eV2wn = u.energy_conversion['wn'] / u.energy_conversion['eV']
#
# Spectral Prefactors for UV and CD
#
uv_cnst = 108.8983364615
cd_cnst = 4.351846416e-2
#
# Lorentzian gamma : HWHM
# Gaussian sigma : HW at 1/e height
#
def lorentzian(SpecRange, ExcEne, Gamma):
lsfunc = ExcEne / np.sqrt(np.pi) * Gamma / (Gamma**2 + (SpecRange - ExcEne)**2)
return lsfunc
def gaussian(SpecRange, ExcEne, Sigma):
expfac = -0.5 * ((SpecRange - ExcEne) / Sigma)**2
lsfunc = SpecRange / (Sigma * np.sqrt(2 * np.pi)) * np.exp(expfac)
return lsfunc
def calcspec(ExcEnes, DipS, RotS, ls="gau", widths=None, npts=500):
# Width in wavenumbers, default value is 1500 cm^-1 for each transitions
# widths is an array, so it possible to have different broadenings for each
# transition
if not widths:
widths = np.array(len(ExcEnes) * [1500])
# Use CGS units
ExcEnes = ExcEnes * eV2wn
if ls == "gau":
ls = gaussian
elif ls == "lor":
ls = lorentzian
# Default number of pts = 500
SpecRange = np.linspace(ExcEnes.min() - 5000, ExcEnes.max() + 8000, npts)
uv = np.zeros(npts)
cd = np.zeros(npts)
for i in range(len(ExcEnes)):
uv += DipS[i] * ls(SpecRange, ExcEnes[i], widths[i])
cd += RotS[i] * ls(SpecRange, ExcEnes[i], widths[i])
uv = uv_cnst * uv
cd = cd_cnst * cd
# Convert SpecRange to both nm and eV
SpecRange_eV = SpecRange / eV2wn
SpecRange_nm = 1e7 / SpecRange
result = np.c_[SpecRange, SpecRange_eV, SpecRange_nm, uv, cd]
return result
def plotspec(data, unit="eV", figname="spectra.svg"):
minloc = ticker.AutoMinorLocator(4)
if unit == "eV":
x = data[:,1]
xlabel = 'E / eV'
xmaj = ticker.MultipleLocator(0.5)
elif unit == "wn":
x = data[:,0] / 1e3
xlabel = r'$\tilde{\nu}$ / $10^3$ cm$^{-1}$)'
xmaj = ticker.MultipleLocator(2)
elif unit == "nm":
x = data[:,2]
xlabel = r'$\lambda$ / nm'
xmaj = ticker.MultipleLocator(100)
uv = data[:,3]
om = np.round(np.floor(np.log10(uv.max())))
uv = data[:,3] / 10**om
cd = data[:,-1]
# Set up 2 plots
fig = plt.figure(figsize=(12,12))
gs = gridspec.GridSpec(2, 1)
gs.update(wspace=0.1, hspace=0.1)
# UV options
ax0 = plt.subplot(gs[1])
ax0.set_xlabel(xlabel)
ax0.xaxis.set_major_locator(xmaj)
ax0.xaxis.set_minor_locator(minloc)
ax0.yaxis.set_minor_locator(minloc)
ax0.set_ylabel(r'$\varepsilon$ / $10^%d$ M$^{-1}$ cm $^{-1}$' % int(om))
ax0.yaxis.set_label_coords(-0.2, 0.5)
ax0.tick_params(axis='both', which='major', length=7, pad=10, direction='in')
ax0.tick_params(axis='both', which='minor', length=3, direction='in')
ax0.xaxis.set_ticks_position('both')
ax0.yaxis.set_ticks_position('both')
ax0.plot(x, uv)
ax0.relim()
ax0.autoscale_view(True,True,True)
ax0.set_aspect(0.65/ax0.get_data_ratio())
plt.minorticks_on()
# CD
ax1 = plt.subplot(gs[0])
ax1.set_ylabel(r'$\Delta\varepsilon$ / M$^{-1}$ cm $^{-1}$')
ax1.yaxis.set_label_coords(-0.2, 0.5)
# ax1.set_xlabel(xlabel, size=24)
ax1.xaxis.set_major_locator(xmaj)
ax1.xaxis.set_minor_locator(minloc)
ax1.yaxis.set_minor_locator(minloc)
ax1.axhline(0, color='black', lw=1)
ax1.set_xticklabels([],visible=False)
ax1.tick_params(axis='both', which='major', length=7, direction='in')
ax1.tick_params(axis='both', which='minor', length=3, direction='in')
ax1.xaxis.set_ticks_position('both')
ax1.yaxis.set_ticks_position('both')
ax1.plot(x, cd)
ax1.relim()
ax1.autoscale_view(True,True,True)
ax1.set_aspect(0.65/ax1.get_data_ratio())
plt.minorticks_on()
mpl.rcParams.update({'font.size': 18})
plt.gcf().subplots_adjust(bottom=0.15)
plt.savefig(figname, dpi=300)
plt.close()
# plt.show()
return
def plotcd(data, unit="eV", figname="contributions.svg"):
minloc = ticker.AutoMinorLocator(4)
if unit == "eV":
x = data[:,1]
xlabel = 'E / eV'
xmaj = ticker.MultipleLocator(0.5)
elif unit == "wn":
x = data[:,0] / 1e3
xlabel = r'$\tilde{\nu}$ / $10^3$ cm$^{-1}$'
xmaj = ticker.MultipleLocator(2)
elif unit == "nm":
x = data[:,2]
xlabel = r'$\lambda$ / nm'
xmaj = ticker.MultipleLocator(100)
extcd = data[:,-3]
intcd = data[:,-2]
cd = data[:,-1]
# Set up 2 plots
fig = plt.figure(figsize=(12,12))
gs = gridspec.GridSpec(1, 1)
# CD
ax1 = plt.subplot(gs[0])
ax1.set_ylabel(r'$\Delta\varepsilon$ / M$^{-1}$ cm $^{-1}$')
ax1.set_xlabel(xlabel)
ax1.xaxis.set_major_locator(xmaj)
ax1.xaxis.set_minor_locator(minloc)
ax1.yaxis.set_minor_locator(minloc)
ax1.axhline(0, color='black', lw=1)
ax1.tick_params(axis='both', which='major', length=7, direction='in')
ax1.tick_params(axis='both', which='minor', length=3, direction='in')
ax1.xaxis.set_ticks_position('both')
ax1.yaxis.set_ticks_position('both')
ax1.plot(x, extcd, color='blue', label="Ext.")
ax1.plot(x, intcd, color='red', label="Int.")
ax1.plot(x, cd, color='black', lw=2, label="Tot.")
ax1.relim()
ax1.autoscale_view(True,True,True)
ax1.set_aspect(0.65/ax1.get_data_ratio())
plt.minorticks_on()
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
ncol=3, mode="expand", borderaxespad=0.).draw_frame(False)
plt.gcf().subplots_adjust(bottom=0.15, left=0.15)
mpl.rcParams.update({'font.size': 18})
plt.savefig(figname, dpi=300)
plt.close()
# plt.show()
return
if __name__ == '__main__':
import textwrap
import argparse as arg
parser = arg.ArgumentParser(description='Convolutes Stick Spectra',
formatter_class=arg.ArgumentDefaultsHelpFormatter)
#
# Input files
#
inp = parser.add_argument_group("Input Data")
inp.add_argument('-i', '--input',
default="results.txt", type=str, dest="InputFile",
help='''Input file''')
#
# Spectra Options
#
spec = parser.add_argument_group("Spectra Convolution Options")
spec.add_argument('--ls',
default="gau", type=str, choices=["gau", "lor"],
dest="LineShape", help='''Spectral LineShape.''')
spec.add_argument('--lw',
default=[1500], type=float, nargs='+', dest="LineWidth",
help='''Spectral LineWidth in wavenumbers (gamma for Lorentzian,
sigma for Gaussian LineShape.''')
spec.add_argument('--unit',
default="eV", type=str, choices=["eV", "wn", "nm"], dest="SpecUnit",
help='''X axis unit for plotting Spectra.''')
#
# Output Options
#
out = parser.add_argument_group("Output Options")
out.add_argument('-o', '--out',
default="Spec", type=str, dest="OutPref",
help='''Output Prefix for files''')
out.add_argument('--figext',
default=None, type=str, choices=["svg", "png", "eps"],
dest="FigExt", help='''Format for image output''')
#
# Parse and create the Options Dictionary
#
args = parser.parse_args()
Opts = vars(args)
if Opts['OutPref']:
Opts['OutPref'] = Opts['OutPref'] + "."
#
# Convolute Spectra
#
data = np.loadtxt(Opts['InputFile'])
ExcEnergies = data[:,1]
ExcDipsStrlen = data[:,3]
ExtExcR = data[:,-3]
IntExcR = data[:,-2]
ExcR = data[:,-1]
widths = Opts['LineWidth']
# Check LineWidths array length in comparison to ExcEnergies
try:
assert len(widths) == len(ExcEnergies)
except AssertionError:
widths = Opts['LineWidth'] * len(ExcEnergies)
finally:
assert len(widths) == len(ExcEnergies)
spectra_tot = calcspec(ExcEnergies, ExcDipsStrlen, ExcR, ls=Opts['LineShape'], widths=widths)
spectra_ext = calcspec(ExcEnergies, ExcDipsStrlen, ExtExcR, ls=Opts['LineShape'], widths=widths)
spectra_int = calcspec(ExcEnergies, ExcDipsStrlen, IntExcR, ls=Opts['LineShape'], widths=widths)
spectra = np.c_[spectra_ext, spectra_int[:,-1], spectra_tot[:,-1]]
# Convoluted Spectra
titles = ("E (cm^-1)", "E (eV)", "lambda (nm)", "UV (M^-1 cm^-1)", "Ext. CD", "Int. CD", "Tot. CD")
header = ("\nCalculated Excitonic Spectra\n"
"Lineshape: %s\n"
"Linewidths (cm^-1): %s \n\n" % (Opts['LineShape'], textwrap.fill(' '.join(map(str, widths)), width=55)))
header1 = "%9s %7s %11s %15s %8s %8s %8s\n" % (titles)
fmt = "%11.2f %7.4f %11.2f %15.2e %8.2f % 8.2f %8.2f"
np.savetxt(Opts['OutPref'] + "spectra.txt", spectra, fmt=fmt, header=header+header1)
if Opts['FigExt']:
# UV, CD
figname = Opts['OutPref'] + "spectra." + Opts['FigExt']
plotspec(spectra, unit=Opts['SpecUnit'], figname=figname)
# CD contributions
figname = Opts['OutPref'] + "contributions." + Opts['FigExt']
plotcd(spectra, unit=Opts['SpecUnit'], figname=figname)
pass
| dpadula85/ExSPy | stable/Spec.py | Python | gpl-3.0 | 9,436 | [
"Gaussian"
] | b8b0456d7eabe2bab42172f8f6412994cecf52a8e0028e9986007253a2e813bd |
#!/usr/bin/env python
# Copyright 2014-2019 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Authors: Artem Pulkin, pyscf authors
from pyscf.pbc.lib.kpts_helper import VectorSplitter, VectorComposer
from pyscf.pbc.mp.kmp2 import padding_k_idx
from pyscf.pbc.cc import kccsd_rhf
import numpy as np
def iter_12(cc_or_eom, k):
"""Iterates over EA index slices."""
if isinstance(cc_or_eom, kccsd_rhf.RCCSD):
cc = cc_or_eom
else:
cc = cc_or_eom._cc
o, v = padding_k_idx(cc, kind="split")
kconserv = cc.khelper.kconserv
yield (v[k],)
for ki in range(cc.nkpts):
for ka in range(cc.nkpts):
kb = kconserv[k, ka, ki]
yield (ki,), (ka,), o[ki], v[ka], v[kb]
def amplitudes_to_vector(cc_or_eom, t1, t2, kshift=0, kconserv=None):
"""EA amplitudes to vector."""
itr = iter_12(cc_or_eom, kshift)
t1, t2 = np.asarray(t1), np.asarray(t2)
vc = VectorComposer(t1.dtype)
vc.put(t1[np.ix_(*next(itr))])
for slc in itr:
vc.put(t2[np.ix_(*slc)])
return vc.flush()
def vector_to_amplitudes(cc_or_eom, vec, kshift=0):
"""EA vector to apmplitudes."""
expected_vs = vector_size(cc_or_eom, kshift)
if expected_vs != len(vec):
raise ValueError("The size of the vector passed {:d} should be exactly {:d}".format(len(vec), expected_vs))
itr = iter_12(cc_or_eom, kshift)
nocc = cc_or_eom.nocc
nmo = cc_or_eom.nmo
nkpts = cc_or_eom.nkpts
nvirt = nmo - nocc
vs = VectorSplitter(vec)
r1 = vs.get(nvirt, slc=next(itr))
r2 = np.zeros((nkpts, nkpts, nocc, nvirt, nvirt), vec.dtype)
for slc in itr:
vs.get(r2, slc=slc)
return r1, r2
def vector_size(cc_or_eom, kshift=0):
"""The total number of elements in EA vector."""
size = 0
for slc in iter_12(cc_or_eom, kshift):
size += np.prod(tuple(len(i) for i in slc))
return size
| gkc1000/pyscf | pyscf/pbc/cc/eom_kccsd_rhf_ea.py | Python | apache-2.0 | 2,448 | [
"PySCF"
] | 6650ccc2a32f924de2bf53e85c61854da8afc4ddcf06bcedd358ca3d6e3966f8 |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2007 Donald N. Allingham
# Copyright (C) 2008 Brian G. Matherly
# Copyright (C) 2008 Stephane Charette
# Copyright (C) 2010 Jakim Friant
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"Find unused objects and remove with the user's permission."
#-------------------------------------------------------------------------
#
# gtk modules
#
#-------------------------------------------------------------------------
from gi.repository import Gdk
from gi.repository import Gtk
from gi.repository import GObject
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from gramps.gen.db import DbTxn
from gramps.gen.errors import WindowActiveError
from gramps.gui.managedwindow import ManagedWindow
from gramps.gen.datehandler import displayer as _dd
from gramps.gen.display.place import displayer as _pd
from gramps.gen.updatecallback import UpdateCallback
from gramps.gui.plug import tool
from gramps.gui.glade import Glade
from gramps.gen.filters import GenericFilterFactory, rules
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#-------------------------------------------------------------------------
#
# runTool
#
#-------------------------------------------------------------------------
class RemoveUnused(tool.Tool, ManagedWindow, UpdateCallback):
MARK_COL = 0
OBJ_ID_COL = 1
OBJ_NAME_COL = 2
OBJ_TYPE_COL = 3
OBJ_HANDLE_COL = 4
BUSY_CURSOR = Gdk.Cursor.new_for_display(Gdk.Display.get_default(),
Gdk.CursorType.WATCH)
def __init__(self, dbstate, user, options_class, name, callback=None):
uistate = user.uistate
self.title = _('Unused Objects')
tool.Tool.__init__(self, dbstate, options_class, name)
if self.db.readonly:
return
ManagedWindow.__init__(self, uistate, [], self.__class__)
UpdateCallback.__init__(self, self.uistate.pulse_progressbar)
self.dbstate = dbstate
self.uistate = uistate
self.tables = {
'events': {'get_func': self.db.get_event_from_handle,
'remove': self.db.remove_event,
'get_text': self.get_event_text,
'editor': 'EditEvent',
'icon': 'gramps-event',
'name_ix': 4},
'sources': {'get_func': self.db.get_source_from_handle,
'remove': self.db.remove_source,
'get_text': None,
'editor': 'EditSource',
'icon': 'gramps-source',
'name_ix': 2},
'citations': {'get_func': self.db.get_citation_from_handle,
'remove': self.db.remove_citation,
'get_text': None,
'editor': 'EditCitation',
'icon': 'gramps-citation',
'name_ix': 3},
'places': {'get_func': self.db.get_place_from_handle,
'remove': self.db.remove_place,
'get_text': self.get_place_text,
'editor': 'EditPlace',
'icon': 'gramps-place',
'name_ix': 2},
'media': {'get_func': self.db.get_media_from_handle,
'remove': self.db.remove_media,
'get_text': None,
'editor': 'EditMedia',
'icon': 'gramps-media',
'name_ix': 4},
'repos': {'get_func': self.db.get_repository_from_handle,
'remove': self.db.remove_repository,
'get_text': None,
'editor': 'EditRepository',
'icon': 'gramps-repository',
'name_ix': 3},
'notes': {'get_func': self.db.get_note_from_handle,
'remove': self.db.remove_note,
'get_text': self.get_note_text,
'editor': 'EditNote',
'icon': 'gramps-notes',
'name_ix': 2},
}
self.init_gui()
def init_gui(self):
self.top = Glade()
window = self.top.toplevel
self.set_window(window, self.top.get_object('title'), self.title)
self.setup_configs('interface.removeunused', 400, 520)
self.events_box = self.top.get_object('events_box')
self.sources_box = self.top.get_object('sources_box')
self.citations_box = self.top.get_object('citations_box')
self.places_box = self.top.get_object('places_box')
self.media_box = self.top.get_object('media_box')
self.repos_box = self.top.get_object('repos_box')
self.notes_box = self.top.get_object('notes_box')
self.find_button = self.top.get_object('find_button')
self.remove_button = self.top.get_object('remove_button')
self.events_box.set_active(self.options.handler.options_dict['events'])
self.sources_box.set_active(
self.options.handler.options_dict['sources'])
self.citations_box.set_active(
self.options.handler.options_dict['citations'])
self.places_box.set_active(
self.options.handler.options_dict['places'])
self.media_box.set_active(self.options.handler.options_dict['media'])
self.repos_box.set_active(self.options.handler.options_dict['repos'])
self.notes_box.set_active(self.options.handler.options_dict['notes'])
self.warn_tree = self.top.get_object('warn_tree')
self.warn_tree.connect('button_press_event', self.double_click)
self.selection = self.warn_tree.get_selection()
self.mark_button = self.top.get_object('mark_button')
self.mark_button.connect('clicked', self.mark_clicked)
self.unmark_button = self.top.get_object('unmark_button')
self.unmark_button.connect('clicked', self.unmark_clicked)
self.invert_button = self.top.get_object('invert_button')
self.invert_button.connect('clicked', self.invert_clicked)
self.real_model = Gtk.ListStore(GObject.TYPE_BOOLEAN,
GObject.TYPE_STRING,
GObject.TYPE_STRING,
GObject.TYPE_STRING,
GObject.TYPE_STRING)
self.sort_model = self.real_model.sort_new_with_model()
self.warn_tree.set_model(self.sort_model)
self.renderer = Gtk.CellRendererText()
self.img_renderer = Gtk.CellRendererPixbuf()
self.bool_renderer = Gtk.CellRendererToggle()
self.bool_renderer.connect('toggled', self.selection_toggled)
# Add mark column
mark_column = Gtk.TreeViewColumn(_('Mark'), self.bool_renderer,
active=RemoveUnused.MARK_COL)
mark_column.set_sort_column_id(RemoveUnused.MARK_COL)
self.warn_tree.append_column(mark_column)
# Add image column
img_column = Gtk.TreeViewColumn(None, self.img_renderer)
img_column.set_cell_data_func(self.img_renderer, self.get_image)
self.warn_tree.append_column(img_column)
# Add column with object gramps_id
id_column = Gtk.TreeViewColumn(_('ID'), self.renderer,
text=RemoveUnused.OBJ_ID_COL)
id_column.set_sort_column_id(RemoveUnused.OBJ_ID_COL)
self.warn_tree.append_column(id_column)
# Add column with object name
name_column = Gtk.TreeViewColumn(_('Name'), self.renderer,
text=RemoveUnused.OBJ_NAME_COL)
name_column.set_sort_column_id(RemoveUnused.OBJ_NAME_COL)
self.warn_tree.append_column(name_column)
self.top.connect_signals({
"destroy_passed_object" : self.close,
"on_remove_button_clicked": self.do_remove,
"on_find_button_clicked" : self.find,
"on_delete_event" : self.close,
})
self.dc_label = self.top.get_object('dc_label')
self.sensitive_list = [self.warn_tree, self.mark_button,
self.unmark_button, self.invert_button,
self.dc_label, self.remove_button]
for item in self.sensitive_list:
item.set_sensitive(False)
self.show()
def build_menu_names(self, obj):
return (self.title, None)
def find(self, obj):
self.options.handler.options_dict.update(
events=self.events_box.get_active(),
sources=self.sources_box.get_active(),
citations=self.citations_box.get_active(),
places=self.places_box.get_active(),
media=self.media_box.get_active(),
repos=self.repos_box.get_active(),
notes=self.notes_box.get_active(),
)
for item in self.sensitive_list:
item.set_sensitive(True)
self.uistate.set_busy_cursor(True)
self.uistate.progress.show()
self.window.get_window().set_cursor(self.BUSY_CURSOR)
self.real_model.clear()
self.collect_unused()
self.uistate.progress.hide()
self.uistate.set_busy_cursor(False)
self.window.get_window().set_cursor(None)
self.reset()
# Save options
self.options.handler.save_options()
def collect_unused(self):
# Run through all requested tables and check all objects
# for being referenced some place. If not, add_results on them.
db = self.db
tables = (
('events', db.get_event_cursor, db.get_number_of_events),
('sources', db.get_source_cursor, db.get_number_of_sources),
('citations', db.get_citation_cursor, db.get_number_of_citations),
('places', db.get_place_cursor, db.get_number_of_places),
('media', db.get_media_cursor, db.get_number_of_media),
('repos', db.get_repository_cursor, db.get_number_of_repositories),
('notes', db.get_note_cursor, db.get_number_of_notes),
)
# bug 7619 : don't select notes from to do list.
# notes associated to the todo list doesn't have references.
# get the todo list (from get_note_list method of the todo gramplet )
all_notes = self.dbstate.db.get_note_handles()
FilterClass = GenericFilterFactory('Note')
filter1 = FilterClass()
filter1.add_rule(rules.note.HasType(["To Do"]))
todo_list = filter1.apply(self.dbstate.db, all_notes)
filter2 = FilterClass()
filter2.add_rule(rules.note.HasType(["Link"]))
link_list = filter2.apply(self.dbstate.db, all_notes)
for (the_type, cursor_func, total_func) in tables:
if not self.options.handler.options_dict[the_type]:
# This table was not requested. Skip it.
continue
with cursor_func() as cursor:
self.set_total(total_func())
fbh = db.find_backlink_handles
for handle, data in cursor:
if not any(h for h in fbh(handle)):
if handle not in todo_list and handle not in link_list:
self.add_results((the_type, handle.decode('utf-8'),
data))
self.update()
self.reset()
def do_remove(self, obj):
with DbTxn(_("Remove unused objects"), self.db, batch=False) as trans:
self.db.disable_signals()
for row_num in range(len(self.real_model)-1, -1, -1):
path = (row_num,)
row = self.real_model[path]
if not row[RemoveUnused.MARK_COL]:
continue
the_type = row[RemoveUnused.OBJ_TYPE_COL]
handle = row[RemoveUnused.OBJ_HANDLE_COL]
remove_func = self.tables[the_type]['remove']
remove_func(handle, trans)
self.real_model.remove(row.iter)
self.db.enable_signals()
self.db.request_rebuild()
def selection_toggled(self, cell, path_string):
sort_path = tuple(map(int, path_string.split(':')))
real_path = self.sort_model.convert_path_to_child_path(Gtk.TreePath(sort_path))
row = self.real_model[real_path]
row[RemoveUnused.MARK_COL] = not row[RemoveUnused.MARK_COL]
self.real_model.row_changed(real_path, row.iter)
def mark_clicked(self, mark_button):
for row_num in range(len(self.real_model)):
path = (row_num,)
row = self.real_model[path]
row[RemoveUnused.MARK_COL] = True
def unmark_clicked(self, unmark_button):
for row_num in range(len(self.real_model)):
path = (row_num,)
row = self.real_model[path]
row[RemoveUnused.MARK_COL] = False
def invert_clicked(self, invert_button):
for row_num in range(len(self.real_model)):
path = (row_num,)
row = self.real_model[path]
row[RemoveUnused.MARK_COL] = not row[RemoveUnused.MARK_COL]
def double_click(self, obj, event):
if event.type == Gdk.EventType._2BUTTON_PRESS and event.button == 1:
(model, node) = self.selection.get_selected()
if not node:
return
sort_path = self.sort_model.get_path(node)
real_path = self.sort_model.convert_path_to_child_path(sort_path)
row = self.real_model[real_path]
the_type = row[RemoveUnused.OBJ_TYPE_COL]
handle = row[RemoveUnused.OBJ_HANDLE_COL]
self.call_editor(the_type, handle)
def call_editor(self, the_type, handle):
try:
obj = self.tables[the_type]['get_func'](handle)
editor_str = 'from gramps.gui.editors import %s as editor' % (
self.tables[the_type]['editor'])
exec(editor_str, globals())
editor(self.dbstate, self.uistate, [], obj)
except WindowActiveError:
pass
def get_image(self, column, cell, model, iter, user_data=None):
the_type = model.get_value(iter, RemoveUnused.OBJ_TYPE_COL)
the_icon = self.tables[the_type]['icon']
cell.set_property('icon-name', the_icon)
def add_results(self, results):
(the_type, handle, data) = results
gramps_id = data[1]
# if we have a function that will return to us some type
# of text summary, then we should use it; otherwise we'll
# use the generic field index provided in the tables above
if self.tables[the_type]['get_text']:
text = self.tables[the_type]['get_text'](the_type, handle, data)
else:
# grab the text field index we know about, and hope
# it represents something useful to the user
name_ix = self.tables[the_type]['name_ix']
text = data[name_ix]
# insert a new row into the table
self.real_model.append(row=[False, gramps_id, text, the_type, handle])
def get_event_text(self, the_type, handle, data):
"""
Come up with a short line of text that we can use as
a summary to represent this event.
"""
# get the event:
event = self.tables[the_type]['get_func'](handle)
# first check to see if the event has a descriptive name
text = event.get_description() # (this is rarely set for events)
# if we don't have a description...
if text == '':
# ... then we merge together several fields
# get the event type (marriage, birth, death, etc.)
text = str(event.get_type())
# see if there is a date
date = _dd.display(event.get_date_object())
if date != '':
text += '; %s' % date
# see if there is a place
if event.get_place_handle():
text += '; %s' % _pd.display_event(self.db, event)
return text
def get_note_text(self, the_type, handle, data):
"""
We need just the first few words of a note as a summary.
"""
# get the note object
note = self.tables[the_type]['get_func'](handle)
# get the note text; this ignores (discards) formatting
text = note.get()
# convert whitespace to a single space
text = " ".join(text.split())
# if the note is too long, truncate it
if len(text) > 80:
text = text[:80] + "..."
return text
def get_place_text(self, the_type, handle, data):
"""
We need just the place name.
"""
# get the place object
place = self.tables[the_type]['get_func'](handle)
# get the name
text = place.get_name().get_value()
return text
#------------------------------------------------------------------------
#
#
#
#------------------------------------------------------------------------
class CheckOptions(tool.ToolOptions):
"""
Defines options and provides handling interface.
"""
def __init__(self, name, person_id=None):
tool.ToolOptions.__init__(self, name, person_id)
# Options specific for this report
self.options_dict = {
'events': 1,
'sources': 1,
'citations': 1,
'places': 1,
'media': 1,
'repos': 1,
'notes': 1,
}
self.options_help = {
'events': ("=0/1", "Whether to use check for unused events",
["Do not check events", "Check events"],
True),
'sources': ("=0/1", "Whether to use check for unused sources",
["Do not check sources", "Check sources"],
True),
'citations': ("=0/1", "Whether to use check for unused citations",
["Do not check citations", "Check citations"],
True),
'places': ("=0/1", "Whether to use check for unused places",
["Do not check places", "Check places"],
True),
'media': ("=0/1", "Whether to use check for unused media",
["Do not check media", "Check media"],
True),
'repos': ("=0/1", "Whether to use check for unused repositories",
["Do not check repositories", "Check repositories"],
True),
'notes': ("=0/1", "Whether to use check for unused notes",
["Do not check notes", "Check notes"],
True),
}
| ennoborg/gramps | gramps/plugins/tool/removeunused.py | Python | gpl-2.0 | 19,797 | [
"Brian"
] | 40958d17aa600ea353e24b6fa90d2bde67716c00a31f3f3b79f5d9840cd58f9e |
../../../../../../../share/pyshared/orca/scripts/apps/nautilus/__init__.py | Alberto-Beralix/Beralix | i386-squashfs-root/usr/lib/python2.7/dist-packages/orca/scripts/apps/nautilus/__init__.py | Python | gpl-3.0 | 74 | [
"ORCA"
] | adba3660b69fc723279964fe6962a9eebce28be069e94b7dd1b1df0d6983d918 |
"""
This contains the TRPO class. Following John's code, this will contain the bulk
of the Tensorflow construction and related code. Call this from the `main.py`
script.
(c) April 2017 by Daniel Seita, based upon `starter code` by John Schulman, who
used a Theano version.
"""
import gym
import numpy as np
import tensorflow as tf
import time
import utils_trpo
from collections import defaultdict
from fxn_approx import *
np.set_printoptions(suppress=True, precision=5, edgeitems=10)
import sys
if "../" not in sys.path:
sys.path.append("../")
from utils import utils_pg as utils
from utils import logz
class TRPO:
""" A TRPO agent. The constructor builds its computational graph. """
def __init__(self, args, sess, env, vf_params):
""" Initializes the TRPO agent. For now, assume continuous control, so
we'll be outputting the mean of Gaussian policies.
It's similar to John Schulman's code. Here, `args` plays roughly the
role of his `usercfg`, and we also initialize the computational graph
here, this time in Tensorflow and not Theano. In his code, agents are
already outfitted with value functions and policy functions, among other
things. We do something similar by supplying the value function as
input. For symbolic variables, I try to be consistent with the naming
conventions at the end with `n`, `o`, and/or `a` to describe dimensions.
"""
self.args = args
self.sess = sess
self.env = env
self.ob_dim = ob_dim = env.observation_space.shape[0]
self.ac_dim = ac_dim = env.action_space.shape[0]
if args.vf_type == 'linear':
self.vf = LinearValueFunction(**vf_params)
elif args.vf_type == 'nn':
self.vf = NnValueFunction(session=sess, ob_dim=ob_dim, **vf_params)
# Placeholders for the feed_dicts, i.e. the "beginning" of the graph.
self.ob_no = tf.placeholder(shape=[None, ob_dim], name="ob", dtype=tf.float32)
self.ac_na = tf.placeholder(shape=[None, ac_dim], name="ac", dtype=tf.float32)
self.adv_n = tf.placeholder(shape=[None], name="adv", dtype=tf.float32)
# Constructing the policy network, mapping from states -> mean vector.
self.h1 = utils.lrelu(utils.dense(self.ob_no, 64, "h1", weight_init=utils.normc_initializer(1.0)))
self.h2 = utils.lrelu(utils.dense(self.h1, 64, "h2", weight_init=utils.normc_initializer(1.0)))
# Last layer of the network to get the mean, plus also an `old` version.
self.mean_na = utils.dense(self.h2, ac_dim, "mean", weight_init=utils.normc_initializer(0.05))
self.oldmean_na = tf.placeholder(shape=[None, ac_dim], name='oldmean', dtype=tf.float32)
# The log standard deviation *vector*, to be concatenated with the mean vector.
self.logstd_a = tf.get_variable("logstd", [ac_dim], initializer=tf.zeros_initializer())
self.oldlogstd_a = tf.placeholder(shape=[ac_dim], name="oldlogstd", dtype=tf.float32)
# In VPG, use logprob in surrogate loss. In TRPO, we also need the old one.
self.logprob_n = utils.gauss_log_prob_1(mu=self.mean_na, logstd=self.logstd_a, x=self.ac_na)
self.oldlogprob_n = utils.gauss_log_prob_1(mu=self.oldmean_na, logstd=self.oldlogstd_a, x=self.ac_na)
self.surr = - tf.reduce_mean(self.adv_n * tf.exp(self.logprob_n - self.oldlogprob_n))
# Sample the action. Here, self.mean_na should be of shape (1,a).
self.sampled_ac = (tf.random_normal(tf.shape(self.mean_na)) * tf.exp(self.logstd_a) + self.mean_na)[0]
# Diagnostics, KL divergence, entropy.
self.kl = tf.reduce_mean(utils.gauss_KL_1(self.mean_na, self.logstd_a, self.oldmean_na, self.oldlogstd_a))
self.ent = 0.5 * ac_dim * tf.log(2.*np.pi*np.e) + 0.5 * tf.reduce_sum(self.logstd_a)
# Do we need these?
## self.nbatch = tf.shape(self.ob_no)[0] (maybe)
## self.stepsize = tf.placeholder(shape=[], dtype=tf.float32) (maybe)
## self.update_op = tf.train.AdamOptimizer(sy_stepsize).minimize(sy_surr) (almost surely delete)
# Policy gradient vector. Only weights for the policy net, NOT value function.
if args.vf_type == 'linear':
self.params = tf.trainable_variables()
elif args.vf_type == 'nn':
self.params = [x for x in tf.trainable_variables() if 'nnvf' not in x.name]
self.pg = self._flatgrad(self.surr, self.params)
assert len((self.pg).get_shape()) == 1
# Prepare the Fisher-Vector product computation. I _think_ this is how
# to do it, stopping gradients from the _current_ policy (not the old
# one) so that the KL divegence is computed with a fixed first argument.
# It seems to make sense from John Schulman's slides. Also, the
# reduce_mean here should be the mean KL approximation to the max KL.
kl_firstfixed = tf.reduce_mean(utils.gauss_KL_1(
tf.stop_gradient(self.mean_na),
tf.stop_gradient(self.logstd_a),
self.mean_na,
self.logstd_a
))
grads = tf.gradients(kl_firstfixed, self.params)
# Here, `flat_tangent` is a placeholder vector of size equal to #of (PG)
# params. Then `tangents` contains various subsets of that vector.
self.flat_tangent = tf.placeholder(tf.float32, shape=[None], name="flat_tangent")
shapes = [var.get_shape().as_list() for var in self.params]
start = 0
tangents = []
for shape in shapes:
size = np.prod(shape)
tangents.append(tf.reshape(self.flat_tangent[start:start+size], shape))
start += size
self.num_params = start
# Do elementwise g*tangent then sum components, then add everything at the end.
# John Schulman used T.add(*[...]). The TF equivalent seems to be tf.add_n.
assert len(grads) == len(tangents)
self.gradient_vector_product = tf.add_n(inputs=
[tf.reduce_sum(g*tangent) for (g, tangent) in zip(grads, tangents)]
)
# The actual Fisher-vector product operation, where the gradients are
# taken w.r.t. the "loss" function `gvp`. I _think_ the `grads` from
# above computes the first derivatives, and then the `gvp` is computing
# the second derivatives. But what about hessian_vector_product?
self.fisher_vector_product = self._flatgrad(self.gradient_vector_product, self.params)
# Deal with logic about *getting* parameters (as a flat vector).
self.get_params_flat_op = tf.concat([tf.reshape(v, [-1]) for v in self.params], axis=0)
# Finally, deal with logic about *setting* parameters.
self.theta = tf.placeholder(tf.float32, shape=[self.num_params], name="theta")
start = 0
updates = []
for v in self.params:
shape = v.get_shape()
size = tf.reduce_prod(shape)
# Note that tf.assign(ref, value) assigns `value` to `ref`.
updates.append(
tf.assign(v, tf.reshape(self.theta[start:start+size], shape))
)
start += size
self.set_params_flat_op = tf.group(*updates) # Performs all updates together.
print("In TRPO init, shapes:\n{}\nstart={}".format(shapes, start))
print("self.pg: {}\ngvp: {}\nfvp: {}".format(self.pg,
self.gradient_vector_product, self.fisher_vector_product))
print("Finished with the TRPO agent initialization.")
self.start_time = time.time()
def update_policy(self, paths, infodict):
""" Performs the TRPO policy update based on a minibach of data.
Note: this is mostly where the differences between TRPO and VPG become
apparent. We do a conjugate gradient step followed by a line search. I'm
not sure if we should be adjusting the step size based on the KL
divergence, as we did in VPG. Right now we don't. This is where we do a
lot of session calls, FYI.
Params:
paths: A LIST of defaultdicts with information from the rollouts.
infodict: A dictionary with statistics for logging later.
"""
prob_np = np.concatenate([path["prob"] for path in paths])
ob_no = np.concatenate([path["observation"] for path in paths])
action_na = np.concatenate([path["action"] for path in paths])
adv_n = np.concatenate([path["advantage"] for path in paths])
assert prob_np.shape[0] == ob_no.shape[0] == action_na.shape[0] == adv_n.shape[0]
assert len(prob_np.shape) == len(ob_no.shape) == len(action_na.shape) == 2
assert len(adv_n.shape) == 1
# Daniel: simply gets a flat vector of the parameters.
thprev = self.sess.run(self.get_params_flat_op)
# Make a feed to avoid clutter later. Note, our code differs slightly
# from John Schulman as we have to explicitly provide the old means and
# old logstds, which we concatenated together into the `prob` keyword.
# The mean is the first half and the logstd is the second half.
k = self.ac_dim
feed = {self.ob_no: ob_no,
self.ac_na: action_na,
self.adv_n: adv_n,
self.oldmean_na: prob_np[:,:k],
self.oldlogstd_a: prob_np[0,k:]} # Use 0 because all logstd are same.
# Had to add the extra flat_tangent to the feed, otherwise I'd get errors.
def fisher_vector_product(p):
feed[self.flat_tangent] = p
fvp = self.sess.run(self.fisher_vector_product, feed_dict=feed)
return fvp + self.args.cg_damping*p
# Get the policy gradient. Also the losses, for debugging.
g = self.sess.run(self.pg, feed_dict=feed)
surrloss_before, kl_before, ent_before = self.sess.run(
[self.surr, self.kl, self.ent], feed_dict=feed)
assert kl_before == 0
if np.allclose(g, 0):
print("\tGot zero gradient, not updating ...")
else:
stepdir = utils_trpo.cg(fisher_vector_product, -g)
shs = 0.5*stepdir.dot(fisher_vector_product(stepdir))
lm = np.sqrt(shs / self.args.max_kl)
infodict["LagrangeM"] = lm
fullstep = stepdir / lm
neggdotstepdir = -g.dot(stepdir)
# Returns the current self.surr (surrogate loss).
def loss(th):
self.sess.run(self.set_params_flat_op, feed_dict={self.theta: th})
return self.sess.run(self.surr, feed_dict=feed)
# Update the weights using `self.set_params_flat_op`.
success, theta = utils_trpo.backtracking_line_search(loss,
thprev, fullstep, neggdotstepdir/lm)
self.sess.run(self.set_params_flat_op, feed_dict={self.theta: theta})
surrloss_after, kl_after, ent_after = self.sess.run(
[self.surr, self.kl, self.ent], feed_dict=feed)
logstd_new = self.sess.run(self.logstd_a, feed_dict=feed)
print("logstd new = {}".format(logstd_new))
# For logging later.
infodict["gNorm"] = np.linalg.norm(g)
infodict["Success"] = success
infodict["LagrangeM"] = lm
infodict["pol_surr_before"] = surrloss_before
infodict["pol_surr_after"] = surrloss_after
infodict["pol_kl_before"] = kl_before
infodict["pol_kl_after"] = kl_after
infodict["pol_ent_before"] = ent_before
infodict["pol_ent_after"] = ent_after
def _flatgrad(self, loss, var_list):
""" A Tensorflow version of John Schulman's `flatgrad` function. It
computes the gradients but does NOT apply them (for now).
This is only called during the `init` of the TRPO graph, so I think it's
OK. Otherwise, wouldn't it be constantly rebuilding the computational
graph? Or doing something else? Eh, for now I think it's OK.
Params:
loss: The loss function we're optimizing, which I assume is always
scalar-valued.
var_list: The list of variables (from `tf.trainable_variables()`) to
take gradients. This should only be for the policynets.
Returns:
A single flat vector with all gradients concatenated.
"""
grads = tf.gradients(loss, var_list)
return tf.concat([tf.reshape(g, [-1]) for g in grads], axis=0)
def _act(self, ob):
""" A "private" method for the TRPO agent so that it acts and then can
provide extra information.
Note that the mean and logstd here are for the current policy. There is
no updating done here; that's done _afterwards_. The agentinfo is a
vector of shape (2a,) where a is the action dimension.
"""
action, mean, logstd = self.sess.run(
[self.sampled_ac, self.mean_na, self.logstd_a],
feed_dict={self.ob_no : ob[None]}
)
agentinfo = dict()
agentinfo["prob"] = np.concatenate((mean.flatten(), logstd.flatten()))
return (action, agentinfo)
def get_paths(self, seed_iter, env):
""" Computes the paths, which contains all the information from the
rollouts that we need for the TRPO update.
We run enough times (which may be many episodes) as desired from our
user-provided parameters, storing relevant material into `paths` for
future use. The main difference from VPG is that we have to get extra
information about the current log probabilities (which will later be the
_old_ log probs) when calling self.act(ob).
Equivalent to John Schulman's `do_rollouts_serial` and `do_rollouts`.
It's easy to put all lists inside a single defaultdict.
Params:
seed_iter: Itertools for getting new random seeds via incrementing.
env: The current OpenAI gym environment.
Returns:
paths: A _list_ where each element is a _dictionary_ corresponding
to statistics from ONE episode.
"""
paths = []
timesteps_sofar = 0
while True:
np.random.seed(seed_iter.next())
ob = env.reset()
data = defaultdict(list)
# Run one episode and put the data inside `data`, then in `paths`.
while True:
data["observation"].append(ob)
action, agentinfo = self._act(ob)
data["action"].append(action)
for (k,v) in agentinfo.iteritems():
data[k].append(v)
ob, rew, done, _ = env.step(action)
data["reward"].append(rew)
if done:
break
data = {k:np.array(v) for (k,v) in data.iteritems()}
paths.append(data)
timesteps_sofar += utils.pathlength(data)
if (timesteps_sofar >= self.args.min_timesteps_per_batch):
break
return paths
def compute_advantages(self, paths):
""" Computes standardized advantages from data collected during the most
recent set of rollouts.
No need to return anything, because advantages can be stored in `paths`.
Also, self.vf is used to estimate the baseline to reduce variance, and
later we will utilize the `path["baseline"]` to refit the value
function. Finally, note that the iteration over `paths` means each
`path` item is a dictionary, corresponding to the statistics garnered
over ONE episode. This makes computing the discount easy since we don't
have to worry about crossing over different episodes.
Params:
paths: A LIST of defaultdicts with information from the rollouts.
Each defaultdict element contains information about ONE episode.
"""
for path in paths:
path["reward"] = utils.discount(path["reward"], self.args.gamma)
path["baseline"] = self.vf.predict(path["observation"])
path["advantage"] = path["reward"] - path["baseline"]
adv_n = np.concatenate([path["advantage"] for path in paths])
for path in paths:
path["advantage"] = (path["advantage"] - adv_n.mean()) / (adv_n.std() + 1e-8)
def fit_value_function(self, paths, vfdict):
""" Fits the TRPO's value function with the current minibatch of data.
Also takes in another dictionary, `vfdict`, for relevant statistics
related to the value function.
"""
ob_no = np.concatenate([path["observation"] for path in paths])
vtarg_n = np.concatenate([path["reward"] for path in paths])
assert ob_no.shape[0] == vtarg_n.shape[0]
out = self.vf.fit(ob_no, vtarg_n)
for key in out:
vfdict[key] = out[key]
def log_diagnostics(self, paths, infodict, vfdict):
""" Just logging using the `logz` functionality. """
ob_no = np.concatenate([path["observation"] for path in paths])
vpred_n = np.concatenate([path["baseline"] for path in paths])
vtarg_n = np.concatenate([path["reward"] for path in paths])
elapsed_time = (time.time() - self.start_time) # In seconds
episode_rewards = np.array([path["reward"].sum() for path in paths])
episode_lengths = np.array([utils.pathlength(path) for path in paths])
# These are *not* logged in John Schulman's code.
#logz.log_tabular("Success", infodict["Success"])
#logz.log_tabular("LagrangeM", infodict["LagrangeM"])
#logz.log_tabular("gNorm", infodict["gNorm"])
# These *are* logged in John Schulman's code. First, rewards:
logz.log_tabular("NumEpBatch", len(paths))
logz.log_tabular("EpRewMean", episode_rewards.mean())
logz.log_tabular("EpRewMax", episode_rewards.max())
logz.log_tabular("EpRewSEM", episode_rewards.std()/np.sqrt(len(paths)))
logz.log_tabular("EpLenMean", episode_lengths.mean())
logz.log_tabular("EpLenMax", episode_lengths.max())
logz.log_tabular("RewPerStep", episode_rewards.sum()/episode_lengths.sum())
logz.log_tabular("vf_mse_before", vfdict["MSEBefore"])
logz.log_tabular("vf_mse_after", vfdict["MSEAfter"])
logz.log_tabular("vf_PredStdevBefore", vfdict["PredStdevBefore"])
logz.log_tabular("vf_PredStdevAfter", vfdict["PredStdevAfter"])
logz.log_tabular("vf_TargStdev", vfdict["TargStdev"])
logz.log_tabular("vf_EV_before", utils.explained_variance_1d(vpred_n, vtarg_n))
logz.log_tabular("vf_EV_after", utils.explained_variance_1d(self.vf.predict(ob_no), vtarg_n))
# If overfitting, EVAfter >> EVBefore. Also, we fit the value function
# _after_ using it to compute the baseline to avoid introducing bias.
logz.log_tabular("pol_surr_before", infodict["pol_surr_before"])
logz.log_tabular("pol_surr_after", infodict["pol_surr_after"])
logz.log_tabular("pol_kl_before", infodict["pol_kl_before"])
logz.log_tabular("pol_kl_after", infodict["pol_kl_after"])
logz.log_tabular("pol_ent_before", infodict["pol_ent_before"])
logz.log_tabular("pol_ent_after", infodict["pol_ent_after"])
logz.log_tabular("TimeElapsed", elapsed_time)
logz.dump_tabular()
| DanielTakeshi/rl_algorithms | trpo/trpo.py | Python | mit | 19,601 | [
"Gaussian"
] | fbed2942241a61bce44c9b54e7e5f64a246cb4b18d398ef2ac5c68a16701707f |
# class generated by DeVIDE::createDeVIDEModuleFromVTKObject
from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase
import vtk
class vtkXMLPUnstructuredGridWriter(SimpleVTKClassModuleBase):
def __init__(self, module_manager):
SimpleVTKClassModuleBase.__init__(
self, module_manager,
vtk.vtkXMLPUnstructuredGridWriter(), 'Writing vtkXMLPUnstructuredGrid.',
('vtkXMLPUnstructuredGrid',), (),
replaceDoc=True,
inputFunctions=None, outputFunctions=None)
| nagyistoce/devide | modules/vtk_basic/vtkXMLPUnstructuredGridWriter.py | Python | bsd-3-clause | 532 | [
"VTK"
] | 54539aab21583a529baa6a399642896d35fb252a3b8856b6222b5f55c9142ef0 |
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2002-2007 Donald N. Allingham
# Copyright (C) 2007-2008 Brian G. Matherly
# Copyright (C) 2011 Tim G L Lyons
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""
Package providing filter rules for Gramps.
"""
from .._hassourcebase import HasSourceBase as HasSource
from ._allsources import AllSources
from ._hasgallery import HasGallery
from ._hasidof import HasIdOf
from ._regexpidof import RegExpIdOf
from ._hasnote import HasNote
from ._hasnoteregexp import HasNoteRegexp
from ._hasnotematchingsubstringof import HasNoteMatchingSubstringOf
from ._hasreferencecountof import HasReferenceCountOf
from ._sourceprivate import SourcePrivate
from ._matchesfilter import MatchesFilter
from ._changedsince import ChangedSince
from ._hasrepository import HasRepository
from ._matchestitlesubstringof import MatchesTitleSubstringOf
from ._hasrepositorycallnumberref import HasRepositoryCallNumberRef
from ._matchesrepositoryfilter import MatchesRepositoryFilter
from ._hastag import HasTag
editor_rule_list = [
AllSources,
HasGallery,
HasIdOf,
RegExpIdOf,
HasNote,
HasNoteRegexp,
HasReferenceCountOf,
SourcePrivate,
MatchesFilter,
ChangedSince,
HasRepository,
MatchesTitleSubstringOf,
HasRepositoryCallNumberRef,
MatchesRepositoryFilter,
HasTag
]
| jralls/gramps | gramps/gen/filters/rules/source/__init__.py | Python | gpl-2.0 | 2,039 | [
"Brian"
] | 92a8901c7c98ff47974cecf66656adb99451a2820810de01738e8f60320b1e3b |
# Imports
import os
import vcf
import math
import h5py
import pysam
import vqsr_cnn
import numpy as np
from Bio import Seq, SeqIO
from collections import Counter
# Keras Imports
import keras.backend as K
def run():
args = vqsr_cnn.parse_args()
if 'write_reference_and_annotation_tensors' == args.mode:
write_reference_and_annotation_tensors(args)
elif 'write_read_and_annotation_tensors' == args.mode:
write_read_and_annotation_tensors(args)
elif 'train_default_1d_model' == args.mode:
train_default_1d_model(args)
elif 'train_default_2d_model' == args.mode:
train_default_2d_model(args)
elif 'train_args_model_on_read_tensors_and_annotations' == args.mode:
train_args_model_on_read_tensors_and_annotations(args)
elif 'train_args_model_on_reference_and_annotations' == args.mode:
train_args_model_on_read_tensors_and_annotations(args)
else:
raise ValueError('Unknown training mode:', args.mode)
def write_reference_and_annotation_tensors(args, include_dna=True, include_annotations=True):
if not args.tensor_name in vqsr_cnn.TENSOR_MAPS_1D:
raise ValueError('Unknown tensor name:', args.tensor_name, '1d maps must be in:', str(vqsr_cnn.TENSOR_MAPS_1D))
record_dict = SeqIO.to_dict(SeqIO.parse(args.reference_fasta, "fasta"))
vcf_reader = get_vcf_reader(args.input_vcf)
vcf_ram = get_vcf_reader(args.train_vcf)
bed_dict = bed_file_to_dict(args.bed_file)
stats = Counter()
if args.chrom:
variants = vcf_reader.fetch(args.chrom, args.start_pos, args.end_pos)
else:
variants = vcf_reader
for variant in variants:
for allele_idx, allele in enumerate(variant.ALT):
idx_offset, ref_start, ref_end = get_variant_window(args, variant)
contig = record_dict[variant.CHROM]
record = contig[variant.POS-idx_offset: variant.POS+idx_offset]
cur_label_key = get_true_label(allele, variant, bed_dict, vcf_ram, stats)
if not cur_label_key or downsample(args, cur_label_key, stats):
continue
if include_annotations:
if all(map(
lambda x: x not in variant.INFO and x not in variant.FORMAT and x != "QUAL", args.annotations)):
stats['Missing ALL annotations'] += 1
continue # Require at least 1 annotation...
annotation_data = get_annotation_data(args, variant, stats)
if include_dna:
dna_data = np.zeros( (args.window_size, len(vqsr_cnn.DNA_SYMBOLS)) )
for i,b in enumerate(record.seq):
if b in vqsr_cnn.DNA_SYMBOLS:
dna_data[i, vqsr_cnn.DNA_SYMBOLS[b]] = 1.0
elif b in vqsr_cnn.AMBIGUITY_CODES:
dna_data[i] = vqsr_cnn.AMBIGUITY_CODES[b]
else:
raise ValueError('Error! Unknown code:', b)
tp = get_path_to_train_valid_or_test(args.data_dir)
tp += cur_label_key +'/'+ plain_name(args.input_vcf) +'_'+ plain_name(args.train_vcf)
tp += '_allele_' + str(allele_idx) +'-'+ variant.CHROM +'_'+ str(variant.POS) + vqsr_cnn.TENSOR_SUFFIX
if not os.path.exists(os.path.dirname(tp)):
os.makedirs(os.path.dirname(tp))
with h5py.File(tp, 'w') as hf:
if include_annotations:
hf.create_dataset(args.annotation_set, data=annotation_data, compression='gzip')
if include_dna:
hf.create_dataset(args.tensor_name, data=dna_data, compression='gzip')
stats[cur_label_key] += 1
stats['count'] += 1
if stats['count']%500==0:
print('Wrote', stats['count'], 'out of:', args.samples, 'Last variant:', variant)
if args.samples <= stats['count']:
break
print('Done Writing 1D Tensors. Tensor Map:', args.tensor_name, ' Annotation set:', args.annotation_set)
for k in stats.keys():
print(k, ' has:', stats[k])
def write_read_and_annotation_tensors(args, include_annotations=True, pileup=False):
'''Create tensors structured as tensor map of reads organized by labels in the data directory.
Defines true variants as those in the args.train_vcf, defines false variants as
those called in args.input_vcf and in the args.bed_file high confidence intervals,
but not in args.train_vcf.
Arguments
args.data_dir: directory where tensors will live. Created here and filled with
subdirectories of test, valid and train, each containing
subdirectories for each label with tensors stored as hd5 files.
args.bam_file: BAM or BAMout file where the aligned reads are stored
args.input_vcf: VCF file with annotation values from Haplotype caller or VQSR
args.train_vcf: VCF file with true variant (from NIST or Platinum genomes, etc.)
args.bed_file: High confidence intervals for the calls in args.train_vcf
args.window_size: Size of sequence window around variant (width of the tensor)
args.read_limit: Maximum number of reads to include (height of the tensor)
args.chrom: Only write tensors from this chromosome (optional, used for parallelization)
args.start_pos: Only write tensors after this position (optional, used for parallelization)
args.end_pos: Only write tensors before this position (optional, used for parallelization)
'''
print('Writing tensors with:', args.tensor_name, 'channel map.')
stats = Counter()
samfile = pysam.AlignmentFile(args.bam_file, "rb")
bed_dict = bed_file_to_dict(args.bed_file)
record_dict = SeqIO.to_dict(SeqIO.parse(args.reference_fasta, "fasta"))
vcf_reader = get_vcf_reader(args.input_vcf)
vcf_ram = get_vcf_reader(args.train_vcf)
if args.chrom:
variants = vcf_reader.fetch(args.chrom, args.start_pos, args.end_pos)
else:
variants = vcf_reader
for variant in variants:
for allele_idx, allele in enumerate(variant.ALT):
idx_offset, ref_start, ref_end = get_variant_window(args, variant)
contig = record_dict[variant.CHROM]
record = contig[ ref_start : ref_end ]
cur_label_key = get_true_label(allele, variant, bed_dict, vcf_ram, stats)
if not cur_label_key or downsample(args, cur_label_key, stats):
continue
if include_annotations:
if all(map(
lambda x: x not in variant.INFO and x not in variant.FORMAT and x != "QUAL", args.annotations)):
stats['Missing ALL annotations'] += 1
continue # Require at least 1 annotation...
annotation_data = get_annotation_data(args, variant, stats)
good_reads, insert_dict = get_good_reads(args, samfile, variant)
if len(good_reads) >= args.read_limit:
stats['More reads than read_limit'] += 1
if len(good_reads) == 0:
stats['No reads aligned'] += 1
continue
reference_seq = record.seq
for i in sorted(insert_dict.keys(), key=int, reverse=True):
if i < 0:
reference_seq = vqsr_cnn.INDEL_CHAR*insert_dict[i] + reference_seq
else:
reference_seq = reference_seq[:i] + vqsr_cnn.INDEL_CHAR*insert_dict[i] + reference_seq[i:]
read_tensor = good_reads_to_tensor(args, good_reads, ref_start, insert_dict)
reference_sequence_into_tensor(args, reference_seq, read_tensor)
tensor_path = get_path_to_train_valid_or_test(args.data_dir)
tensor_prefix = plain_name(args.input_vcf) +'_'+ plain_name(args.train_vcf)
tensor_prefix += '_allele_' + str(allele_idx) + '-' + cur_label_key
tensor_path += cur_label_key + '/' + tensor_prefix + '-' + variant.CHROM
tensor_path += '_' + str(variant.POS) + vqsr_cnn.TENSOR_SUFFIX
stats[cur_label_key] += 1
if not os.path.exists(os.path.dirname(tensor_path)):
os.makedirs(os.path.dirname(tensor_path))
with h5py.File(tensor_path, 'w') as hf:
if pileup:
pileup_tensor = read_tensor_to_pileup(args, read_tensor)
hf.create_dataset('pileup_tensor', data=pileup_tensor, compression='gzip')
hf.create_dataset(args.tensor_name, data=read_tensor, compression='gzip')
if include_annotations:
hf.create_dataset(args.annotation_set, data=annotation_data, compression='gzip')
stats['count'] += 1
if stats['count']%100 == 0:
print('Wrote', stats['count'], 'tensors out of', args.samples, ' last variant:', str(variant))
if stats['count'] >= args.samples:
break
for s in stats.keys():
print(s, 'has:', stats[s])
if variant:
print('Done generating tensors. Last variant:', str(variant), 'from vcf:', args.input_vcf)
def train_default_1d_model(args):
'''Train a 1D Convolution plus reference tracks and MLP Annotation architecture.
Arguments:
args.data_dir: must be set to an appropriate directory with
subdirectories of test, valid and train, each containing
subdirectories for each label with tensors stored as hd5 files.
Reference and Annotation tensors must be generated by calling
write_reference_and_annotation_tensors() before this function is used.
Performance curves for CNN are plotted on the test dataset.
'''
train_paths, valid_paths, test_paths = get_train_valid_test_paths(args)
generate_train = dna_annotation_generator(args, train_paths)
generate_valid = dna_annotation_generator(args, valid_paths)
weight_path = vqsr_cnn.weight_path_from_args(args)
model = vqsr_cnn.build_default_1d_annotation_model(args)
model = vqsr_cnn.train_model_from_generators(args, model, generate_train, generate_valid, weight_path)
test = load_dna_annotations_positions_from_class_dirs(args, test_paths, per_class_max=args.samples)
if args.image_dir:
vqsr_cnn.plot_roc_per_class(model, [test[0], test[1]], test[2], args.labels, args.id, prefix=args.image_dir)
def train_default_2d_model(args):
'''Trains a reference, read, and annotation CNN architecture on tensors at the supplied data directory.
This architecture looks at reads, read flags, reference sequence, and variant annotations.
Tensors must be generated by calling write_read_and_annotation_tensors() before this function is used.
After training with early stopping performance curves are plotted on the test dataset.
Arguments:
args.data_dir: must be set to an appropriate directory with
subdirectories of test, valid and train, each containing
subdirectories for each label with tensors stored as hd5 files.
'''
train_paths, valid_paths, test_paths = get_train_valid_test_paths(args)
generate_train = tensor_generator_from_label_dirs_and_args(args, train_paths)
generate_valid = tensor_generator_from_label_dirs_and_args(args, valid_paths)
weight_path = vqsr_cnn.weight_path_from_args(args)
model = vqsr_cnn.build_default_2d_annotation_model(args)
model = vqsr_cnn.train_model_from_generators(args, model, generate_train, generate_valid, weight_path)
test = load_tensors_and_annotations_from_class_dirs(args, test_paths, per_class_max=args.samples)
if args.image_dir:
vqsr_cnn.plot_roc_per_class(model, [test[0], test[1]], test[2], args.labels, args.id,
prefix=args.image_dir, batch_size=args.batch_size)
def train_args_model_on_read_tensors_and_annotations(args):
'''Trains a reference, read, and annotation CNN architecture on tensors at the supplied data directory.
This architecture looks at reads, read flags, reference sequence, and variant annotations.
Tensors must be generated by calling write_read_and_annotation_tensors() before this function is used.
After training with early stopping performance curves are plotted on the test dataset.
Arguments:
args.data_dir: must be set to an appropriate directory with
subdirectories of test, valid and train, each containing
subdirectories for each label with tensors stored as hd5 files.
'''
train_paths, valid_paths, test_paths = get_train_valid_test_paths(args)
generate_train = tensor_generator_from_label_dirs_and_args(args, train_paths)
generate_valid = tensor_generator_from_label_dirs_and_args(args, valid_paths)
weight_path = vqsr_cnn.weight_path_from_args(args)
model = vqsr_cnn.build_2d_annotation_model_from_args(args)
model = vqsr_cnn.train_model_from_generators(args, model, generate_train, generate_valid, weight_path)
test = load_tensors_and_annotations_from_class_dirs(args, test_paths, per_class_max=args.samples)
if args.image_dir:
vqsr_cnn.plot_roc_per_class(model, [test[0], test[1]], test[2], args.labels, args.id,
prefix=args.image_dir, batch_size=args.batch_size)
def train_small_model_on_read_tensors_and_annotations(args):
'''Trains a reference, read, and annotation CNN architecture on tensors at the supplied data directory.
This architecture looks at reads, read flags, reference sequence, and variant annotations.
Tensors must be generated by calling write_read_and_annotation_tensors() before this function is used.
After training with early stopping performance curves are plotted on the test dataset.
Arguments:
args.data_dir: must be set to an appropriate directory with
subdirectories of test, valid and train, each containing
subdirectories for each label with tensors stored as hd5 files.
'''
train_paths, valid_paths, test_paths = get_train_valid_test_paths(args)
generate_train = tensor_generator_from_label_dirs_and_args(args, train_paths)
generate_valid = tensor_generator_from_label_dirs_and_args(args, valid_paths)
weight_path = vqsr_cnn.weight_path_from_args(args)
model = vqsr_cnn.build_small_2d_annotation_model(args)
model = vqsr_cnn.train_model_from_generators(args, model, generate_train, generate_valid, weight_path)
test = load_tensors_and_annotations_from_class_dirs(args, test_paths, per_class_max=args.samples)
if args.image_dir:
vqsr_cnn.plot_roc_per_class(model, [test[0], test[1]], test[2], args.labels, args.id,
prefix=args.image_dir, batch_size=args.batch_size)
def get_annotation_data(args, annotation_variant, stats):
'''Return an array annotation data about the variant.
Arguments:
args.annotations: List of variant annotations to use
annotation_variant: the variant with annotation
stats: Counter of run statistics
Returns:
annotation_data: numpy array of annotation values
'''
annotation_data = np.zeros((len(args.annotations),))
for i, a in enumerate(args.annotations):
if a == 'QUAL':
annotation_data[i] = annotation_variant.QUAL
elif a == 'AF':
annotation_data[i] = annotation_variant.INFO[a][0]
elif a in annotation_variant.INFO and not math.isnan(annotation_variant.INFO[a]):
annotation_data[i] = annotation_variant.INFO[a]
elif a == 'MBQ':
call = annotation_variant.genotype(args.sample_name)
annotation_data[i] = call.data.MBQ
elif a == 'MPOS':
call = annotation_variant.genotype(args.sample_name)
annotation_data[i] = call.data.MPOS
elif a == 'MMQ':
call = annotation_variant.genotype(args.sample_name)
annotation_data[i] = call.data.MMQ
elif a == 'MFRL_0':
call = annotation_variant.genotype(args.sample_name)
annotation_data[i] = call.data.MFRL[0]
elif a == 'MFRL_1':
call = annotation_variant.genotype(args.sample_name)
annotation_data[i] = call.data.MFRL[1]
elif a == 'AD_0':
call = annotation_variant.genotype(args.sample_name)
annotation_data[i] = call.data.AD[0]
elif a == 'AD_1':
call = annotation_variant.genotype(args.sample_name)
annotation_data[i] = call.data.AD[1]
else:
stats['Could not find annotation:' + a] += 1
return annotation_data
def get_good_reads(args, samfile, variant, sort_by='base'):
'''Return an array of usable reads centered at the variant.
Ignores artificial haplotype read group.
Relies on pysam's cigartuples structure see: http://pysam.readthedocs.io/en/latest/api.html
Match, M -> 0
Insert, I -> 1
Deletion, D -> 2
Ref Skip, N -> 3
Soft Clip, S -> 4
Arguments:
args.read_limit: maximum number of reads to return
samfile: the BAM (or BAMout) file
variant: the variant around which reads will load
Returns:
good_reads: array of usable reads sorted by reference start position
insert_dict: a dict mapping read indices to max insertions at that point
'''
good_reads = []
insert_dict = {}
idx_offset, ref_start, ref_end = get_variant_window(args, variant)
for read in samfile.fetch(variant.CHROM, variant.POS-1, variant.POS+1):
if not read or not hasattr(read, 'cigarstring') or read.cigarstring is None:
continue
read_group = read.get_tag('RG')
if 'artificial' in read_group.lower():
continue
index_dif = ref_start - read.reference_start
if abs(index_dif) >= args.window_size:
continue
if 'I' in read.cigarstring:
cur_idx = 0
for t in read.cigartuples:
if t[0] == vqsr_cnn.CIGAR_CODE['I']:
insert_idx = cur_idx - index_dif
if insert_idx not in insert_dict:
insert_dict[insert_idx] = t[1]
elif insert_dict[insert_idx] < t[1]:
insert_dict[insert_idx] = t[1]
if t[0] in [vqsr_cnn.CIGAR_CODE['M'], vqsr_cnn.CIGAR_CODE['I'],
vqsr_cnn.CIGAR_CODE['S'], vqsr_cnn.CIGAR_CODE['D']]:
cur_idx += t[1]
good_reads.append(read)
if len(good_reads) > args.read_limit:
good_reads = np.random.choice(good_reads, size=args.read_limit, replace=False).tolist()
good_reads.sort(key=lambda x: x.reference_start + x.query_alignment_start)
if sort_by == 'base':
good_reads.sort(key=lambda read: get_base_to_sort_by(read, variant))
return good_reads, insert_dict
def get_base_to_sort_by(read, variant):
if len(read.query_alignment_sequence) > 0:
max_idx = len(read.query_alignment_sequence)-1
else:
return 'Z'
if variant.is_snp:
return read.query_alignment_sequence[clamp((variant.POS-read.reference_start)-1, 0, max_idx)]
elif variant.is_indel:
var_idx = variant.POS-read.reference_start
cur_idx = 0
for cur_op, length in read.cigartuples:
cur_idx += length
if cur_idx > var_idx:
if cur_op == vqsr_cnn.CIGAR_CODE['M']:
return read.query_alignment_sequence[clamp(var_idx, 0, max_idx)]
else:
return vqsr_cnn.CODE2CIGAR[cur_op]
return 'Y'
def clamp(n, minn, maxn):
return max(min(maxn, n), minn)
def good_reads_to_tensor(args, good_reads, ref_start, insert_dict):
'''Create a read tensor based on a tensor channel map.
Assumes read pairs have the same name.
Only loads reads that might align inside the tensor.
Arguments:
args.read_limit: maximum number of reads to return
good_reads: list of reads to make arrays from
ref_start: the beginning of the window in reference coordinates
insert_dict: a dict mapping read indices to max insertions at that point.
Returns:
tensor: 3D read tensor.
'''
channel_map = vqsr_cnn.get_tensor_channel_map_from_args(args)
tensor = np.zeros( vqsr_cnn.tensor_shape_from_args(args) )
for j,read in enumerate(good_reads):
rseq, rqual = sequence_and_qualities_from_read(args, read, ref_start, insert_dict)
flag_start = -1
flag_end = 0
for i,b in enumerate(rseq):
if i == args.window_size:
break
if b == vqsr_cnn.SKIP_CHAR:
continue
elif flag_start == -1:
flag_start = i
else:
flag_end = i
if b in args.input_symbols:
if b == vqsr_cnn.INDEL_CHAR:
if K.image_data_format() == 'channels_last':
tensor[j, i, args.input_symbols[b]] = 1.0
else:
tensor[args.input_symbols[b], j, i] = 1.0
else:
hot_array = quality_from_mode(args, rqual[i], b, args.input_symbols)
if K.image_data_format() == 'channels_last':
tensor[j, i, :4] = hot_array
else:
tensor[:4, j, i] = hot_array
elif b in vqsr_cnn.AMBIGUITY_CODES:
if K.image_data_format() == 'channels_last':
tensor[j, i, :4] = vqsr_cnn.AMBIGUITY_CODES[b]
else:
tensor[:4, j, i] = vqsr_cnn.AMBIGUITY_CODES[b]
else:
print('Error! Unknown symbol in seq block:', b)
return
flags = flag_to_array(read.flag)
for i in range(vqsr_cnn.READ_FLAGS):
flag_str = 'flag_bit_'+ str(i)
if flags[i] and flag_str in channel_map:
if K.image_data_format() == 'channels_last':
tensor[j, flag_start:flag_end, channel_map[flag_str]] = 1.0
else:
tensor[channel_map[flag_str], j, flag_start:flag_end] = 1.0
if 'mapping_quality' in channel_map:
mq = float(read.mapping_quality)/vqsr_cnn.MAPPING_QUALITY_MAX
if K.image_data_format() == 'channels_last':
tensor[j, flag_start:flag_end, channel_map['mapping_quality']] = mq
else:
tensor[channel_map['mapping_quality'], j, flag_start:flag_end] = mq
return tensor
def sequence_and_qualities_from_read(args, read, ref_start, insert_dict):
cur_idx = 0
my_indel_dict = {}
no_qual_filler = 0
index_dif = ref_start - read.reference_start
for t in read.cigartuples:
my_ref_idx = cur_idx - index_dif
if t[0] == vqsr_cnn.CIGAR_CODE['I'] and my_ref_idx in insert_dict:
my_indel_dict[my_ref_idx] = insert_dict[my_ref_idx] - t[1]
elif t[0] == vqsr_cnn.CIGAR_CODE['D']:
my_indel_dict[my_ref_idx] = t[1]
if t[0] in [vqsr_cnn.CIGAR_CODE['M'], vqsr_cnn.CIGAR_CODE['I'],
vqsr_cnn.CIGAR_CODE['S'], vqsr_cnn.CIGAR_CODE['D']]:
cur_idx += t[1]
for k in insert_dict.keys():
if k not in my_indel_dict:
my_indel_dict[k] = insert_dict[k]
rseq = read.query_alignment_sequence[:args.window_size]
rqual = read.query_alignment_qualities[:args.window_size].tolist()
if index_dif > 0:
rseq = rseq[index_dif:]
rqual = rqual[index_dif:]
elif index_dif < 0:
rseq = vqsr_cnn.SKIP_CHAR*(-index_dif) + rseq
rqual = [no_qual_filler]*(-index_dif) + rqual
for j in sorted(my_indel_dict.keys(), key=int, reverse=True):
if j < 1:
rseq = (vqsr_cnn.INDEL_CHAR*my_indel_dict[j]) + rseq
rqual = ([no_qual_filler]*my_indel_dict[j]) + rqual
else:
rseq = rseq[:j] + (vqsr_cnn.INDEL_CHAR*my_indel_dict[j]) + rseq[j:]
rqual = rqual[:j] + ([no_qual_filler]*my_indel_dict[j]) + rqual[j:]
return rseq, rqual
def read_tensor_to_pileup(args, read_tensor):
tensor_map = vqsr_cnn.get_tensor_channel_map_from_args(args)
channels = vqsr_cnn.get_reference_and_read_channels(args)
pileup_tensor = np.zeros((args.window_size, channels))
for i in range(args.window_size):
for key in tensor_map:
if 'read' not in key and 'reference' not in key:
continue
if 'read' in key and K.image_data_format() == 'channels_last':
pileup_tensor[i, tensor_map[key]] = np.sum(read_tensor[:, i, tensor_map[key]]) / args.window_size
elif 'read' in key:
pileup_tensor[i, tensor_map[key]] = np.sum(read_tensor[tensor_map[key], :, i]) / args.window_size
elif 'reference' in key and K.image_data_format() == 'channels_last':
pileup_tensor[i, tensor_map[key]] = np.amax(read_tensor[:, i, tensor_map[key]])
elif 'reference' in key:
pileup_tensor[i, tensor_map[key]] = np.amax(read_tensor[tensor_map[key], :, i])
else:
raise ValueError('Error unexpected key:'+key)
return pileup_tensor
def reference_sequence_into_tensor(args, reference_seq, tensor):
ref_offset = len(set(args.input_symbols.values()))
for i,b in enumerate(reference_seq):
if i == args.window_size:
break
if b in args.input_symbols:
if K.image_data_format() == 'channels_last':
tensor[:, i, ref_offset+args.input_symbols[b]] = 1.0
else:
tensor[ref_offset+args.input_symbols[b], :, i] = 1.0
elif b in vqsr_cnn.AMBIGUITY_CODES:
ambiguous_vector = np.tile(vqsr_cnn.AMBIGUITY_CODES[b], (args.read_limit, 1))
if K.image_data_format() == 'channels_last':
tensor[:, i, ref_offset:ref_offset+4] = ambiguous_vector
else:
tensor[ref_offset:ref_offset+4, :, i] = np.transpose(ambiguous_vector)
def flag_to_array(flag):
flags = []
for i in range(vqsr_cnn.READ_FLAGS):
flags.append((flag>>i)&1)
return np.array(flags)
def add_flags_to_read_tensor(args, tensor, tensor_channel_map, flags):
for k in tensor_channel_map.keys():
if 'flag' in k:
flag_bit = int(k.split('_')[-1])
for read_idx in range(flags.shape[1]):
if K.image_data_format() == 'channels_last':
tensor[read_idx, :, tensor_channel_map[k]] = flags[flag_bit, read_idx]
else:
tensor[tensor_channel_map[k], read_idx, :] = flags[flag_bit, read_idx]
def add_mq_to_read_tensor(args, tensor, tensor_channel_map, mapping_qualities):
if not 'mapping_quality' in tensor_channel_map:
return
for read_idx, mq in enumerate(mapping_qualities):
if K.image_data_format() == 'channels_last':
tensor[read_idx, :, tensor_channel_map['mapping_quality']] = float(mq) / vqsr_cnn.MAPPING_QUALITY_MAX
else:
tensor[tensor_channel_map['mapping_quality'], read_idx, :] = float(mq) / vqsr_cnn.MAPPING_QUALITY_MAX
def base_quality_to_phred_array(base_quality, base, base_dict):
phred = np.zeros((4,))
exponent = float(-base_quality) / 10.0
p = 1.0-(10.0**exponent) # Convert to probability
not_p = (1.0-p) / 3.0 # Error could be any of the other 3 bases
not_base_quality = -10 * np.log10(not_p) # Back to Phred
for b in base_dict.keys():
if b == vqsr_cnn.INDEL_CHAR:
continue
elif b == base:
phred[base_dict[b]] = base_quality
else:
phred[base_dict[b]] = not_base_quality
return phred
def base_quality_to_p_hot_array(base_quality, base, base_dict):
phot = np.zeros((4,))
exponent = float(-base_quality) / 10.0
p = 1.0-(10.0**exponent)
not_p = (1.0-p)/3.0
for b in base_dict.keys():
if b == base:
phot[base_dict[b]] = p
elif b == vqsr_cnn.INDEL_CHAR:
continue
else:
phot[base_dict[b]] = not_p
return phot
def quality_from_mode(args, base_quality, base, base_dict):
if args.base_quality_mode == 'phot':
return base_quality_to_p_hot_array(base_quality, base, base_dict)
elif args.base_quality_mode == 'phred':
return base_quality_to_phred_array(base_quality, base, base_dict)
elif args.base_quality_mode == '1hot':
one_hot = np.zeros((4,))
one_hot[base_dict[base]] = 1.0
return one_hot
else:
raise ValueError('Error! Unknown base quality mode:', args.base_quality_mode)
def get_true_label(allele, variant, bed_dict, truth_vcf, stats):
'''Defines the truth status of a variant allele given a truth vcf and confident region.
Arguments:
allele: The allele to check
variant: the variant whose allele we will check
bed_dict: confident region dict defined by intervals e.g. from bed_file_to_dict()
truth_vcf: vcf of validated variants
stats: Counter dict used to keep track of the label distribution, etc.
Returns:
None if outside the confident region
Otherwise a label string:
SNP if variant is snp and in truth vcf
INDEL if variant is indel and in truth vcf
NOT_SNP if variant is snp and not in truth vcf
NOT_INDEL if variant is indel and not in truth vcf
'''
in_bed = in_bed_file(bed_dict, variant.CHROM, variant.POS)
if allele_in_vcf(allele, variant, truth_vcf) and in_bed:
class_prefix = ''
elif in_bed:
class_prefix = 'NOT_'
else:
stats['Variant outside confident bed file'] += 1
return None
if variant.is_snp:
cur_label_key = class_prefix + 'SNP'
elif variant.is_indel:
cur_label_key = class_prefix + 'INDEL'
else:
stats['Not SNP or INDEL'] += 1
return None
return cur_label_key
def downsample(args, cur_label_key, stats):
'''Indicates whether or not to downsample a variant.
Arguments:
args.skip_positive_class: Skip all positive examples
args.downsample_snps: fraction of SNPs to keep
args.downsample_indels: fraction of INDELs to keep
cur_label_key: truth label from get_true_label()
stats: Counter dict used to keep track of a run
Returns:
Boolean: should we downsample this variant or not.
'''
if args.skip_positive_class and cur_label_key in ['SNP', 'INDEL']:
stats['Downsampled positive examples'] += 1
return True
if args.downsample_snps < 1.0 and cur_label_key == 'SNP':
dice = np.random.rand()
if dice > args.downsample_snps:
stats['Downsampled SNPs'] += 1
return True
elif args.downsample_indels < 1.0 and cur_label_key == 'INDEL':
dice = np.random.rand()
if dice > args.downsample_indels:
stats['Downsampled INDELs'] += 1
return True
if args.downsample_not_snps < 1.0 and cur_label_key == 'NOT_SNP':
dice = np.random.rand()
if dice > args.downsample_not_snps:
stats['Downsampled NOT_SNPs'] += 1
return True
elif args.downsample_not_indels < 1.0 and cur_label_key == 'NOT_INDEL':
dice = np.random.rand()
if dice > args.downsample_not_indels:
stats['Downsampled NOT_INDELs'] += 1
return True
return False
def interval_file_to_dict(interval_file, shift1=0, skip=['@']):
''' Create a dict to store intervals from a interval list file.
Arguments:
interval_file: the file to load either a bed file -> shift1 should be 1
or a picard style interval_list file -> shift1 should be 0
shift1: Shift the intervals 1 position over to align with 1-indexed VCFs
skip: Comment character to ignore
Returns:
intervals: dict where keys in the dict are contig ids
values are a tuple of arrays the first array
in the tuple contains the start positions
the second array contains the end positions.
'''
intervals = {}
with open(interval_file) as f:
for line in f:
if line[0] in skip:
continue
parts = line.split()
contig = parts[0]
lower = int(parts[1])+shift1
upper = int(parts[2])+shift1
if contig not in intervals:
intervals[contig] = ([], [])
intervals[contig][0].append(lower)
intervals[contig][1].append(upper)
for k in intervals.keys():
intervals[k] = (np.array(intervals[k][0]), np.array(intervals[k][1]))
return intervals
def bed_file_to_dict(bed_file):
return interval_file_to_dict(bed_file, shift1=1)
def in_bed_file(bed_dict, contig, pos):
if not contig in bed_dict:
return False
lows = bed_dict[contig][0]
ups = bed_dict[contig][1]
# Half open interval [#,#)
return np.any((lows <= pos) & (pos < ups))
def allele_in_vcf(allele, variant, vcf_ram):
''' Check if variant's allele is in a VCF file.
Arguments
allele: the allele from the provided variant that we are checking
variant: the variant whose allele we are looking for
vcf_ram: the VCF we look in, must have an index (tbi, or idx)
Returns
variant if it is found otherwise None
'''
if not variant.CHROM in vcf_ram.contigs:
return None
try:
variants = vcf_ram.fetch(variant.CHROM, variant.POS-1, variant.POS)
except ValueError as e:
print('catching value error on fetch')
return None
for v in variants:
if v.CHROM == variant.CHROM and v.POS == variant.POS and allele in v.ALT:
return v
return None
def get_variant_window(args, variant):
index_offset = (args.window_size//2)
reference_start = variant.POS-(index_offset+1)
reference_end = variant.POS+index_offset
return index_offset, reference_start, reference_end
def dna_annotation_generator(args, train_paths):
"""Data generator of DNA and annotation tensors.
Assumes train paths contains example in labelled directories.
Loops over all examples sampling args.batch_size examples
uniformly from each label.
Arguments:
args: args object needed for batch_size, labels, and annotations
train_paths: array of label directories with hd5 tensors within each
Returns:
A tuple with a dict of the input tensors
and a 1-Hot matrix (2D numpy array) of the labels.
"""
per_batch_per_label = (args.batch_size // len(args.labels))
tensor_counts = Counter()
tensors = {}
if args.window_size > 0:
channel_map = vqsr_cnn.get_tensor_channel_map_from_args(args)
tensor = np.zeros((args.batch_size, args.window_size, len(channel_map)))
annotation_data = np.zeros((args.batch_size, len(args.annotations)))
label_matrix = np.zeros((args.batch_size, len(args.labels)))
for tp in train_paths:
label_key = os.path.basename(tp)
if label_key not in args.labels:
print('Skipping label directory:', label_key, ' which is not in args label set:', args.labels.keys())
continue
label = args.labels[label_key]
tensors[label] = [os.path.join(tp, t) for t in os.listdir(tp)
if os.path.splitext(t)[1] == vqsr_cnn.TENSOR_SUFFIX]
tensor_counts[label] = 0
print('Found ', len(tensors[label]), 'examples of label:', label, 'in:', tp)
while True:
cur_example = 0
for label in tensors.keys():
for i in range(per_batch_per_label):
tensor_path = tensors[label][tensor_counts[label]]
label_matrix[cur_example, label] = 1.0
with h5py.File(tensor_path,'r') as hf:
annotation_data[cur_example,:] = np.array(hf.get(args.annotation_set))
if args.window_size > 0:
tensor[cur_example,:,:] = np.array(hf.get(args.tensor_name))
tensor_counts[label] += 1
if tensor_counts[label] == len(tensors[label]):
np.random.shuffle(tensors[label])
print('\nGenerator shuffled & looped over:', tensor_counts[label],
'examples of label:',label, '\nLast tensor was:', tensor_path)
tensor_counts[label] = 0
cur_example += 1
if cur_example == args.batch_size:
break
if args.window_size > 0:
yield ({args.tensor_name:tensor, args.annotation_set:annotation_data}, label_matrix)
else:
yield (annotation_data, label_matrix)
def tensor_generator_from_label_dirs_and_args(args, train_paths, with_positions=False):
"""Data generator of tensors with reads, and annotations.
Assumes train paths contains example in labelled directories.
Loops over all examples sampling args.batch_size examples
uniformly from each label.
Arguments:
args: args object needed for batch_size, labels, and annotations
train_paths: array of label directories with hd5 tensors within each
with_positions: boolean if True will include a position string
(i.e. "1_1234_0" for tensor from contig one base 1234 and first allele)
as the last element in each tensor tuple.
Returns:
A tuple with a dict of the input tensors
and a 1-Hot matrix (2D numpy array) of the labels.
"""
batch = {}
tensors = {}
tensor_counts = Counter()
per_batch_per_label = (args.batch_size // len(args.labels) )
tm = vqsr_cnn.get_tensor_channel_map_from_args(args)
if tm:
tensor_shape = vqsr_cnn.tensor_shape_from_args(args)
batch[args.tensor_name] = np.zeros(((args.batch_size,)+tensor_shape))
if vqsr_cnn.annotations_from_args(args):
batch[args.annotation_set] = np.zeros((args.batch_size, len(args.annotations)))
if with_positions:
positions = []
label_matrix = np.zeros((args.batch_size, len(args.labels)))
for tp in train_paths:
label_key = os.path.basename(tp)
if label_key not in args.labels:
print('Skipping label directory:', label_key, ' which is not in args label set:', args.labels.keys())
continue
label = args.labels[label_key]
tensors[label] = [os.path.join(tp, t) for t in os.listdir(tp)
if os.path.splitext(t)[1] == vqsr_cnn.TENSOR_SUFFIX]
tensor_counts[label] = 0
print('Found ', len(tensors[label]), 'examples of label:', label, 'in:', tp)
while True:
cur_example = 0
for label in tensors.keys():
for i in range(per_batch_per_label):
tensor_path = tensors[label][tensor_counts[label]]
with h5py.File(tensor_path, 'r') as hf:
for key in batch.keys():
batch[key][cur_example] = np.array(hf.get(key))
label_matrix[cur_example, label] = 1.0
tensor_counts[label] += 1
if tensor_counts[label] == len(tensors[label]):
np.random.shuffle(tensors[label])
print('\nGenerator looped over:', tensor_counts[label],
'examples of label:', label, '\nShuffled them. Last tensor was:', tensor_path)
tensor_counts[label] = 0
if with_positions:
positions.append(position_string_from_tensor_name(tensor_path))
cur_example += 1
if cur_example == args.batch_size:
break
if with_positions:
yield (batch, label_matrix, positions)
positions = []
else:
yield (batch, label_matrix)
label_matrix = np.zeros((args.batch_size, len(args.labels)))
if with_positions and tm:
tensor_shape = vqsr_cnn.tensor_shape_from_args(args)
batch[args.tensor_name] = np.zeros(((args.batch_size,)+tensor_shape))
if with_positions and vqsr_cnn.annotations_from_args(args):
batch[args.annotation_set] = np.zeros((args.batch_size, len(args.annotations)))
def load_dna_annotations_positions_from_class_dirs(args, train_paths,
per_class_max=4000, include_dna=True, include_annotations=True):
count = 0
annotation_data = []
reference_data = []
labels_data = []
positions = []
for tp in train_paths:
label_key = os.path.basename(tp)
if label_key not in args.labels:
print('Skipping label directory:', label_key, ' which is not in args label set:', args.labels.keys())
continue
label = args.labels[label_key]
imgs = os.listdir(tp)
count += 1
print(count, " dir out of:", len(train_paths), tp, "has:", len(imgs))
this_t = 0
for t in imgs:
this_t += 1
if this_t > per_class_max:
print('Per class max reached. bailing at', this_t)
break
fn, file_extension = os.path.splitext(t)
if not file_extension.lower() == vqsr_cnn.TENSOR_SUFFIX:
continue
with h5py.File(tp+'/'+t, 'r') as hf:
if include_annotations:
annotation_data.append(np.array(hf.get(args.annotation_set)))
if include_dna:
reference_data.append(np.array(hf.get(args.tensor_name)))
y_vector = np.zeros(len(args.labels)) # One hot Y vector of size labels, correct label is 1 others are 0
y_vector[label] = 1.0
labels_data.append(y_vector)
positions.append(position_string_from_tensor_name(t))
if include_dna and include_annotations:
return np.asarray(reference_data), np.asarray(annotation_data), np.asarray(labels_data), np.asarray(positions)
elif include_annotations:
return np.asarray(annotation_data), np.asarray(labels_data), np.asarray(positions)
elif include_dna:
return np.asarray(reference_data), np.asarray(labels_data), np.asarray(positions)
def load_tensors_and_annotations_from_class_dirs(args, train_paths, per_class_max=2500, position_dict=None):
annotations = []
positions = []
tensors = []
labels = []
count = 0
for tp in train_paths:
label_key = os.path.basename(tp)
if label_key not in args.labels:
print('Skipping label directory:', label_key, ' which is not in args label set:', args.labels.keys())
continue
label = args.labels[label_key]
imgs = os.listdir(tp)
count += 1
this_t = 0
for t in imgs:
if this_t > per_class_max:
print('Per class max reached. bailing at', this_t)
break
fn, file_extension = os.path.splitext(t)
if not file_extension.lower() == vqsr_cnn.TENSOR_SUFFIX:
continue
with h5py.File(tp+'/'+t, 'r') as hf:
tensors.append(np.array(hf.get(args.tensor_name)))
annotations.append(np.array(hf.get(args.annotation_set)))
y_vector = np.zeros(len(args.labels)) # One hot Y vector of size labels, correct label is 1 all others are 0
y_vector[label] = 1.0
labels.append(y_vector)
positions.append(position_string_from_tensor_name(t))
this_t += 1
print(count, " dir out of:", len(train_paths), tp, "has:", len(imgs), 'Loaded:', this_t)
return np.asarray(tensors), np.asarray(annotations), np.asarray(labels), np.asarray(positions)
def position_string_from_tensor_name(tensor_name):
'''Genomic position as underscore delineated string from a filename.
Includes an allele index if the filename includes _allele_
This is ugly, we need file names ending with genomic position
(e.g. my_tensor-12_1234.h5 returns 12_1234 and a_tensor_allele_1-8_128.hd5 returns 8_128_1)
Arguments:
tensor_name: the filename to parse
Returns:
Genomic position string Contig_Position or Contig_Position_AlleleIndex
'''
slash_split = tensor_name.split('/')
dash_split = slash_split[-1].split('-')
gsplit = dash_split[0].split('_')
gpos = dash_split[-1]
chrom = gpos.split('_')[0]
pos = os.path.splitext(gpos.split('_')[1])[0]
pos_str = chrom + '_' + pos
for i,p in enumerate(gsplit):
if p == 'allele':
pos_str += '_'+str(gsplit[i+1])
return pos_str
def get_path_to_train_valid_or_test(path, valid_ratio=0.1, test_ratio=0.2, valid_contig='-19_', test_contig='-20_'):
dice = np.random.rand()
if dice < valid_ratio or valid_contig in path:
return os.path.join(path, 'valid/')
elif dice < valid_ratio+test_ratio or test_contig in path:
return os.path.join(path, 'test/')
else:
return os.path.join(path, 'train/')
def get_train_valid_test_paths(args):
train_dir = args.data_dir + 'train/'
valid_dir = args.data_dir + 'valid/'
test_dir = args.data_dir + 'test/'
train_paths = [train_dir + tp for tp in sorted(os.listdir(train_dir)) if os.path.isdir(train_dir + tp)]
valid_paths = [valid_dir + vp for vp in sorted(os.listdir(valid_dir)) if os.path.isdir(valid_dir + vp)]
test_paths = [test_dir + vp for vp in sorted(os.listdir(test_dir)) if os.path.isdir(test_dir + vp)]
assert(len(train_paths) == len(valid_paths) == len(test_paths))
return train_paths, valid_paths, test_paths
def plain_name(full_name):
name = os.path.basename(full_name)
return name.split('.')[0]
def get_vcf_reader(my_vcf):
if os.path.splitext(my_vcf)[-1].lower() == '.gz':
return vcf.Reader(open(my_vcf, 'rb'))
else:
return vcf.Reader(open(my_vcf, 'r'))
# Back to the top!
if "__main__" == __name__:
run() | broadinstitute/hellbender | src/main/resources/org/broadinstitute/hellbender/tools/walkers/vqsr/training.py | Python | bsd-3-clause | 46,409 | [
"pysam"
] | 3d60c3aa3fe88dc7f81c68960a006bedef8d402980a721bd212a97e81f0e9360 |
import time
import unittest
import os
import numpy as np
from phonopy.interface.vasp import read_vasp
from phonopy.structure.cells import _get_smallest_vectors, get_primitive
from upho.harmonic.dynamical_matrix import (
get_smallest_vectors as get_smallest_vectors_upho)
POSCAR_DIR = os.path.join(os.path.dirname(__file__), 'poscars')
class TestRotationalProjector(unittest.TestCase):
def setUp(self):
self._atoms = read_vasp(os.path.join(POSCAR_DIR, 'POSCAR_fcc_2x2x2'))
self._primitive_matrix = np.array([
[0.00, 0.25, 0.25],
[0.25, 0.00, 0.25],
[0.25, 0.25, 0.00],
])
def test(self):
natoms = self._atoms.get_number_of_atoms()
primitive = get_primitive(self._atoms, self._primitive_matrix)
symprec = 1e-6
smallest_vectors0, multiplicity0 = _get_smallest_vectors(
self._atoms, primitive, symprec)
smallest_vectors1, multiplicity1 = get_smallest_vectors_upho(
self._atoms, primitive, symprec)
dt_old = 0.0
dt_new = 0.0
for i in range(natoms):
for j in range(primitive.get_number_of_atoms()):
t0 = time.time()
tmp0 = smallest_vectors0[i, j, :multiplicity0[i][j]]
t1 = time.time()
dt_old += t1 - t0
t0 = time.time()
tmp1 = smallest_vectors1[i, j, :multiplicity1[i][j]]
t1 = time.time()
dt_new += t1 - t0
print(tmp0)
print(tmp1)
self.assertTrue(np.array_equal(tmp0, tmp1))
print(dt_old)
print(dt_new)
if __name__ == "__main__":
unittest.main()
| yuzie007/ph_unfolder | tests/test_get_smallest_vectors.py | Python | mit | 1,720 | [
"VASP",
"phonopy"
] | c39a3f73ad4765f08c420bdae47623f84441cb08dc67a0eba3f5cfe20e400544 |
from __future__ import division
from builtins import input
from builtins import range
import numpy as np
from matplotlib import pyplot as plt
plt.interactive(True)
from pybasicbayes import models, distributions
GENERATE_DATA = True
###########################
# generate or load data #
###########################
alpha_0=5.0
obs_hypparams=dict(mu_0=np.zeros(2),sigma_0=np.eye(2),kappa_0=0.05,nu_0=5)
priormodel = models.Mixture(alpha_0=alpha_0,
components=[distributions.Gaussian(**obs_hypparams) for itr in range(30)])
data, _ = priormodel.generate(100)
del priormodel
plt.figure()
plt.plot(data[:,0],data[:,1],'kx')
plt.title('data')
input() # pause for effect
###############
# inference #
###############
posteriormodel = models.Mixture(alpha_0=alpha_0,
components=[distributions.Gaussian(**obs_hypparams) for itr in range(30)])
posteriormodel.add_data(data)
vlbs = []
plt.figure(2,figsize=(8,6))
posteriormodel.plot()
plt.figure(3,figsize=(8,6))
while True:
if input().lower() == 'break': # pause at each iteration
break
vlb = posteriormodel.meanfield_coordinate_descent_step()
plt.figure(2)
plt.clf()
posteriormodel.plot()
plt.figure(3)
plt.clf()
vlbs.append(vlb)
plt.plot(vlbs)
| mattjj/pybasicbayes | examples/meanfield_steps.py | Python | mit | 1,265 | [
"Gaussian"
] | 6c462556b23bb3df8ac06358f88e8fb4087de3ed914f180f99f8e952e2b421ba |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2015, Brian Coca <bcoca@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>
ANSIBLE_METADATA = {'status': ['stableinterface'],
'supported_by': 'community',
'version': '1.0'}
# This is a modification of @bcoca's `svc` module
DOCUMENTATION = '''
---
module: runit
author: "James Sumners (@jsumners)"
version_added: "2.3"
short_description: Manage runit services.
description:
- Controls runit services on remote hosts using the sv utility.
options:
name:
required: true
description:
- Name of the service to manage.
state:
required: false
choices: [ started, stopped, restarted, killed, reloaded, once ]
description:
- C(started)/C(stopped) are idempotent actions that will not run
commands unless necessary. C(restarted) will always bounce the
service (sv restart) and C(killed) will always bounce the service (sv force-stop).
C(reloaded) will send a HUP (sv reload).
C(once) will run a normally downed sv once (sv once), not really
an idempotent operation.
enabled:
required: false
choices: [ "yes", "no" ]
description:
- Wheater the service is enabled or not, if disabled it also implies stopped.
service_dir:
required: false
default: /var/service
description:
- directory runsv watches for services
service_src:
required: false
default: /etc/sv
description:
- directory where services are defined, the source of symlinks to service_dir.
'''
EXAMPLES = '''
# Example action to start sv dnscache, if not running
- sv:
name: dnscache
state: started
# Example action to stop sv dnscache, if running
- sv:
name: dnscache
state: stopped
# Example action to kill sv dnscache, in all cases
- sv:
name: dnscache
state: killed
# Example action to restart sv dnscache, in all cases
- sv:
name: dnscache
state: restarted
# Example action to reload sv dnscache, in all cases
- sv:
name: dnscache
state: reloaded
# Example using alt sv directory location
- sv:
name: dnscache
state: reloaded
service_dir: /run/service
'''
import platform
import shlex
from ansible.module_utils.pycompat24 import get_exception
from ansible.module_utils.basic import *
def _load_dist_subclass(cls, *args, **kwargs):
'''
Used for derivative implementations
'''
subclass = None
distro = kwargs['module'].params['distro']
# get the most specific superclass for this platform
if distro is not None:
for sc in cls.__subclasses__():
if sc.distro is not None and sc.distro == distro:
subclass = sc
if subclass is None:
subclass = cls
return super(cls, subclass).__new__(subclass)
class Sv(object):
"""
Main class that handles daemontools, can be subclassed and overridden in case
we want to use a 'derivative' like encore, s6, etc
"""
#def __new__(cls, *args, **kwargs):
# return _load_dist_subclass(cls, args, kwargs)
def __init__(self, module):
self.extra_paths = [ ]
self.report_vars = ['state', 'enabled', 'svc_full', 'src_full', 'pid', 'duration', 'full_state']
self.module = module
self.name = module.params['name']
self.service_dir = module.params['service_dir']
self.service_src = module.params['service_src']
self.enabled = None
self.full_state = None
self.state = None
self.pid = None
self.duration = None
self.svc_cmd = module.get_bin_path('sv', opt_dirs=self.extra_paths)
self.svstat_cmd = module.get_bin_path('sv', opt_dirs=self.extra_paths)
self.svc_full = '/'.join([ self.service_dir, self.name ])
self.src_full = '/'.join([ self.service_src, self.name ])
self.enabled = os.path.lexists(self.svc_full)
if self.enabled:
self.get_status()
else:
self.state = 'stopped'
def enable(self):
if os.path.exists(self.src_full):
try:
os.symlink(self.src_full, self.svc_full)
except OSError:
e = get_exception()
self.module.fail_json(path=self.src_full, msg='Error while linking: %s' % str(e))
else:
self.module.fail_json(msg="Could not find source for service to enable (%s)." % self.src_full)
def disable(self):
self.execute_command([self.svc_cmd,'force-stop',self.src_full])
try:
os.unlink(self.svc_full)
except OSError:
e = get_exception()
self.module.fail_json(path=self.svc_full, msg='Error while unlinking: %s' % str(e))
def get_status(self):
(rc, out, err) = self.execute_command([self.svstat_cmd, 'status', self.svc_full])
if err is not None and err:
self.full_state = self.state = err
else:
self.full_state = out
m = re.search('\(pid (\d+)\)', out)
if m:
self.pid = m.group(1)
m = re.search(' (\d+)s', out)
if m:
self.duration = m.group(1)
if re.search('run:', out):
self.state = 'started'
elif re.search('down:', out):
self.state = 'stopped'
else:
self.state = 'unknown'
return
def started(self):
return self.start()
def start(self):
return self.execute_command([self.svc_cmd, 'start', self.svc_full])
def stopped(self):
return self.stop()
def stop(self):
return self.execute_command([self.svc_cmd, 'stop', self.svc_full])
def once(self):
return self.execute_command([self.svc_cmd, 'once', self.svc_full])
def reloaded(self):
return self.reload()
def reload(self):
return self.execute_command([self.svc_cmd, 'reload', self.svc_full])
def restarted(self):
return self.restart()
def restart(self):
return self.execute_command([self.svc_cmd, 'restart', self.svc_full])
def killed(self):
return self.kill()
def kill(self):
return self.execute_command([self.svc_cmd, 'force-stop', self.svc_full])
def execute_command(self, cmd):
try:
(rc, out, err) = self.module.run_command(' '.join(cmd))
except Exception:
e = get_exception()
self.module.fail_json(msg="failed to execute: %s" % str(e))
return (rc, out, err)
def report(self):
self.get_status()
states = {}
for k in self.report_vars:
states[k] = self.__dict__[k]
return states
# ===========================================
# Main control flow
def main():
module = AnsibleModule(
argument_spec = dict(
name = dict(required=True),
state = dict(choices=['started', 'stopped', 'restarted', 'killed', 'reloaded', 'once']),
enabled = dict(required=False, type='bool'),
dist = dict(required=False, default='runit'),
service_dir = dict(required=False, default='/var/service'),
service_src = dict(required=False, default='/etc/sv'),
),
supports_check_mode=True,
)
module.run_command_environ_update = dict(LANG='C', LC_ALL='C', LC_MESSAGES='C', LC_CTYPE='C')
state = module.params['state']
enabled = module.params['enabled']
sv = Sv(module)
changed = False
orig_state = sv.report()
if enabled is not None and enabled != sv.enabled:
changed = True
if not module.check_mode:
try:
if enabled:
sv.enable()
else:
sv.disable()
except (OSError, IOError):
e = get_exception()
module.fail_json(msg="Could not change service link: %s" % str(e))
if state is not None and state != sv.state:
changed = True
if not module.check_mode:
getattr(sv,state)()
module.exit_json(changed=changed, sv=sv.report())
if __name__ == '__main__':
main()
| camradal/ansible | lib/ansible/modules/system/runit.py | Python | gpl-3.0 | 9,034 | [
"Brian"
] | feb3170cdd69c293a40289cfb0d8fe4969a9163f3f38956db32eff5fcf45a09e |
# CubETL
# Copyright (c) 2013-2019 Jose Juan Montes
# This is a CubETL example
# See: https://github.com/jjmontesl/cubetl
from cubetl import flow, fs, script, olap, table, geoip
from cubetl.cubes import cubes10
from cubetl.http import useragent
from cubetl.olap import sqlschema, query
from cubetl.olap.sql import TableMapper
from cubetl.sql import sql
from cubetl.table import cache
from cubetl.text import functions
from cubetl.util import log
def cubetl_config(ctx):
#ctx.include('${ ctx.library_path }/datetime.py')
#ctx.include('${ ctx.library_path }/geo.py')
#ctx.include('${ ctx.library_path }/net.py')
ctx.include('${ ctx.library_path }/http.py')
# Process configuration
ctx.props['db_url'] = 'sqlite:///loganalyzer.sqlite3'
ctx.props['domain'] = 'cubesviewer.com' # ctx.interpolate('${ }')
ctx.props['file_path'] = ctx.props.get('file_path', 'access.log')
ctx.props['download_extensions'] = 'zip, tgz, gz, 7z, rar, iso, msi, exe, avi, mp3, mp4, ogg, mkv, pdf'
ctx.props['download_extensions_list'] = [e.strip().lower() for e in ctx.props['download_extensions'].split(',')]
ctx.props['download_size_bytes'] = 10 * 1024 * 1024
# Database connection for loaded OLAP data
ctx.add('loganalyzer.sql.connection',
#sql.Connection(url=lambda ctx: ctx.props.get("db_url", None))
sql.Connection(url='sqlite:///loganalyzer.sqlite3'))
# Generate a SQL star schema and mappings automatically
sqlschema.OLAPToSQL.olap2sql(ctx, connection=ctx.get('loganalyzer.sql.connection'))
ctx.get('olap2sql.olapmapper').entity_mapper(ctx.get('cubetl.http.request')).store_mode = TableMapper.STORE_MODE_INSERT
# Processes a log file and loads the database for OLAP
ctx.add('loganalyzer.process', flow.Chain(steps=[
ctx.get('cubetl.config.print'),
# Generate a Cubes model
cubes10.Cubes10ModelWriter(olapmapper=ctx.get('olap2sql.olapmapper'),
model_path="loganalyzer.cubes-model.json",
config_path="loganalyzer.cubes-config.ini"),
script.Delete(['cubesmodel', 'cubesmodel_json']),
sql.Transaction(connection=ctx.get('loganalyzer.sql.connection')),
fs.FileLineReader(path='${ ctx.props["file_path"] }', encoding=None),
ctx.get('cubetl.http.parse.apache_combined'),
geoip.GeoIPFromAddress(data="${ m['address'] }"),
useragent.UserAgentParse(data="${ m['user_agent_string'] }"),
cache.CachedTableLookup(
table=ctx.get("cubetl.http.status.table"),
lookup={'status_code': lambda m: m['status_code']},
default={'status_description': 'Unknown'}),
script.Function(process_data),
ctx.get('cubetl.util.print'),
olap.Store(entity=ctx.get('cubetl.http.request'),
mapper=ctx.get('olap2sql.olapmapper')),
log.LogPerformance(),
]))
# This node runs several test queries
ctx.add('loganalyzer.query', flow.Chain(steps=[
#ctx.get('cubetl.config.print'),
query.OlapQueryAggregate(fact=ctx.get('cubetl.http.request'),
mapper=ctx.get('olap2sql.olapmapper'),
#drills=['referer.source'],
cuts={'contcountry.id': 16}),
#query.OlapQueryFacts(fact=ctx.get('cubetl.http.request'),
# mapper=ctx.get('olap2sql.olapmapper'),
# cuts={'contcountry': 16}),
#query.OlapQueryDimension(fact=ctx.get('cubetl.http.request'),
# mapper=ctx.get('olap2sql.olapmapper'),
# drill=['contcountry.country']),
ctx.get('cubetl.util.print'),
]))
def process_data(ctx, m):
m['datetime'] = functions.extract_date(m['date_string'], dayfirst=True)
m['served_bytes'] = 0 if m['served_bytes'] == '-' else int(m['served_bytes'])
m['client_address'] = m['address']
# For date dimension
m['year'] = m['datetime'].year
m['quarter'] = int((m["datetime"].month - 1) / 3) + 1
m['month'] = m['datetime'].month
m['day'] = m['datetime'].day
m['week'] = int(m["datetime"].strftime('%W'))
m['http_method'] = m['verb'].split(' ')[0]
m['protocol'] = m['verb'].split(' ')[-1]
m['referer_domain'] = ctx.f.text.urlparse(m['referer']).hostname
m['referer_path'] = ctx.f.text.urlparse(m['referer']).path
m['referer_origin'] = ("Internal" if m['referer_domain'].endswith(ctx.props['domain']) else "External") if m['referer_domain'] else "Unknown"
m['tld'] = m['referer_domain'].split('.')[-1] if (m['referer_domain'] and len(m['referer_domain'].split('.')) > 0) else ''
m['domain'] = m['referer_domain'].split('.')[-2] if (m['referer_domain'] and len(m['referer_domain'].split('.')) > 1) else ''
m['subdomain'] = m['referer_domain'].split('.')[-3] if (m['referer_domain'] and len(m['referer_domain'].split('.')) > 2) else ''
m['continent_code'] = functions.slugu(m["geoip_cont_name"]) if m["geoip_cont_name"] else "unknown"
m['continent_name'] = m["geoip_cont_name"]
m['country_iso2'] = m["geoip_country_code"]
m['country_name'] = m["geoip_country_name"]
m['user_agent_family'] = m['ua_user_agent_family']
m['user_agent_version'] = m['ua_user_agent_version_string']
m['operating_system_family'] = m['ua_os_family']
m['operating_system_version'] = m['ua_os_version_string']
m['device'] = m['ua_device_family']
m['is_mobile'] = m['ua_is_mobile']
m['is_tablet'] = m['ua_is_tablet']
m['is_pc'] = m['ua_is_pc']
m['is_bot'] = m['ua_is_bot']
m['status_description'] = "%s %s" % (m['status_code'], m['status_description'])
m['status_type_label'] = m['status_type']
m['status_type_code'] = functions.slugu(m['status_type'])
m['path'] = " ".join(m['verb'].split(' ')[1:-1]).split('?')[0]
m['path1'] = m['path'].split('/')[1] if len(m['path'].split('/')) > 1 else ""
m['path2'] = m['path'].split('/')[2] if len(m['path'].split('/')) > 2 else ""
m['path3'] = m['path'].split('/')[3] if len(m['path'].split('/')) > 3 else ""
m['path4'] = "/".join(m['path'].split('/')[4:]) if len(m['path'].split('/')) > 4 else ""
m['mimetype'] = functions.mimetype_guess(m['path']) or "Unknown/Unknown"
m['mimetype_type'] = m['mimetype'].split('/')[0]
m['mimetype_subtype'] = m['mimetype'].split('/')[1]
m['file_name'] = m['path'].split('/')[-1] if (len(m['path'].split('/')) > 0) else ""
m['file_extension'] = m['file_name'].split('.')[-1] if (len(m['file_name'].split('.')) > 1) else ""
m['is_download'] = m['file_extension'].lower() in ctx.props['download_extensions_list'] or int(m['served_bytes']) >= int(ctx.props['download_size_bytes'])
'''
def process_sessions(ctx, m):
# Check that time hasn't gone backwards
#if 'last_datetime' in ctx.props and m['datetime'] < ctx.props['last_datetime']:
# raise Exception("Log date going backwards")
#ctx.props['last_datetime'] = m['datetime']
# Calculate sessions
if 'sessions' not in ctx.props:
ctx.props['sessions'] = {}
sessions = ctx.props['sessions']
session_expiry_seconds = 30 * 60
session_key = "%s-%s" % (m['address'], m['user_agent_string'])
new_session = True
new_visitor = True
if session_key in sessions:
new_visitor = False
last_datetime = sessions[session_key]['last_time']
if (m['datetime'] - last_datetime).total_seconds() < session_expiry_seconds:
new_session = False
else:
session = {'session_key': session_key,
'start_time': m['datetime'],
'end_time': None,
'last_time': m['datetime'],
'visitor_type': 'new', # 'returning', 'unknown'
}
# response size category (small, medium, large...), and sub category (<1k, <10k, <100k, etc)
# response size metric in log2
# visitors / sessions / hits - track each user entry (visitor=ip+os+caching_analysis in session, session=time_span+ip+full-user-agent)
# first visit, last visit, entry pages/exit pages
# anomaly/500 (many 5xx any URL any IP in short period)
# anomaly/404 (many 4xx in short period same IP -visit)
# tracking javascript ??? (screen size, browser size, support, sessions, campaign / organic...)
# IP PTR -> SOA authority ( IP owner? )
# organic/etc by referer?? (requires db)
'''
| jjmontesl/cubetl | examples/loganalyzer/loganalyzer.py | Python | mit | 8,564 | [
"VisIt"
] | bab0929098d0426a2a3cdafac1388e8cec5d24e1e6e2ac43fa3085ffffc5fe1d |
# $Id$
from itcc.molecule import relalist
from itcc.tinker import molparam
__revision__ = '$Rev$'
def gettortype(mol, tor):
assert len(tor) == 4
return tuple([mol.atoms[idx].type for idx in tor])
def gettorsbytype(mol, types):
types = [molparam.torsion_uni(type_) for type_ in types]
result = {}
for typ in types:
result[typ] = []
mol.confirmconnect()
tors = relalist.genD(relalist.genconns(mol.connect))
for tor in tors:
typ = molparam.torsion_uni(gettortype(mol, tor))
if typ in types:
result[typ].append(tor)
return result
| lidaobing/itcc | itcc/tinker/analyze.py | Python | gpl-3.0 | 608 | [
"TINKER"
] | d59f50fd9ca2369cee8ae5223bc72d90b3a46acec87e66d0cfd1ba2295ce2ff4 |
'''
Created on Feb 5, 2014
@author: mborodin
'''
import tempfile
import xml.dom.minidom
import zipfile
import requests
import xlrd
def open_tempfile_from_url(url,tempfile_suffix):
filename = tempfile.mkstemp(suffix=tempfile_suffix)[1]
response = requests.get(url)
response_status_code = response.status_code
if (response.status_code != 200):
raise RuntimeError("URL %s return code %i" % (url, response_status_code))
with open(filename, 'wb') as output:
for buf in response.iter_content(65536):
output.write(buf)
return filename
def open_google_ss(google_key, output_format):
"""Download google spread sheet to a local temp file.
:param google_key: A key for google sreapsheet.
:param output_format: supported google download format(csv,xls,ods)
Returns a temp file path.
"""
url = "https://docs.google.com/spreadsheet/ccc?output=%s&key=%s" % (output_format, google_key)
return open_tempfile_from_url(url,'.%s' % output_format)
class XlrParser(object):
def __init__(self):
self.result_dictr = {}
def open_by_key(self,google_key):
"""Parse google spreadsheet as xls file.
:param google_key: A key for google sreapsheet.
Returns a dict tuple (result dict, color dict)
"""
with open(open_google_ss(google_key,'xls')) as f:
res = self.__parse_xsl(f)
return res
def open_by_open_file(self,file_object):
"""Parse xls file.
:param file_object: An open file descriptor.
Returns a dict tuple (result dict, color dict)
"""
return self.__parse_xsl(file_object)
def __parse_xsl(self, file_object):
nocolor = False
file_contents = file_object.read()
try:
book = xlrd.open_workbook(file_contents=file_contents, formatting_info=1)
except NotImplementedError:
book = xlrd.open_workbook(file_contents=file_contents)
nocolor = True
self.result_dict = {}
color_dict = {}
slice_index = 2
for sheet_index in range(book.nsheets):
sheet = book.sheet_by_index(sheet_index)
for row_index in range(sheet.nrows):
row_dict = {}
row_color_dict = {}
for col_index in range(sheet.ncols):
if(row_index >= 1):
cell_value = sheet.cell(row_index, col_index).value
if cell_value:
row_dict[col_index] = cell_value
if not nocolor:
xfx = sheet.cell_xf_index(row_index, col_index)
xf = book.xf_list[xfx]
row_color_dict[col_index] = xf.background.pattern_colour_index
if row_dict:
self.result_dict[slice_index] = row_dict
if color_dict:
color_dict[slice_index] = row_color_dict
slice_index += 1
return (self.result_dict, color_dict)
class OdfReader(object):
def __init__(self, googlekey):
"""
Open an ODF file.
"""
self.filename = open_google_ss(googlekey, 'ods')
self.m_odf = zipfile.ZipFile(self.filename)
self.filelist = self.m_odf.infolist()
self.parse_details() # Get the rows
def parse_details(self):
"""
Do the thing.
"""
ostr = self.m_odf.read('content.xml')
doc = xml.dom.minidom.parseString(ostr)
tbls = doc.getElementsByTagName('table:table')
self.details = {}
for t in tbls:
table_name = t.attributes['table:name'].value
# Select first spreadsheet
rows = t.getElementsByTagName('table:table-row')
nrows = 1
for r in rows:
cells = r.getElementsByTagName('table:table-cell')
htxt = {}
ic = 0
#alab=["brief","ds","format","jo","evfs","eva2","prio","evgen","simul","merge","digi","reco","rmerge","rtag","a2","a2merge","a2tag","LO","feff","NLO","gen","ecm","ef","comm","contact","store"]
for c in cells:
entry = c.firstChild
stxt = ''
try:
rep = int(c.attributes['table:number-columns-repeated'].value)
except:
rep = 1
if entry != None:
stxt = "notext" #TODO: Why it's here?
sstat = ""
for t in entry.childNodes:
if t.nodeType == t.TEXT_NODE:
intxt = t.data.encode('utf-8')
if stxt.find("notext") != -1:
stxt = intxt
else:
stxt = stxt + intxt
if nrows > 1 and len(stxt) > 0 :
htxt[ic] = stxt
ic += rep
if htxt:
self.details[nrows] = htxt
nrows += 1
def get_details(self):
"""
Return dictionary with contents
"""
return self.details
| kiae-grid/panda-bigmon-core | core/xls_parser.py | Python | apache-2.0 | 5,533 | [
"FEFF"
] | efb6c97d6f6658d4cb013b71ad85969f7c66a5e22acdfd6b6dd4bcfc85a95f3d |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A basic example demonstrating using JAX to do Gaussian process regression.
"""
from absl import app
from absl import flags
from functools import partial
from jax import grad
from jax import jit
from jax import vmap
from jax.config import config
import jax.numpy as jnp
import jax.random as random
import jax.scipy as scipy
import matplotlib.pyplot as plt
FLAGS = flags.FLAGS
def main(unused_argv):
numpts = 7
key = random.PRNGKey(0)
eye = jnp.eye(numpts)
def cov_map(cov_func, xs, xs2=None):
"""Compute a covariance matrix from a covariance function and data points.
Args:
cov_func: callable function, maps pairs of data points to scalars.
xs: array of data points, stacked along the leading dimension.
Returns:
A 2d array `a` such that `a[i, j] = cov_func(xs[i], xs[j])`.
"""
if xs2 is None:
return vmap(lambda x: vmap(lambda y: cov_func(x, y))(xs))(xs)
else:
return vmap(lambda x: vmap(lambda y: cov_func(x, y))(xs))(xs2).T
def softplus(x):
return jnp.logaddexp(x, 0.)
# Note, writing out the vectorized form of the identity
# ||x-y||^2 = <x-y,x-y> = ||x||^2 + ||y||^2 - 2<x,y>
# for computing squared distances would be more efficient (but less succinct).
def exp_quadratic(x1, x2):
return jnp.exp(-jnp.sum((x1 - x2)**2))
def gp(params, x, y, xtest=None, compute_marginal_likelihood=False):
noise = softplus(params['noise'])
amp = softplus(params['amplitude'])
ls = softplus(params['lengthscale'])
ymean = jnp.mean(y)
y = y - ymean
x = x / ls
train_cov = amp*cov_map(exp_quadratic, x) + eye * (noise + 1e-6)
chol = scipy.linalg.cholesky(train_cov, lower=True)
kinvy = scipy.linalg.solve_triangular(
chol.T, scipy.linalg.solve_triangular(chol, y, lower=True))
if compute_marginal_likelihood:
log2pi = jnp.log(2. * 3.1415)
ml = jnp.sum(
-0.5 * jnp.dot(y.T, kinvy) -
jnp.sum(jnp.log(jnp.diag(chol))) -
(numpts / 2.) * log2pi)
ml -= jnp.sum(-0.5 * jnp.log(2 * 3.1415) - jnp.log(amp)**2) # lognormal prior
return -ml
if xtest is not None:
xtest = xtest / ls
cross_cov = amp*cov_map(exp_quadratic, x, xtest)
mu = jnp.dot(cross_cov.T, kinvy) + ymean
v = scipy.linalg.solve_triangular(chol, cross_cov, lower=True)
var = (amp * cov_map(exp_quadratic, xtest) - jnp.dot(v.T, v))
return mu, var
marginal_likelihood = partial(gp, compute_marginal_likelihood=True)
predict = partial(gp, compute_marginal_likelihood=False)
grad_fun = jit(grad(marginal_likelihood))
# Covariance hyperparameters to be learned
params = {"amplitude": jnp.zeros((1, 1)),
"noise": jnp.zeros((1, 1)) - 5.,
"lengthscale": jnp.zeros((1, 1))}
momentums = dict([(k, p * 0.) for k, p in params.items()])
scales = dict([(k, p * 0. + 1.) for k, p in params.items()])
lr = 0.01 # Learning rate
def train_step(params, momentums, scales, x, y):
grads = grad_fun(params, x, y)
for k in params:
momentums[k] = 0.9 * momentums[k] + 0.1 * grads[k][0]
scales[k] = 0.9 * scales[k] + 0.1 * grads[k][0]**2
params[k] -= lr * momentums[k]/jnp.sqrt(scales[k] + 1e-5)
return params, momentums, scales
# Create a really simple toy 1D function
y_fun = lambda x: jnp.sin(x) + 0.1 * random.normal(key, shape=(x.shape[0], 1))
x = (random.uniform(key, shape=(numpts, 1)) * 4.) + 1
y = y_fun(x)
xtest = jnp.linspace(0, 6., 200)[:, None]
for i in range(1000):
params, momentums, scales = train_step(params, momentums, scales, x, y)
if i % 50 == 0:
ml = marginal_likelihood(params, x, y)
print("Step: %d, neg marginal likelihood: %f" % (i, ml))
print(params)
mu, var = predict(params, x, y, xtest)
std = jnp.sqrt(jnp.diag(var))
plt.plot(x, y, "k.")
plt.plot(xtest, mu)
plt.fill_between(xtest.flatten(),
mu.flatten() - std * 2, mu.flatten() + std * 2)
if __name__ == "__main__":
config.config_with_absl()
app.run(main)
| google/jax | examples/gaussian_process_regression.py | Python | apache-2.0 | 4,604 | [
"Gaussian"
] | c0946ecd4cf126d4da62a1d3b04c712871afcd12cf467171ff4329f244ecf6aa |
#Input file for test problem for pyaneti
#Created by Barragan O.
#This file contains the basic parameters to change for simple pyaneti run
#There are more flags which can control the input/output of the code
#They can be found inside src/default.py, all the flags inside this file
#can be changed inside the input file.
#Telescope labels
#This vector has to be filled with the label that we use for each telescope in the RV data file
telescopes = ['S']
#This vector has to be filled with the name of each telescope telescopes[i]
telescopes_labels = ['Super_telescope']
#Input files
#fname_rv contains the RV data
fname_rv = ['earth_rv.dat']
#fname_tr contains the transit data
fname_tr = ['earth_lc.dat']
#MCMC controls
#the thin factor for the chains
thin_factor = 1
#The number of iterations to be taken into account
#The TOTAL number of iterations for the burn-in phase is thin_factor*niter
niter = 500
#Number of independent Markov chains for the ensemble sampler
nchains = 100
#Choose the method that we want to use
# mcmc -> runs the mcmc fit program
# plot -> this option create the plots only if a previus run was done
method = 'mcmc'
#method = 'plot'
#If you want a plot with the seaborn library, is_seaborn_plot has to be True
is_seaborn_plot = False
#Define the star parameters to calculate the planet parameters
mstar_mean = 1.0
mstar_sigma = 0.1
rstar_mean = 1.0
rstar_sigma = 0.1
tstar_mean = 5772.0
tstar_sigma = 50.
#What units do you prefer for your planet parameters?
# earth, jupiter or solar
unit_mass = 'earth'
#If we want posterior, correlation and/or chain plots these options have to be set True
is_plot_posterior = True
is_plot_correlations = True
is_plot_chains = False
#Are we setting gaussian priors on the semi-major axis based on the stellar parameters?
a_from_kepler = [True]
#if you are in my_test uncomment the next line
#a_from_kepler = [False]
#We want to fit transit and RV
#For a pure RV fit, fit_tr has to be False
#For a pure TR fit, fit_rv has to be False
#For multi-planet fits fit_rv and fit_tr have the form [True,True,False,...]
#one element for each planet.
fit_rv = [True]
fit_tr = [True]
#is_ew controls the parametrization sqrt(e)sin w and sqrt(e) cos w
#if True we fit for the parametrization parameters
#if False we fit for e and w
#Default is True
is_ew = True
#Prior section
# f -> fixed value
# u -> Uniform priors
# g -> Gaussian priors
fit_t0 = ['u'] #We fit for t0 with uniform priors
fit_P = ['u'] #We fit for P with uniform priors
fit_ew1= ['f'] #We fix sqrt(e) sin w, it works only if is_ew = True
fit_ew2= ['f'] #We fix sqrt(e) cos w, it works only if is_ew = True
fit_e = ['f'] #We fix e, it works only if is_ew = False
fit_w = ['f'] #We fix w, it works only if is_ew = False
fit_b = ['f'] #We fix the impact factor
fit_a = ['g'] #We fit a with gaussian priors (given by the stellar parameters)
fit_rp = ['u'] #We fit rp with uniform priors
fit_k = ['u'] #We fit k with uniform priors
fit_v0 = 'u' #We fit systemc velicities with uniform priors
fit_q1 = 'g' #We fit q1 with gaussian priors
fit_q2 = 'g' #We fit q2 with gaussian priors
#if you are in my_test uncomment the next two line
#fit_b = ['u'] #We fit the impact factor
#fit_a = ['u'] #We fit the scaled semi-major axis
#Prior ranges for a parameter A
#if 'f' is selected for the parameter A, A is fixed to the one given by min_A
#if 'u' is selected for the parameter A, sets uniform priors between min_A and max_A
#if 'g' is selected for the parameter A, sets gaussian priors with mean min_A and standard deviation max_A
min_t0 = [2448285.05]
max_t0 = [2448285.15]
min_P = [365.206]
max_P = [365.306]
min_ew1 = [0.0]
min_ew2 = [0.0]
max_ew1 = [1.0]
max_ew2 = [1.0]
min_a = [200.]
max_a = [250.]
min_b = [0.0]
max_b = [1.0]
min_k = [0.0]
max_k = [0.001]
min_rp = [0.0]
max_rp = [0.1]
min_q1 = 0.3464
max_q1 = 0.05
min_q2 = 0.2839
max_q2 = 0.05
| oscaribv/pyaneti | inpy/test/input_fit.py | Python | gpl-3.0 | 3,970 | [
"Gaussian"
] | 4504cf3f891cf64ed75b8df5fb498f5fff5be60e20f166ca282b186f251968ca |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import time
# Configuration, please edit
# Data about this site
BLOG_AUTHOR = "Matías Lang"
BLOG_TITLE = "Nodo Las Pircas"
# This is the main URL for your site. It will be used
# in a prominent link
SITE_URL = "http://laspircas.lan/"
# This is the URL where nikola's output will be deployed.
# If not set, defaults to SITE_URL
# BASE_URL = "http://getnikola.com/"
BLOG_EMAIL = "shareman1204@gmail.com"
BLOG_DESCRIPTION = "Sitio web del Nodo Las Pircas de BuenosAiresLibre"
# Nikola is multilingual!
#
# Currently supported languages are:
# en English
# bg Bulgarian
# ca Catalan
# zh_cn Chinese (Simplified)
# hr Croatian
# nl Dutch
# fr French
# el Greek [NOT gr!]
# de German
# it Italian
# jp Japanese
# fa Persian
# pl Polish
# pt_br Portuguese (Brasil)
# ru Russian
# es Spanish
# tr_tr Turkish (Turkey)
#
# If you want to use Nikola with a non-supported language you have to provide
# a module containing the necessary translations
# (p.e. look at the modules at: ./nikola/data/themes/default/messages/fr.py).
# If a specific post is not translated to a language, then the version
# in the default language will be shown instead.
# What is the default language?
DEFAULT_LANG = "es"
# What other languages do you have?
# The format is {"translationcode" : "path/to/translation" }
# the path will be used as a prefix for the generated pages location
TRANSLATIONS = {
DEFAULT_LANG: "",
# Example for another language:
# "es": "./es",
}
# Links for the sidebar / navigation bar.
# You should provide a key-value pair for each used language.
NAVIGATION_LINKS = {
DEFAULT_LANG: (
('/archive.html', 'Archivo'),
('/categories/index.html', 'Tags'),
('/shared', 'Documentos compartidos'),
('/rss.xml', 'RSS'),
),
}
# Below this point, everything is optional
# POSTS and PAGES contains (wildcard, destination, template) tuples.
#
# The wildcard is used to generate a list of reSt source files
# (whatever/thing.txt).
#
# That fragment could have an associated metadata file (whatever/thing.meta),
# and opcionally translated files (example for spanish, with code "es"):
# whatever/thing.txt.es and whatever/thing.meta.es
#
# From those files, a set of HTML fragment files will be generated:
# cache/whatever/thing.html (and maybe cache/whatever/thing.html.es)
#
# These files are combinated with the template to produce rendered
# pages, which will be placed at
# output / TRANSLATIONS[lang] / destination / pagename.html
#
# where "pagename" is the "slug" specified in the metadata file.
#
# The difference between POSTS and PAGES is that POSTS are added
# to feeds and are considered part of a blog, while PAGES are
# just independent HTML pages.
#
POSTS = (
("posts/*.txt", "posts", "post.tmpl"),
("posts/*.rst", "posts", "post.tmpl"),
("posts/*.md", "posts", "post.tmpl"),
("posts/*.html", "posts", "post.tmpl"),
)
PAGES = (
("stories/*.txt", "stories", "story.tmpl"),
("stories/*.rst", "stories", "story.tmpl"),
("stories/*.md", "stories", "story.tmpl"),
("stories/*.html", "stories", "story.tmpl"),
)
# One or more folders containing files to be copied as-is into the output.
# The format is a dictionary of "source" "relative destination".
# Default is:
# FILES_FOLDERS = {'files': '' }
# Which means copy 'files' into 'output'
# A mapping of languages to file-extensions that represent that language.
# Feel free to add or delete extensions to any list, but don't add any new
# compilers unless you write the interface for it yourself.
#
# 'rest' is reStructuredText
# 'markdown' is MarkDown
# 'html' assumes the file is html and just copies it
COMPILERS = {
"rest": ('.txt', '.rst'),
"markdown": ('.md', '.mdown', '.markdown'),
"textile": ('.textile',),
"txt2tags": ('.t2t',),
"bbcode": ('.bb',),
"wiki": ('.wiki',),
"ipynb": ('.ipynb',),
"html": ('.html', '.htm'),
# Pandoc detects the input from the source filename
# but is disabled by default as it would conflict
# with many of the others.
# "pandoc": ('.rst', '.md', '.txt'),
}
# Create by default posts in one file format?
# Set to False for two-file posts, with separate metadata.
# ONE_FILE_POSTS = True
# If this is set to True, then posts that are not translated to a language
# LANG will not be visible at all in the pages in that language.
# If set to False, the DEFAULT_LANG version will be displayed for
# untranslated posts.
# HIDE_UNTRANSLATED_POSTS = False
# Paths for different autogenerated bits. These are combined with the
# translation paths.
# Final locations are:
# output / TRANSLATION[lang] / TAG_PATH / index.html (list of tags)
# output / TRANSLATION[lang] / TAG_PATH / tag.html (list of posts for a tag)
# output / TRANSLATION[lang] / TAG_PATH / tag.xml (RSS feed for a tag)
# TAG_PATH = "categories"
# If TAG_PAGES_ARE_INDEXES is set to True, each tag's page will contain
# the posts themselves. If set to False, it will be just a list of links.
# TAG_PAGES_ARE_INDEXES = True
# Final location is output / TRANSLATION[lang] / INDEX_PATH / index-*.html
# INDEX_PATH = ""
# Create per-month archives instead of per-year
# CREATE_MONTHLY_ARCHIVE = False
# Final locations for the archives are:
# output / TRANSLATION[lang] / ARCHIVE_PATH / ARCHIVE_FILENAME
# output / TRANSLATION[lang] / ARCHIVE_PATH / YEAR / index.html
# output / TRANSLATION[lang] / ARCHIVE_PATH / YEAR / MONTH / index.html
# ARCHIVE_PATH = ""
# ARCHIVE_FILENAME = "archive.html"
# Final locations are:
# output / TRANSLATION[lang] / RSS_PATH / rss.xml
# RSS_PATH = ""
# Number of posts in RSS feeds
# FEED_LENGTH = 10
# Slug the Tag URL easier for users to type, special characters are
# often removed or replaced as well.
# SLUG_TAG_PATH = True
# A list of redirection tuples, [("foo/from.html", "/bar/to.html")].
#
# A HTML file will be created in output/foo/from.html that redirects
# to the "/bar/to.html" URL. notice that the "from" side MUST be a
# relative URL.
#
# If you don't need any of these, just set to []
# REDIRECTIONS = []
# Commands to execute to deploy. Can be anything, for example,
# you may use rsync:
# "rsync -rav output/* joe@my.site:/srv/www/site"
# And then do a backup, or ping pingomatic.
# To do manual deployment, set it to []
DEPLOY_COMMANDS = [
"rsync -rav output/ root@192.168.2.23:/www"
]
# Where the output site should be located
# If you don't use an absolute path, it will be considered as relative
# to the location of conf.py
# OUTPUT_FOLDER = 'output'
# where the "cache" of partial generated content should be located
# default: 'cache'
# CACHE_FOLDER = 'cache'
# Filters to apply to the output.
# A directory where the keys are either: a file extensions, or
# a tuple of file extensions.
#
# And the value is a list of commands to be applied in order.
#
# Each command must be either:
#
# A string containing a '%s' which will
# be replaced with a filename. The command *must* produce output
# in place.
#
# Or:
#
# A python callable, which will be called with the filename as
# argument.
#
# By default, there are no filters.
#
# Many filters are shipped with Nikola. A list is available in the manual:
# <http://getnikola.com/handbook.html#post-processing-filters>
# FILTERS = {
# ".jpg": ["jpegoptim --strip-all -m75 -v %s"],
# }
# Create a gzipped copy of each generated file. Cheap server-side optimization.
# GZIP_FILES = False
# File extensions that will be compressed
# GZIP_EXTENSIONS = ('.txt', '.htm', '.html', '.css', '.js', '.json')
# Use an external gzip command? None means no.
# Example: GZIP_COMMAND = "pigz -k {filename}"
# GZIP_COMMAND = None
# #############################################################################
# Image Gallery Options
# #############################################################################
# Galleries are folders in galleries/
# Final location of galleries will be output / GALLERY_PATH / gallery_name
# GALLERY_PATH = "galleries"
# THUMBNAIL_SIZE = 180
# MAX_IMAGE_SIZE = 1280
# USE_FILENAME_AS_TITLE = True
# #############################################################################
# HTML fragments and diverse things that are used by the templates
# #############################################################################
# Data about post-per-page indexes
# INDEXES_TITLE = "" # If this is empty, the default is BLOG_TITLE
# INDEXES_PAGES = "" # If this is empty, the default is 'old posts page %d'
# translated
# Name of the theme to use.
THEME = "buenosaireslibre"
# Color scheme to be used for code blocks. If your theme provides
# "assets/css/code.css" this is ignored.
# Can be any of autumn borland bw colorful default emacs friendly fruity manni
# monokai murphy native pastie perldoc rrt tango trac vim vs
# CODE_COLOR_SCHEME = 'default'
# If you use 'site-reveal' theme you can select several subthemes
# THEME_REVEAL_CONFIG_SUBTHEME = 'sky'
# You can also use: beige/serif/simple/night/default
# Again, if you use 'site-reveal' theme you can select several transitions
# between the slides
# THEME_REVEAL_CONFIG_TRANSITION = 'cube'
# You can also use: page/concave/linear/none/default
# date format used to display post dates.
# (str used by datetime.datetime.strftime)
# DATE_FORMAT = '%Y-%m-%d %H:%M'
# FAVICONS contains (name, file, size) tuples.
# Used for create favicon link like this:
# <link rel="name" href="file" sizes="size"/>
# For creating favicons, take a look at:
# http://www.netmagazine.com/features/create-perfect-favicon
# FAVICONS = {
# ("icon", "/favicon.ico", "16x16"),
# ("icon", "/icon_128x128.png", "128x128"),
# }
# Show only teasers in the index pages? Defaults to False.
INDEX_TEASERS = True
# A HTML fragment with the Read more... link.
# The following tags exist and are replaced for you:
# {link} A link to the full post page.
# {read_more} The string “Read more” in the current language.
# {{ A literal { (U+007B LEFT CURLY BRACKET)
# }} A literal } (U+007D RIGHT CURLY BRACKET)
# READ_MORE_LINK = '<p class="more"><a href="{link}">{read_more}…</a></p>'
# A HTML fragment describing the license, for the sidebar.
LICENSE = "GPLv3"
# I recommend using the Creative Commons' wizard:
# http://creativecommons.org/choose/
# LICENSE = """
# <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/2.5/ar/">
# <img alt="Creative Commons License BY-NC-SA"
# style="border-width:0; margin-bottom:12px;"
# src="http://i.creativecommons.org/l/by-nc-sa/2.5/ar/88x31.png"></a>"""
# A small copyright notice for the page footer (in HTML).
# Default is ''
CONTENT_FOOTER = 'Contents © {date} <a href="mailto:{email}">{author}</a> - Powered by <a href="http://getnikola.com">Nikola</a> {license}'
CONTENT_FOOTER = CONTENT_FOOTER.format(email=BLOG_EMAIL,
author=BLOG_AUTHOR,
date=time.gmtime().tm_year,
license=LICENSE)
# To use comments, you can choose between different third party comment
# systems, one of "disqus", "livefyre", "intensedebate", "moot",
# "googleplus" or "facebook"
COMMENT_SYSTEM = None
# And you also need to add your COMMENT_SYSTEM_ID which
# depends on what comment system you use. The default is
# "nikolademo" which is a test account for Disqus. More information
# is in the manual.
COMMENT_SYSTEM_ID = ""
# Create index.html for story folders?
# STORY_INDEX = False
# Enable comments on story pages?
# COMMENTS_IN_STORIES = False
# Enable comments on picture gallery pages?
# COMMENTS_IN_GALLERIES = False
# What file should be used for directory indexes?
# Defaults to index.html
# Common other alternatives: default.html for IIS, index.php
# INDEX_FILE = "index.html"
# If a link ends in /index.html, drop the index.html part.
# http://mysite/foo/bar/index.html => http://mysite/foo/bar/
# (Uses the INDEX_FILE setting, so if that is, say, default.html,
# it will instead /foo/default.html => /foo)
# (Note: This was briefly STRIP_INDEX_HTML in v 5.4.3 and 5.4.4)
# Default = False
# STRIP_INDEXES = False
# Should the sitemap list directories which only include other directories
# and no files.
# Default to True
# If this is False
# e.g. /2012 includes only /01, /02, /03, /04, ...: don't add it to the sitemap
# if /2012 includes any files (including index.html)... add it to the sitemap
# SITEMAP_INCLUDE_FILELESS_DIRS = True
# Instead of putting files in <slug>.html, put them in
# <slug>/index.html. Also enables STRIP_INDEXES
# This can be disabled on a per-page/post basis by adding
# .. pretty_url: False
# to the metadata
# PRETTY_URLS = False
# If True, publish future dated posts right away instead of scheduling them.
# Defaults to False.
# FUTURE_IS_NOW = False
# If True, future dated posts are allowed in deployed output
# Only the individual posts are published/deployed; not in indexes/sitemap
# Generally, you want FUTURE_IS_NOW and DEPLOY_FUTURE to be the same value.
# DEPLOY_FUTURE = False
# If False, draft posts will not be deployed
# DEPLOY_DRAFTS = True
# Allows scheduling of posts using the rule specified here (new_post -s)
# Specify an iCal Recurrence Rule: http://www.kanzaki.com/docs/ical/rrule.html
# SCHEDULE_RULE = ''
# If True, use the scheduling rule to all posts by default
# SCHEDULE_ALL = False
# If True, schedules post to today if possible, even if scheduled hour is over
# SCHEDULE_FORCE_TODAY = False
# Do you want a add a Mathjax config file?
# MATHJAX_CONFIG = ""
# If you are using the compile-ipynb plugin, just add this one:
#MATHJAX_CONFIG = """
#<script type="text/x-mathjax-config">
#MathJax.Hub.Config({
# tex2jax: {
# inlineMath: [ ['$','$'], ["\\\(","\\\)"] ],
# displayMath: [ ['$$','$$'], ["\\\[","\\\]"] ]
# },
# displayAlign: 'left', // Change this to 'center' to center equations.
# "HTML-CSS": {
# styles: {'.MathJax_Display': {"margin": 0}}
# }
#});
#</script>
#"""
# What MarkDown extensions to enable?
# You will also get gist, nikola and podcast because those are
# done in the code, hope you don't mind ;-)
# MARKDOWN_EXTENSIONS = ['fenced_code', 'codehilite']
# Social buttons. This is sample code for AddThis (which was the default for a
# long time). Insert anything you want here, or even make it empty.
SOCIAL_BUTTONS_CODE = ""
# Hide link to source for the posts?
# HIDE_SOURCELINK = False
# Copy the source files for your pages?
# Setting it to False implies HIDE_SOURCELINK = True
# COPY_SOURCES = True
# Modify the number of Post per Index Page
# Defaults to 10
# INDEX_DISPLAY_POST_COUNT = 10
# RSS_LINK is a HTML fragment to link the RSS or Atom feeds. If set to None,
# the base.tmpl will use the feed Nikola generates. However, you may want to
# change it for a feedburner feed or something else.
# RSS_LINK = None
# Show only teasers in the RSS feed? Default to True
RSS_TEASERS = False
# A search form to search this site, for the sidebar. You can use a google
# custom search (http://www.google.com/cse/)
# Or a duckduckgo search: https://duckduckgo.com/search_box.html
# Default is no search form.
# SEARCH_FORM = ""
#
# This search form works for any site and looks good in the "site" theme where
# it appears on the navigation bar:
#
#SEARCH_FORM = """
#<!-- Custom search -->
#<form method="get" id="search" action="http://duckduckgo.com/"
# class="navbar-form pull-left">
#<input type="hidden" name="sites" value="%s"/>
#<input type="hidden" name="k8" value="#444444"/>
#<input type="hidden" name="k9" value="#D51920"/>
#<input type="hidden" name="kt" value="h"/>
#<input type="text" name="q" maxlength="255"
# placeholder="Search…" class="span2" style="margin-top: 4px;"/>
#<input type="submit" value="DuckDuckGo Search" style="visibility: hidden;" />
#</form>
#<!-- End of custom search -->
#""" % SITE_URL
#
# If you prefer a google search form, here's an example that should just work:
#SEARCH_FORM = """
#<!-- Custom search with google-->
#<form id="search" action="http://google.com/search" method="get" class="navbar-form pull-left">
#<input type="hidden" name="q" value="site:%s" />
#<input type="text" name="q" maxlength="255" results="0" placeholder="Search"/>
#</form>
#<!-- End of custom search -->
#""" % SITE_URL
# Also, there is a local search plugin you can use, based on Tipue, but it requires setting several
# options:
# SEARCH_FORM = """
# <span class="navbar-form pull-left">
# <input type="text" id="tipue_search_input">
# </span>"""
#
# BODY_END = """
# <script type="text/javascript" src="/assets/js/tipuesearch_set.js"></script>
# <script type="text/javascript" src="/assets/js/tipuesearch.js"></script>
# <script type="text/javascript">
# $(document).ready(function() {
# $('#tipue_search_input').tipuesearch({
# 'mode': 'json',
# 'contentLocation': '/assets/js/tipuesearch_content.json',
# 'showUrl': false
# });
# });
# </script>
# """
# EXTRA_HEAD_DATA = """
# <link rel="stylesheet" type="text/css" href="/assets/css/tipuesearch.css">
# <div id="tipue_search_content" style="margin-left: auto; margin-right: auto; padding: 20px;"></div>
# """
# ENABLED_EXTRAS = ['local_search']
#
# Use content distribution networks for jquery and twitter-bootstrap css and js
# If this is True, jquery is served from the Google CDN and twitter-bootstrap
# is served from the NetDNA CDN
# Set this to False if you want to host your site without requiring access to
# external resources.
# USE_CDN = False
# Extra things you want in the pages HEAD tag. This will be added right
# before </HEAD>
# EXTRA_HEAD_DATA = ""
# Google analytics or whatever else you use. Added to the bottom of <body>
# in the default template (base.tmpl).
# BODY_END = ""
# The possibility to extract metadata from the filename by using a
# regular expression.
# To make it work you need to name parts of your regular expression.
# The following names will be used to extract metadata:
# - title
# - slug
# - date
# - tags
# - link
# - description
#
# An example re is the following:
# '(?P<date>\d{4}-\d{2}-\d{2})-(?P<slug>.*)-(?P<title>.*)\.md'
# FILE_METADATA_REGEXP = None
# Additional metadata that is added to a post when creating a new_post
# ADDITIONAL_METADATA = {}
# Nikola supports Twitter Card summaries / Open Graph.
# Twitter cards make it possible for you to attach media to Tweets
# that link to your content.
#
# IMPORTANT:
# Please note, that you need to opt-in for using Twitter Cards!
# To do this please visit
# https://dev.twitter.com/form/participate-twitter-cards
#
# Uncomment and modify to following lines to match your accounts.
# Specifying the id for either 'site' or 'creator' will be preferred
# over the cleartext username. Specifying an ID is not necessary.
# Displaying images is currently not supported.
# TWITTER_CARD = {
# # 'use_twitter_cards': True, # enable Twitter Cards / Open Graph
# # 'site': '@website', # twitter nick for the website
# # 'site:id': 123456, # Same as site, but the website's Twitter user ID
# # instead.
# # 'creator': '@username', # Username for the content creator / author.
# # 'creator:id': 654321, # Same as creator, but the Twitter user's ID.
# }
# If you want to use formatted post time in W3C-DTF Format
# (ex. 2012-03-30T23:00:00+02:00),
# set timzone if you want a localized posted date.
#
# TIMEZONE = 'Europe/Zurich'
# If webassets is installed, bundle JS and CSS to make site loading faster
# USE_BUNDLES = True
# Plugins you don't want to use. Be careful :-)
# DISABLED_PLUGINS = ["render_galleries"]
# Experimental plugins - use at your own risk.
# They probably need some manual adjustments - please see their respective
# readme.
# ENABLED_EXTRAS = [
# 'planetoid',
# 'ipynb',
# 'local_search',
# 'render_mustache',
# ]
# List of regular expressions, links matching them will always be considered
# valid by "nikola check -l"
# LINK_CHECK_WHITELIST = []
# If set to True, enable optional hyphenation in your posts (requires pyphen)
# HYPHENATE = False
# Put in global_context things you want available on all your templates.
# It can be anything, data, functions, modules, etc.
GLOBAL_CONTEXT = {}
| sh4r3m4n/Nikola-BuenosAiresLibre | conf.py | Python | gpl-3.0 | 20,401 | [
"VisIt"
] | 01f3e958795f1e8cf90e2501ceaa45d720bbc91953a1036c8c09ff1542a99fc4 |
# coding=utf-8
import base64
import datetime
import json
import time
import mock
from nose.tools import eq_, ok_
from nose.plugins.attrib import attr
from pyquery import PyQuery as pq
from urlparse import urlparse
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.core import mail
from django.db.models import Q
from django.test.client import (FakePayload, encode_multipart,
BOUNDARY, CONTENT_TYPE_RE, MULTIPART_CONTENT)
from django.http import Http404
from django.utils.encoding import smart_str
import constance.config
from waffle.models import Flag, Switch
from kuma.authkeys.models import Key
from kuma.core.cache import memcache as cache
from kuma.core.helpers import urlparams
from kuma.core.models import IPBan
from kuma.core.tests import post, get, override_constance_settings
from kuma.core.urlresolvers import reverse
from kuma.users.tests import UserTestCase, user
from ..content import get_seo_description
from ..events import EditDocumentEvent
from ..models import (Document, Revision, RevisionIP, DocumentZone,
DocumentTag, DocumentDeletionLog)
from ..tests import (doc_rev, document, new_document_data, revision,
normalize_html, create_template_test_users,
make_translation, WikiTestCase, FakeResponse)
from ..forms import MIDAIR_COLLISION
class RedirectTests(UserTestCase, WikiTestCase):
"""Tests for the REDIRECT wiki directive"""
localizing_client = True
def test_redirect_suppression(self):
"""The document view shouldn't redirect when passed redirect=no."""
redirect, _ = doc_rev('REDIRECT <a class="redirect" '
'href="/en-US/docs/blah">smoo</a>')
url = redirect.get_absolute_url() + '?redirect=no'
response = self.client.get(url, follow=True)
self.assertContains(response, 'REDIRECT ')
def test_redirects_only_internal(self):
"""Ensures redirects cannot be used to link to other sites"""
redirect, _ = doc_rev('REDIRECT <a class="redirect" '
'href="//davidwalsh.name">DWB</a>')
url = redirect.get_absolute_url()
response = self.client.get(url, follow=True)
self.assertContains(response, 'DWB')
def test_redirects_only_internal_2(self):
"""Ensures redirects cannot be used to link to other sites"""
redirect, _ = doc_rev('REDIRECT <a class="redirect" '
'href="http://davidwalsh.name">DWB</a>')
url = redirect.get_absolute_url()
response = self.client.get(url, follow=True)
self.assertContains(response, 'DWB')
def test_self_redirect_suppression(self):
"""The document view shouldn't redirect to itself."""
slug = 'redirdoc'
html = ('REDIRECT <a class="redirect" href="/en-US/docs/%s">smoo</a>' %
slug)
doc = document(title='blah', slug=slug, html=html, save=True,
locale=settings.WIKI_DEFAULT_LANGUAGE)
rev = revision(document=doc, content=html, is_approved=True, save=True)
response = self.client.get(doc.get_absolute_url(), follow=True)
self.assertContains(response, html)
class LocaleRedirectTests(UserTestCase, WikiTestCase):
"""Tests for fallbacks to en-US and such for slug lookups."""
# Some of these may fail or be invalid if your WIKI_DEFAULT_LANGUAGE is de.
localizing_client = True
def test_fallback_to_translation(self):
"""If a slug isn't found in the requested locale but is in the default
locale and if there is a translation of that default-locale document to
the requested locale, the translation should be served."""
en_doc, de_doc = self._create_en_and_de_docs()
response = self.client.get(reverse('wiki.document',
args=(en_doc.slug,),
locale='de'),
follow=True)
self.assertRedirects(response, de_doc.get_absolute_url())
def test_fallback_with_query_params(self):
"""The query parameters should be passed along to the redirect."""
en_doc, de_doc = self._create_en_and_de_docs()
url = reverse('wiki.document', args=[en_doc.slug], locale='de')
response = self.client.get(url + '?x=y&x=z', follow=True)
self.assertRedirects(response, de_doc.get_absolute_url() + '?x=y&x=z')
def test_redirect_with_no_slug(self):
"""Bug 775241: Fix exception in redirect for URL with ui-locale"""
loc = settings.WIKI_DEFAULT_LANGUAGE
url = '/%s/docs/%s/' % (loc, loc)
try:
self.client.get(url, follow=True)
except Http404, e:
pass
except Exception, e:
self.fail("The only exception should be a 404, not this: %s" % e)
def _create_en_and_de_docs(self):
en = settings.WIKI_DEFAULT_LANGUAGE
en_doc = document(locale=en, slug='english-slug', save=True)
de_doc = document(locale='de', parent=en_doc, save=True)
de_rev = revision(document=de_doc, is_approved=True, save=True)
return en_doc, de_doc
class ViewTests(UserTestCase, WikiTestCase):
fixtures = UserTestCase.fixtures + ['wiki/documents.json']
localizing_client = True
@attr('bug875349')
def test_json_view(self):
expected_tags = sorted(['foo', 'bar', 'baz'])
expected_review_tags = sorted(['tech', 'editorial'])
doc = Document.objects.get(pk=1)
doc.tags.set(*expected_tags)
doc.current_revision.review_tags.set(*expected_review_tags)
url = reverse('wiki.json', locale=settings.WIKI_DEFAULT_LANGUAGE)
resp = self.client.get(url, {'title': 'an article title'})
eq_(200, resp.status_code)
data = json.loads(resp.content)
eq_('article-title', data['slug'])
result_tags = sorted([str(x) for x in data['tags']])
eq_(expected_tags, result_tags)
result_review_tags = sorted([str(x) for x in data['review_tags']])
eq_(expected_review_tags, result_review_tags)
url = reverse('wiki.json_slug', args=('article-title',),
locale=settings.WIKI_DEFAULT_LANGUAGE)
Switch.objects.create(name='application_ACAO', active=True)
resp = self.client.get(url)
ok_('Access-Control-Allow-Origin' in resp)
eq_('*', resp['Access-Control-Allow-Origin'])
eq_(200, resp.status_code)
data = json.loads(resp.content)
eq_('an article title', data['title'])
ok_('translations' in data)
result_tags = sorted([str(x) for x in data['tags']])
eq_(expected_tags, result_tags)
result_review_tags = sorted([str(x) for x in data['review_tags']])
eq_(expected_review_tags, result_review_tags)
def test_history_view(self):
slug = 'history-view-test-doc'
html = 'history view test doc'
doc = document(title='History view test doc', slug=slug,
html=html, save=True,
locale=settings.WIKI_DEFAULT_LANGUAGE)
for i in xrange(1, 51):
rev = revision(document=doc, content=html,
comment='Revision %s' % i,
is_approved=True, save=True)
url = reverse('wiki.document_revisions', args=(slug,),
locale=settings.WIKI_DEFAULT_LANGUAGE)
resp = self.client.get(url)
eq_(200, resp.status_code)
all_url = urlparams(reverse('wiki.document_revisions', args=(slug,),
locale=settings.WIKI_DEFAULT_LANGUAGE),
limit='all')
resp = self.client.get(all_url)
eq_(403, resp.status_code)
self.client.login(username='testuser', password='testpass')
resp = self.client.get(all_url)
eq_(200, resp.status_code)
def test_toc_view(self):
slug = 'toc_test_doc'
html = '<h2>Head 2</h2><h3>Head 3</h3>'
doc = document(title='blah', slug=slug, html=html, save=True,
locale=settings.WIKI_DEFAULT_LANGUAGE)
rev = revision(document=doc, content=html, is_approved=True, save=True)
url = reverse('wiki.toc', args=[slug],
locale=settings.WIKI_DEFAULT_LANGUAGE)
Switch.objects.create(name='application_ACAO', active=True)
resp = self.client.get(url)
ok_('Access-Control-Allow-Origin' in resp)
eq_('*', resp['Access-Control-Allow-Origin'])
eq_(resp.content, '<ol><li><a href="#Head_2" rel="internal">Head 2</a>'
'<ol><li><a href="#Head_3" rel="internal">Head 3</a>'
'</ol></li></ol>')
@attr('bug875349')
def test_children_view(self):
test_content = '<p>Test <a href="http://example.com">Summary</a></p>'
def _make_doc(title, slug, parent=None, is_redir=False):
doc = document(title=title,
slug=slug,
save=True,
is_redirect=is_redir)
if is_redir:
content = 'REDIRECT <a class="redirect" href="/en-US/blah">Blah</a>'
else:
content = test_content
revision(document=doc,
content=test_content,
summary=get_seo_description(
test_content,
strip_markup=False),
save=True)
doc.html = content
if parent:
doc.parent_topic = parent
doc.save()
return doc
root_doc = _make_doc('Root', 'Root')
child_doc_1 = _make_doc('Child 1', 'Root/Child_1', root_doc)
_make_doc('Grandchild 1', 'Root/Child_1/Grandchild_1', child_doc_1)
grandchild_doc_2 = _make_doc('Grandchild 2',
'Root/Child_1/Grandchild_2',
child_doc_1)
_make_doc('Great Grandchild 1',
'Root/Child_1/Grandchild_2/Great_Grand_Child_1',
grandchild_doc_2)
_make_doc('Child 2', 'Root/Child_2', root_doc)
_make_doc('Child 3', 'Root/Child_3', root_doc, True)
Switch.objects.create(name='application_ACAO', active=True)
for expand in (True, False):
url = reverse('wiki.get_children', args=['Root'],
locale=settings.WIKI_DEFAULT_LANGUAGE)
if expand:
url = '%s?expand' % url
resp = self.client.get(url)
ok_('Access-Control-Allow-Origin' in resp)
eq_('*', resp['Access-Control-Allow-Origin'])
json_obj = json.loads(resp.content)
# Basic structure creation testing
eq_(json_obj['slug'], 'Root')
if not expand:
ok_('summary' not in json_obj)
else:
eq_(json_obj['summary'],
'Test <a href="http://example.com">Summary</a>')
ok_('tags' in json_obj)
ok_('review_tags' in json_obj)
eq_(len(json_obj['subpages']), 2)
eq_(len(json_obj['subpages'][0]['subpages']), 2)
eq_(json_obj['subpages'][0]['subpages'][1]['title'],
'Grandchild 2')
# Depth parameter testing
def _depth_test(depth, aught):
url = reverse('wiki.get_children', args=['Root'],
locale=settings.WIKI_DEFAULT_LANGUAGE) + '?depth=' + str(depth)
resp = self.client.get(url)
json_obj = json.loads(resp.content)
eq_(len(json_obj['subpages'][0]['subpages'][1]['subpages']), aught)
_depth_test(2, 0)
_depth_test(3, 1)
_depth_test(6, 1)
# Sorting test
sort_root_doc = _make_doc('Sort Root', 'Sort_Root')
_make_doc('B Child', 'Sort_Root/B_Child', sort_root_doc)
_make_doc('A Child', 'Sort_Root/A_Child', sort_root_doc)
resp = self.client.get(reverse('wiki.get_children', args=['Sort_Root'],
locale=settings.WIKI_DEFAULT_LANGUAGE))
json_obj = json.loads(resp.content)
eq_(json_obj['subpages'][0]['title'], 'A Child')
# Test if we are serving an error json if document does not exist
no_doc_url = reverse('wiki.get_children', args=['nonexistentDocument'],
locale=settings.WIKI_DEFAULT_LANGUAGE)
resp = self.client.get(no_doc_url)
result = json.loads(resp.content)
eq_(result, {'error': 'Document does not exist.'})
def test_summary_view(self):
"""The ?summary option should restrict document view to summary"""
d, r = doc_rev("""
<p>Foo bar <a href="http://example.com">baz</a></p>
<p>Quux xyzzy</p>
""")
resp = self.client.get('%s?raw&summary' % d.get_absolute_url())
eq_(resp.content, 'Foo bar <a href="http://example.com">baz</a>')
def test_revision_view_bleached_content(self):
"""Bug 821988: Revision content should be cleaned with bleach"""
d, r = doc_rev("""
<a href="#" onload=alert(3)>Hahaha</a>
<svg><svg onload=alert(3);>
""")
resp = self.client.get(r.get_absolute_url())
page = pq(resp.content)
ct = page.find('#wikiArticle').html()
ok_('<svg>' not in ct)
ok_('<a href="#">Hahaha</a>' in ct)
class PermissionTests(UserTestCase, WikiTestCase):
localizing_client = True
def setUp(self):
"""Set up the permissions, groups, and users needed for the tests"""
super(PermissionTests, self).setUp()
self.perms, self.groups, self.users, self.superuser = (
create_template_test_users())
def test_template_revert_permission(self):
locale = 'en-US'
slug = 'Template:test-revert-perm'
doc = document(save=True, slug=slug, title=slug, locale=locale)
rev = revision(save=True, document=doc)
# Revision template should not show revert button
url = reverse('wiki.revision', args=([doc.full_path, rev.id]))
resp = self.client.get(url)
ok_('Revert' not in resp.content)
# Revert POST should give permission denied to user without perm
username = self.users['none'].username
self.client.login(username=username, password='testpass')
url = reverse('wiki.revert_document',
args=([doc.full_path, rev.id]))
resp = self.client.post(url, {'comment': 'test'})
eq_(403, resp.status_code)
# Revert POST should give success to user with perm
username = self.users['change'].username
self.client.login(username=username, password='testpass')
url = reverse('wiki.revert_document',
args=([doc.full_path, rev.id]))
resp = self.client.post(url, {'comment': 'test'}, follow=True)
eq_(200, resp.status_code)
def test_template_permissions(self):
msg = ('edit', 'create')
for is_add in (True, False):
slug_trials = (
('test_for_%s', (
(True, self.superuser),
(True, self.users['none']),
(True, self.users['all']),
(True, self.users['add']),
(True, self.users['change']),
)),
('Template:test_for_%s', (
(True, self.superuser),
(False, self.users['none']),
(True, self.users['all']),
(is_add, self.users['add']),
(not is_add, self.users['change']),
))
)
for slug_tmpl, trials in slug_trials:
for expected, user in trials:
username = user.username
slug = slug_tmpl % username
locale = settings.WIKI_DEFAULT_LANGUAGE
Document.objects.all().filter(slug=slug).delete()
if not is_add:
doc = document(save=True, slug=slug, title=slug,
locale=locale)
revision(save=True, document=doc)
self.client.login(username=username, password='testpass')
data = new_document_data()
slug = slug_tmpl % username
data.update({"title": slug, "slug": slug})
if is_add:
url = reverse('wiki.new_document', locale=locale)
resp = self.client.post(url, data, follow=False)
else:
data['form'] = 'rev'
url = reverse('wiki.edit_document', args=(slug,),
locale=locale)
resp = self.client.post(url, data, follow=False)
if expected:
eq_(302, resp.status_code,
"%s should be able to %s %s" %
(user, msg[is_add], slug))
Document.objects.filter(slug=slug).delete()
else:
eq_(403, resp.status_code,
"%s should not be able to %s %s" %
(user, msg[is_add], slug))
class ConditionalGetTests(UserTestCase, WikiTestCase):
"""Tests for conditional GET on document view"""
localizing_client = True
def test_last_modified(self):
"""Ensure the last-modified stamp of a document is cached"""
doc, rev = doc_rev()
get_url = reverse('wiki.document',
args=[doc.slug],
locale=settings.WIKI_DEFAULT_LANGUAGE)
# There should be a last-modified date cached for this document already
cache_key = doc.last_modified_cache_key
ok_(cache.get(cache_key))
# Now, try a request, and ensure that the last-modified header is
# present.
response = self.client.get(get_url, follow=False)
ok_(response.has_header('last-modified'))
last_mod = response['last-modified']
# Try another request, using If-Modified-Since. This should be a 304
response = self.client.get(get_url, follow=False,
HTTP_IF_MODIFIED_SINCE=last_mod)
eq_(304, response.status_code)
# Finally, ensure that the last-modified was cached.
cached_last_mod = cache.get(cache_key)
eq_(doc.modified.strftime('%s'), cached_last_mod)
# Let the clock tick, so the last-modified will change on edit.
time.sleep(1.0)
# Edit the document, ensure the last-modified has been invalidated.
revision(document=doc, content="New edits", save=True)
ok_(cache.get(cache_key) != cached_last_mod)
# This should be another 304, but the last-modified in response and
# cache should have changed.
response = self.client.get(get_url, follow=False,
HTTP_IF_MODIFIED_SINCE=last_mod)
eq_(200, response.status_code)
ok_(last_mod != response['last-modified'])
ok_(cached_last_mod != cache.get(cache_key))
def test_deletion_clears_last_modified(self):
"""Deleting a page clears any last-modified caching"""
# Setup mostly the same as previous test, to get a doc and set
# last-modified info.
doc, rev = doc_rev()
self.url = reverse('wiki.document',
args=[doc.slug],
locale=settings.WIKI_DEFAULT_LANGUAGE)
cache_key = doc.last_modified_cache_key
last_mod = cache.get(cache_key)
ok_(last_mod) # exists already because pre-filled
self.client.get(self.url, follow=False)
ok_(cache.get(cache_key) == last_mod)
# Now delete the doc and make sure there's no longer
# last-modified data in the cache for it afterward.
doc.delete()
ok_(not cache.get(cache_key))
def test_deleted_doc_returns_404(self):
"""Requesting a deleted doc returns 404"""
doc, rev = doc_rev()
doc.delete()
DocumentDeletionLog.objects.create(locale=doc.locale, slug=doc.slug,
user=rev.creator, reason="test")
response = self.client.get(doc.get_absolute_url(), follow=False)
eq_(404, response.status_code)
class ReadOnlyTests(UserTestCase, WikiTestCase):
"""Tests readonly scenarios"""
fixtures = UserTestCase.fixtures + ['wiki/documents.json']
localizing_client = True
def setUp(self):
super(ReadOnlyTests, self).setUp()
self.d, r = doc_rev()
self.edit_url = reverse('wiki.edit_document', args=[self.d.full_path])
def test_everyone(self):
""" kumaediting: everyone, kumabanned: none """
self.kumaediting_flag.everyone = True
self.kumaediting_flag.save()
self.client.login(username='testuser', password='testpass')
resp = self.client.get(self.edit_url)
eq_(200, resp.status_code)
def test_superusers_only(self):
""" kumaediting: superusers, kumabanned: none """
self.kumaediting_flag.everyone = None
self.kumaediting_flag.superusers = True
self.kumaediting_flag.save()
self.client.login(username='testuser', password='testpass')
resp = self.client.get(self.edit_url)
eq_(403, resp.status_code)
ok_('The wiki is in read-only mode.' in resp.content)
self.client.logout()
self.client.login(username='admin', password='testpass')
resp = self.client.get(self.edit_url)
eq_(200, resp.status_code)
def test_banned_users(self):
""" kumaediting: everyone, kumabanned: testuser2 """
self.kumaediting_flag.everyone = True
self.kumaediting_flag.save()
# ban testuser2
kumabanned = Flag.objects.create(name='kumabanned')
kumabanned.users = User.objects.filter(username='testuser2')
kumabanned.save()
# testuser can still access
self.client.login(username='testuser', password='testpass')
resp = self.client.get(self.edit_url)
eq_(200, resp.status_code)
self.client.logout()
# testuser2 cannot
self.client.login(username='testuser2', password='testpass')
resp = self.client.get(self.edit_url)
eq_(403, resp.status_code)
ok_('Your profile has been banned from making edits.' in resp.content)
# ban testuser01 and testuser2
kumabanned.users = User.objects.filter(Q(username='testuser2') |
Q(username='testuser01'))
kumabanned.save()
# testuser can still access
self.client.login(username='testuser', password='testpass')
resp = self.client.get(self.edit_url)
eq_(200, resp.status_code)
self.client.logout()
# testuser2 cannot access
self.client.login(username='testuser2', password='testpass')
resp = self.client.get(self.edit_url)
eq_(403, resp.status_code)
ok_('Your profile has been banned from making edits.' in resp.content)
# testuser01 cannot access
self.client.login(username='testuser01', password='testpass')
resp = self.client.get(self.edit_url)
eq_(403, resp.status_code)
ok_('Your profile has been banned from making edits.' in resp.content)
class BannedIPTests(UserTestCase, WikiTestCase):
"""Tests readonly scenarios"""
fixtures = UserTestCase.fixtures + ['wiki/documents.json']
localizing_client = True
def setUp(self):
super(BannedIPTests, self).setUp()
self.ip = '127.0.0.1'
self.ip_ban = IPBan.objects.create(ip=self.ip)
self.doc, rev = doc_rev()
self.edit_url = reverse('wiki.edit_document',
args=[self.doc.full_path])
def tearDown(self):
cache.clear()
def test_banned_ip_cant_get_edit(self):
self.client.login(username='testuser', password='testpass')
response = self.client.get(self.edit_url, REMOTE_ADDR=self.ip)
eq_(403, response.status_code)
def test_banned_ip_cant_post_edit(self):
self.client.login(username='testuser', password='testpass')
response = self.client.get(self.edit_url, REMOTE_ADDR=self.ip)
eq_(403, response.status_code)
def test_banned_ip_can_still_get_articles(self):
response = self.client.get(self.doc.get_absolute_url(),
REMOTE_ADDR=self.ip)
eq_(200, response.status_code)
class KumascriptIntegrationTests(UserTestCase, WikiTestCase):
"""
Tests for usage of the kumascript service.
Note that these tests really just check whether or not the service was
used, and are not integration tests meant to exercise the real service.
"""
localizing_client = True
def setUp(self):
super(KumascriptIntegrationTests, self).setUp()
self.d, self.r = doc_rev()
self.r.content = "TEST CONTENT"
self.r.save()
self.d.tags.set('foo', 'bar', 'baz')
self.url = reverse('wiki.document',
args=(self.d.slug,),
locale=self.d.locale)
# TODO: upgrade mock to 0.8.0 so we can do this.
# self.mock_kumascript_get = (
# mock.patch('kuma.wiki.kumascript.get'))
# self.mock_kumascript_get.return_value = self.d.html
def tearDown(self):
super(KumascriptIntegrationTests, self).tearDown()
# TODO: upgrade mock to 0.8.0 so we can do this.
# self.mock_kumascript_get.stop()
@override_constance_settings(KUMASCRIPT_TIMEOUT=1.0)
@mock.patch('kuma.wiki.kumascript.get')
def test_basic_view(self, mock_kumascript_get):
"""When kumascript timeout is non-zero, the service should be used"""
mock_kumascript_get.return_value = (self.d.html, None)
self.client.get(self.url, follow=False)
ok_(mock_kumascript_get.called,
"kumascript should have been used")
@override_constance_settings(KUMASCRIPT_TIMEOUT=0.0)
@mock.patch('kuma.wiki.kumascript.get')
def test_disabled(self, mock_kumascript_get):
"""When disabled, the kumascript service should not be used"""
mock_kumascript_get.return_value = (self.d.html, None)
self.client.get(self.url, follow=False)
ok_(not mock_kumascript_get.called,
"kumascript not should have been used")
@override_constance_settings(KUMASCRIPT_TIMEOUT=0.0)
@mock.patch('kuma.wiki.kumascript.get')
def test_disabled_rendering(self, mock_kumascript_get):
"""When disabled, the kumascript service should not be used
in rendering"""
mock_kumascript_get.return_value = (self.d.html, None)
settings.CELERY_ALWAYS_EAGER = True
self.d.schedule_rendering('max-age=0')
ok_(not mock_kumascript_get.called,
"kumascript not should have been used")
@override_constance_settings(KUMASCRIPT_TIMEOUT=1.0)
@mock.patch('kuma.wiki.kumascript.get')
def test_nomacros(self, mock_kumascript_get):
mock_kumascript_get.return_value = (self.d.html, None)
self.client.get('%s?nomacros' % self.url, follow=False)
ok_(not mock_kumascript_get.called,
"kumascript should not have been used")
@override_constance_settings(KUMASCRIPT_TIMEOUT=1.0)
@mock.patch('kuma.wiki.kumascript.get')
def test_raw(self, mock_kumascript_get):
mock_kumascript_get.return_value = (self.d.html, None)
self.client.get('%s?raw' % self.url, follow=False)
ok_(not mock_kumascript_get.called,
"kumascript should not have been used")
@override_constance_settings(KUMASCRIPT_TIMEOUT=1.0)
@mock.patch('kuma.wiki.kumascript.get')
def test_raw_macros(self, mock_kumascript_get):
mock_kumascript_get.return_value = (self.d.html, None)
self.client.get('%s?raw¯os' % self.url, follow=False)
ok_(mock_kumascript_get.called,
"kumascript should have been used")
@override_constance_settings(KUMASCRIPT_TIMEOUT=1.0,
KUMASCRIPT_MAX_AGE=1234)
@mock.patch('requests.get')
def test_ua_max_age_zero(self, mock_requests_get):
"""Authenticated users can request a zero max-age for kumascript"""
trap = {}
def my_requests_get(url, headers=None, timeout=None):
trap['headers'] = headers
return FakeResponse(status_code=200,
headers={}, text='HELLO WORLD')
mock_requests_get.side_effect = my_requests_get
self.client.get(self.url, follow=False,
HTTP_CACHE_CONTROL='no-cache')
eq_('max-age=1234', trap['headers']['Cache-Control'])
self.client.login(username='admin', password='testpass')
self.client.get(self.url, follow=False,
HTTP_CACHE_CONTROL='no-cache')
eq_('no-cache', trap['headers']['Cache-Control'])
@override_constance_settings(KUMASCRIPT_TIMEOUT=1.0,
KUMASCRIPT_MAX_AGE=1234)
@mock.patch('requests.get')
def test_ua_no_cache(self, mock_requests_get):
"""Authenticated users can request no-cache for kumascript"""
trap = {}
def my_requests_get(url, headers=None, timeout=None):
trap['headers'] = headers
return FakeResponse(status_code=200,
headers={}, text='HELLO WORLD')
mock_requests_get.side_effect = my_requests_get
self.client.get(self.url, follow=False,
HTTP_CACHE_CONTROL='no-cache')
eq_('max-age=1234', trap['headers']['Cache-Control'])
self.client.login(username='admin', password='testpass')
self.client.get(self.url, follow=False,
HTTP_CACHE_CONTROL='no-cache')
eq_('no-cache', trap['headers']['Cache-Control'])
@override_constance_settings(KUMASCRIPT_TIMEOUT=1.0,
KUMASCRIPT_MAX_AGE=1234)
@mock.patch('requests.get')
def test_conditional_get(self, mock_requests_get):
"""Ensure conditional GET in requests to kumascript work as expected"""
expected_etag = "8675309JENNY"
expected_modified = "Wed, 14 Mar 2012 22:29:17 GMT"
expected_content = "HELLO THERE, WORLD"
trap = dict(req_cnt=0)
def my_requests_get(url, headers=None, timeout=None):
trap['req_cnt'] += 1
trap['headers'] = headers
if trap['req_cnt'] in [1, 2]:
return FakeResponse(status_code=200, text=expected_content,
headers={
"etag": expected_etag,
"last-modified": expected_modified,
"age": 456
})
else:
return FakeResponse(status_code=304, text='',
headers={
"etag": expected_etag,
"last-modified": expected_modified,
"age": 123
})
mock_requests_get.side_effect = my_requests_get
# First request to let the view cache etag / last-modified
response = self.client.get(self.url)
# Clear rendered_html to force another request.
self.d.rendered_html = ''
self.d.save()
# Second request to verify the view sends them back
response = self.client.get(self.url)
eq_(expected_etag, trap['headers']['If-None-Match'])
eq_(expected_modified, trap['headers']['If-Modified-Since'])
# Third request to verify content was cached and served on a 304
response = self.client.get(self.url)
ok_(expected_content in response.content)
@override_constance_settings(KUMASCRIPT_TIMEOUT=1.0,
KUMASCRIPT_MAX_AGE=600)
@mock.patch('requests.get')
def test_error_reporting(self, mock_requests_get):
"""Kumascript reports errors in HTTP headers, Kuma should display"""
# Make sure we have enough log messages to ensure there are more than
# 10 lines of Base64 in headers. This ensures that there'll be a
# failure if the view sorts FireLogger sequence number alphabetically
# instead of numerically.
expected_errors = {
"logs": [
{"level": "debug",
"message": "Message #1",
"args": ['TestError', {}, {'name': 'SomeMacro', 'token':{'args':'arguments here'}}],
"time": "12:32:03 GMT-0400 (EDT)",
"timestamp": "1331829123101000"},
{"level": "warning",
"message": "Message #2",
"args": ['TestError', {}, {'name': 'SomeMacro2'}],
"time": "12:33:58 GMT-0400 (EDT)",
"timestamp": "1331829238052000"},
{"level": "info",
"message": "Message #3",
"args": ['TestError'],
"time": "12:34:22 GMT-0400 (EDT)",
"timestamp": "1331829262403000"},
{"level": "debug",
"message": "Message #4",
"time": "12:32:03 GMT-0400 (EDT)",
"timestamp": "1331829123101000"},
{"level": "warning",
"message": "Message #5",
"time": "12:33:58 GMT-0400 (EDT)",
"timestamp": "1331829238052000"},
{"level": "info",
"message": "Message #6",
"time": "12:34:22 GMT-0400 (EDT)",
"timestamp": "1331829262403000"},
]
}
# Pack it up, get ready to ship it out.
d_json = json.dumps(expected_errors)
d_b64 = base64.encodestring(d_json)
d_lines = [x for x in d_b64.split("\n") if x]
# Headers are case-insensitive, so let's just drive that point home
p = ['firelogger', 'FIRELOGGER', 'FireLogger']
fl_uid = 8675309
headers_out = {}
for i in range(0, len(d_lines)):
headers_out['%s-%s-%s' % (p[i % len(p)], fl_uid, i)] = d_lines[i]
# Now, trap the request from the view.
trap = {}
def my_requests_get(url, headers=None, timeout=None):
trap['headers'] = headers
return FakeResponse(
status_code=200,
text='HELLO WORLD',
headers=headers_out
)
mock_requests_get.side_effect = my_requests_get
# Finally, fire off the request to the view and ensure that the log
# messages were received and displayed on the page. But, only for a
# logged in user.
self.client.login(username='admin', password='testpass')
response = self.client.get(self.url)
eq_(trap['headers']['X-FireLogger'], '1.2')
for error in expected_errors['logs']:
ok_(error['message'] in response.content)
eq_(response.status_code, 200)
@override_constance_settings(KUMASCRIPT_TIMEOUT=1.0,
KUMASCRIPT_MAX_AGE=600)
@mock.patch('requests.post')
def test_preview_nonascii(self, mock_post):
"""POSTing non-ascii to kumascript should encode to utf8"""
content = u'Français'
trap = {}
def my_post(url, timeout=None, headers=None, data=None):
trap['data'] = data
return FakeResponse(status_code=200, headers={},
text=content.encode('utf8'))
mock_post.side_effect = my_post
self.client.login(username='admin', password='testpass')
self.client.post(reverse('wiki.preview'), {'content': content})
try:
trap['data'].decode('utf8')
except UnicodeDecodeError:
self.fail("Data wasn't posted as utf8")
class DocumentSEOTests(UserTestCase, WikiTestCase):
"""Tests for the document seo logic"""
localizing_client = True
def test_seo_title(self):
self.client.login(username='admin', password='testpass')
# Utility to make a quick doc
def _make_doc(title, aught_titles, slug):
doc = document(save=True, slug=slug, title=title,
locale=settings.WIKI_DEFAULT_LANGUAGE)
revision(save=True, document=doc)
response = self.client.get(reverse('wiki.document', args=[slug],
locale=settings.WIKI_DEFAULT_LANGUAGE))
page = pq(response.content)
ok_(page.find('title').text() in aught_titles)
# Test nested document titles
_make_doc('One', ['One | MDN'], 'one')
_make_doc('Two', ['Two - One | MDN'], 'one/two')
_make_doc('Three', ['Three - One | MDN'], 'one/two/three')
_make_doc(u'Special Φ Char', [u'Special \u03a6 Char - One | MDN',
u'Special \xce\xa6 Char - One | MDN'],
'one/two/special_char')
# Additional tests for /Web/* changes
_make_doc('Firefox OS', ['Firefox OS | MDN'], 'firefox_os')
_make_doc('Email App', ['Email App - Firefox OS | MDN'],
'firefox_os/email_app')
_make_doc('Web', ['Web | MDN'], 'Web')
_make_doc('HTML', ['HTML | MDN'], 'Web/html')
_make_doc('Fieldset', ['Fieldset - HTML | MDN'], 'Web/html/fieldset')
_make_doc('Legend', ['Legend - HTML | MDN'],
'Web/html/fieldset/legend')
def test_seo_script(self):
self.client.login(username='admin', password='testpass')
def make_page_and_compare_seo(slug, content, aught_preview):
# Create the doc
data = new_document_data()
data.update({'title': 'blah', 'slug': slug, 'content': content})
response = self.client.post(reverse('wiki.new_document',
locale=settings.WIKI_DEFAULT_LANGUAGE),
data)
eq_(302, response.status_code)
# Connect to newly created page
response = self.client.get(reverse('wiki.document', args=[slug],
locale=settings.WIKI_DEFAULT_LANGUAGE))
page = pq(response.content)
meta_content = page.find('meta[name=description]').attr('content')
eq_(str(meta_content).decode('utf-8'),
str(aught_preview).decode('utf-8'))
# Test pages - very basic
good = 'This is the content which should be chosen, man.'
make_page_and_compare_seo('one', '<p>' + good + '</p>', good)
# No content, no seo
make_page_and_compare_seo('two', 'blahblahblahblah<br />', None)
# No summary, no seo
make_page_and_compare_seo('three', '<div><p>You cant see me</p></div>',
None)
# Warning paragraph ignored
make_page_and_compare_seo('four',
'<div class="geckoVersion">'
'<p>No no no</p></div><p>yes yes yes</p>',
'yes yes yes')
# Warning paragraph ignored, first one chosen if multiple matches
make_page_and_compare_seo('five',
'<div class="geckoVersion"><p>No no no</p>'
'</div><p>yes yes yes</p>'
'<p>ignore ignore ignore</p>',
'yes yes yes')
# Don't take legacy crumbs
make_page_and_compare_seo('six', u'<p>« CSS</p><p>I am me!</p>',
'I am me!')
# Take the seoSummary class'd element
make_page_and_compare_seo('seven',
u'<p>I could be taken</p>'
'<p class="seoSummary">I should be though</p>',
'I should be though')
# Two summaries append
make_page_and_compare_seo('eight',
u'<p>I could be taken</p>'
'<p class="seoSummary">a</p>'
'<p class="seoSummary">b</p>',
'a b')
# No brackets
make_page_and_compare_seo('nine',
u'<p>I <em>am</em> awesome.'
' <a href="blah">A link</a> is also <cool></p>',
u'I am awesome. A link is also cool')
class DocumentEditingTests(UserTestCase, WikiTestCase):
"""Tests for the document-editing view"""
localizing_client = True
def test_noindex_post(self):
self.client.login(username='admin', password='testpass')
# Go to new document page to ensure no-index header works
response = self.client.get(reverse('wiki.new_document', args=[],
locale=settings.WIKI_DEFAULT_LANGUAGE))
eq_(response['X-Robots-Tag'], 'noindex')
@attr('bug821986')
def test_editor_safety_filter(self):
"""Safety filter should be applied before rendering editor"""
self.client.login(username='admin', password='testpass')
r = revision(save=True, content="""
<svg><circle onload=confirm(3)>
""")
args = [r.document.full_path]
urls = (
reverse('wiki.edit_document', args=args),
'%s?tolocale=%s' % (reverse('wiki.translate', args=args), 'fr')
)
for url in urls:
page = pq(self.client.get(url).content)
editor_src = page.find('#id_content').text()
ok_('onload' not in editor_src)
def test_create_on_404(self):
self.client.login(username='admin', password='testpass')
# Create the parent page.
d, r = doc_rev()
# Establish attribs of child page.
locale = settings.WIKI_DEFAULT_LANGUAGE
local_slug = 'Some_New_Title'
slug = '%s/%s' % (d.slug, local_slug)
url = reverse('wiki.document', args=[slug], locale=locale)
# Ensure redirect to create new page on attempt to visit non-existent
# child page.
resp = self.client.get(url)
eq_(302, resp.status_code)
ok_('docs/new' in resp['Location'])
ok_('?slug=%s' % local_slug in resp['Location'])
# Ensure real 404 for visit to non-existent page with params common to
# kumascript and raw content API.
for p_name in ('raw', 'include', 'nocreate'):
sub_url = '%s?%s=1' % (url, p_name)
resp = self.client.get(sub_url)
eq_(404, resp.status_code)
# Ensure root level documents work, not just children
response = self.client.get(reverse('wiki.document',
args=['noExist'], locale=locale))
eq_(302, response.status_code)
response = self.client.get(reverse('wiki.document',
args=['Template:NoExist'],
locale=locale))
eq_(302, response.status_code)
def test_new_document_comment(self):
"""Creating a new document with a revision comment saves the comment"""
self.client.login(username='admin', password='testpass')
comment = 'I am the revision comment'
slug = 'Test-doc-comment'
loc = settings.WIKI_DEFAULT_LANGUAGE
# Create a new doc.
data = new_document_data()
data.update({'slug': slug, 'comment': comment})
self.client.post(reverse('wiki.new_document'), data)
doc = Document.objects.get(slug=slug, locale=loc)
eq_(comment, doc.current_revision.comment)
@attr('toc')
def test_toc_initial(self):
self.client.login(username='admin', password='testpass')
resp = self.client.get(reverse('wiki.new_document'))
eq_(200, resp.status_code)
page = pq(resp.content)
toc_select = page.find('#id_toc_depth')
toc_options = toc_select.find('option')
for option in toc_options:
opt_element = pq(option)
found_selected = False
if opt_element.attr('selected'):
found_selected = True
eq_(str(Revision.TOC_DEPTH_H4), opt_element.attr('value'))
if not found_selected:
raise AssertionError("No ToC depth initially selected.")
@attr('retitle')
def test_retitling_solo_doc(self):
""" Editing just title of non-parent doc:
* Changes title
* Doesn't cause errors
* Doesn't create redirect
"""
# Not testing slug changes separately; the model tests cover those plus
# slug+title changes. If title changes work in the view, the rest
# should also.
self.client.login(username='admin', password='testpass')
new_title = 'Some New Title'
d, r = doc_rev()
old_title = d.title
data = new_document_data()
data.update({'title': new_title,
'form': 'rev'})
data['slug'] = ''
url = reverse('wiki.edit_document', args=[d.full_path])
self.client.post(url, data)
eq_(new_title,
Document.objects.get(slug=d.slug, locale=d.locale).title)
try:
Document.objects.get(title=old_title)
self.fail("Should not find doc by old title after retitling.")
except Document.DoesNotExist:
pass
@attr('retitle')
def test_retitling_parent_doc(self):
""" Editing just title of parent doc:
* Changes title
* Doesn't cause errors
* Doesn't create redirect
"""
# Not testing slug changes separately; the model tests cover those plus
# slug+title changes. If title changes work in the view, the rest
# should also.
self.client.login(username='admin', password='testpass')
# create parent doc & rev along with child doc & rev
d = document(title='parent', save=True)
revision(document=d, content='parent', save=True)
d2 = document(title='child', parent_topic=d, save=True)
revision(document=d2, content='child', save=True)
old_title = d.title
new_title = 'Some New Title'
data = new_document_data()
data.update({'title': new_title,
'form': 'rev'})
data['slug'] = ''
url = reverse('wiki.edit_document', args=[d.full_path])
self.client.post(url, data)
eq_(new_title,
Document.objects.get(slug=d.slug, locale=d.locale).title)
try:
Document.objects.get(title=old_title)
self.fail("Should not find doc by old title after retitling.")
except Document.DoesNotExist:
pass
def test_slug_change_ignored_for_iframe(self):
"""When the title of an article is edited in an iframe, the change is
ignored."""
self.client.login(username='admin', password='testpass')
new_slug = 'some_new_slug'
d, r = doc_rev()
old_slug = d.slug
data = new_document_data()
data.update({'title': d.title,
'slug': new_slug,
'form': 'rev'})
self.client.post('%s?iframe=1' % reverse('wiki.edit_document',
args=[d.full_path]), data)
eq_(old_slug, Document.objects.get(slug=d.slug,
locale=d.locale).slug)
assert "REDIRECT" not in Document.objects.get(slug=old_slug).html
@attr('clobber')
def test_slug_collision_errors(self):
"""When an attempt is made to retitle an article and another with that
title already exists, there should be form errors"""
self.client.login(username='admin', password='testpass')
exist_slug = "existing-doc"
# Create a new doc.
data = new_document_data()
data.update({"slug": exist_slug})
resp = self.client.post(reverse('wiki.new_document'), data)
eq_(302, resp.status_code)
# Create another new doc.
data = new_document_data()
data.update({"slug": 'some-new-title'})
resp = self.client.post(reverse('wiki.new_document'), data)
eq_(302, resp.status_code)
# Now, post an update with duplicate slug
data.update({
'form': 'rev',
'slug': exist_slug
})
resp = self.client.post(reverse('wiki.edit_document',
args=['some-new-title']), data)
eq_(200, resp.status_code)
p = pq(resp.content)
ok_(p.find('.errorlist').length > 0)
ok_(p.find('.errorlist a[href="#id_slug"]').length > 0)
@attr('clobber')
def test_redirect_can_be_clobbered(self):
"""When an attempt is made to retitle an article, and another article
with that title exists but is a redirect, there should be no errors and
the redirect should be replaced."""
self.client.login(username='admin', password='testpass')
exist_title = "Existing doc"
exist_slug = "existing-doc"
changed_title = 'Changed title'
changed_slug = 'changed-title'
# Create a new doc.
data = new_document_data()
data.update({"title": exist_title, "slug": exist_slug})
resp = self.client.post(reverse('wiki.new_document'), data)
eq_(302, resp.status_code)
# Change title and slug
data.update({'form': 'rev',
'title': changed_title,
'slug': changed_slug})
resp = self.client.post(reverse('wiki.edit_document',
args=[exist_slug]),
data)
eq_(302, resp.status_code)
# Change title and slug back to originals, clobbering the redirect
data.update({'form': 'rev',
'title': exist_title,
'slug': exist_slug})
resp = self.client.post(reverse('wiki.edit_document',
args=[changed_slug]),
data)
eq_(302, resp.status_code)
def test_invalid_slug(self):
"""Slugs cannot contain "$", but can contain "/"."""
self.client.login(username='admin', password='testpass')
data = new_document_data()
data['title'] = 'valid slug'
data['slug'] = 'valid'
response = self.client.post(reverse('wiki.new_document'), data)
self.assertRedirects(response,
reverse('wiki.document', args=[data['slug']],
locale=settings.WIKI_DEFAULT_LANGUAGE))
# Slashes should not be acceptable via form input
data['title'] = 'valid with slash'
data['slug'] = 'va/lid'
response = self.client.post(reverse('wiki.new_document'), data)
self.assertContains(response, 'The slug provided is not valid.')
# Dollar sign is reserved for verbs
data['title'] = 'invalid with dollars'
data['slug'] = 'inva$lid'
response = self.client.post(reverse('wiki.new_document'), data)
self.assertContains(response, 'The slug provided is not valid.')
# Question mark is reserved for query params
data['title'] = 'invalid with questions'
data['slug'] = 'inva?lid'
response = self.client.post(reverse('wiki.new_document'), data)
self.assertContains(response, 'The slug provided is not valid.')
def test_invalid_reserved_term_slug(self):
"""Slugs should not collide with reserved URL patterns"""
self.client.login(username='admin', password='testpass')
data = new_document_data()
# TODO: This is info derived from urls.py, but unsure how to DRY it
reserved_slugs = (
'ckeditor_config.js',
'watch-ready-for-review',
'unwatch-ready-for-review',
'watch-approved',
'unwatch-approved',
'.json',
'new',
'all',
'preview-wiki-content',
'category/10',
'needs-review/technical',
'needs-review/',
'feeds/atom/all/',
'feeds/atom/needs-review/technical',
'feeds/atom/needs-review/',
'tag/tasty-pie'
)
for term in reserved_slugs:
data['title'] = 'invalid with %s' % term
data['slug'] = term
response = self.client.post(reverse('wiki.new_document'), data)
self.assertContains(response, 'The slug provided is not valid.')
def test_slug_revamp(self):
self.client.login(username='admin', password='testpass')
def _createAndRunTests(slug):
# Create some vars
locale = settings.WIKI_DEFAULT_LANGUAGE
foreign_locale = 'es'
new_doc_url = reverse('wiki.new_document')
invalid_slug = invalid_slug1 = "some/thing"
invalid_slug2 = "some?thing"
invalid_slug3 = "some thing"
child_slug = 'kiddy'
grandchild_slug = 'grandkiddy'
# Create the document data
doc_data = new_document_data()
doc_data['title'] = slug + ' Doc'
doc_data['slug'] = slug
doc_data['content'] = 'This is the content'
doc_data['is_localizable'] = True
""" NEW DOCUMENT CREATION, CHILD CREATION """
# Create the document, validate it exists
response = self.client.post(new_doc_url, doc_data)
eq_(302, response.status_code) # 302 = good, forward to new page
ok_(slug in response['Location'])
self.assertRedirects(response, reverse('wiki.document',
locale=locale, args=[slug]))
doc_url = reverse('wiki.document', locale=locale, args=[slug])
eq_(self.client.get(doc_url).status_code, 200)
doc = Document.objects.get(locale=locale, slug=slug)
eq_(doc.slug, slug)
eq_(0, len(Document.objects.filter(title=doc_data['title'] + 'Redirect')))
# Create child document data
child_data = new_document_data()
child_data['title'] = slug + ' Child Doc'
child_data['slug'] = invalid_slug
child_data['content'] = 'This is the content'
child_data['is_localizable'] = True
# Attempt to create the child with invalid slug, validate it fails
def test_invalid_slug(inv_slug, url, data, doc):
data['slug'] = inv_slug
response = self.client.post(url, data)
page = pq(response.content)
eq_(200, response.status_code) # 200 = bad, invalid data
# Slug doesn't add parent
eq_(inv_slug, page.find('input[name=slug]')[0].value)
eq_(doc.get_absolute_url(),
page.find('.metadataDisplay').attr('href'))
self.assertContains(response,
'The slug provided is not valid.')
test_invalid_slug(invalid_slug1,
new_doc_url + '?parent=' + str(doc.id),
child_data, doc)
test_invalid_slug(invalid_slug2,
new_doc_url + '?parent=' + str(doc.id),
child_data, doc)
test_invalid_slug(invalid_slug3,
new_doc_url + '?parent=' + str(doc.id),
child_data, doc)
# Attempt to create the child with *valid* slug,
# should succeed and redirect
child_data['slug'] = child_slug
full_child_slug = slug + '/' + child_data['slug']
response = self.client.post(new_doc_url + '?parent=' + str(doc.id),
child_data)
eq_(302, response.status_code)
self.assertRedirects(response, reverse('wiki.document',
locale=locale,
args=[full_child_slug]))
child_doc = Document.objects.get(locale=locale,
slug=full_child_slug)
eq_(child_doc.slug, full_child_slug)
eq_(0, len(Document.objects.filter(
title=child_data['title'] + ' Redirect 1',
locale=locale)))
# Create grandchild data
grandchild_data = new_document_data()
grandchild_data['title'] = slug + ' Grandchild Doc'
grandchild_data['slug'] = invalid_slug
grandchild_data['content'] = 'This is the content'
grandchild_data['is_localizable'] = True
# Attempt to create the child with invalid slug, validate it fails
response = self.client.post(
new_doc_url + '?parent=' + str(child_doc.id), grandchild_data)
page = pq(response.content)
eq_(200, response.status_code) # 200 = bad, invalid data
# Slug doesn't add parent
eq_(invalid_slug, page.find('input[name=slug]')[0].value)
eq_(child_doc.get_absolute_url(),
page.find('.metadataDisplay').attr('href'))
self.assertContains(response, 'The slug provided is not valid.')
# Attempt to create the child with *valid* slug,
# should succeed and redirect
grandchild_data['slug'] = grandchild_slug
full_grandchild_slug = (full_child_slug
+ '/' + grandchild_data['slug'])
response = self.client.post(new_doc_url
+ '?parent=' + str(child_doc.id),
grandchild_data)
eq_(302, response.status_code)
self.assertRedirects(response,
reverse('wiki.document', locale=locale,
args=[full_grandchild_slug]))
grandchild_doc = Document.objects.get(locale=locale,
slug=full_grandchild_slug)
eq_(grandchild_doc.slug, full_grandchild_slug)
missing_title = grandchild_data['title'] + ' Redirect 1'
eq_(0, len(Document.objects.filter(title=missing_title,
locale=locale)))
def _run_edit_tests(edit_slug, edit_data, edit_doc,
edit_parent_path):
"""EDIT DOCUMENT TESTING"""
# Load "Edit" page for the root doc, ensure no "/" in the slug
# Also ensure the 'parent' link is not present
response = self.client.get(reverse('wiki.edit_document',
args=[edit_doc.slug], locale=locale))
eq_(200, response.status_code)
page = pq(response.content)
eq_(edit_data['slug'], page.find('input[name=slug]')[0].value)
eq_(edit_parent_path,
page.find('.metadataDisplay').attr('href'))
# Attempt an invalid edit of the root,
# ensure the slug stays the same (i.e. no parent prepending)
def test_invalid_slug_edit(inv_slug, url, data):
data['slug'] = inv_slug
data['form'] = 'rev'
response = self.client.post(url, data)
eq_(200, response.status_code) # 200 = bad, invalid data
page = pq(response.content)
# Slug doesn't add parent
eq_(inv_slug, page.find('input[name=slug]')[0].value)
eq_(edit_parent_path,
page.find('.metadataDisplay').attr('href'))
self.assertContains(response,
'The slug provided is not valid.')
# Ensure no redirect
redirect_title = data['title'] + ' Redirect 1'
eq_(0, len(Document.objects.filter(title=redirect_title,
locale=locale)))
# Push a valid edit, without changing the slug
edit_data['slug'] = edit_slug
edit_data['form'] = 'rev'
response = self.client.post(reverse('wiki.edit_document',
args=[edit_doc.slug],
locale=locale),
edit_data)
eq_(302, response.status_code)
# Ensure no redirect
redirect_title = edit_data['title'] + ' Redirect 1'
eq_(0, len(Document.objects.filter(title=redirect_title,
locale=locale)))
self.assertRedirects(response,
reverse('wiki.document',
locale=locale,
args=[edit_doc.slug]))
def _run_translate_tests(translate_slug, translate_data,
translate_doc):
"""TRANSLATION DOCUMENT TESTING"""
foreign_url = (reverse('wiki.translate',
args=[translate_doc.slug],
locale=locale)
+ '?tolocale='
+ foreign_locale)
foreign_doc_url = reverse('wiki.document',
args=[translate_doc.slug],
locale=foreign_locale)
# Verify translate page form is populated correctly
response = self.client.get(foreign_url)
eq_(200, response.status_code)
page = pq(response.content)
eq_(translate_data['slug'],
page.find('input[name=slug]')[0].value)
# Attempt an invalid edit of the root
# ensure the slug stays the same (i.e. no parent prepending)
def test_invalid_slug_translate(inv_slug, url, data):
data['slug'] = inv_slug
data['form'] = 'both'
response = self.client.post(url, data)
eq_(200, response.status_code) # 200 = bad, invalid data
page = pq(response.content)
# Slug doesn't add parent
eq_(inv_slug, page.find('input[name=slug]')[0].value)
self.assertContains(response,
'The slug provided is not valid.')
# Ensure no redirect
eq_(0, len(Document.objects.filter(title=data['title'] +
' Redirect 1',
locale=foreign_locale)))
# Push a valid translation
translate_data['slug'] = translate_slug
translate_data['form'] = 'both'
response = self.client.post(foreign_url, translate_data)
eq_(302, response.status_code)
# Ensure no redirect
redirect_title = translate_data['title'] + ' Redirect 1'
eq_(0, len(Document.objects.filter(title=redirect_title,
locale=foreign_locale)))
self.assertRedirects(response, foreign_doc_url)
return Document.objects.get(locale=foreign_locale,
slug=translate_doc.slug)
_run_translate_tests(slug, doc_data, doc)
_run_translate_tests(child_slug, child_data, child_doc)
_run_translate_tests(grandchild_slug, grandchild_data,
grandchild_doc)
def _run_translate_edit_tests(edit_slug, edit_data, edit_doc):
"""TEST BASIC EDIT OF TRANSLATION"""
# Hit the initial URL
response = self.client.get(reverse('wiki.edit_document',
args=[edit_doc.slug],
locale=foreign_locale))
eq_(200, response.status_code)
page = pq(response.content)
eq_(edit_data['slug'], page.find('input[name=slug]')[0].value)
# Attempt an invalid edit of the root, ensure the slug stays
# the same (i.e. no parent prepending)
edit_data['slug'] = invalid_slug
edit_data['form'] = 'both'
response = self.client.post(reverse('wiki.edit_document',
args=[edit_doc.slug],
locale=foreign_locale),
edit_data)
eq_(200, response.status_code) # 200 = bad, invalid data
page = pq(response.content)
# Slug doesn't add parent
eq_(invalid_slug, page.find('input[name=slug]')[0].value)
self.assertContains(response, page.find('ul.errorlist li'
' a[href="#id_slug"]').
text())
# Ensure no redirect
eq_(0, len(Document.objects.filter(title=edit_data['title'] +
' Redirect 1',
locale=foreign_locale)))
# Push a valid edit, without changing the slug
edit_data['slug'] = edit_slug
response = self.client.post(reverse('wiki.edit_document',
args=[edit_doc.slug],
locale=foreign_locale),
edit_data)
eq_(302, response.status_code)
# Ensure no redirect
eq_(0, len(Document.objects.filter(title=edit_data['title'] +
' Redirect 1',
locale=foreign_locale)))
self.assertRedirects(response, reverse('wiki.document',
locale=foreign_locale,
args=[edit_doc.slug]))
""" TEST EDITING SLUGS AND TRANSLATIONS """
def _run_slug_edit_tests(edit_slug, edit_data, edit_doc, loc):
edit_data['slug'] = edit_data['slug'] + '_Updated'
edit_data['form'] = 'rev'
response = self.client.post(reverse('wiki.edit_document',
args=[edit_doc.slug],
locale=loc),
edit_data)
eq_(302, response.status_code)
# HACK: the es doc gets a 'Redirigen 1' if locale/ is updated
# Ensure *1* redirect
eq_(1,
len(Document.objects.filter(
title__contains=edit_data['title'] + ' Redir',
locale=loc)))
self.assertRedirects(response,
reverse('wiki.document',
locale=loc,
args=[edit_doc.slug.replace(
edit_slug,
edit_data['slug'])]))
# Run all of the tests
_createAndRunTests("parent")
# Test that slugs with the same "specific" slug but in different levels
# in the heiharachy are validate properly upon submission
# Create base doc
parent_doc = document(title='Length',
slug='length',
is_localizable=True,
locale=settings.WIKI_DEFAULT_LANGUAGE)
parent_doc.save()
r = revision(document=parent_doc)
r.save()
# Create child, try to use same slug, should work
child_data = new_document_data()
child_data['title'] = 'Child Length'
child_data['slug'] = 'length'
child_data['content'] = 'This is the content'
child_data['is_localizable'] = True
child_url = (reverse('wiki.new_document') +
'?parent=' +
str(parent_doc.id))
response = self.client.post(child_url, child_data)
eq_(302, response.status_code)
self.assertRedirects(response,
reverse('wiki.document',
args=['length/length'],
locale=settings.WIKI_DEFAULT_LANGUAGE))
# Editing "length/length" document doesn't cause errors
child_data['form'] = 'rev'
child_data['slug'] = ''
edit_url = reverse('wiki.edit_document', args=['length/length'],
locale=settings.WIKI_DEFAULT_LANGUAGE)
response = self.client.post(edit_url, child_data)
eq_(302, response.status_code)
self.assertRedirects(response, reverse('wiki.document',
args=['length/length'],
locale=settings.WIKI_DEFAULT_LANGUAGE))
# Creating a new translation of "length" and "length/length"
# doesn't cause errors
child_data['form'] = 'both'
child_data['slug'] = 'length'
translate_url = reverse('wiki.document', args=[child_data['slug']],
locale=settings.WIKI_DEFAULT_LANGUAGE)
response = self.client.post(translate_url + '$translate?tolocale=es',
child_data)
eq_(302, response.status_code)
self.assertRedirects(response, reverse('wiki.document',
args=[child_data['slug']],
locale='es'))
translate_url = reverse('wiki.document', args=['length/length'],
locale=settings.WIKI_DEFAULT_LANGUAGE)
response = self.client.post(translate_url + '$translate?tolocale=es',
child_data)
eq_(302, response.status_code)
slug = 'length/' + child_data['slug']
self.assertRedirects(response, reverse('wiki.document',
args=[slug],
locale='es'))
def test_translate_keeps_topical_parent(self):
self.client.login(username='admin', password='testpass')
en_doc, de_doc = make_translation()
en_child_doc = document(parent_topic=en_doc, slug='en-child',
save=True)
en_child_rev = revision(document=en_child_doc, save=True)
de_child_doc = document(parent_topic=de_doc, locale='de',
slug='de-child', parent=en_child_doc,
save=True)
revision(document=de_child_doc, save=True)
post_data = {}
post_data['slug'] = de_child_doc.slug
post_data['title'] = 'New title'
post_data['form'] = 'both'
post_data['content'] = 'New translation'
post_data['tolocale'] = 'de'
post_data['toc_depth'] = 0
post_data['based_on'] = en_child_rev.id
post_data['parent_id'] = en_child_doc.id
translate_url = reverse('wiki.edit_document',
args=[de_child_doc.slug],
locale='de')
self.client.post(translate_url, post_data)
de_child_doc = Document.objects.get(locale='de', slug='de-child')
eq_(en_child_doc, de_child_doc.parent)
eq_(de_doc, de_child_doc.parent_topic)
eq_('New translation', de_child_doc.current_revision.content)
def test_translate_keeps_toc_depth(self):
self.client.login(username='admin', password='testpass')
locale = settings.WIKI_DEFAULT_LANGUAGE
original_slug = 'eng-doc'
foreign_locale = 'es'
foreign_slug = 'es-doc'
en_doc = document(title='Eng Doc', slug=original_slug,
is_localizable=True, locale=locale)
en_doc.save()
r = revision(document=en_doc, toc_depth=1)
r.save()
post_data = new_document_data()
post_data['title'] = 'ES Doc'
post_data['slug'] = foreign_slug
post_data['content'] = 'This is the content'
post_data['is_localizable'] = True
post_data['form'] = 'both'
post_data['toc_depth'] = r.toc_depth
translate_url = reverse('wiki.document', args=[original_slug],
locale=settings.WIKI_DEFAULT_LANGUAGE)
translate_url += '$translate?tolocale=' + foreign_locale
response = self.client.post(translate_url, post_data)
self.assertRedirects(response, reverse('wiki.document',
args=[foreign_slug],
locale=foreign_locale))
es_d = Document.objects.get(locale=foreign_locale, slug=foreign_slug)
eq_(r.toc_depth, es_d.current_revision.toc_depth)
@override_constance_settings(KUMASCRIPT_TIMEOUT=1.0)
def test_translate_rebuilds_source_json(self):
self.client.login(username='admin', password='testpass')
# Create an English original and a Spanish translation.
en_slug = 'en-doc'
es_locale = 'es'
es_slug = 'es-doc'
en_doc = document(title='EN Doc',
slug=en_slug,
is_localizable=True,
locale=settings.WIKI_DEFAULT_LANGUAGE)
en_doc.save()
en_doc.render()
en_doc = Document.objects.get(locale=settings.WIKI_DEFAULT_LANGUAGE,
slug=en_slug)
old_en_json = json.loads(en_doc.json)
r = revision(document=en_doc)
r.save()
translation_data = new_document_data()
translation_data['title'] = 'ES Doc'
translation_data['slug'] = es_slug
translation_data['content'] = 'This is the content'
translation_data['is_localizable'] = False
translation_data['form'] = 'both'
translate_url = reverse('wiki.document', args=[en_slug],
locale=settings.WIKI_DEFAULT_LANGUAGE)
translate_url += '$translate?tolocale=' + es_locale
response = self.client.post(translate_url, translation_data)
# Sanity to make sure the translate succeeded.
self.assertRedirects(response, reverse('wiki.document',
args=[es_slug],
locale=es_locale))
es_doc = Document.objects.get(locale=es_locale,
slug=es_slug)
es_doc.render()
new_en_json = json.loads(Document.objects.get(pk=en_doc.pk).json)
ok_('translations' in new_en_json)
ok_(translation_data['title'] in [t['title'] for t in \
new_en_json['translations']])
es_translation_json = [t for t in new_en_json['translations'] if \
t['title'] == translation_data['title']][0]
eq_(es_translation_json['last_edit'],
es_doc.current_revision.created.isoformat())
def test_slug_translate(self):
"""Editing a translated doc keeps the correct slug"""
self.client.login(username='admin', password='testpass')
# Settings
original_slug = 'eng-doc'
child_slug = 'child-eng-doc'
foreign_locale = 'es'
foreign_slug = 'es-doc'
foreign_child_slug = 'child-es-doc'
# Create the one-level English Doc
en_doc = document(title='Eng Doc',
slug=original_slug,
is_localizable=True,
locale=settings.WIKI_DEFAULT_LANGUAGE)
en_doc.save()
r = revision(document=en_doc)
r.save()
# Translate to ES
parent_data = new_document_data()
parent_data['title'] = 'ES Doc'
parent_data['slug'] = foreign_slug
parent_data['content'] = 'This is the content'
parent_data['is_localizable'] = True
parent_data['form'] = 'both'
translate_url = reverse('wiki.document', args=[original_slug],
locale=settings.WIKI_DEFAULT_LANGUAGE)
translate_url += '$translate?tolocale=' + foreign_locale
response = self.client.post(translate_url, parent_data)
self.assertRedirects(response, reverse('wiki.document',
args=[foreign_slug],
locale=foreign_locale))
# Go to edit the translation, ensure the the slug is correct
response = self.client.get(reverse('wiki.edit_document',
args=[foreign_slug],
locale=foreign_locale))
page = pq(response.content)
eq_(page.find('input[name=slug]')[0].value, foreign_slug)
# Create an English child now
en_doc = document(title='Child Eng Doc',
slug=original_slug + '/' + child_slug,
is_localizable=True,
locale=settings.WIKI_DEFAULT_LANGUAGE,
parent_topic=en_doc)
en_doc.save()
r = revision(document=en_doc)
r.save()
# Translate to ES
child_data = new_document_data()
child_data['title'] = 'ES Child Doc'
child_data['slug'] = foreign_child_slug
child_data['content'] = 'This is the content'
child_data['is_localizable'] = True
child_data['form'] = 'both'
translate_url = reverse('wiki.document',
args=[original_slug + '/' + child_slug],
locale=settings.WIKI_DEFAULT_LANGUAGE)
translate_url += '$translate?tolocale=' + foreign_locale
response = self.client.post(translate_url, child_data)
slug = foreign_slug + '/' + child_data['slug']
self.assertRedirects(response, reverse('wiki.document',
args=[slug],
locale=foreign_locale))
def test_clone(self):
self.client.login(username='admin', password='testpass')
slug = None
title = None
content = '<p>Hello!</p>'
test_revision = revision(save=True, title=title, slug=slug,
content=content)
document = test_revision.document
response = self.client.get(reverse('wiki.new_document',
args=[],
locale=settings.WIKI_DEFAULT_LANGUAGE) + '?clone=' + str(document.id))
page = pq(response.content)
eq_(page.find('input[name=title]')[0].value, title)
eq_(page.find('input[name=slug]')[0].value, slug)
eq_(page.find('textarea[name=content]')[0].value, content)
def test_localized_based_on(self):
"""Editing a localized article 'based on' an older revision of the
localization is OK."""
self.client.login(username='admin', password='testpass')
en_r = revision(save=True)
fr_d = document(parent=en_r.document, locale='fr', save=True)
fr_r = revision(document=fr_d, based_on=en_r, save=True)
url = reverse('wiki.new_revision_based_on',
locale='fr', args=(fr_d.full_path, fr_r.pk,))
response = self.client.get(url)
input = pq(response.content)('#id_based_on')[0]
eq_(int(input.value), en_r.pk)
def test_restore_translation_source(self):
"""Edit a localized article without an English parent allows user to
set translation parent."""
# Create english doc
self.client.login(username='admin', password='testpass')
data = new_document_data()
self.client.post(reverse('wiki.new_document'), data)
en_d = Document.objects.get(locale=data['locale'], slug=data['slug'])
# Create french doc
data.update({'locale': 'fr',
'full_path': 'fr/a-test-article',
'title': 'A Tést Articlé',
'content': "C'ést bon."})
self.client.post(reverse('wiki.new_document', locale='fr'), data)
fr_d = Document.objects.get(locale=data['locale'], slug=data['slug'])
# Check edit doc page for choose parent box
url = reverse('wiki.edit_document', args=[fr_d.slug], locale='fr')
response = self.client.get(url)
ok_(pq(response.content)('li.metadata-choose-parent'))
# Set the parent
data.update({'form': 'rev', 'parent_id': en_d.id})
resp = self.client.post(url, data)
eq_(302, resp.status_code)
ok_('fr/docs/a-test-article' in resp['Location'])
# Check the languages drop-down
resp = self.client.get(resp['Location'])
translations = pq(resp.content)('ul#translations li')
ok_('A Test Article' in translations.html())
ok_('English (US)' in translations.text())
def test_translation_source(self):
"""Allow users to change "translation source" settings"""
self.client.login(username='admin', password='testpass')
data = new_document_data()
self.client.post(reverse('wiki.new_document'), data)
parent = Document.objects.get(locale=data['locale'], slug=data['slug'])
data.update({'full_path': 'en-US/a-test-article',
'title': 'Another Test Article',
'content': "Yahoooo!",
'parent_id': parent.id})
self.client.post(reverse('wiki.new_document'), data)
child = Document.objects.get(locale=data['locale'], slug=data['slug'])
url = reverse('wiki.edit_document', args=[child.slug])
response = self.client.get(url)
content = pq(response.content)
ok_(content('li.metadata-choose-parent'))
ok_(str(parent.id) in content.html())
@attr('tags')
@mock.patch.object(Site.objects, 'get_current')
def test_document_tags(self, get_current):
"""Document tags can be edited through revisions"""
data = new_document_data()
locale = data['locale']
slug = data['slug']
path = slug
ts1 = ('JavaScript', 'AJAX', 'DOM')
ts2 = ('XML', 'JSON')
get_current.return_value.domain = 'su.mo.com'
self.client.login(username='admin', password='testpass')
def assert_tag_state(yes_tags, no_tags):
# Ensure the tags are found for the Documents
doc = Document.objects.get(locale=locale, slug=slug)
doc_tags = [x.name for x in doc.tags.all()]
for t in yes_tags:
ok_(t in doc_tags)
for t in no_tags:
ok_(t not in doc_tags)
# Ensure the tags are found in the Document view
response = self.client.get(reverse('wiki.document',
args=[doc.full_path]), data)
page = pq(response.content)
for t in yes_tags:
eq_(1, page.find('.tags li a:contains("%s")' % t).length,
'%s should NOT appear in document view tags' % t)
for t in no_tags:
eq_(0, page.find('.tags li a:contains("%s")' % t).length,
'%s should appear in document view tags' % t)
# Check for the document slug (title in feeds) in the tag listing
for t in yes_tags:
response = self.client.get(reverse('wiki.tag', args=[t]))
ok_(doc.slug in response.content.decode('utf-8'))
response = self.client.get(reverse('wiki.feeds.recent_documents',
args=['atom', t]))
ok_(doc.title in response.content.decode('utf-8'))
for t in no_tags:
response = self.client.get(reverse('wiki.tag', args=[t]))
ok_(doc.slug not in response.content.decode('utf-8'))
response = self.client.get(reverse('wiki.feeds.recent_documents',
args=['atom', t]))
ok_(doc.title not in response.content.decode('utf-8'))
# Create a new doc with tags
data.update({'slug': slug, 'tags': ','.join(ts1)})
self.client.post(reverse('wiki.new_document'), data)
assert_tag_state(ts1, ts2)
# Now, update the tags.
data.update({'form': 'rev', 'tags': ', '.join(ts2)})
self.client.post(reverse('wiki.edit_document',
args=[path]), data)
assert_tag_state(ts2, ts1)
@attr('review_tags')
@mock.patch.object(Site.objects, 'get_current')
def test_review_tags(self, get_current):
"""Review tags can be managed on document revisions"""
get_current.return_value.domain = 'su.mo.com'
self.client.login(username='admin', password='testpass')
# Create a new doc with one review tag
data = new_document_data()
data.update({'review_tags': ['technical']})
response = self.client.post(reverse('wiki.new_document'), data)
# Ensure there's now a doc with that expected tag in its newest
# revision
doc = Document.objects.get(slug="a-test-article")
rev = doc.revisions.order_by('-id').all()[0]
review_tags = [x.name for x in rev.review_tags.all()]
eq_(['technical'], review_tags)
# Now, post an update with two tags
data.update({
'form': 'rev',
'review_tags': ['editorial', 'technical'],
})
response = self.client.post(reverse('wiki.edit_document',
args=[doc.full_path]), data)
# Ensure the doc's newest revision has both tags.
doc = Document.objects.get(locale=settings.WIKI_DEFAULT_LANGUAGE,
slug="a-test-article")
rev = doc.revisions.order_by('-id').all()[0]
review_tags = [x.name for x in rev.review_tags.all()]
review_tags.sort()
eq_(['editorial', 'technical'], review_tags)
# Now, ensure that warning boxes appear for the review tags.
response = self.client.get(reverse('wiki.document',
args=[doc.full_path]), data)
page = pq(response.content)
eq_(2, page.find('.warning.warning-review').length)
# Ensure the page appears on the listing pages
response = self.client.get(reverse('wiki.list_review'))
eq_(1, pq(response.content).find("ul.document-list li a:contains('%s')" %
doc.title).length)
response = self.client.get(reverse('wiki.list_review_tag',
args=('technical',)))
eq_(1, pq(response.content).find("ul.document-list li a:contains('%s')" %
doc.title).length)
response = self.client.get(reverse('wiki.list_review_tag',
args=('editorial',)))
eq_(1, pq(response.content).find("ul.document-list li a:contains('%s')" %
doc.title).length)
# Also, ensure that the page appears in the proper feeds
# HACK: Too lazy to parse the XML. Lazy lazy.
response = self.client.get(reverse('wiki.feeds.list_review',
args=('atom',)))
ok_('<entry><title>%s</title>' % doc.title in response.content)
response = self.client.get(reverse('wiki.feeds.list_review_tag',
args=('atom', 'technical', )))
ok_('<entry><title>%s</title>' % doc.title in response.content)
response = self.client.get(reverse('wiki.feeds.list_review_tag',
args=('atom', 'editorial', )))
ok_('<entry><title>%s</title>' % doc.title in response.content)
# Post an edit that removes one of the tags.
data.update({
'form': 'rev',
'review_tags': ['editorial', ]
})
response = self.client.post(reverse('wiki.edit_document',
args=[doc.full_path]), data)
# Ensure only one of the tags' warning boxes appears, now.
response = self.client.get(reverse('wiki.document',
args=[doc.full_path]), data)
page = pq(response.content)
eq_(1, page.find('.warning.warning-review').length)
# Ensure the page appears on the listing pages
response = self.client.get(reverse('wiki.list_review'))
eq_(1, pq(response.content).find("ul.document-list li a:contains('%s')" %
doc.title).length)
response = self.client.get(reverse('wiki.list_review_tag',
args=('technical',)))
eq_(0, pq(response.content).find("ul.document-list li a:contains('%s')" %
doc.title).length)
response = self.client.get(reverse('wiki.list_review_tag',
args=('editorial',)))
eq_(1, pq(response.content).find("ul.document-list li a:contains('%s')" %
doc.title).length)
# Also, ensure that the page appears in the proper feeds
# HACK: Too lazy to parse the XML. Lazy lazy.
response = self.client.get(reverse('wiki.feeds.list_review',
args=('atom',)))
ok_('<entry><title>%s</title>' % doc.title in response.content)
response = self.client.get(reverse('wiki.feeds.list_review_tag',
args=('atom', 'technical', )))
ok_('<entry><title>%s</title>' % doc.title not in response.content)
response = self.client.get(reverse('wiki.feeds.list_review_tag',
args=('atom', 'editorial', )))
ok_('<entry><title>%s</title>' % doc.title in response.content)
@attr('review-tags')
def test_quick_review(self):
"""Test the quick-review button."""
self.client.login(username='admin', password='testpass')
test_data = [
{
'params': {'approve_technical': 1},
'expected_tags': ['editorial'],
'name': 'technical',
'message_contains': ['Technical review completed.']
},
{
'params': {'approve_editorial': 1},
'expected_tags': ['technical'],
'name': 'editorial',
'message_contains': ['Editorial review completed.']
},
{
'params': {
'approve_technical': 1,
'approve_editorial': 1
},
'expected_tags': [],
'name': 'editorial-technical',
'message_contains': [
'Technical review completed.',
'Editorial review completed.',
]
}
]
for data_dict in test_data:
slug = 'test-quick-review-%s' % data_dict['name']
data = new_document_data()
data.update({'review_tags': ['editorial', 'technical'],
'slug': slug})
resp = self.client.post(reverse('wiki.new_document'), data)
doc = Document.objects.get(slug=slug)
rev = doc.revisions.order_by('-id').all()[0]
review_url = reverse('wiki.quick_review',
args=[doc.full_path])
params = dict(data_dict['params'], revision_id=rev.id)
resp = self.client.post(review_url, params)
eq_(302, resp.status_code)
doc = Document.objects.get(locale=settings.WIKI_DEFAULT_LANGUAGE,
slug=slug)
rev = doc.revisions.order_by('-id').all()[0]
review_tags = [x.name for x in rev.review_tags.all()]
review_tags.sort()
for expected_str in data_dict['message_contains']:
ok_(expected_str in rev.summary)
eq_(data_dict['expected_tags'], review_tags)
@attr('midair')
def test_edit_midair_collision(self):
self.client.login(username='admin', password='testpass')
# Post a new document.
data = new_document_data()
resp = self.client.post(reverse('wiki.new_document'), data)
doc = Document.objects.get(slug=data['slug'])
# Edit #1 starts...
resp = self.client.get(reverse('wiki.edit_document',
args=[doc.full_path]))
page = pq(resp.content)
rev_id1 = page.find('input[name="current_rev"]').attr('value')
# Edit #2 starts...
resp = self.client.get(reverse('wiki.edit_document',
args=[doc.full_path]))
page = pq(resp.content)
rev_id2 = page.find('input[name="current_rev"]').attr('value')
# Edit #2 submits successfully
data.update({
'form': 'rev',
'content': 'This edit got there first',
'current_rev': rev_id2
})
resp = self.client.post(reverse('wiki.edit_document',
args=[doc.full_path]), data)
eq_(302, resp.status_code)
# Edit #1 submits, but receives a mid-aired notification
data.update({
'form': 'rev',
'content': 'This edit gets mid-aired',
'current_rev': rev_id1
})
resp = self.client.post(reverse('wiki.edit_document',
args=[doc.full_path]), data)
eq_(200, resp.status_code)
ok_(unicode(MIDAIR_COLLISION).encode('utf-8') in resp.content,
"Midair collision message should appear")
@attr('toc')
def test_toc_toggle_off(self):
"""Toggling of table of contents in revisions"""
self.client.login(username='admin', password='testpass')
d, _ = doc_rev()
data = new_document_data()
ok_(Document.objects.get(slug=d.slug, locale=d.locale).show_toc)
data['form'] = 'rev'
data['toc_depth'] = 0
data['slug'] = d.slug
data['title'] = d.title
self.client.post(reverse('wiki.edit_document',
args=[d.full_path]),
data)
doc = Document.objects.get(slug=d.slug, locale=d.locale)
eq_(0, doc.current_revision.toc_depth)
@attr('toc')
def test_toc_toggle_on(self):
"""Toggling of table of contents in revisions"""
self.client.login(username='admin', password='testpass')
d, r = doc_rev()
new_r = revision(document=d, content=r.content, toc_depth=0,
is_approved=True)
new_r.save()
ok_(not Document.objects.get(slug=d.slug, locale=d.locale).show_toc)
data = new_document_data()
data['form'] = 'rev'
data['slug'] = d.slug
data['title'] = d.title
self.client.post(reverse('wiki.edit_document',
args=[d.full_path]),
data)
ok_(Document.objects.get(slug=d.slug, locale=d.locale).show_toc)
def test_parent_topic(self):
"""Selection of a parent topic when creating a document."""
self.client.login(username='admin', password='testpass')
d = document(title='HTML8')
d.save()
r = revision(document=d)
r.save()
data = new_document_data()
data['title'] = 'Replicated local storage'
data['parent_topic'] = d.id
resp = self.client.post(reverse('wiki.new_document'), data)
eq_(302, resp.status_code)
ok_(d.children.count() == 1)
ok_(d.children.all()[0].title == 'Replicated local storage')
def test_repair_breadcrumbs(self):
english_top = document(locale=settings.WIKI_DEFAULT_LANGUAGE,
title='English top',
save=True)
english_mid = document(locale=settings.WIKI_DEFAULT_LANGUAGE,
title='English mid',
parent_topic=english_top,
save=True)
english_bottom = document(locale=settings.WIKI_DEFAULT_LANGUAGE,
title='English bottom',
parent_topic=english_mid,
save=True)
french_top = document(locale='fr',
title='French top',
parent=english_top,
save=True)
french_mid = document(locale='fr',
title='French mid',
parent=english_mid,
parent_topic=english_mid,
save=True)
french_bottom = document(locale='fr',
title='French bottom',
parent=english_bottom,
parent_topic=english_bottom,
save=True)
self.client.login(username='admin', password='testpass')
resp = self.client.get(reverse('wiki.repair_breadcrumbs',
args=[french_bottom.full_path],
locale='fr'))
eq_(302, resp.status_code)
ok_(french_bottom.get_absolute_url() in resp['Location'])
french_bottom_fixed = Document.objects.get(locale='fr',
title=french_bottom.title)
eq_(french_mid.id, french_bottom_fixed.parent_topic.id)
eq_(french_top.id, french_bottom_fixed.parent_topic.parent_topic.id)
def test_translate_on_edit(self):
d1 = document(title="Doc1", locale=settings.WIKI_DEFAULT_LANGUAGE,
save=True)
revision(document=d1, save=True)
d2 = document(title="TransDoc1", locale='de', parent=d1, save=True)
revision(document=d2, save=True)
self.client.login(username='admin', password='testpass')
url = reverse('wiki.edit_document', args=(d2.slug,), locale=d2.locale)
resp = self.client.get(url)
eq_(200, resp.status_code)
def test_discard_location(self):
"""Testing that the 'discard' HREF goes to the correct place when it's
explicitely and implicitely set"""
self.client.login(username='admin', password='testpass')
def _create_doc(slug, locale):
doc = document(slug=slug, is_localizable=True, locale=locale)
doc.save()
r = revision(document=doc)
r.save()
return doc
# Test that the 'discard' button on an edit goes to the original page
doc = _create_doc('testdiscarddoc', settings.WIKI_DEFAULT_LANGUAGE)
response = self.client.get(reverse('wiki.edit_document',
args=[doc.slug], locale=doc.locale))
eq_(pq(response.content).find('.btn-discard').attr('href'),
reverse('wiki.document', args=[doc.slug], locale=doc.locale))
# Test that the 'discard button on a new translation goes
# to the en-US page'
response = self.client.get(reverse('wiki.translate',
args=[doc.slug], locale=doc.locale) + '?tolocale=es')
eq_(pq(response.content).find('.btn-discard').attr('href'),
reverse('wiki.document', args=[doc.slug], locale=doc.locale))
# Test that the 'discard' button on an existing translation goes
# to the 'es' page
foreign_doc = _create_doc('testdiscarddoc', 'es')
response = self.client.get(reverse('wiki.edit_document',
args=[foreign_doc.slug],
locale=foreign_doc.locale))
eq_(pq(response.content).find('.btn-discard').attr('href'),
reverse('wiki.document', args=[foreign_doc.slug],
locale=foreign_doc.locale))
# Test new
response = self.client.get(reverse('wiki.new_document',
locale=settings.WIKI_DEFAULT_LANGUAGE))
eq_(pq(response.content).find('.btn-discard').attr('href'),
reverse('wiki.new_document',
locale=settings.WIKI_DEFAULT_LANGUAGE))
@override_constance_settings(KUMASCRIPT_TIMEOUT=1.0)
@mock.patch('kuma.wiki.kumascript.get')
def test_revert(self, mock_kumascript_get):
self.client.login(username='admin', password='testpass')
mock_kumascript_get.return_value = (
'lorem ipsum dolor sit amet', None)
data = new_document_data()
data['title'] = 'A Test Article For Reverting'
data['slug'] = 'test-article-for-reverting'
response = self.client.post(reverse('wiki.new_document'), data)
doc = Document.objects.get(locale=settings.WIKI_DEFAULT_LANGUAGE,
slug='test-article-for-reverting')
rev = doc.revisions.order_by('-id').all()[0]
data['content'] = 'Not lorem ipsum anymore'
data['comment'] = 'Nobody likes Latin anyway'
response = self.client.post(reverse('wiki.edit_document',
args=[doc.full_path]), data)
mock_kumascript_get.called = False
response = self.client.post(reverse('wiki.revert_document',
args=[doc.full_path, rev.id]),
{'revert': True, 'comment': 'Blah blah'})
ok_(mock_kumascript_get.called,
"kumascript should have been used")
ok_(302 == response.status_code)
rev = doc.revisions.order_by('-id').all()[0]
ok_('lorem ipsum dolor sit amet' == rev.content)
ok_('Blah blah' in rev.comment)
mock_kumascript_get.called = False
rev = doc.revisions.order_by('-id').all()[1]
response = self.client.post(reverse('wiki.revert_document',
args=[doc.full_path, rev.id]),
{'revert': True})
ok_(302 == response.status_code)
rev = doc.revisions.order_by('-id').all()[0]
ok_(not ': ' in rev.comment)
ok_(mock_kumascript_get.called,
"kumascript should have been used")
def test_store_revision_ip(self):
self.client.login(username='testuser', password='testpass')
data = new_document_data()
slug = 'test-article-for-storing-revision-ip'
data.update({'title': 'A Test Article For Storing Revision IP',
'slug': slug})
self.client.post(reverse('wiki.new_document'), data)
doc = Document.objects.get(locale=settings.WIKI_DEFAULT_LANGUAGE,
slug=slug)
data.update({'form': 'rev',
'content': 'This revision should NOT record IP',
'comment': 'This revision should NOT record IP'})
self.client.post(reverse('wiki.edit_document', args=[doc.full_path]),
data)
eq_(0, RevisionIP.objects.all().count())
Switch.objects.create(name='store_revision_ips', active=True)
data.update({'content': 'Store the IP address for the revision.',
'comment': 'Store the IP address for the revision.'})
self.client.post(reverse('wiki.edit_document', args=[doc.full_path]),
data)
eq_(1, RevisionIP.objects.all().count())
rev = doc.revisions.order_by('-id').all()[0]
rev_ip = RevisionIP.objects.get(revision=rev)
eq_('127.0.0.1', rev_ip.ip)
@mock.patch.object(Site.objects, 'get_current')
def test_email_for_first_edits(self, get_current):
get_current.return_value.domain = 'dev.mo.org'
self.client.login(username='testuser', password='testpass')
data = new_document_data()
slug = 'test-article-for-storing-revision-ip'
data.update({'title': 'A Test Article For First Edit Emails',
'slug': slug})
self.client.post(reverse('wiki.new_document'), data)
eq_(1, len(mail.outbox))
doc = Document.objects.get(
locale=settings.WIKI_DEFAULT_LANGUAGE, slug=slug)
data.update({'form': 'rev',
'content': 'This edit should not send an email',
'comment': 'This edit should not send an email'})
self.client.post(reverse('wiki.edit_document',
args=[doc.full_path]),
data)
eq_(1, len(mail.outbox))
self.client.login(username='admin', password='testpass')
data.update({'content': 'Admin first edit should send an email',
'comment': 'Admin first edit should send an email'})
self.client.post(reverse('wiki.edit_document',
args=[doc.full_path]),
data)
eq_(2, len(mail.outbox))
def _check_message_for_headers(message, username):
ok_("%s made their first edit" % username in message.subject)
eq_({'X-Kuma-Document-Url': "https://dev.mo.org%s" % doc.get_absolute_url(),
'X-Kuma-Editor-Username': username}, message.extra_headers)
testuser_message = mail.outbox[0]
admin_message = mail.outbox[1]
_check_message_for_headers(testuser_message, 'testuser')
_check_message_for_headers(admin_message, 'admin')
class DocumentWatchTests(UserTestCase, WikiTestCase):
"""Tests for un/subscribing to document edit notifications."""
localizing_client = True
def setUp(self):
super(DocumentWatchTests, self).setUp()
self.document, self.r = doc_rev()
self.client.login(username='testuser', password='testpass')
def test_watch_GET_405(self):
"""Watch document with HTTP GET results in 405."""
response = get(self.client, 'wiki.subscribe_document',
args=[self.document.slug])
eq_(405, response.status_code)
def test_unwatch_GET_405(self):
"""Unwatch document with HTTP GET results in 405."""
response = get(self.client, 'wiki.subscribe_document',
args=[self.document.slug])
eq_(405, response.status_code)
def test_watch_unwatch(self):
"""Watch and unwatch a document."""
user = User.objects.get(username='testuser')
# Subscribe
response = post(self.client, 'wiki.subscribe_document', args=[self.document.slug])
eq_(200, response.status_code)
assert EditDocumentEvent.is_notifying(user, self.document), \
'Watch was not created'
# Unsubscribe
response = post(self.client, 'wiki.subscribe_document', args=[self.document.slug])
eq_(200, response.status_code)
assert not EditDocumentEvent.is_notifying(user, self.document), \
'Watch was not destroyed'
class SectionEditingResourceTests(UserTestCase, WikiTestCase):
localizing_client = True
def test_raw_source(self):
"""The raw source for a document can be requested"""
self.client.login(username='admin', password='testpass')
d, r = doc_rev("""
<h1 id="s1">s1</h1>
<p>test</p>
<p>test</p>
<h1 id="s2">s2</h1>
<p>test</p>
<p>test</p>
<h1 id="s3">s3</h1>
<p>test</p>
<p>test</p>
""")
expected = """
<h1 id="s1">s1</h1>
<p>test</p>
<p>test</p>
<h1 id="s2">s2</h1>
<p>test</p>
<p>test</p>
<h1 id="s3">s3</h1>
<p>test</p>
<p>test</p>
"""
Switch.objects.create(name='application_ACAO', active=True)
response = self.client.get('%s?raw=true' %
reverse('wiki.document', args=[d.full_path]),
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
ok_('Access-Control-Allow-Origin' in response)
eq_('*', response['Access-Control-Allow-Origin'])
eq_(normalize_html(expected),
normalize_html(response.content))
@attr('bug821986')
def test_raw_editor_safety_filter(self):
"""Safety filter should be applied before rendering editor"""
self.client.login(username='admin', password='testpass')
d, r = doc_rev("""
<p onload=alert(3)>FOO</p>
<svg><circle onload=confirm(3)>HI THERE</circle></svg>
""")
response = self.client.get('%s?raw=true' %
reverse('wiki.document', args=[d.full_path]),
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
ok_('<p onload=' not in response.content)
ok_('<circle onload=' not in response.content)
def test_raw_with_editing_links_source(self):
"""The raw source for a document can be requested, with section editing
links"""
self.client.login(username='admin', password='testpass')
d, r = doc_rev("""
<h1 id="s1">s1</h1>
<p>test</p>
<p>test</p>
<h1 id="s2">s2</h1>
<p>test</p>
<p>test</p>
<h1 id="s3">s3</h1>
<p>test</p>
<p>test</p>
""")
expected = """
<h1 id="s1"><a class="edit-section" data-section-id="s1" data-section-src-url="/en-US/docs/%(full_path)s?raw=true&section=s1" href="/en-US/docs/%(full_path)s$edit?section=s1&edit_links=true" title="Edit section">Edit</a>s1</h1>
<p>test</p>
<p>test</p>
<h1 id="s2"><a class="edit-section" data-section-id="s2" data-section-src-url="/en-US/docs/%(full_path)s?raw=true&section=s2" href="/en-US/docs/%(full_path)s$edit?section=s2&edit_links=true" title="Edit section">Edit</a>s2</h1>
<p>test</p>
<p>test</p>
<h1 id="s3"><a class="edit-section" data-section-id="s3" data-section-src-url="/en-US/docs/%(full_path)s?raw=true&section=s3" href="/en-US/docs/%(full_path)s$edit?section=s3&edit_links=true" title="Edit section">Edit</a>s3</h1>
<p>test</p>
<p>test</p>
""" % {'full_path': d.full_path}
response = self.client.get('%s?raw=true&edit_links=true' %
reverse('wiki.document', args=[d.full_path]),
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
eq_(normalize_html(expected),
normalize_html(response.content))
def test_raw_section_source(self):
"""The raw source for a document section can be requested"""
self.client.login(username='admin', password='testpass')
d, r = doc_rev("""
<h1 id="s1">s1</h1>
<p>test</p>
<p>test</p>
<h1 id="s2">s2</h1>
<p>test</p>
<p>test</p>
<h1 id="s3">s3</h1>
<p>test</p>
<p>test</p>
""")
expected = """
<h1 id="s2">s2</h1>
<p>test</p>
<p>test</p>
"""
response = self.client.get('%s?section=s2&raw=true' %
reverse('wiki.document',
args=[d.full_path]),
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
eq_(normalize_html(expected),
normalize_html(response.content))
@attr('midair')
@attr('rawsection')
def test_raw_section_edit(self):
self.client.login(username='admin', password='testpass')
d, r = doc_rev("""
<h1 id="s1">s1</h1>
<p>test</p>
<p>test</p>
<h1 id="s2">s2</h1>
<p>test</p>
<p>test</p>
<h1 id="s3">s3</h1>
<p>test</p>
<p>test</p>
""")
replace = """
<h1 id="s2">s2</h1>
<p>replace</p>
"""
expected = """
<h1 id="s2">s2</h1>
<p>replace</p>
"""
response = self.client.post('%s?section=s2&raw=true' %
reverse('wiki.edit_document',
args=[d.full_path]),
{"form": "rev",
"slug": d.slug,
"content": replace},
follow=True,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
eq_(normalize_html(expected),
normalize_html(response.content))
expected = """
<h1 id="s1">s1</h1>
<p>test</p>
<p>test</p>
<h1 id="s2">s2</h1>
<p>replace</p>
<h1 id="s3">s3</h1>
<p>test</p>
<p>test</p>
"""
response = self.client.get('%s?raw=true' %
reverse('wiki.document',
args=[d.full_path]),
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
eq_(normalize_html(expected),
normalize_html(response.content))
@attr('midair')
def test_midair_section_merge(self):
"""If a page was changed while someone was editing, but the changes
didn't affect the specific section being edited, then ignore the midair
warning"""
self.client.login(username='admin', password='testpass')
doc, rev = doc_rev("""
<h1 id="s1">s1</h1>
<p>test</p>
<p>test</p>
<h1 id="s2">s2</h1>
<p>test</p>
<p>test</p>
<h1 id="s3">s3</h1>
<p>test</p>
<p>test</p>
""")
replace_1 = """
<h1 id="replace1">replace1</h1>
<p>replace</p>
"""
replace_2 = """
<h1 id="replace2">replace2</h1>
<p>replace</p>
"""
expected = """
<h1 id="replace1">replace1</h1>
<p>replace</p>
<h1 id="replace2">replace2</h1>
<p>replace</p>
<h1 id="s3">s3</h1>
<p>test</p>
<p>test</p>
"""
data = {
'form': 'rev',
'content': rev.content,
'slug': ''
}
# Edit #1 starts...
resp = self.client.get('%s?section=s1' %
reverse('wiki.edit_document',
args=[doc.full_path]),
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
page = pq(resp.content)
rev_id1 = page.find('input[name="current_rev"]').attr('value')
# Edit #2 starts...
resp = self.client.get('%s?section=s2' %
reverse('wiki.edit_document',
args=[doc.full_path]),
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
page = pq(resp.content)
rev_id2 = page.find('input[name="current_rev"]').attr('value')
# Edit #2 submits successfully
data.update({
'form': 'rev',
'content': replace_2,
'current_rev': rev_id2,
'slug': doc.slug
})
resp = self.client.post('%s?section=s2&raw=true' %
reverse('wiki.edit_document',
args=[doc.full_path]),
data,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
eq_(302, resp.status_code)
# Edit #1 submits, but since it's a different section, there's no
# mid-air collision
data.update({
'form': 'rev',
'content': replace_1,
'current_rev': rev_id1
})
resp = self.client.post('%s?section=s1&raw=true' %
reverse('wiki.edit_document', args=[doc.full_path]),
data,
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
# No conflict, but we should get a 205 Reset as an indication that the
# page needs a refresh.
eq_(205, resp.status_code)
# Finally, make sure that all the edits landed
response = self.client.get('%s?raw=true' %
reverse('wiki.document',
args=[doc.full_path]),
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
eq_(normalize_html(expected),
normalize_html(response.content))
# Also, ensure that the revision is slipped into the headers
eq_(unicode(Document.objects.get(slug=doc.slug, locale=doc.locale)
.current_revision.id),
unicode(response['x-kuma-revision']))
@attr('midair')
def test_midair_section_collision(self):
"""If both a revision and the edited section has changed, then a
section edit is a collision."""
self.client.login(username='admin', password='testpass')
doc, rev = doc_rev("""
<h1 id="s1">s1</h1>
<p>test</p>
<p>test</p>
<h1 id="s2">s2</h1>
<p>test</p>
<p>test</p>
<h1 id="s3">s3</h1>
<p>test</p>
<p>test</p>
""")
replace_1 = """
<h1 id="s2">replace</h1>
<p>replace</p>
"""
replace_2 = """
<h1 id="s2">first replace</h1>
<p>first replace</p>
"""
data = {
'form': 'rev',
'content': rev.content
}
# Edit #1 starts...
resp = self.client.get('%s?section=s2' %
reverse('wiki.edit_document',
args=[doc.full_path]),
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
page = pq(resp.content)
rev_id1 = page.find('input[name="current_rev"]').attr('value')
# Edit #2 starts...
resp = self.client.get('%s?section=s2' %
reverse('wiki.edit_document',
args=[doc.full_path]),
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
page = pq(resp.content)
rev_id2 = page.find('input[name="current_rev"]').attr('value')
# Edit #2 submits successfully
data.update({
'form': 'rev',
'content': replace_2,
'slug': doc.slug,
'current_rev': rev_id2
})
resp = self.client.post('%s?section=s2&raw=true' %
reverse('wiki.edit_document',
args=[doc.full_path]),
data, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
eq_(302, resp.status_code)
# Edit #1 submits, but since it's the same section, there's a collision
data.update({
'form': 'rev',
'content': replace_1,
'current_rev': rev_id1
})
resp = self.client.post('%s?section=s2&raw=true' %
reverse('wiki.edit_document',
args=[doc.full_path]),
data, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
# With the raw API, we should get a 409 Conflict on collision.
eq_(409, resp.status_code)
def test_raw_include_option(self):
doc_src = u"""
<div class="noinclude">{{ XULRefAttr() }}</div>
<dl>
<dt>{{ XULAttr("maxlength") }}</dt>
<dd>Type: <em>integer</em></dd>
<dd>Przykłady 例 예제 示例</dd>
</dl>
<div class="noinclude">
<p>{{ languages( { "ja": "ja/XUL/Attribute/maxlength" } ) }}</p>
</div>
"""
doc, rev = doc_rev(doc_src)
expected = u"""
<dl>
<dt>{{ XULAttr("maxlength") }}</dt>
<dd>Type: <em>integer</em></dd>
<dd>Przykłady 例 예제 示例</dd>
</dl>
"""
resp = self.client.get('%s?raw&include' %
reverse('wiki.document', args=[doc.full_path]),
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
eq_(normalize_html(expected),
normalize_html(resp.content.decode('utf-8')))
def test_section_edit_toc(self):
"""show_toc is preserved in section editing."""
self.client.login(username='admin', password='testpass')
doc, rev = doc_rev("""
<h1 id="s1">s1</h1>
<p>test</p>
<p>test</p>
<h1 id="s2">s2</h1>
<p>test</p>
<p>test</p>
<h1 id="s3">s3</h1>
<p>test</p>
<p>test</p>
""")
rev.toc_depth = 1
rev.save()
replace = """
<h1 id="s2">s2</h1>
<p>replace</p>
"""
self.client.post('%s?section=s2&raw=true' %
reverse('wiki.edit_document', args=[doc.full_path]),
{"form": "rev", "slug": doc.slug, "content": replace},
follow=True, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
changed = Document.objects.get(pk=doc.id).current_revision
ok_(rev.id != changed.id)
eq_(1, changed.toc_depth)
def test_section_edit_review_tags(self):
"""review tags are preserved in section editing."""
self.client.login(username='admin', password='testpass')
doc, rev = doc_rev("""
<h1 id="s1">s1</h1>
<p>test</p>
<p>test</p>
<h1 id="s2">s2</h1>
<p>test</p>
<p>test</p>
<h1 id="s3">s3</h1>
<p>test</p>
<p>test</p>
""")
tags_to_save = ['bar', 'foo']
rev.save()
rev.review_tags.set(*tags_to_save)
replace = """
<h1 id="s2">s2</h1>
<p>replace</p>
"""
self.client.post('%s?section=s2&raw=true' %
reverse('wiki.edit_document', args=[doc.full_path]),
{"form": "rev", "slug": doc.slug, "content": replace},
follow=True, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
changed = Document.objects.get(pk=doc.id).current_revision
ok_(rev.id != changed.id)
eq_(set(tags_to_save),
set([t.name for t in changed.review_tags.all()]))
class MindTouchRedirectTests(UserTestCase, WikiTestCase):
"""
Test that we appropriately redirect old-style MindTouch URLs to
new-style kuma URLs.
"""
# A note on these tests: we could try to use assertRedirects on
# these, but for the most part we're just constructing a URL
# similar enough to the wiki app's own built-in redirects that
# it'll pick up the request and do what we want with it. But it
# may end up issuing its own redirects, which are tricky to sort
# out from the ones the legacy MindTouch handling will emit, so
# instead we just test that A) we did issue a redirect and B) the
# URL we constructed is enough for the document views to go on.
localizing_client = True
server_prefix = 'http://testserver/%s/docs' % settings.WIKI_DEFAULT_LANGUAGE
namespace_urls = (
# One for each namespace.
{'mindtouch': '/Help:Foo',
'kuma': '%s/Help:Foo' % server_prefix},
{'mindtouch': '/Help_talk:Foo',
'kuma': '%s/Help_talk:Foo' % server_prefix},
{'mindtouch': '/Project:En/MDC_editor_guide',
'kuma': '%s/Project:MDC_editor_guide' % server_prefix},
{'mindtouch': '/Project_talk:En/MDC_style_guide',
'kuma': '%s/Project_talk:MDC_style_guide' % server_prefix},
{'mindtouch': '/Special:Foo',
'kuma': '%s/Special:Foo' % server_prefix},
{'mindtouch': '/Talk:en/Foo',
'kuma': '%s/Talk:Foo' % server_prefix},
{'mindtouch': '/Template:Foo',
'kuma': '%s/Template:Foo' % server_prefix},
{'mindtouch': '/User:Foo',
'kuma': '%s/User:Foo' % server_prefix},
)
documents = (
{'title': 'XHTML', 'mt_locale': 'cn', 'kuma_locale': 'zh-CN',
'expected': '/zh-CN/docs/XHTML'},
{'title': 'JavaScript', 'mt_locale': 'zh_cn', 'kuma_locale': 'zh-CN',
'expected': '/zh-CN/docs/JavaScript'},
{'title': 'XHTML6', 'mt_locale': 'zh_tw', 'kuma_locale': 'zh-CN',
'expected': '/zh-TW/docs/XHTML6'},
{'title': 'HTML7', 'mt_locale': 'fr', 'kuma_locale': 'fr',
'expected': '/fr/docs/HTML7'},
)
def test_namespace_urls(self):
new_doc = document()
new_doc.title = 'User:Foo'
new_doc.slug = 'User:Foo'
new_doc.save()
for namespace_test in self.namespace_urls:
resp = self.client.get(namespace_test['mindtouch'], follow=False)
eq_(301, resp.status_code)
eq_(namespace_test['kuma'], resp['Location'])
def test_trailing_slash(self):
d = document()
d.locale = 'zh-CN'
d.slug = 'foofoo'
d.title = 'FooFoo'
d.save()
mt_url = '/cn/%s/' % (d.slug,)
resp = self.client.get(mt_url)
eq_(301, resp.status_code)
eq_('http://testserver%s' % d.get_absolute_url(), resp['Location'])
def test_document_urls(self):
for doc in self.documents:
d = document()
d.title = doc['title']
d.slug = doc['title']
d.locale = doc['kuma_locale']
d.save()
mt_url = '/%s' % '/'.join([doc['mt_locale'], doc['title']])
resp = self.client.get(mt_url)
eq_(301, resp.status_code)
eq_('http://testserver%s' % doc['expected'], resp['Location'])
def test_view_param(self):
d = document()
d.locale = settings.WIKI_DEFAULT_LANGUAGE
d.slug = 'HTML/HTML5'
d.title = 'HTML 5'
d.save()
mt_url = '/en-US/%s?view=edit' % (d.slug,)
resp = self.client.get(mt_url)
eq_(301, resp.status_code)
expected_url = 'http://testserver%s$edit' % d.get_absolute_url()
eq_(expected_url, resp['Location'])
class AutosuggestDocumentsTests(WikiTestCase):
"""
Test the we're properly filtering out the Redirects from the document list
"""
localizing_client = True
def test_autosuggest_no_term(self):
url = reverse('wiki.autosuggest_documents',
locale=settings.WIKI_DEFAULT_LANGUAGE)
resp = self.client.get(url)
eq_(400, resp.status_code)
def test_document_redirects(self):
# All contain "e", so that will be the search term
invalid_documents = (
{
'title': 'Something Redirect 8',
'html': 'REDIRECT <a class="redirect" href="/blah">Something Redirect</a>',
'is_redirect': 1
},
)
valid_documents = (
{'title': 'e 6', 'html': '<p>Blah text Redirect'},
{'title': 'e 7', 'html': 'AppleTalk'},
{'title': 'Response.Redirect'},
)
for doc in invalid_documents + valid_documents:
d = document()
d.title = doc['title']
if 'html' in doc:
d.html = doc['html']
if 'slug' in doc:
d.slug = doc['slug']
if 'is_redirect' in doc:
d.is_redirect = 1
d.save()
url = reverse('wiki.autosuggest_documents',
locale=settings.WIKI_DEFAULT_LANGUAGE) + '?term=e'
Switch.objects.create(name='application_ACAO', active=True)
resp = self.client.get(url)
ok_('Access-Control-Allow-Origin' in resp)
eq_('*', resp['Access-Control-Allow-Origin'])
eq_(200, resp.status_code)
data = json.loads(resp.content)
eq_(len(data), len(valid_documents))
# Ensure that the valid docs found are all in the valid list
for d in data:
found = False
for v in valid_documents:
if v['title'] in d['title']:
found = True
break
eq_(True, found)
def test_list_no_redirects(self):
Document.objects.all().delete()
invalid_documents = [
{
'title': 'Something Redirect 8',
'slug': 'xx',
'html': 'REDIRECT <a class="redirect" href="%s">yo</a>' % settings.SITE_URL
},
{
'title': 'My Template',
'slug': 'Template:Something',
'html': 'blah',
},
]
valid_documents = [
{'title': 'A Doc', 'slug': 'blah', 'html': 'Blah blah blah'}
]
for doc in invalid_documents + valid_documents:
document(save=True, slug=doc['slug'],
title=doc['title'], html=doc['html'])
resp = self.client.get(reverse('wiki.all_documents',
locale=settings.WIKI_DEFAULT_LANGUAGE))
eq_(len(valid_documents), len(pq(resp.content).find('.document-list li')))
class CodeSampleViewTests(UserTestCase, WikiTestCase):
localizing_client = True
@override_constance_settings(
KUMA_WIKI_IFRAME_ALLOWED_HOSTS='^https?\:\/\/testserver')
def test_code_sample_1(self):
"""The raw source for a document can be requested"""
d, r = doc_rev("""
<p>This is a page. Deal with it.</p>
<div id="sample1" class="code-sample">
<pre class="brush: html">Some HTML</pre>
<pre class="brush: css">.some-css { color: red; }</pre>
<pre class="brush: js">window.alert("HI THERE")</pre>
</div>
<p>test</p>
""")
expecteds = (
'<style type="text/css">.some-css { color: red; }</style>',
'Some HTML',
'<script type="text/javascript">window.alert("HI THERE")</script>',
)
Switch.objects.create(name='application_ACAO', active=True)
response = self.client.get(reverse('wiki.code_sample',
args=[d.full_path, 'sample1']),
HTTP_HOST='testserver')
ok_('Access-Control-Allow-Origin' in response)
eq_('*', response['Access-Control-Allow-Origin'])
eq_(200, response.status_code)
normalized = normalize_html(response.content)
# Content checks
ok_('<!DOCTYPE html>' in response.content)
for item in expecteds:
ok_(item in normalized)
@override_constance_settings(
KUMA_WIKI_IFRAME_ALLOWED_HOSTS='^https?\:\/\/sampleserver')
def test_code_sample_host_restriction(self):
d, r = doc_rev("""
<p>This is a page. Deal with it.</p>
<div id="sample1" class="code-sample">
<pre class="brush: html">Some HTML</pre>
<pre class="brush: css">.some-css { color: red; }</pre>
<pre class="brush: js">window.alert("HI THERE")</pre>
</div>
<p>test</p>
""")
response = self.client.get(reverse('wiki.code_sample',
args=[d.full_path, 'sample1']),
HTTP_HOST='testserver')
eq_(403, response.status_code)
response = self.client.get(reverse('wiki.code_sample',
args=[d.full_path, 'sample1']),
HTTP_HOST='sampleserver')
eq_(200, response.status_code)
@override_constance_settings(
KUMA_WIKI_IFRAME_ALLOWED_HOSTS='^https?\:\/\/sampleserver')
def test_code_sample_iframe_embed(self):
slug = 'test-code-embed'
embed_url = ('https://sampleserver/%s/docs/%s$samples/sample1' %
(settings.WIKI_DEFAULT_LANGUAGE, slug))
doc_src = """
<p>This is a page. Deal with it.</p>
<div id="sample1" class="code-sample">
<pre class="brush: html">Some HTML</pre>
<pre class="brush: css">.some-css { color: red; }</pre>
<pre class="brush: js">window.alert("HI THERE")</pre>
</div>
<iframe id="if1" src="%(embed_url)s"></iframe>
<iframe id="if2" src="http://testserver"></iframe>
<iframe id="if3" src="https://some.alien.site.com"></iframe>
<p>test</p>
""" % dict(embed_url=embed_url)
slug = 'test-code-doc'
d, r = doc_rev()
revision(save=True, document=d, title="Test code doc", slug=slug,
content=doc_src)
response = self.client.get(reverse('wiki.document', args=(d.slug,)))
eq_(200, response.status_code)
page = pq(response.content)
if1 = page.find('#if1')
eq_(if1.length, 1)
eq_(if1.attr('src'), embed_url)
if2 = page.find('#if2')
eq_(if2.length, 1)
eq_(if2.attr('src'), '')
if3 = page.find('#if3')
eq_(if3.length, 1)
eq_(if3.attr('src'), '')
class DeferredRenderingViewTests(UserTestCase, WikiTestCase):
"""Tests for the deferred rendering system and interaction with views"""
localizing_client = True
def setUp(self):
super(DeferredRenderingViewTests, self).setUp()
self.rendered_content = 'HELLO RENDERED CONTENT'
self.raw_content = 'THIS IS RAW CONTENT'
self.d, self.r = doc_rev(self.raw_content)
# Disable TOC, makes content inspection easier.
self.r.toc_depth = 0
self.r.save()
self.d.html = self.raw_content
self.d.rendered_html = self.rendered_content
self.d.save()
self.url = reverse('wiki.document',
args=(self.d.slug,),
locale=self.d.locale)
constance.config.KUMASCRIPT_TIMEOUT = 5.0
constance.config.KUMASCRIPT_MAX_AGE = 600
def tearDown(self):
super(DeferredRenderingViewTests, self).tearDown()
constance.config.KUMASCRIPT_TIMEOUT = 0
constance.config.KUMASCRIPT_MAX_AGE = 0
@mock.patch('kuma.wiki.kumascript.get')
def test_rendered_content(self, mock_kumascript_get):
"""Document view should serve up rendered content when available"""
mock_kumascript_get.return_value = (self.rendered_content, None)
resp = self.client.get(self.url, follow=False)
p = pq(resp.content)
txt = p.find('#wikiArticle').text()
ok_(self.rendered_content in txt)
ok_(self.raw_content not in txt)
eq_(0, p.find('#doc-rendering-in-progress').length)
eq_(0, p.find('#doc-render-raw-fallback').length)
def test_rendering_in_progress_warning(self):
"""Document view should serve up rendered content when available"""
# Make the document look like there's a rendering in progress.
self.d.render_started_at = datetime.datetime.now()
self.d.save()
resp = self.client.get(self.url, follow=False)
p = pq(resp.content)
txt = p.find('#wikiArticle').text()
# Even though a rendering looks like it's in progress, ensure the
# last-known render is displayed.
ok_(self.rendered_content in txt)
ok_(self.raw_content not in txt)
eq_(0, p.find('#doc-rendering-in-progress').length)
# Only for logged-in users, ensure the render-in-progress warning is
# displayed.
self.client.login(username='testuser', password='testpass')
resp = self.client.get(self.url, follow=False)
p = pq(resp.content)
eq_(1, p.find('#doc-rendering-in-progress').length)
@mock.patch('kuma.wiki.kumascript.get')
def test_raw_content_during_initial_render(self, mock_kumascript_get):
"""Raw content should be displayed during a document's initial
deferred rendering"""
mock_kumascript_get.return_value = (self.rendered_content, None)
# Make the document look like there's no rendered content, but that a
# rendering is in progress.
self.d.html = self.raw_content
self.d.rendered_html = ''
self.d.render_started_at = datetime.datetime.now()
self.d.save()
# Now, ensure that raw content is shown in the view.
resp = self.client.get(self.url, follow=False)
p = pq(resp.content)
txt = p.find('#wikiArticle').text()
ok_(self.rendered_content not in txt)
ok_(self.raw_content in txt)
eq_(0, p.find('#doc-render-raw-fallback').length)
# Only for logged-in users, ensure that a warning is displayed about
# the fallback
self.client.login(username='testuser', password='testpass')
resp = self.client.get(self.url, follow=False)
p = pq(resp.content)
eq_(1, p.find('#doc-render-raw-fallback').length)
@attr('schedule_rendering')
@mock.patch.object(Document, 'schedule_rendering')
@mock.patch('kuma.wiki.kumascript.get')
def test_schedule_rendering(self, mock_kumascript_get,
mock_document_schedule_rendering):
mock_kumascript_get.return_value = (self.rendered_content, None)
self.client.login(username='testuser', password='testpass')
data = new_document_data()
data.update({
'form': 'rev',
'content': 'This is an update',
})
edit_url = reverse('wiki.edit_document', args=[self.d.full_path])
resp = self.client.post(edit_url, data)
eq_(302, resp.status_code)
ok_(mock_document_schedule_rendering.called)
mock_document_schedule_rendering.reset_mock()
data.update({
'form': 'both',
'content': 'This is a translation',
})
translate_url = (reverse('wiki.translate', args=[data['slug']],
locale=settings.WIKI_DEFAULT_LANGUAGE) + '?tolocale=fr')
response = self.client.post(translate_url, data)
eq_(302, response.status_code)
ok_(mock_document_schedule_rendering.called)
@mock.patch('kuma.wiki.kumascript.get')
@mock.patch('requests.post')
def test_alternate_bleach_whitelist(self, mock_requests_post,
mock_kumascript_get):
# Some test content with contentious tags.
test_content = """
<p id="foo">
<a style="position: absolute; border: 1px;" href="http://example.com">This is a test</a>
<textarea name="foo"></textarea>
</p>
"""
# Expected result filtered through old/current Bleach rules
expected_content_old = """
<p id="foo">
<a style="position: absolute; border: 1px;" href="http://example.com">This is a test</a>
<textarea name="foo"></textarea>
</p>
"""
# Expected result filtered through alternate whitelist
expected_content_new = """
<p id="foo">
<a style="border: 1px;" href="http://example.com">This is a test</a>
<textarea name="foo"></textarea>
</p>
"""
# Set up an alternate set of whitelists...
constance.config.BLEACH_ALLOWED_TAGS = json.dumps([
"a", "p"
])
constance.config.BLEACH_ALLOWED_ATTRIBUTES = json.dumps({
"a": ['href', 'style'],
"p": ['id']
})
constance.config.BLEACH_ALLOWED_STYLES = json.dumps([
"border"
])
constance.config.KUMASCRIPT_TIMEOUT = 100
# Rig up a mocked response from KumaScript GET method
mock_kumascript_get.return_value = (test_content, None)
# Rig up a mocked response from KumaScript POST service
# Digging a little deeper into the stack, so that the rest of
# kumascript.post processing happens.
from StringIO import StringIO
m_resp = mock.Mock()
m_resp.status_code = 200
m_resp.text = test_content
m_resp.read = StringIO(test_content).read
mock_requests_post.return_value = m_resp
d, r = doc_rev(test_content)
trials = (
(False, '', expected_content_old),
(False, '&bleach_new', expected_content_old),
(True, '', expected_content_old),
(True, '&bleach_new', expected_content_new),
)
for trial in trials:
do_login, param, expected = trial
if do_login:
self.client.login(username='testuser', password='testpass')
else:
self.client.logout()
url = ('%s?raw¯os%s' % (
reverse('wiki.document', args=(d.slug,), locale=d.locale),
param))
resp = self.client.get(url, follow=True)
eq_(normalize_html(expected),
normalize_html(resp.content),
"Should match? %s %s %s %s" %
(do_login, param, expected, resp.content))
class APITests(UserTestCase, WikiTestCase):
localizing_client = True
def setUp(self):
super(APITests, self).setUp()
self.username = 'tester23'
self.password = 'trustno1'
self.email = 'tester23@example.com'
self.user = user(username=self.username,
email=self.email,
password=self.password,
save=True)
self.key = Key(user=self.user, description='Test Key 1')
self.secret = self.key.generate_secret()
self.key_id = self.key.key
self.key.save()
auth = '%s:%s' % (self.key_id, self.secret)
self.basic_auth = 'Basic %s' % base64.encodestring(auth)
self.d, self.r = doc_rev("""
<h3 id="S1">Section 1</h3>
<p>This is a page. Deal with it.</p>
<h3 id="S2">Section 2</h3>
<p>This is a page. Deal with it.</p>
<h3 id="S3">Section 3</h3>
<p>This is a page. Deal with it.</p>
""")
self.r.tags = "foo, bar, baz"
self.r.review_tags.set('technical', 'editorial')
self.url = self.d.get_absolute_url()
def tearDown(self):
super(APITests, self).tearDown()
Document.objects.filter(current_revision__creator=self.user).delete()
Revision.objects.filter(creator=self.user).delete()
Key.objects.filter(user=self.user).delete()
self.user.delete()
def test_put_existing(self):
"""PUT API should allow overwrite of existing document content"""
data = dict(
summary="Look, I made an edit!",
content="""
<p>This is an edit to the page. We've dealt with it.</p>
""",
)
# No auth key leads to a 403 Forbidden
resp = self._put(self.url, data)
eq_(403, resp.status_code)
# But, this should work, given a proper auth key
resp = self._put(self.url, data,
HTTP_AUTHORIZATION=self.basic_auth)
eq_(205, resp.status_code)
# Verify the edit happened.
curr_d = Document.objects.get(pk=self.d.pk)
eq_(normalize_html(data['content'].strip()),
normalize_html(Document.objects.get(pk=self.d.pk).html))
# Also, verify that this resulted in a new revision.
curr_r = curr_d.current_revision
ok_(self.r.pk != curr_r.pk)
eq_(data['summary'], curr_r.summary)
r_tags = ','.join(sorted(t.name for t in curr_r.review_tags.all()))
eq_('editorial,technical', r_tags)
def test_put_section_edit(self):
"""PUT API should allow overwrite of a specific section of an existing
document"""
data = dict(
content="""
<h3 id="S2">Section 2</h3>
<p>This is an edit to the page. We've dealt with it.</p>
""",
# Along with the section, let's piggyback in some other metadata
# edits just for good measure. They're not tied to section edit
# though.
title="Hahah this is a new title!",
tags="hello,quux,xyzzy",
review_tags="technical",
)
resp = self._put('%s?section=S2' % self.url, data,
HTTP_AUTHORIZATION=self.basic_auth)
eq_(205, resp.status_code)
expected = """
<h3 id="S1">Section 1</h3>
<p>This is a page. Deal with it.</p>
<h3 id="S2">Section 2</h3>
<p>This is an edit to the page. We've dealt with it.</p>
<h3 id="S3">Section 3</h3>
<p>This is a page. Deal with it.</p>
"""
# Verify the section edit happened.
curr_d = Document.objects.get(pk=self.d.pk)
eq_(normalize_html(expected.strip()),
normalize_html(curr_d.html))
eq_(data['title'], curr_d.title)
d_tags = ','.join(sorted(t.name for t in curr_d.tags.all()))
eq_(data['tags'], d_tags)
# Also, verify that this resulted in a new revision.
curr_r = curr_d.current_revision
ok_(self.r.pk != curr_r.pk)
r_tags = ','.join(sorted(t.name for t in curr_r.review_tags.all()))
eq_(data['review_tags'], r_tags)
def test_put_new_root(self):
"""PUT API should allow creation of a document whose path would place
it at the root of the topic hierarchy."""
slug = 'new-root-doc'
url = reverse('wiki.document', args=(slug,),
locale=settings.WIKI_DEFAULT_LANGUAGE)
data = dict(
title="This is the title of a new page",
content="""
<p>This is a new page, hooray!</p>
""",
tags="hello,quux,xyzzy",
review_tags="technical",
)
resp = self._put(url, data,
HTTP_AUTHORIZATION=self.basic_auth)
eq_(201, resp.status_code)
def test_put_new_child(self):
"""PUT API should allow creation of a document whose path would make it
a child of an existing parent."""
data = dict(
title="This is the title of a new page",
content="""
<p>This is a new page, hooray!</p>
""",
tags="hello,quux,xyzzy",
review_tags="technical",
)
# This first attempt should fail; the proposed parent does not exist.
url = '%s/nonexistent/newchild' % self.url
resp = self._put(url, data,
HTTP_AUTHORIZATION=self.basic_auth)
eq_(404, resp.status_code)
# TODO: I suppose we could rework this part to create the chain of
# missing parents with stub content, but currently this demands
# that API users do that themselves.
# Now, fill in the parent gap...
p_doc = document(slug='%s/nonexistent' % self.d.slug,
locale=settings.WIKI_DEFAULT_LANGUAGE,
parent_topic=self.d)
p_doc.save()
p_rev = revision(document=p_doc,
slug='%s/nonexistent' % self.d.slug,
title='I EXIST NOW', save=True)
p_rev.save()
# The creation should work, now.
resp = self._put(url, data,
HTTP_AUTHORIZATION=self.basic_auth)
eq_(201, resp.status_code)
new_slug = '%s/nonexistent/newchild' % self.d.slug
new_doc = Document.objects.get(locale=settings.WIKI_DEFAULT_LANGUAGE,
slug=new_slug)
eq_(p_doc.pk, new_doc.parent_topic.pk)
def test_put_unsupported_content_type(self):
"""PUT API should complain with a 400 Bad Request on an unsupported
content type submission"""
slug = 'new-root-doc'
url = reverse('wiki.document', args=(slug,),
locale=settings.WIKI_DEFAULT_LANGUAGE)
data = "I don't even know what this content is."
resp = self._put(url, json.dumps(data),
content_type='x-super-happy-fun-text',
HTTP_AUTHORIZATION=self.basic_auth)
eq_(400, resp.status_code)
def test_put_json(self):
"""PUT API should handle application/json requests"""
slug = 'new-root-json-doc'
url = reverse('wiki.document', args=(slug,),
locale=settings.WIKI_DEFAULT_LANGUAGE)
data = dict(
title="This is the title of a new page",
content="""
<p>This is a new page, hooray!</p>
""",
tags="hello,quux,xyzzy",
review_tags="technical",
)
resp = self._put(url, json.dumps(data),
content_type='application/json',
HTTP_AUTHORIZATION=self.basic_auth)
eq_(201, resp.status_code)
new_doc = Document.objects.get(locale=settings.WIKI_DEFAULT_LANGUAGE,
slug=slug)
eq_(data['title'], new_doc.title)
eq_(normalize_html(data['content']), normalize_html(new_doc.html))
def test_put_simple_html(self):
"""PUT API should handle text/html requests"""
slug = 'new-root-html-doc-1'
url = reverse('wiki.document', args=(slug,),
locale=settings.WIKI_DEFAULT_LANGUAGE)
html = """
<p>This is a new page, hooray!</p>
"""
resp = self._put(url, html, content_type='text/html',
HTTP_AUTHORIZATION=self.basic_auth)
eq_(201, resp.status_code)
new_doc = Document.objects.get(locale=settings.WIKI_DEFAULT_LANGUAGE,
slug=slug)
eq_(normalize_html(html), normalize_html(new_doc.html))
def test_put_complex_html(self):
"""PUT API should handle text/html requests with complex HTML documents
and extract document fields from the markup"""
slug = 'new-root-html-doc-2'
url = reverse('wiki.document', args=(slug,),
locale=settings.WIKI_DEFAULT_LANGUAGE)
data = dict(
title='This is a complex document',
content="""
<p>This is a new page, hooray!</p>
""",
)
html = """
<html>
<head>
<title>%(title)s</title>
</head>
<body>%(content)s</body>
</html>
""" % data
resp = self._put(url, html, content_type='text/html',
HTTP_AUTHORIZATION=self.basic_auth)
eq_(201, resp.status_code)
new_doc = Document.objects.get(locale=settings.WIKI_DEFAULT_LANGUAGE,
slug=slug)
eq_(data['title'], new_doc.title)
eq_(normalize_html(data['content']), normalize_html(new_doc.html))
# TODO: Anything else useful to extract from HTML?
# Extract tags from head metadata?
def test_put_track_authkey(self):
"""Revisions modified by PUT API should track the auth key used"""
slug = 'new-root-doc'
url = reverse('wiki.document', args=(slug,),
locale=settings.WIKI_DEFAULT_LANGUAGE)
data = dict(
title="This is the title of a new page",
content="""
<p>This is a new page, hooray!</p>
""",
tags="hello,quux,xyzzy",
review_tags="technical",
)
resp = self._put(url, data, HTTP_AUTHORIZATION=self.basic_auth)
eq_(201, resp.status_code)
last_log = self.key.history.order_by('-pk').all()[0]
eq_('created', last_log.action)
data['title'] = 'New title for old page'
resp = self._put(url, data, HTTP_AUTHORIZATION=self.basic_auth)
eq_(205, resp.status_code)
last_log = self.key.history.order_by('-pk').all()[0]
eq_('updated', last_log.action)
def test_put_etag_conflict(self):
"""A PUT request with an if-match header throws a 412 Precondition
Failed if the underlying document has been changed."""
resp = self.client.get(self.url)
orig_etag = resp['ETag']
content1 = """
<h2 id="s1">Section 1</h2>
<p>New section 1</p>
<h2 id="s2">Section 2</h2>
<p>New section 2</p>
"""
# First update should work.
resp = self._put(self.url, dict(content=content1),
HTTP_IF_MATCH=orig_etag,
HTTP_AUTHORIZATION=self.basic_auth)
eq_(205, resp.status_code)
# Get the new etag, ensure it doesn't match the original.
resp = self.client.get(self.url)
new_etag = resp['ETag']
ok_(orig_etag != new_etag)
# But, the ETag should have changed, so this update shouldn't work.
# Using the old ETag suggests a mid-air edit collision happened.
resp = self._put(self.url, dict(content=content1),
HTTP_IF_MATCH=orig_etag,
HTTP_AUTHORIZATION=self.basic_auth)
eq_(412, resp.status_code)
# Just for good measure, switching to the new ETag should work
resp = self._put(self.url, dict(content=content1),
HTTP_IF_MATCH=new_etag,
HTTP_AUTHORIZATION=self.basic_auth)
eq_(205, resp.status_code)
def _put(self, path, data={}, content_type=MULTIPART_CONTENT,
follow=False, **extra):
"""django.test.client.put() does the wrong thing, here. This does
better, based on post()."""
if content_type is MULTIPART_CONTENT:
post_data = encode_multipart(BOUNDARY, data)
else:
# Encode the content so that the byte representation is correct.
match = CONTENT_TYPE_RE.match(content_type)
if match:
charset = match.group(1)
else:
charset = settings.DEFAULT_CHARSET
post_data = smart_str(data, encoding=charset)
parsed = urlparse(path)
params = {
'CONTENT_LENGTH': len(post_data),
'CONTENT_TYPE': content_type,
'PATH_INFO': self.client._get_path(parsed),
'QUERY_STRING': parsed[4],
'REQUEST_METHOD': 'PUT',
'wsgi.input': FakePayload(post_data),
}
params.update(extra)
response = self.client.request(**params)
if follow:
response = self.client._handle_redirects(response, **extra)
return response
class PageMoveTests(UserTestCase, WikiTestCase):
localizing_client = True
def setUp(self):
page_move_flag = Flag.objects.create(name='page_move')
page_move_flag.users = User.objects.filter(is_superuser=True)
page_move_flag.save()
super(PageMoveTests, self).setUp()
def test_move_conflict(self):
parent = revision(title='Test page move views',
slug='test-page-move-views',
is_approved=True,
save=True)
parent_doc = parent.document
child = revision(title='Child of page-move view test',
slug='page-move/test-views',
is_approved=True,
save=True)
child_doc = child.document
child_doc.parent_topic = parent.document
child_doc.save()
revision(title='Conflict for page-move view',
slug='moved/test-page-move-views/test-views',
is_approved=True,
save=True)
data = {'slug': 'moved/test-page-move-views'}
self.client.login(username='admin', password='testpass')
resp = self.client.post(reverse('wiki.move',
args=(parent_doc.slug,),
locale=parent_doc.locale),
data=data)
eq_(200, resp.status_code)
class DocumentZoneTests(UserTestCase, WikiTestCase):
localizing_client = True
def setUp(self):
super(DocumentZoneTests, self).setUp()
root_rev = revision(title='ZoneRoot', slug='ZoneRoot',
content='This is the Zone Root',
is_approved=True, save=True)
self.root_doc = root_rev.document
middle_rev = revision(title='middlePage', slug='middlePage',
content='This is a middlepage',
is_approved=True, save=True)
self.middle_doc = middle_rev.document
self.middle_doc.parent_topic = self.root_doc
self.middle_doc.save()
sub_rev = revision(title='SubPage', slug='SubPage',
content='This is a subpage',
is_approved=True, save=True)
self.sub_doc = sub_rev.document
self.sub_doc.parent_topic = self.middle_doc
self.sub_doc.save()
self.root_zone = DocumentZone(document=self.root_doc)
self.root_zone.styles = """
article { color: blue; }
"""
self.root_zone.save()
self.middle_zone = DocumentZone(document=self.middle_doc)
self.middle_zone.styles = """
article { font-weight: bold; }
"""
self.middle_zone.save()
def test_zone_styles(self):
"""Ensure CSS styles for a zone can be fetched"""
url = reverse('wiki.styles', args=(self.root_doc.slug,),
locale=settings.WIKI_DEFAULT_LANGUAGE)
response = self.client.get(url, follow=True)
eq_(self.root_zone.styles, response.content)
url = reverse('wiki.styles', args=(self.middle_doc.slug,),
locale=settings.WIKI_DEFAULT_LANGUAGE)
response = self.client.get(url, follow=True)
eq_(self.middle_zone.styles, response.content)
url = reverse('wiki.styles', args=(self.sub_doc.slug,),
locale=settings.WIKI_DEFAULT_LANGUAGE)
response = self.client.get(url, follow=True)
eq_(404, response.status_code)
def test_zone_styles_links(self):
"""Ensure link to zone style appears in child document views"""
url = reverse('wiki.document', args=(self.sub_doc.slug,),
locale=settings.WIKI_DEFAULT_LANGUAGE)
response = self.client.get(url, follow=True)
styles_url = reverse('wiki.styles', args=(self.root_doc.slug,),
locale=settings.WIKI_DEFAULT_LANGUAGE)
root_expected = ('<link rel="stylesheet" type="text/css" href="%s"' %
styles_url)
ok_(root_expected in response.content)
styles_url = reverse('wiki.styles', args=(self.middle_doc.slug,),
locale=settings.WIKI_DEFAULT_LANGUAGE)
middle_expected = ('<link rel="stylesheet" type="text/css" href="%s"' %
styles_url)
ok_(middle_expected in response.content)
class ListDocumentTests(UserTestCase, WikiTestCase):
"""Tests for list_documents view"""
localizing_client = True
fixtures = UserTestCase.fixtures + ['wiki/documents.json']
def test_case_insensitive_tags(self):
"""
Bug 976071 - Tags shouldn't be case sensitive
https://bugzil.la/976071
"""
lower_tag = DocumentTag.objects.create(name='foo', slug='foo')
lower_tag.save()
doc = Document.objects.get(pk=1)
doc.tags.set(lower_tag)
response = self.client.get(reverse('wiki.tag', args=['foo']))
ok_(doc.slug in response.content.decode('utf-8'))
response = self.client.get(reverse('wiki.tag', args=['Foo']))
ok_(doc.slug in response.content.decode('utf-8'))
| scrollback/kuma | kuma/wiki/tests/test_views.py | Python | mpl-2.0 | 162,884 | [
"VisIt"
] | d1271beb086391aa34b1d706266555adb98847cf68eaca6943ca5ba4a2e4ea04 |
"""
pyNEAT
Copyright (C) 2007-2008 Brian Greer
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
"""
import random
class Synapse:
def __init__(self, input, output, weight, recurrent = False, trait = None):
self.input = input
self.output = output
self.weight = weight
self.recurrent = recurrent
self.trait = trait
self.enabled = True
if output is not None:
self.output.synapses.append(self)
def deriveTrait(self, trait):
self.params = trait.params
def perturb(self, sigma=0.75):
self.weight += random.gauss(0.0, sigma)
| liquidkarma/pyneat | pyNEAT/Synapse.py | Python | gpl-2.0 | 1,244 | [
"Brian"
] | f0ac54197c62025c1c83a8ccac68b1377b0b2fc757fe45832b76bf7a7e95970b |
"""
local path implementation.
"""
from __future__ import with_statement
from contextlib import contextmanager
import sys, os, re, atexit, io
import py
from py._path import common
from stat import S_ISLNK, S_ISDIR, S_ISREG
from os.path import abspath, normpath, isabs, exists, isdir, isfile, islink
iswin32 = sys.platform == "win32" or (getattr(os, '_name', False) == 'nt')
if sys.version_info > (3,0):
def map_as_list(func, iter):
return list(map(func, iter))
else:
map_as_list = map
class Stat(object):
def __getattr__(self, name):
return getattr(self._osstatresult, "st_" + name)
def __init__(self, path, osstatresult):
self.path = path
self._osstatresult = osstatresult
@property
def owner(self):
if iswin32:
raise NotImplementedError("XXX win32")
import pwd
entry = py.error.checked_call(pwd.getpwuid, self.uid)
return entry[0]
@property
def group(self):
""" return group name of file. """
if iswin32:
raise NotImplementedError("XXX win32")
import grp
entry = py.error.checked_call(grp.getgrgid, self.gid)
return entry[0]
def isdir(self):
return S_ISDIR(self._osstatresult.st_mode)
def isfile(self):
return S_ISREG(self._osstatresult.st_mode)
def islink(self):
st = self.path.lstat()
return S_ISLNK(self._osstatresult.st_mode)
class PosixPath(common.PathBase):
def chown(self, user, group, rec=0):
""" change ownership to the given user and group.
user and group may be specified by a number or
by a name. if rec is True change ownership
recursively.
"""
uid = getuserid(user)
gid = getgroupid(group)
if rec:
for x in self.visit(rec=lambda x: x.check(link=0)):
if x.check(link=0):
py.error.checked_call(os.chown, str(x), uid, gid)
py.error.checked_call(os.chown, str(self), uid, gid)
def readlink(self):
""" return value of a symbolic link. """
return py.error.checked_call(os.readlink, self.strpath)
def mklinkto(self, oldname):
""" posix style hard link to another name. """
py.error.checked_call(os.link, str(oldname), str(self))
def mksymlinkto(self, value, absolute=1):
""" create a symbolic link with the given value (pointing to another name). """
if absolute:
py.error.checked_call(os.symlink, str(value), self.strpath)
else:
base = self.common(value)
# with posix local paths '/' is always a common base
relsource = self.__class__(value).relto(base)
reldest = self.relto(base)
n = reldest.count(self.sep)
target = self.sep.join(('..', )*n + (relsource, ))
py.error.checked_call(os.symlink, target, self.strpath)
def getuserid(user):
import pwd
if not isinstance(user, int):
user = pwd.getpwnam(user)[2]
return user
def getgroupid(group):
import grp
if not isinstance(group, int):
group = grp.getgrnam(group)[2]
return group
FSBase = not iswin32 and PosixPath or common.PathBase
class LocalPath(FSBase):
""" object oriented interface to os.path and other local filesystem
related information.
"""
class ImportMismatchError(ImportError):
""" raised on pyimport() if there is a mismatch of __file__'s"""
sep = os.sep
class Checkers(common.Checkers):
def _stat(self):
try:
return self._statcache
except AttributeError:
try:
self._statcache = self.path.stat()
except py.error.ELOOP:
self._statcache = self.path.lstat()
return self._statcache
def dir(self):
return S_ISDIR(self._stat().mode)
def file(self):
return S_ISREG(self._stat().mode)
def exists(self):
return self._stat()
def link(self):
st = self.path.lstat()
return S_ISLNK(st.mode)
def __init__(self, path=None, expanduser=False):
""" Initialize and return a local Path instance.
Path can be relative to the current directory.
If path is None it defaults to the current working directory.
If expanduser is True, tilde-expansion is performed.
Note that Path instances always carry an absolute path.
Note also that passing in a local path object will simply return
the exact same path object. Use new() to get a new copy.
"""
if path is None:
self.strpath = py.error.checked_call(os.getcwd)
elif isinstance(path, common.PathBase):
self.strpath = path.strpath
elif isinstance(path, py.builtin._basestring):
if expanduser:
path = os.path.expanduser(path)
self.strpath = abspath(normpath(path))
else:
raise ValueError("can only pass None, Path instances "
"or non-empty strings to LocalPath")
def __hash__(self):
return hash(self.strpath)
def __eq__(self, other):
s1 = self.strpath
s2 = getattr(other, "strpath", other)
if iswin32:
s1 = s1.lower()
try:
s2 = s2.lower()
except AttributeError:
return False
return s1 == s2
def __ne__(self, other):
return not (self == other)
def __lt__(self, other):
return self.strpath < getattr(other, "strpath", other)
def __gt__(self, other):
return self.strpath > getattr(other, "strpath", other)
def samefile(self, other):
""" return True if 'other' references the same file as 'self'.
"""
other = getattr(other, "strpath", other)
if not isabs(other):
other = abspath(other)
if self == other:
return True
if iswin32:
return False # there is no samefile
return py.error.checked_call(
os.path.samefile, self.strpath, other)
def remove(self, rec=1, ignore_errors=False):
""" remove a file or directory (or a directory tree if rec=1).
if ignore_errors is True, errors while removing directories will
be ignored.
"""
if self.check(dir=1, link=0):
if rec:
# force remove of readonly files on windows
if iswin32:
self.chmod(448, rec=1) # octcal 0700
py.error.checked_call(py.std.shutil.rmtree, self.strpath,
ignore_errors=ignore_errors)
else:
py.error.checked_call(os.rmdir, self.strpath)
else:
if iswin32:
self.chmod(448) # octcal 0700
py.error.checked_call(os.remove, self.strpath)
def computehash(self, hashtype="md5", chunksize=524288):
""" return hexdigest of hashvalue for this file. """
try:
try:
import hashlib as mod
except ImportError:
if hashtype == "sha1":
hashtype = "sha"
mod = __import__(hashtype)
hash = getattr(mod, hashtype)()
except (AttributeError, ImportError):
raise ValueError("Don't know how to compute %r hash" %(hashtype,))
f = self.open('rb')
try:
while 1:
buf = f.read(chunksize)
if not buf:
return hash.hexdigest()
hash.update(buf)
finally:
f.close()
def new(self, **kw):
""" create a modified version of this path.
the following keyword arguments modify various path parts::
a:/some/path/to/a/file.ext
xx drive
xxxxxxxxxxxxxxxxx dirname
xxxxxxxx basename
xxxx purebasename
xxx ext
"""
obj = object.__new__(self.__class__)
if not kw:
obj.strpath = self.strpath
return obj
drive, dirname, basename, purebasename,ext = self._getbyspec(
"drive,dirname,basename,purebasename,ext")
if 'basename' in kw:
if 'purebasename' in kw or 'ext' in kw:
raise ValueError("invalid specification %r" % kw)
else:
pb = kw.setdefault('purebasename', purebasename)
try:
ext = kw['ext']
except KeyError:
pass
else:
if ext and not ext.startswith('.'):
ext = '.' + ext
kw['basename'] = pb + ext
if ('dirname' in kw and not kw['dirname']):
kw['dirname'] = drive
else:
kw.setdefault('dirname', dirname)
kw.setdefault('sep', self.sep)
obj.strpath = normpath(
"%(dirname)s%(sep)s%(basename)s" % kw)
return obj
def _getbyspec(self, spec):
""" see new for what 'spec' can be. """
res = []
parts = self.strpath.split(self.sep)
args = filter(None, spec.split(',') )
append = res.append
for name in args:
if name == 'drive':
append(parts[0])
elif name == 'dirname':
append(self.sep.join(parts[:-1]))
else:
basename = parts[-1]
if name == 'basename':
append(basename)
else:
i = basename.rfind('.')
if i == -1:
purebasename, ext = basename, ''
else:
purebasename, ext = basename[:i], basename[i:]
if name == 'purebasename':
append(purebasename)
elif name == 'ext':
append(ext)
else:
raise ValueError("invalid part specification %r" % name)
return res
def join(self, *args, **kwargs):
""" return a new path by appending all 'args' as path
components. if abs=1 is used restart from root if any
of the args is an absolute path.
"""
sep = self.sep
strargs = [getattr(arg, "strpath", arg) for arg in args]
strpath = self.strpath
if kwargs.get('abs'):
newargs = []
for arg in reversed(strargs):
if isabs(arg):
strpath = arg
strargs = newargs
break
newargs.insert(0, arg)
for arg in strargs:
arg = arg.strip(sep)
if iswin32:
# allow unix style paths even on windows.
arg = arg.strip('/')
arg = arg.replace('/', sep)
strpath = strpath + sep + arg
obj = object.__new__(self.__class__)
obj.strpath = normpath(strpath)
return obj
def open(self, mode='r', ensure=False, encoding=None):
""" return an opened file with the given mode.
If ensure is True, create parent directories if needed.
"""
if ensure:
self.dirpath().ensure(dir=1)
if encoding:
return py.error.checked_call(io.open, self.strpath, mode, encoding=encoding)
return py.error.checked_call(open, self.strpath, mode)
def _fastjoin(self, name):
child = object.__new__(self.__class__)
child.strpath = self.strpath + self.sep + name
return child
def islink(self):
return islink(self.strpath)
def check(self, **kw):
if not kw:
return exists(self.strpath)
if len(kw) == 1:
if "dir" in kw:
return not kw["dir"] ^ isdir(self.strpath)
if "file" in kw:
return not kw["file"] ^ isfile(self.strpath)
return super(LocalPath, self).check(**kw)
_patternchars = set("*?[" + os.path.sep)
def listdir(self, fil=None, sort=None):
""" list directory contents, possibly filter by the given fil func
and possibly sorted.
"""
if fil is None and sort is None:
names = py.error.checked_call(os.listdir, self.strpath)
return map_as_list(self._fastjoin, names)
if isinstance(fil, py.builtin._basestring):
if not self._patternchars.intersection(fil):
child = self._fastjoin(fil)
if exists(child.strpath):
return [child]
return []
fil = common.FNMatcher(fil)
names = py.error.checked_call(os.listdir, self.strpath)
res = []
for name in names:
child = self._fastjoin(name)
if fil is None or fil(child):
res.append(child)
self._sortlist(res, sort)
return res
def size(self):
""" return size of the underlying file object """
return self.stat().size
def mtime(self):
""" return last modification time of the path. """
return self.stat().mtime
def copy(self, target, mode=False):
""" copy path to target."""
if self.check(file=1):
if target.check(dir=1):
target = target.join(self.basename)
assert self!=target
copychunked(self, target)
if mode:
copymode(self, target)
else:
def rec(p):
return p.check(link=0)
for x in self.visit(rec=rec):
relpath = x.relto(self)
newx = target.join(relpath)
newx.dirpath().ensure(dir=1)
if x.check(link=1):
newx.mksymlinkto(x.readlink())
continue
elif x.check(file=1):
copychunked(x, newx)
elif x.check(dir=1):
newx.ensure(dir=1)
if mode:
copymode(x, newx)
def rename(self, target):
""" rename this path to target. """
target = getattr(target, "strpath", target)
return py.error.checked_call(os.rename, self.strpath, target)
def dump(self, obj, bin=1):
""" pickle object into path location"""
f = self.open('wb')
try:
py.error.checked_call(py.std.pickle.dump, obj, f, bin)
finally:
f.close()
def mkdir(self, *args):
""" create & return the directory joined with args. """
p = self.join(*args)
py.error.checked_call(os.mkdir, getattr(p, "strpath", p))
return p
def write_binary(self, data, ensure=False):
""" write binary data into path. If ensure is True create
missing parent directories.
"""
if ensure:
self.dirpath().ensure(dir=1)
with self.open('wb') as f:
f.write(data)
def write_text(self, data, encoding, ensure=False):
""" write text data into path using the specified encoding.
If ensure is True create missing parent directories.
"""
if ensure:
self.dirpath().ensure(dir=1)
with self.open('w', encoding=encoding) as f:
f.write(data)
def write(self, data, mode='w', ensure=False):
""" write data into path. If ensure is True create
missing parent directories.
"""
if ensure:
self.dirpath().ensure(dir=1)
if 'b' in mode:
if not py.builtin._isbytes(data):
raise ValueError("can only process bytes")
else:
if not py.builtin._istext(data):
if not py.builtin._isbytes(data):
data = str(data)
else:
data = py.builtin._totext(data, sys.getdefaultencoding())
f = self.open(mode)
try:
f.write(data)
finally:
f.close()
def _ensuredirs(self):
parent = self.dirpath()
if parent == self:
return self
if parent.check(dir=0):
parent._ensuredirs()
if self.check(dir=0):
try:
self.mkdir()
except py.error.EEXIST:
# race condition: file/dir created by another thread/process.
# complain if it is not a dir
if self.check(dir=0):
raise
return self
def ensure(self, *args, **kwargs):
""" ensure that an args-joined path exists (by default as
a file). if you specify a keyword argument 'dir=True'
then the path is forced to be a directory path.
"""
p = self.join(*args)
if kwargs.get('dir', 0):
return p._ensuredirs()
else:
p.dirpath()._ensuredirs()
if not p.check(file=1):
p.open('w').close()
return p
def stat(self, raising=True):
""" Return an os.stat() tuple. """
if raising == True:
return Stat(self, py.error.checked_call(os.stat, self.strpath))
try:
return Stat(self, os.stat(self.strpath))
except KeyboardInterrupt:
raise
except Exception:
return None
def lstat(self):
""" Return an os.lstat() tuple. """
return Stat(self, py.error.checked_call(os.lstat, self.strpath))
def setmtime(self, mtime=None):
""" set modification time for the given path. if 'mtime' is None
(the default) then the file's mtime is set to current time.
Note that the resolution for 'mtime' is platform dependent.
"""
if mtime is None:
return py.error.checked_call(os.utime, self.strpath, mtime)
try:
return py.error.checked_call(os.utime, self.strpath, (-1, mtime))
except py.error.EINVAL:
return py.error.checked_call(os.utime, self.strpath, (self.atime(), mtime))
def chdir(self):
""" change directory to self and return old current directory """
try:
old = self.__class__()
except py.error.ENOENT:
old = None
py.error.checked_call(os.chdir, self.strpath)
return old
@contextmanager
def as_cwd(self):
""" return context manager which changes to current dir during the
managed "with" context. On __enter__ it returns the old dir.
"""
old = self.chdir()
try:
yield old
finally:
old.chdir()
def realpath(self):
""" return a new path which contains no symbolic links."""
return self.__class__(os.path.realpath(self.strpath))
def atime(self):
""" return last access time of the path. """
return self.stat().atime
def __repr__(self):
return 'local(%r)' % self.strpath
def __str__(self):
""" return string representation of the Path. """
return self.strpath
def pypkgpath(self, pkgname=None):
""" return the Python package path by looking for a
pkgname. If pkgname is None look for the last
directory upwards which still contains an __init__.py
and whose basename is python-importable.
Return None if a pkgpath can not be determined.
"""
pkgpath = None
for parent in self.parts(reverse=True):
if pkgname is None:
if parent.check(file=1):
continue
if not isimportable(parent.basename):
break
if parent.join('__init__.py').check():
pkgpath = parent
continue
return pkgpath
else:
if parent.basename == pkgname:
return parent
return pkgpath
def _prependsyspath(self, path):
s = str(path)
if s != sys.path[0]:
#print "prepending to sys.path", s
sys.path.insert(0, s)
def chmod(self, mode, rec=0):
""" change permissions to the given mode. If mode is an
integer it directly encodes the os-specific modes.
if rec is True perform recursively.
"""
if not isinstance(mode, int):
raise TypeError("mode %r must be an integer" % (mode,))
if rec:
for x in self.visit(rec=rec):
py.error.checked_call(os.chmod, str(x), mode)
py.error.checked_call(os.chmod, str(self), mode)
def pyimport(self, modname=None, ensuresyspath=True):
""" return path as an imported python module.
if modname is None, look for the containing package
and construct an according module name.
The module will be put/looked up in sys.modules.
"""
if not self.check():
raise py.error.ENOENT(self)
#print "trying to import", self
pkgpath = None
if modname is None:
pkgpath = self.pypkgpath()
if pkgpath is not None:
if ensuresyspath:
self._prependsyspath(pkgpath.dirpath())
__import__(pkgpath.basename)
pkg = sys.modules[pkgpath.basename]
names = self.new(ext='').relto(pkgpath.dirpath())
names = names.split(self.sep)
if names and names[-1] == "__init__":
names.pop()
modname = ".".join(names)
else:
# no package scope, still make it possible
if ensuresyspath:
self._prependsyspath(self.dirpath())
modname = self.purebasename
__import__(modname)
mod = sys.modules[modname]
if self.basename == "__init__.py":
return mod # we don't check anything as we might
# we in a namespace package ... too icky to check
modfile = mod.__file__
if modfile[-4:] in ('.pyc', '.pyo'):
modfile = modfile[:-1]
elif modfile.endswith('$py.class'):
modfile = modfile[:-9] + '.py'
if modfile.endswith(os.path.sep + "__init__.py"):
if self.basename != "__init__.py":
modfile = modfile[:-12]
try:
issame = self.samefile(modfile)
except py.error.ENOENT:
issame = False
if not issame:
raise self.ImportMismatchError(modname, modfile, self)
return mod
else:
try:
return sys.modules[modname]
except KeyError:
# we have a custom modname, do a pseudo-import
mod = py.std.types.ModuleType(modname)
mod.__file__ = str(self)
sys.modules[modname] = mod
try:
py.builtin.execfile(str(self), mod.__dict__)
except:
del sys.modules[modname]
raise
return mod
def sysexec(self, *argv, **popen_opts):
""" return stdout text from executing a system child process,
where the 'self' path points to executable.
The process is directly invoked and not through a system shell.
"""
from subprocess import Popen, PIPE
argv = map_as_list(str, argv)
popen_opts['stdout'] = popen_opts['stderr'] = PIPE
proc = Popen([str(self)] + argv, **popen_opts)
stdout, stderr = proc.communicate()
ret = proc.wait()
if py.builtin._isbytes(stdout):
stdout = py.builtin._totext(stdout, sys.getdefaultencoding())
if ret != 0:
if py.builtin._isbytes(stderr):
stderr = py.builtin._totext(stderr, sys.getdefaultencoding())
raise py.process.cmdexec.Error(ret, ret, str(self),
stdout, stderr,)
return stdout
def sysfind(cls, name, checker=None, paths=None):
""" return a path object found by looking at the systems
underlying PATH specification. If the checker is not None
it will be invoked to filter matching paths. If a binary
cannot be found, None is returned
Note: This is probably not working on plain win32 systems
but may work on cygwin.
"""
if isabs(name):
p = py.path.local(name)
if p.check(file=1):
return p
else:
if paths is None:
if iswin32:
paths = py.std.os.environ['Path'].split(';')
if '' not in paths and '.' not in paths:
paths.append('.')
try:
systemroot = os.environ['SYSTEMROOT']
except KeyError:
pass
else:
paths = [re.sub('%SystemRoot%', systemroot, path)
for path in paths]
else:
paths = py.std.os.environ['PATH'].split(':')
tryadd = []
if iswin32:
tryadd += os.environ['PATHEXT'].split(os.pathsep)
tryadd.append("")
for x in paths:
for addext in tryadd:
p = py.path.local(x).join(name, abs=True) + addext
try:
if p.check(file=1):
if checker:
if not checker(p):
continue
return p
except py.error.EACCES:
pass
return None
sysfind = classmethod(sysfind)
def _gethomedir(cls):
try:
x = os.environ['HOME']
except KeyError:
try:
x = os.environ["HOMEDRIVE"] + os.environ['HOMEPATH']
except KeyError:
return None
return cls(x)
_gethomedir = classmethod(_gethomedir)
#"""
#special class constructors for local filesystem paths
#"""
def get_temproot(cls):
""" return the system's temporary directory
(where tempfiles are usually created in)
"""
return py.path.local(py.std.tempfile.gettempdir())
get_temproot = classmethod(get_temproot)
def mkdtemp(cls, rootdir=None):
""" return a Path object pointing to a fresh new temporary directory
(which we created ourself).
"""
import tempfile
if rootdir is None:
rootdir = cls.get_temproot()
return cls(py.error.checked_call(tempfile.mkdtemp, dir=str(rootdir)))
mkdtemp = classmethod(mkdtemp)
def make_numbered_dir(cls, prefix='session-', rootdir=None, keep=3,
lock_timeout = 172800): # two days
""" return unique directory with a number greater than the current
maximum one. The number is assumed to start directly after prefix.
if keep is true directories with a number less than (maxnum-keep)
will be removed.
"""
if rootdir is None:
rootdir = cls.get_temproot()
def parse_num(path):
""" parse the number out of a path (if it matches the prefix) """
bn = path.basename
if bn.startswith(prefix):
try:
return int(bn[len(prefix):])
except ValueError:
pass
# compute the maximum number currently in use with the
# prefix
lastmax = None
while True:
maxnum = -1
for path in rootdir.listdir():
num = parse_num(path)
if num is not None:
maxnum = max(maxnum, num)
# make the new directory
try:
udir = rootdir.mkdir(prefix + str(maxnum+1))
except py.error.EEXIST:
# race condition: another thread/process created the dir
# in the meantime. Try counting again
if lastmax == maxnum:
raise
lastmax = maxnum
continue
break
# put a .lock file in the new directory that will be removed at
# process exit
if lock_timeout:
lockfile = udir.join('.lock')
mypid = os.getpid()
if hasattr(lockfile, 'mksymlinkto'):
lockfile.mksymlinkto(str(mypid))
else:
lockfile.write(str(mypid))
def try_remove_lockfile():
# in a fork() situation, only the last process should
# remove the .lock, otherwise the other processes run the
# risk of seeing their temporary dir disappear. For now
# we remove the .lock in the parent only (i.e. we assume
# that the children finish before the parent).
if os.getpid() != mypid:
return
try:
lockfile.remove()
except py.error.Error:
pass
atexit.register(try_remove_lockfile)
# prune old directories
if keep:
for path in rootdir.listdir():
num = parse_num(path)
if num is not None and num <= (maxnum - keep):
lf = path.join('.lock')
try:
t1 = lf.lstat().mtime
t2 = lockfile.lstat().mtime
if not lock_timeout or abs(t2-t1) < lock_timeout:
continue # skip directories still locked
except py.error.Error:
pass # assume that it means that there is no 'lf'
try:
path.remove(rec=1)
except KeyboardInterrupt:
raise
except: # this might be py.error.Error, WindowsError ...
pass
# make link...
try:
username = os.environ['USER'] #linux, et al
except KeyError:
try:
username = os.environ['USERNAME'] #windows
except KeyError:
username = 'current'
src = str(udir)
dest = src[:src.rfind('-')] + '-' + username
try:
os.unlink(dest)
except OSError:
pass
try:
os.symlink(src, dest)
except (OSError, AttributeError, NotImplementedError):
pass
return udir
make_numbered_dir = classmethod(make_numbered_dir)
def copymode(src, dest):
py.std.shutil.copymode(str(src), str(dest))
def copychunked(src, dest):
chunksize = 524288 # half a meg of bytes
fsrc = src.open('rb')
try:
fdest = dest.open('wb')
try:
while 1:
buf = fsrc.read(chunksize)
if not buf:
break
fdest.write(buf)
finally:
fdest.close()
finally:
fsrc.close()
def isimportable(name):
if name:
if not (name[0].isalpha() or name[0] == '_'):
return False
name= name.replace("_", '')
return not name or name.isalnum()
| Spanarchie/pyRest | pyRest/lib/python2.7/site-packages/py/_path/local.py | Python | unlicense | 31,893 | [
"VisIt"
] | 9d15b75a0fb865a13cdfa0100d4cb75ac8f9e5e2b7b62b5bb0a734af4ce510e8 |
"""Mayavi/traits GUI for setting MRI fiducials"""
# Authors: Christian Brodbeck <christianbrodbeck@nyu.edu>
#
# License: BSD (3-clause)
import os
from ..externals.six.moves import map
# allow import without traits
try:
from mayavi.core.ui.mayavi_scene import MayaviScene
from mayavi.tools.mlab_scene_model import MlabSceneModel
import numpy as np
from pyface.api import confirm, error, FileDialog, OK, YES
from traits.api import (HasTraits, HasPrivateTraits, on_trait_change,
cached_property, DelegatesTo, Event, Instance,
Property, Array, Bool, Button, Enum)
from traitsui.api import HGroup, Item, VGroup, View
from traitsui.menu import NoButtons
from tvtk.pyface.scene_editor import SceneEditor
except Exception:
from ..utils import trait_wraith
HasTraits = HasPrivateTraits = object
cached_property = on_trait_change = MayaviScene = MlabSceneModel = \
Array = Bool = Button = DelegatesTo = Enum = Event = Instance = \
Property = View = Item = HGroup = VGroup = SceneEditor = \
NoButtons = error = trait_wraith
from ..coreg import (fid_fname, head_bem_fname, _find_fiducials_files,
_find_high_res_head)
from ..io import write_fiducials
from ..io.constants import FIFF
from ..utils import get_subjects_dir, logger
from ._file_traits import (SurfaceSource, fid_wildcard, FiducialsSource,
MRISubjectSource, SubjectSelectorPanel)
from ._viewer import (defaults, HeadViewController, PointObject, SurfaceObject,
headview_borders)
class MRIHeadWithFiducialsModel(HasPrivateTraits):
"""Represent an MRI head shape with fiducials
Attributes
----------
points : array (n_points, 3)
MRI head surface points.
tris : array (n_tris, 3)
Triangles based on points.
lpa : array (1, 3)
Left peri-auricular point coordinates.
nasion : array (1, 3)
Nasion coordinates.
rpa : array (1, 3)
Right peri-auricular point coordinates.
"""
subject_source = Instance(MRISubjectSource, ())
bem = Instance(SurfaceSource, ())
fid = Instance(FiducialsSource, ())
fid_file = DelegatesTo('fid', 'file')
fid_fname = DelegatesTo('fid', 'fname')
fid_points = DelegatesTo('fid', 'points')
subjects_dir = DelegatesTo('subject_source')
subject = DelegatesTo('subject_source')
subject_has_bem = DelegatesTo('subject_source')
use_high_res_head = DelegatesTo('subject_source')
points = DelegatesTo('bem')
norms = DelegatesTo('bem')
tris = DelegatesTo('bem')
lpa = Array(float, (1, 3))
nasion = Array(float, (1, 3))
rpa = Array(float, (1, 3))
reset = Event(desc="Reset fiducials to the file.")
# info
can_save = Property(depends_on=['file', 'can_save_as'])
can_save_as = Property(depends_on=['lpa', 'nasion', 'rpa'])
can_reset = Property(depends_on=['file', 'fid.points', 'lpa', 'nasion',
'rpa'])
fid_ok = Property(depends_on=['lpa', 'nasion', 'rpa'], desc="All points "
"are set")
default_fid_fname = Property(depends_on=['subjects_dir', 'subject'],
desc="the default file name for the "
"fiducials fif file")
# switch for the GUI (has no effect in the model)
lock_fiducials = Bool(False, desc="Used by GIU, has no effect in the "
"model.")
@on_trait_change('fid_points')
def reset_fiducials(self):
if self.fid_points is not None:
self.lpa = self.fid_points[0:1]
self.nasion = self.fid_points[1:2]
self.rpa = self.fid_points[2:3]
def save(self, fname=None):
"""Save the current fiducials to a file
Parameters
----------
fname : str
Destination file path. If None, will use the current fid filename
if available, or else use the default pattern.
"""
if fname is None:
fname = self.fid_file
if not fname:
fname = self.default_fid_fname
dig = [{'kind': 1, 'ident': 1, 'r': np.array(self.lpa[0])},
{'kind': 1, 'ident': 2, 'r': np.array(self.nasion[0])},
{'kind': 1, 'ident': 3, 'r': np.array(self.rpa[0])}]
write_fiducials(fname, dig, FIFF.FIFFV_COORD_MRI)
self.fid_file = fname
@cached_property
def _get_can_reset(self):
if not self.fid_file:
return False
elif np.any(self.lpa != self.fid.points[0:1]):
return True
elif np.any(self.nasion != self.fid.points[1:2]):
return True
elif np.any(self.rpa != self.fid.points[2:3]):
return True
return False
@cached_property
def _get_can_save_as(self):
can = not (np.all(self.nasion == self.lpa) or
np.all(self.nasion == self.rpa) or
np.all(self.lpa == self.rpa))
return can
@cached_property
def _get_can_save(self):
if not self.can_save_as:
return False
elif self.fid_file:
return True
elif self.subjects_dir and self.subject:
return True
else:
return False
@cached_property
def _get_default_fid_fname(self):
fname = fid_fname.format(subjects_dir=self.subjects_dir,
subject=self.subject)
return fname
@cached_property
def _get_fid_ok(self):
return all(np.any(pt) for pt in (self.nasion, self.lpa, self.rpa))
def _reset_fired(self):
self.reset_fiducials()
# if subject changed because of a change of subjects_dir this was not
# triggered
@on_trait_change('subjects_dir,subject,use_high_res_head')
def _subject_changed(self):
subject = self.subject
subjects_dir = self.subjects_dir
if not subjects_dir or not subject:
return
path = None
if self.use_high_res_head:
path = _find_high_res_head(subjects_dir=subjects_dir,
subject=subject)
if not path:
error(None, "No high resolution head model was found for "
"subject {0}, using standard head instead. In order to "
"generate a high resolution head model, run:\n\n"
" $ mne make_scalp_surfaces -s {0}"
"\n\n".format(subject), "No High Resolution Head")
if not path:
path = head_bem_fname.format(subjects_dir=subjects_dir,
subject=subject)
self.bem.file = path
# find fiducials file
fid_files = _find_fiducials_files(subject, subjects_dir)
if len(fid_files) == 0:
self.fid.reset_traits(['file'])
self.lock_fiducials = False
else:
self.fid_file = fid_files[0].format(subjects_dir=subjects_dir,
subject=subject)
self.lock_fiducials = True
# does not seem to happen by itself ... so hard code it:
self.reset_fiducials()
class FiducialsPanel(HasPrivateTraits):
"""Set fiducials on an MRI surface"""
model = Instance(MRIHeadWithFiducialsModel)
fid_file = DelegatesTo('model')
fid_fname = DelegatesTo('model')
lpa = DelegatesTo('model')
nasion = DelegatesTo('model')
rpa = DelegatesTo('model')
can_save = DelegatesTo('model')
can_save_as = DelegatesTo('model')
can_reset = DelegatesTo('model')
fid_ok = DelegatesTo('model')
locked = DelegatesTo('model', 'lock_fiducials')
set = Enum('LPA', 'Nasion', 'RPA')
current_pos = Array(float, (1, 3)) # for editing
save_as = Button(label='Save As...')
save = Button(label='Save')
reset_fid = Button(label="Reset to File")
headview = Instance(HeadViewController)
hsp_obj = Instance(SurfaceObject)
picker = Instance(object)
# the layout of the dialog created
view = View(VGroup(Item('fid_file', label='Fiducials File'),
Item('fid_fname', show_label=False, style='readonly'),
Item('set', style='custom'),
Item('current_pos', label='Pos'),
HGroup(Item('save', enabled_when='can_save',
tooltip="If a filename is currently "
"specified, save to that file, otherwise "
"save to the default file name"),
Item('save_as', enabled_when='can_save_as'),
Item('reset_fid', enabled_when='can_reset'),
show_labels=False),
enabled_when="locked==False"))
def __init__(self, *args, **kwargs):
super(FiducialsPanel, self).__init__(*args, **kwargs)
self.sync_trait('lpa', self, 'current_pos', mutual=True)
def _reset_fid_fired(self):
self.model.reset = True
def _save_fired(self):
self.model.save()
def _save_as_fired(self):
if self.fid_file:
default_path = self.fid_file
else:
default_path = self.model.default_fid_fname
dlg = FileDialog(action="save as", wildcard=fid_wildcard,
default_path=default_path)
dlg.open()
if dlg.return_code != OK:
return
path = dlg.path
if not path.endswith('.fif'):
path = path + '.fif'
if os.path.exists(path):
answer = confirm(None, "The file %r already exists. Should it "
"be replaced?", "Overwrite File?")
if answer != YES:
return
self.model.save(path)
def _on_pick(self, picker):
if self.locked:
return
self.picker = picker
n_pos = len(picker.picked_positions)
if n_pos == 0:
logger.debug("GUI: picked empty location")
return
if picker.actor is self.hsp_obj.surf.actor.actor:
idxs = []
idx = None
pt = [picker.pick_position]
elif self.hsp_obj.surf.actor.actor in picker.actors:
idxs = [i for i in range(n_pos) if picker.actors[i] is
self.hsp_obj.surf.actor.actor]
idx = idxs[-1]
pt = [picker.picked_positions[idx]]
else:
logger.debug("GUI: picked object other than MRI")
def round_(x):
return round(x, 3)
poss = [map(round_, pos) for pos in picker.picked_positions]
pos = map(round_, picker.pick_position)
msg = ["Pick Event: %i picked_positions:" % n_pos]
line = str(pos)
if idx is None:
line += " <-pick_position"
msg.append(line)
for i, pos in enumerate(poss):
line = str(pos)
if i == idx:
line += " <- MRI mesh"
elif i in idxs:
line += " (<- also MRI mesh)"
msg.append(line)
logger.debug(os.linesep.join(msg))
if self.set == 'Nasion':
self.nasion = pt
elif self.set == 'LPA':
self.lpa = pt
elif self.set == 'RPA':
self.rpa = pt
else:
raise ValueError("set = %r" % self.set)
@on_trait_change('set')
def _on_set_change(self, obj, name, old, new):
self.sync_trait(old.lower(), self, 'current_pos', mutual=True,
remove=True)
self.sync_trait(new.lower(), self, 'current_pos', mutual=True)
if new == 'Nasion':
self.headview.front = True
elif new == 'LPA':
self.headview.left = True
elif new == 'RPA':
self.headview.right = True
# FiducialsPanel view that allows manipulating all coordinates numerically
view2 = View(VGroup(Item('fid_file', label='Fiducials File'),
Item('fid_fname', show_label=False, style='readonly'),
Item('set', style='custom'), 'lpa', 'nasion', 'rpa',
HGroup(Item('save', enabled_when='can_save'),
Item('save_as', enabled_when='can_save_as'),
Item('reset_fid', enabled_when='can_reset'),
show_labels=False),
enabled_when="locked==False"))
class FiducialsFrame(HasTraits):
"""GUI for interpolating between two KIT marker files
Parameters
----------
subject : None | str
Set the subject which is initially selected.
subjects_dir : None | str
Override the SUBJECTS_DIR environment variable.
"""
model = Instance(MRIHeadWithFiducialsModel, ())
scene = Instance(MlabSceneModel, ())
headview = Instance(HeadViewController)
spanel = Instance(SubjectSelectorPanel)
panel = Instance(FiducialsPanel)
mri_obj = Instance(SurfaceObject)
point_scale = float(defaults['mri_fid_scale'])
lpa_obj = Instance(PointObject)
nasion_obj = Instance(PointObject)
rpa_obj = Instance(PointObject)
def _headview_default(self):
return HeadViewController(scene=self.scene, system='RAS')
def _panel_default(self):
panel = FiducialsPanel(model=self.model, headview=self.headview)
panel.trait_view('view', view2)
return panel
def _spanel_default(self):
return SubjectSelectorPanel(model=self.model.subject_source)
view = View(HGroup(Item('scene',
editor=SceneEditor(scene_class=MayaviScene),
dock='vertical'),
VGroup(headview_borders,
VGroup(Item('spanel', style='custom'),
label="Subject", show_border=True,
show_labels=False),
VGroup(Item('panel', style="custom"),
label="Fiducials", show_border=True,
show_labels=False),
show_labels=False),
show_labels=False),
resizable=True,
buttons=NoButtons)
def __init__(self, subject=None, subjects_dir=None, **kwargs):
super(FiducialsFrame, self).__init__(**kwargs)
subjects_dir = get_subjects_dir(subjects_dir)
if subjects_dir is not None:
self.spanel.subjects_dir = subjects_dir
if subject is not None:
if subject in self.spanel.subjects:
self.spanel.subject = subject
@on_trait_change('scene.activated')
def _init_plot(self):
self.scene.disable_render = True
lpa_color = defaults['lpa_color']
nasion_color = defaults['nasion_color']
rpa_color = defaults['rpa_color']
# bem
color = defaults['mri_color']
self.mri_obj = SurfaceObject(points=self.model.points, color=color,
tri=self.model.tris, scene=self.scene)
self.model.on_trait_change(self._on_mri_src_change, 'tris')
self.panel.hsp_obj = self.mri_obj
# fiducials
self.lpa_obj = PointObject(scene=self.scene, color=lpa_color,
point_scale=self.point_scale)
self.panel.sync_trait('lpa', self.lpa_obj, 'points', mutual=False)
self.sync_trait('point_scale', self.lpa_obj, mutual=False)
self.nasion_obj = PointObject(scene=self.scene, color=nasion_color,
point_scale=self.point_scale)
self.panel.sync_trait('nasion', self.nasion_obj, 'points',
mutual=False)
self.sync_trait('point_scale', self.nasion_obj, mutual=False)
self.rpa_obj = PointObject(scene=self.scene, color=rpa_color,
point_scale=self.point_scale)
self.panel.sync_trait('rpa', self.rpa_obj, 'points', mutual=False)
self.sync_trait('point_scale', self.rpa_obj, mutual=False)
self.headview.left = True
self.scene.disable_render = False
# picker
self.scene.mayavi_scene.on_mouse_pick(self.panel._on_pick, type='cell')
def _on_mri_src_change(self):
if (not np.any(self.model.points)) or (not np.any(self.model.tris)):
self.mri_obj.clear()
return
self.mri_obj.points = self.model.points
self.mri_obj.tri = self.model.tris
self.mri_obj.plot()
| jniediek/mne-python | mne/gui/_fiducials_gui.py | Python | bsd-3-clause | 16,783 | [
"Mayavi"
] | cae3cb8689c8fd4c7c690a0980733148616e3e56c984574cbad3b309c874d248 |
"""Get useful information from live Python objects.
This module encapsulates the interface provided by the internal special
attributes (co_*, im_*, tb_*, etc.) in a friendlier fashion.
It also provides some help for examining source code and class layout.
Here are some of the useful functions provided by this module:
ismodule(), isclass(), ismethod(), isfunction(), isgeneratorfunction(),
isgenerator(), istraceback(), isframe(), iscode(), isbuiltin(),
isroutine() - check object types
getmembers() - get members of an object that satisfy a given condition
getfile(), getsourcefile(), getsource() - find an object's source code
getdoc(), getcomments() - get documentation on an object
getmodule() - determine the module that an object came from
getclasstree() - arrange classes so as to represent their hierarchy
getargspec(), getargvalues(), getcallargs() - get info about function arguments
getfullargspec() - same, with support for Python 3 features
formatargspec(), formatargvalues() - format an argument spec
getouterframes(), getinnerframes() - get info about frames
currentframe() - get the current stack frame
stack(), trace() - get info about frames on the stack or in a traceback
signature() - get a Signature object for the callable
"""
# This module is in the public domain. No warranties.
__author__ = ('Ka-Ping Yee <ping@lfw.org>',
'Yury Selivanov <yselivanov@sprymix.com>')
import ast
import dis
import collections.abc
import enum
import importlib.machinery
import itertools
import linecache
import os
import re
import sys
import tokenize
import token
import types
import warnings
import functools
import builtins
from operator import attrgetter
from collections import namedtuple, OrderedDict
# Create constants for the compiler flags in Include/code.h
# We try to get them from dis to avoid duplication
mod_dict = globals()
for k, v in dis.COMPILER_FLAG_NAMES.items():
mod_dict["CO_" + v] = k
# See Include/object.h
TPFLAGS_IS_ABSTRACT = 1 << 20
# ----------------------------------------------------------- type-checking
def ismodule(object):
"""Return true if the object is a module.
Module objects provide these attributes:
__cached__ pathname to byte compiled file
__doc__ documentation string
__file__ filename (missing for built-in modules)"""
return isinstance(object, types.ModuleType)
def isclass(object):
"""Return true if the object is a class.
Class objects provide these attributes:
__doc__ documentation string
__module__ name of module in which this class was defined"""
return isinstance(object, type)
def ismethod(object):
"""Return true if the object is an instance method.
Instance method objects provide these attributes:
__doc__ documentation string
__name__ name with which this method was defined
__func__ function object containing implementation of method
__self__ instance to which this method is bound"""
return isinstance(object, types.MethodType)
def ismethoddescriptor(object):
"""Return true if the object is a method descriptor.
But not if ismethod() or isclass() or isfunction() are true.
This is new in Python 2.2, and, for example, is true of int.__add__.
An object passing this test has a __get__ attribute but not a __set__
attribute, but beyond that the set of attributes varies. __name__ is
usually sensible, and __doc__ often is.
Methods implemented via descriptors that also pass one of the other
tests return false from the ismethoddescriptor() test, simply because
the other tests promise more -- you can, e.g., count on having the
__func__ attribute (etc) when an object passes ismethod()."""
if isclass(object) or ismethod(object) or isfunction(object):
# mutual exclusion
return False
tp = type(object)
return hasattr(tp, "__get__") and not hasattr(tp, "__set__")
def isdatadescriptor(object):
"""Return true if the object is a data descriptor.
Data descriptors have both a __get__ and a __set__ attribute. Examples are
properties (defined in Python) and getsets and members (defined in C).
Typically, data descriptors will also have __name__ and __doc__ attributes
(properties, getsets, and members have both of these attributes), but this
is not guaranteed."""
if isclass(object) or ismethod(object) or isfunction(object):
# mutual exclusion
return False
tp = type(object)
return hasattr(tp, "__set__") and hasattr(tp, "__get__")
if hasattr(types, 'MemberDescriptorType'):
# CPython and equivalent
def ismemberdescriptor(object):
"""Return true if the object is a member descriptor.
Member descriptors are specialized descriptors defined in extension
modules."""
return isinstance(object, types.MemberDescriptorType)
else:
# Other implementations
def ismemberdescriptor(object):
"""Return true if the object is a member descriptor.
Member descriptors are specialized descriptors defined in extension
modules."""
return False
if hasattr(types, 'GetSetDescriptorType'):
# CPython and equivalent
def isgetsetdescriptor(object):
"""Return true if the object is a getset descriptor.
getset descriptors are specialized descriptors defined in extension
modules."""
return isinstance(object, types.GetSetDescriptorType)
else:
# Other implementations
def isgetsetdescriptor(object):
"""Return true if the object is a getset descriptor.
getset descriptors are specialized descriptors defined in extension
modules."""
return False
def isfunction(object):
"""Return true if the object is a user-defined function.
Function objects provide these attributes:
__doc__ documentation string
__name__ name with which this function was defined
__code__ code object containing compiled function bytecode
__defaults__ tuple of any default values for arguments
__globals__ global namespace in which this function was defined
__annotations__ dict of parameter annotations
__kwdefaults__ dict of keyword only parameters with defaults"""
return isinstance(object, types.FunctionType)
def isgeneratorfunction(object):
"""Return true if the object is a user-defined generator function.
Generator function objects provides same attributes as functions.
See help(isfunction) for attributes listing."""
return bool((isfunction(object) or ismethod(object)) and
object.__code__.co_flags & CO_GENERATOR)
def iscoroutinefunction(object):
"""Return true if the object is a coroutine function.
Coroutine functions are defined with "async def" syntax,
or generators decorated with "types.coroutine".
"""
return bool((isfunction(object) or ismethod(object)) and
object.__code__.co_flags & CO_COROUTINE)
def isgenerator(object):
"""Return true if the object is a generator.
Generator objects provide these attributes:
__iter__ defined to support iteration over container
close raises a new GeneratorExit exception inside the
generator to terminate the iteration
gi_code code object
gi_frame frame object or possibly None once the generator has
been exhausted
gi_running set to 1 when generator is executing, 0 otherwise
next return the next item from the container
send resumes the generator and "sends" a value that becomes
the result of the current yield-expression
throw used to raise an exception inside the generator"""
return isinstance(object, types.GeneratorType)
def iscoroutine(object):
"""Return true if the object is a coroutine."""
return isinstance(object, types.CoroutineType)
def isawaitable(object):
"""Return true is object can be passed to an ``await`` expression."""
return (isinstance(object, types.CoroutineType) or
isinstance(object, types.GeneratorType) and
object.gi_code.co_flags & CO_ITERABLE_COROUTINE or
isinstance(object, collections.abc.Awaitable))
def istraceback(object):
"""Return true if the object is a traceback.
Traceback objects provide these attributes:
tb_frame frame object at this level
tb_lasti index of last attempted instruction in bytecode
tb_lineno current line number in Python source code
tb_next next inner traceback object (called by this level)"""
return isinstance(object, types.TracebackType)
def isframe(object):
"""Return true if the object is a frame object.
Frame objects provide these attributes:
f_back next outer frame object (this frame's caller)
f_builtins built-in namespace seen by this frame
f_code code object being executed in this frame
f_globals global namespace seen by this frame
f_lasti index of last attempted instruction in bytecode
f_lineno current line number in Python source code
f_locals local namespace seen by this frame
f_trace tracing function for this frame, or None"""
return isinstance(object, types.FrameType)
def iscode(object):
"""Return true if the object is a code object.
Code objects provide these attributes:
co_argcount number of arguments (not including * or ** args)
co_code string of raw compiled bytecode
co_consts tuple of constants used in the bytecode
co_filename name of file in which this code object was created
co_firstlineno number of first line in Python source code
co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
co_lnotab encoded mapping of line numbers to bytecode indices
co_name name with which this code object was defined
co_names tuple of names of local variables
co_nlocals number of local variables
co_stacksize virtual machine stack space required
co_varnames tuple of names of arguments and local variables"""
return isinstance(object, types.CodeType)
def isbuiltin(object):
"""Return true if the object is a built-in function or method.
Built-in functions and methods provide these attributes:
__doc__ documentation string
__name__ original name of this function or method
__self__ instance to which a method is bound, or None"""
return isinstance(object, types.BuiltinFunctionType)
def isroutine(object):
"""Return true if the object is any kind of function or method."""
return (isbuiltin(object)
or isfunction(object)
or ismethod(object)
or ismethoddescriptor(object))
def isabstract(object):
"""Return true if the object is an abstract base class (ABC)."""
return bool(isinstance(object, type) and object.__flags__ & TPFLAGS_IS_ABSTRACT)
def getmembers(object, predicate=None):
"""Return all members of an object as (name, value) pairs sorted by name.
Optionally, only return members that satisfy a given predicate."""
if isclass(object):
mro = (object,) + getmro(object)
else:
mro = ()
results = []
processed = set()
names = dir(object)
# :dd any DynamicClassAttributes to the list of names if object is a class;
# this may result in duplicate entries if, for example, a virtual
# attribute with the same name as a DynamicClassAttribute exists
try:
for base in object.__bases__:
for k, v in base.__dict__.items():
if isinstance(v, types.DynamicClassAttribute):
names.append(k)
except AttributeError:
pass
for key in names:
# First try to get the value via getattr. Some descriptors don't
# like calling their __get__ (see bug #1785), so fall back to
# looking in the __dict__.
try:
value = getattr(object, key)
# handle the duplicate key
if key in processed:
raise AttributeError
except AttributeError:
for base in mro:
if key in base.__dict__:
value = base.__dict__[key]
break
else:
# could be a (currently) missing slot member, or a buggy
# __dir__; discard and move on
continue
if not predicate or predicate(value):
results.append((key, value))
processed.add(key)
results.sort(key=lambda pair: pair[0])
return results
Attribute = namedtuple('Attribute', 'name kind defining_class object')
def classify_class_attrs(cls):
"""Return list of attribute-descriptor tuples.
For each name in dir(cls), the return list contains a 4-tuple
with these elements:
0. The name (a string).
1. The kind of attribute this is, one of these strings:
'class method' created via classmethod()
'static method' created via staticmethod()
'property' created via property()
'method' any other flavor of method or descriptor
'data' not a method
2. The class which defined this attribute (a class).
3. The object as obtained by calling getattr; if this fails, or if the
resulting object does not live anywhere in the class' mro (including
metaclasses) then the object is looked up in the defining class's
dict (found by walking the mro).
If one of the items in dir(cls) is stored in the metaclass it will now
be discovered and not have None be listed as the class in which it was
defined. Any items whose home class cannot be discovered are skipped.
"""
mro = getmro(cls)
metamro = getmro(type(cls)) # for attributes stored in the metaclass
metamro = tuple([cls for cls in metamro if cls not in (type, object)])
class_bases = (cls,) + mro
all_bases = class_bases + metamro
names = dir(cls)
# :dd any DynamicClassAttributes to the list of names;
# this may result in duplicate entries if, for example, a virtual
# attribute with the same name as a DynamicClassAttribute exists.
for base in mro:
for k, v in base.__dict__.items():
if isinstance(v, types.DynamicClassAttribute):
names.append(k)
result = []
processed = set()
for name in names:
# Get the object associated with the name, and where it was defined.
# Normal objects will be looked up with both getattr and directly in
# its class' dict (in case getattr fails [bug #1785], and also to look
# for a docstring).
# For DynamicClassAttributes on the second pass we only look in the
# class's dict.
#
# Getting an obj from the __dict__ sometimes reveals more than
# using getattr. Static and class methods are dramatic examples.
homecls = None
get_obj = None
dict_obj = None
if name not in processed:
try:
if name == '__dict__':
raise Exception("__dict__ is special, don't want the proxy")
get_obj = getattr(cls, name)
except Exception as exc:
pass
else:
homecls = getattr(get_obj, "__objclass__", homecls)
if homecls not in class_bases:
# if the resulting object does not live somewhere in the
# mro, drop it and search the mro manually
homecls = None
last_cls = None
# first look in the classes
for srch_cls in class_bases:
srch_obj = getattr(srch_cls, name, None)
if srch_obj is get_obj:
last_cls = srch_cls
# then check the metaclasses
for srch_cls in metamro:
try:
srch_obj = srch_cls.__getattr__(cls, name)
except AttributeError:
continue
if srch_obj is get_obj:
last_cls = srch_cls
if last_cls is not None:
homecls = last_cls
for base in all_bases:
if name in base.__dict__:
dict_obj = base.__dict__[name]
if homecls not in metamro:
homecls = base
break
if homecls is None:
# unable to locate the attribute anywhere, most likely due to
# buggy custom __dir__; discard and move on
continue
obj = get_obj if get_obj is not None else dict_obj
# Classify the object or its descriptor.
if isinstance(dict_obj, staticmethod):
kind = "static method"
obj = dict_obj
elif isinstance(dict_obj, classmethod):
kind = "class method"
obj = dict_obj
elif isinstance(dict_obj, property):
kind = "property"
obj = dict_obj
elif isroutine(obj):
kind = "method"
else:
kind = "data"
result.append(Attribute(name, kind, homecls, obj))
processed.add(name)
return result
# ----------------------------------------------------------- class helpers
def getmro(cls):
"Return tuple of base classes (including cls) in method resolution order."
return cls.__mro__
# -------------------------------------------------------- function helpers
def unwrap(func, *, stop=None):
"""Get the object wrapped by *func*.
Follows the chain of :attr:`__wrapped__` attributes returning the last
object in the chain.
*stop* is an optional callback accepting an object in the wrapper chain
as its sole argument that allows the unwrapping to be terminated early if
the callback returns a true value. If the callback never returns a true
value, the last object in the chain is returned as usual. For example,
:func:`signature` uses this to stop unwrapping if any object in the
chain has a ``__signature__`` attribute defined.
:exc:`ValueError` is raised if a cycle is encountered.
"""
if stop is None:
def _is_wrapper(f):
return hasattr(f, '__wrapped__')
else:
def _is_wrapper(f):
return hasattr(f, '__wrapped__') and not stop(f)
f = func # remember the original func for error reporting
memo = {id(f)} # Memoise by id to tolerate non-hashable objects
while _is_wrapper(func):
func = func.__wrapped__
id_func = id(func)
if id_func in memo:
raise ValueError('wrapper loop when unwrapping {!r}'.format(f))
memo.add(id_func)
return func
# -------------------------------------------------- source code extraction
def indentsize(line):
"""Return the indent size, in spaces, at the start of a line of text."""
expline = line.expandtabs()
return len(expline) - len(expline.lstrip())
def _findclass(func):
cls = sys.modules.get(func.__module__)
if cls is None:
return None
for name in func.__qualname__.split('.')[:-1]:
cls = getattr(cls, name)
if not isclass(cls):
return None
return cls
def _finddoc(obj):
if isclass(obj):
for base in obj.__mro__:
if base is not object:
try:
doc = base.__doc__
except AttributeError:
continue
if doc is not None:
return doc
return None
if ismethod(obj):
name = obj.__func__.__name__
self = obj.__self__
if (isclass(self) and
getattr(getattr(self, name, None), '__func__') is obj.__func__):
# classmethod
cls = self
else:
cls = self.__class__
elif isfunction(obj):
name = obj.__name__
cls = _findclass(obj)
if cls is None or getattr(cls, name) is not obj:
return None
elif isbuiltin(obj):
name = obj.__name__
self = obj.__self__
if (isclass(self) and
self.__qualname__ + '.' + name == obj.__qualname__):
# classmethod
cls = self
else:
cls = self.__class__
elif ismethoddescriptor(obj) or isdatadescriptor(obj):
name = obj.__name__
cls = obj.__objclass__
if getattr(cls, name) is not obj:
return None
elif isinstance(obj, property):
func = f.fget
name = func.__name__
cls = _findclass(func)
if cls is None or getattr(cls, name) is not obj:
return None
else:
return None
for base in cls.__mro__:
try:
doc = getattr(base, name).__doc__
except AttributeError:
continue
if doc is not None:
return doc
return None
def getdoc(object):
"""Get the documentation string for an object.
All tabs are expanded to spaces. To clean up docstrings that are
indented to line up with blocks of code, any whitespace than can be
uniformly removed from the second line onwards is removed."""
try:
doc = object.__doc__
except AttributeError:
return None
if doc is None:
try:
doc = _finddoc(object)
except (AttributeError, TypeError):
return None
if not isinstance(doc, str):
return None
return cleandoc(doc)
def cleandoc(doc):
"""Clean up indentation from docstrings.
Any whitespace that can be uniformly removed from the second line
onwards is removed."""
try:
lines = doc.expandtabs().split('\n')
except UnicodeError:
return None
else:
# Find minimum indentation of any non-blank lines after first line.
margin = sys.maxsize
for line in lines[1:]:
content = len(line.lstrip())
if content:
indent = len(line) - content
margin = min(margin, indent)
# Remove indentation.
if lines:
lines[0] = lines[0].lstrip()
if margin < sys.maxsize:
for i in range(1, len(lines)): lines[i] = lines[i][margin:]
# Remove any trailing or leading blank lines.
while lines and not lines[-1]:
lines.pop()
while lines and not lines[0]:
lines.pop(0)
return '\n'.join(lines)
def getfile(object):
"""Work out which source or compiled file an object was defined in."""
if ismodule(object):
if hasattr(object, '__file__'):
return object.__file__
raise TypeError('{!r} is a built-in module'.format(object))
if isclass(object):
if hasattr(object, '__module__'):
object = sys.modules.get(object.__module__)
if hasattr(object, '__file__'):
return object.__file__
raise TypeError('{!r} is a built-in class'.format(object))
if ismethod(object):
object = object.__func__
if isfunction(object):
object = object.__code__
if istraceback(object):
object = object.tb_frame
if isframe(object):
object = object.f_code
if iscode(object):
return object.co_filename
raise TypeError('{!r} is not a module, class, method, '
'function, traceback, frame, or code object'.format(object))
ModuleInfo = namedtuple('ModuleInfo', 'name suffix mode module_type')
def getmoduleinfo(path):
"""Get the module name, suffix, mode, and module type for a given file."""
warnings.warn('inspect.getmoduleinfo() is deprecated', DeprecationWarning,
2)
with warnings.catch_warnings():
warnings.simplefilter('ignore', PendingDeprecationWarning)
import imp
filename = os.path.basename(path)
suffixes = [(-len(suffix), suffix, mode, mtype)
for suffix, mode, mtype in imp.get_suffixes()]
suffixes.sort() # try longest suffixes first, in case they overlap
for neglen, suffix, mode, mtype in suffixes:
if filename[neglen:] == suffix:
return ModuleInfo(filename[:neglen], suffix, mode, mtype)
def getmodulename(path):
"""Return the module name for a given file, or None."""
fname = os.path.basename(path)
# Check for paths that look like an actual module file
suffixes = [(-len(suffix), suffix)
for suffix in importlib.machinery.all_suffixes()]
suffixes.sort() # try longest suffixes first, in case they overlap
for neglen, suffix in suffixes:
if fname.endswith(suffix):
return fname[:neglen]
return None
def getsourcefile(object):
"""Return the filename that can be used to locate an object's source.
Return None if no way can be identified to get the source.
"""
filename = getfile(object)
all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
if any(filename.endswith(s) for s in all_bytecode_suffixes):
filename = (os.path.splitext(filename)[0] +
importlib.machinery.SOURCE_SUFFIXES[0])
elif any(filename.endswith(s) for s in
importlib.machinery.EXTENSION_SUFFIXES):
return None
if os.path.exists(filename):
return filename
# only return a non-existent filename if the module has a PEP 302 loader
if getattr(getmodule(object, filename), '__loader__', None) is not None:
return filename
# or it is in the linecache
if filename in linecache.cache:
return filename
def getabsfile(object, _filename=None):
"""Return an absolute path to the source or compiled file for an object.
The idea is for each object to have a unique origin, so this routine
normalizes the result as much as possible."""
if _filename is None:
_filename = getsourcefile(object) or getfile(object)
return os.path.normcase(os.path.abspath(_filename))
modulesbyfile = {}
_filesbymodname = {}
def getmodule(object, _filename=None):
"""Return the module an object was defined in, or None if not found."""
if ismodule(object):
return object
if hasattr(object, '__module__'):
return sys.modules.get(object.__module__)
# Try the filename to modulename cache
if _filename is not None and _filename in modulesbyfile:
return sys.modules.get(modulesbyfile[_filename])
# Try the cache again with the absolute file name
try:
file = getabsfile(object, _filename)
except TypeError:
return None
if file in modulesbyfile:
return sys.modules.get(modulesbyfile[file])
# Update the filename to module name cache and check yet again
# Copy sys.modules in order to cope with changes while iterating
for modname, module in list(sys.modules.items()):
if ismodule(module) and hasattr(module, '__file__'):
f = module.__file__
if f == _filesbymodname.get(modname, None):
# Have already mapped this module, so skip it
continue
_filesbymodname[modname] = f
f = getabsfile(module)
# Always map to the name the module knows itself by
modulesbyfile[f] = modulesbyfile[
os.path.realpath(f)] = module.__name__
if file in modulesbyfile:
return sys.modules.get(modulesbyfile[file])
# Check the main module
main = sys.modules['__main__']
if not hasattr(object, '__name__'):
return None
if hasattr(main, object.__name__):
mainobject = getattr(main, object.__name__)
if mainobject is object:
return main
# Check builtins
builtin = sys.modules['builtins']
if hasattr(builtin, object.__name__):
builtinobject = getattr(builtin, object.__name__)
if builtinobject is object:
return builtin
def findsource(object):
"""Return the entire source file and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of all the lines
in the file and the line number indexes a line in that list. An OSError
is raised if the source code cannot be retrieved."""
file = getsourcefile(object)
if file:
# Invalidate cache if needed.
linecache.checkcache(file)
else:
file = getfile(object)
# Allow filenames in form of "<something>" to pass through.
# `doctest` monkeypatches `linecache` module to enable
# inspection, so let `linecache.getlines` to be called.
if not (file.startswith('<') and file.endswith('>')):
raise OSError('source code not available')
module = getmodule(object, file)
if module:
lines = linecache.getlines(file, module.__dict__)
else:
lines = linecache.getlines(file)
if not lines:
raise OSError('could not get source code')
if ismodule(object):
return lines, 0
if isclass(object):
name = object.__name__
pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
# make some effort to find the best matching class definition:
# use the one with the least indentation, which is the one
# that's most probably not inside a function definition.
candidates = []
for i in range(len(lines)):
match = pat.match(lines[i])
if match:
# if it's at toplevel, it's already the best one
if lines[i][0] == 'c':
return lines, i
# else add whitespace to candidate list
candidates.append((match.group(1), i))
if candidates:
# this will sort by whitespace, and by line number,
# less whitespace first
candidates.sort()
return lines, candidates[0][1]
else:
raise OSError('could not find class definition')
if ismethod(object):
object = object.__func__
if isfunction(object):
object = object.__code__
if istraceback(object):
object = object.tb_frame
if isframe(object):
object = object.f_code
if iscode(object):
if not hasattr(object, 'co_firstlineno'):
raise OSError('could not find function definition')
lnum = object.co_firstlineno - 1
pat = re.compile(r'^(\s*def\s)|(\s*async\s+def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
while lnum > 0:
if pat.match(lines[lnum]): break
lnum = lnum - 1
return lines, lnum
raise OSError('could not find code object')
def getcomments(object):
"""Get lines of comments immediately preceding an object's source code.
Returns None when source can't be found.
"""
try:
lines, lnum = findsource(object)
except (OSError, TypeError):
return None
if ismodule(object):
# Look for a comment block at the top of the file.
start = 0
if lines and lines[0][:2] == '#!': start = 1
while start < len(lines) and lines[start].strip() in ('', '#'):
start = start + 1
if start < len(lines) and lines[start][:1] == '#':
comments = []
end = start
while end < len(lines) and lines[end][:1] == '#':
comments.append(lines[end].expandtabs())
end = end + 1
return ''.join(comments)
# Look for a preceding block of comments at the same indentation.
elif lnum > 0:
indent = indentsize(lines[lnum])
end = lnum - 1
if end >= 0 and lines[end].lstrip()[:1] == '#' and \
indentsize(lines[end]) == indent:
comments = [lines[end].expandtabs().lstrip()]
if end > 0:
end = end - 1
comment = lines[end].expandtabs().lstrip()
while comment[:1] == '#' and indentsize(lines[end]) == indent:
comments[:0] = [comment]
end = end - 1
if end < 0: break
comment = lines[end].expandtabs().lstrip()
while comments and comments[0].strip() == '#':
comments[:1] = []
while comments and comments[-1].strip() == '#':
comments[-1:] = []
return ''.join(comments)
class EndOfBlock(Exception): pass
class BlockFinder:
"""Provide a tokeneater() method to detect the end of a code block."""
def __init__(self):
self.indent = 0
self.islambda = False
self.started = False
self.passline = False
self.indecorator = False
self.decoratorhasargs = False
self.last = 1
def tokeneater(self, type, token, srowcol, erowcol, line):
if not self.started and not self.indecorator:
# skip any decorators
if token == "@":
self.indecorator = True
# look for the first "def", "class" or "lambda"
elif token in ("def", "class", "lambda"):
if token == "lambda":
self.islambda = True
self.started = True
self.passline = True # skip to the end of the line
elif token == "(":
if self.indecorator:
self.decoratorhasargs = True
elif token == ")":
if self.indecorator:
self.indecorator = False
self.decoratorhasargs = False
elif type == tokenize.NEWLINE:
self.passline = False # stop skipping when a NEWLINE is seen
self.last = srowcol[0]
if self.islambda: # lambdas always end at the first NEWLINE
raise EndOfBlock
# hitting a NEWLINE when in a decorator without args
# ends the decorator
if self.indecorator and not self.decoratorhasargs:
self.indecorator = False
elif self.passline:
pass
elif type == tokenize.INDENT:
self.indent = self.indent + 1
self.passline = True
elif type == tokenize.DEDENT:
self.indent = self.indent - 1
# the end of matching indent/dedent pairs end a block
# (note that this only works for "def"/"class" blocks,
# not e.g. for "if: else:" or "try: finally:" blocks)
if self.indent <= 0:
raise EndOfBlock
elif self.indent == 0 and type not in (tokenize.COMMENT, tokenize.NL):
# any other token on the same indentation level end the previous
# block as well, except the pseudo-tokens COMMENT and NL.
raise EndOfBlock
def getblock(lines):
"""Extract the block of code at the top of the given list of lines."""
blockfinder = BlockFinder()
try:
tokens = tokenize.generate_tokens(iter(lines).__next__)
for _token in tokens:
blockfinder.tokeneater(*_token)
except (EndOfBlock, IndentationError):
pass
return lines[:blockfinder.last]
def getsourcelines(object):
"""Return a list of source lines and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of the lines
corresponding to the object and the line number indicates where in the
original source file the first line of code was found. An OSError is
raised if the source code cannot be retrieved."""
object = unwrap(object)
lines, lnum = findsource(object)
if ismodule(object):
return lines, 0
else:
return getblock(lines[lnum:]), lnum + 1
def getsource(object):
"""Return the text of the source code for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a single string. An
OSError is raised if the source code cannot be retrieved."""
lines, lnum = getsourcelines(object)
return ''.join(lines)
# --------------------------------------------------- class tree extraction
def walktree(classes, children, parent):
"""Recursive helper function for getclasstree()."""
results = []
classes.sort(key=attrgetter('__module__', '__name__'))
for c in classes:
results.append((c, c.__bases__))
if c in children:
results.append(walktree(children[c], children, c))
return results
def getclasstree(classes, unique=False):
"""Arrange the given list of classes into a hierarchy of nested lists.
Where a nested list appears, it contains classes derived from the class
whose entry immediately precedes the list. Each entry is a 2-tuple
containing a class and a tuple of its base classes. If the 'unique'
argument is true, exactly one entry appears in the returned structure
for each class in the given list. Otherwise, classes using multiple
inheritance and their descendants will appear multiple times."""
children = {}
roots = []
for c in classes:
if c.__bases__:
for parent in c.__bases__:
if not parent in children:
children[parent] = []
if c not in children[parent]:
children[parent].append(c)
if unique and parent in classes: break
elif c not in roots:
roots.append(c)
for parent in children:
if parent not in classes:
roots.append(parent)
return walktree(roots, children, None)
# ------------------------------------------------ argument list extraction
Arguments = namedtuple('Arguments', 'args, varargs, varkw')
def getargs(co):
"""Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where
'args' is the list of argument names. Keyword-only arguments are
appended. 'varargs' and 'varkw' are the names of the * and **
arguments or None."""
args, varargs, kwonlyargs, varkw = _getfullargs(co)
return Arguments(args + kwonlyargs, varargs, varkw)
def _getfullargs(co):
"""Get information about the arguments accepted by a code object.
Four things are returned: (args, varargs, kwonlyargs, varkw), where
'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
and 'varkw' are the names of the * and ** arguments or None."""
if not iscode(co):
raise TypeError('{!r} is not a code object'.format(co))
nargs = co.co_argcount
names = co.co_varnames
nkwargs = co.co_kwonlyargcount
args = list(names[:nargs])
kwonlyargs = list(names[nargs:nargs+nkwargs])
step = 0
nargs += nkwargs
varargs = None
if co.co_flags & CO_VARARGS:
varargs = co.co_varnames[nargs]
nargs = nargs + 1
varkw = None
if co.co_flags & CO_VARKEYWORDS:
varkw = co.co_varnames[nargs]
return args, varargs, kwonlyargs, varkw
ArgSpec = namedtuple('ArgSpec', 'args varargs keywords defaults')
def getargspec(func):
"""Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, keywords, defaults).
'args' is a list of the argument names, including keyword-only argument names.
'varargs' and 'keywords' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.
Use the getfullargspec() API for Python 3 code, as annotations
and keyword arguments are supported. getargspec() will raise ValueError
if the func has either annotations or keyword arguments.
"""
warnings.warn("inspect.getargspec() is deprecated, "
"use inspect.signature() instead", DeprecationWarning,
stacklevel=2)
args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
getfullargspec(func)
if kwonlyargs or ann:
raise ValueError("Function has keyword-only arguments or annotations"
", use getfullargspec() API which can support them")
return ArgSpec(args, varargs, varkw, defaults)
FullArgSpec = namedtuple('FullArgSpec',
'args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, annotations')
def getfullargspec(func):
"""Get the names and default values of a callable object's arguments.
A tuple of seven things is returned:
(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
'args' is a list of the argument names.
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.
'kwonlyargs' is a list of keyword-only argument names.
'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
'annotations' is a dictionary mapping argument names to annotations.
The first four items in the tuple correspond to getargspec().
This function is deprecated, use inspect.signature() instead.
"""
try:
# Re: `skip_bound_arg=False`
#
# There is a notable difference in behaviour between getfullargspec
# and Signature: the former always returns 'self' parameter for bound
# methods, whereas the Signature always shows the actual calling
# signature of the passed object.
#
# To simulate this behaviour, we "unbind" bound methods, to trick
# inspect.signature to always return their first parameter ("self",
# usually)
# Re: `follow_wrapper_chains=False`
#
# getfullargspec() historically ignored __wrapped__ attributes,
# so we ensure that remains the case in 3.3+
sig = _signature_from_callable(func,
follow_wrapper_chains=False,
skip_bound_arg=False,
sigcls=Signature)
except Exception as ex:
# Most of the times 'signature' will raise ValueError.
# But, it can also raise AttributeError, and, maybe something
# else. So to be fully backwards compatible, we catch all
# possible exceptions here, and reraise a TypeError.
raise TypeError('unsupported callable') from ex
args = []
varargs = None
varkw = None
kwonlyargs = []
defaults = ()
annotations = {}
defaults = ()
kwdefaults = {}
if sig.return_annotation is not sig.empty:
annotations['return'] = sig.return_annotation
for param in sig.parameters.values():
kind = param.kind
name = param.name
if kind is _POSITIONAL_ONLY:
args.append(name)
elif kind is _POSITIONAL_OR_KEYWORD:
args.append(name)
if param.default is not param.empty:
defaults += (param.default,)
elif kind is _VAR_POSITIONAL:
varargs = name
elif kind is _KEYWORD_ONLY:
kwonlyargs.append(name)
if param.default is not param.empty:
kwdefaults[name] = param.default
elif kind is _VAR_KEYWORD:
varkw = name
if param.annotation is not param.empty:
annotations[name] = param.annotation
if not kwdefaults:
# compatibility with 'func.__kwdefaults__'
kwdefaults = None
if not defaults:
# compatibility with 'func.__defaults__'
defaults = None
return FullArgSpec(args, varargs, varkw, defaults,
kwonlyargs, kwdefaults, annotations)
ArgInfo = namedtuple('ArgInfo', 'args varargs keywords locals')
def getargvalues(frame):
"""Get information about arguments passed into a particular frame.
A tuple of four things is returned: (args, varargs, varkw, locals).
'args' is a list of the argument names.
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'locals' is the locals dictionary of the given frame."""
args, varargs, varkw = getargs(frame.f_code)
return ArgInfo(args, varargs, varkw, frame.f_locals)
def formatannotation(annotation, base_module=None):
if isinstance(annotation, type):
if annotation.__module__ in ('builtins', base_module):
return annotation.__qualname__
return annotation.__module__+'.'+annotation.__qualname__
return repr(annotation)
def formatannotationrelativeto(object):
module = getattr(object, '__module__', None)
def _formatannotation(annotation):
return formatannotation(annotation, module)
return _formatannotation
def formatargspec(args, varargs=None, varkw=None, defaults=None,
kwonlyargs=(), kwonlydefaults={}, annotations={},
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value),
formatreturns=lambda text: ' -> ' + text,
formatannotation=formatannotation):
"""Format an argument spec from the values returned by getargspec
or getfullargspec.
The first seven arguments are (args, varargs, varkw, defaults,
kwonlyargs, kwonlydefaults, annotations). The other five arguments
are the corresponding optional formatting functions that are called to
turn names and values into strings. The last argument is an optional
function to format the sequence of arguments."""
def formatargandannotation(arg):
result = formatarg(arg)
if arg in annotations:
result += ': ' + formatannotation(annotations[arg])
return result
specs = []
if defaults:
firstdefault = len(args) - len(defaults)
for i, arg in enumerate(args):
spec = formatargandannotation(arg)
if defaults and i >= firstdefault:
spec = spec + formatvalue(defaults[i - firstdefault])
specs.append(spec)
if varargs is not None:
specs.append(formatvarargs(formatargandannotation(varargs)))
else:
if kwonlyargs:
specs.append('*')
if kwonlyargs:
for kwonlyarg in kwonlyargs:
spec = formatargandannotation(kwonlyarg)
if kwonlydefaults and kwonlyarg in kwonlydefaults:
spec += formatvalue(kwonlydefaults[kwonlyarg])
specs.append(spec)
if varkw is not None:
specs.append(formatvarkw(formatargandannotation(varkw)))
result = '(' + ', '.join(specs) + ')'
if 'return' in annotations:
result += formatreturns(formatannotation(annotations['return']))
return result
def formatargvalues(args, varargs, varkw, locals,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value)):
"""Format an argument spec from the 4 values returned by getargvalues.
The first four arguments are (args, varargs, varkw, locals). The
next four arguments are the corresponding optional formatting functions
that are called to turn names and values into strings. The ninth
argument is an optional function to format the sequence of arguments."""
def convert(name, locals=locals,
formatarg=formatarg, formatvalue=formatvalue):
return formatarg(name) + formatvalue(locals[name])
specs = []
for i in range(len(args)):
specs.append(convert(args[i]))
if varargs:
specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
if varkw:
specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
return '(' + ', '.join(specs) + ')'
def _missing_arguments(f_name, argnames, pos, values):
names = [repr(name) for name in argnames if name not in values]
missing = len(names)
if missing == 1:
s = names[0]
elif missing == 2:
s = "{} and {}".format(*names)
else:
tail = ", {} and {}".format(*names[-2:])
del names[-2:]
s = ", ".join(names) + tail
raise TypeError("%s() missing %i required %s argument%s: %s" %
(f_name, missing,
"positional" if pos else "keyword-only",
"" if missing == 1 else "s", s))
def _too_many(f_name, args, kwonly, varargs, defcount, given, values):
atleast = len(args) - defcount
kwonly_given = len([arg for arg in kwonly if arg in values])
if varargs:
plural = atleast != 1
sig = "at least %d" % (atleast,)
elif defcount:
plural = True
sig = "from %d to %d" % (atleast, len(args))
else:
plural = len(args) != 1
sig = str(len(args))
kwonly_sig = ""
if kwonly_given:
msg = " positional argument%s (and %d keyword-only argument%s)"
kwonly_sig = (msg % ("s" if given != 1 else "", kwonly_given,
"s" if kwonly_given != 1 else ""))
raise TypeError("%s() takes %s positional argument%s but %d%s %s given" %
(f_name, sig, "s" if plural else "", given, kwonly_sig,
"was" if given == 1 and not kwonly_given else "were"))
def getcallargs(*func_and_positional, **named):
"""Get the mapping of arguments to values.
A dict is returned, with keys the function argument names (including the
names of the * and ** arguments, if any), and values the respective bound
values from 'positional' and 'named'."""
func = func_and_positional[0]
positional = func_and_positional[1:]
spec = getfullargspec(func)
args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
f_name = func.__name__
arg2value = {}
if ismethod(func) and func.__self__ is not None:
# implicit 'self' (or 'cls' for classmethods) argument
positional = (func.__self__,) + positional
num_pos = len(positional)
num_args = len(args)
num_defaults = len(defaults) if defaults else 0
n = min(num_pos, num_args)
for i in range(n):
arg2value[args[i]] = positional[i]
if varargs:
arg2value[varargs] = tuple(positional[n:])
possible_kwargs = set(args + kwonlyargs)
if varkw:
arg2value[varkw] = {}
for kw, value in named.items():
if kw not in possible_kwargs:
if not varkw:
raise TypeError("%s() got an unexpected keyword argument %r" %
(f_name, kw))
arg2value[varkw][kw] = value
continue
if kw in arg2value:
raise TypeError("%s() got multiple values for argument %r" %
(f_name, kw))
arg2value[kw] = value
if num_pos > num_args and not varargs:
_too_many(f_name, args, kwonlyargs, varargs, num_defaults,
num_pos, arg2value)
if num_pos < num_args:
req = args[:num_args - num_defaults]
for arg in req:
if arg not in arg2value:
_missing_arguments(f_name, req, True, arg2value)
for i, arg in enumerate(args[num_args - num_defaults:]):
if arg not in arg2value:
arg2value[arg] = defaults[i]
missing = 0
for kwarg in kwonlyargs:
if kwarg not in arg2value:
if kwonlydefaults and kwarg in kwonlydefaults:
arg2value[kwarg] = kwonlydefaults[kwarg]
else:
missing += 1
if missing:
_missing_arguments(f_name, kwonlyargs, False, arg2value)
return arg2value
ClosureVars = namedtuple('ClosureVars', 'nonlocals globals builtins unbound')
def getclosurevars(func):
"""
Get the mapping of free variables to their current values.
Returns a named tuple of dicts mapping the current nonlocal, global
and builtin references as seen by the body of the function. A final
set of unbound names that could not be resolved is also provided.
"""
if ismethod(func):
func = func.__func__
if not isfunction(func):
raise TypeError("'{!r}' is not a Python function".format(func))
code = func.__code__
# Nonlocal references are named in co_freevars and resolved
# by looking them up in __closure__ by positional index
if func.__closure__ is None:
nonlocal_vars = {}
else:
nonlocal_vars = {
var : cell.cell_contents
for var, cell in zip(code.co_freevars, func.__closure__)
}
# Global and builtin references are named in co_names and resolved
# by looking them up in __globals__ or __builtins__
global_ns = func.__globals__
builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
if ismodule(builtin_ns):
builtin_ns = builtin_ns.__dict__
global_vars = {}
builtin_vars = {}
unbound_names = set()
for name in code.co_names:
if name in ("None", "True", "False"):
# Because these used to be builtins instead of keywords, they
# may still show up as name references. We ignore them.
continue
try:
global_vars[name] = global_ns[name]
except KeyError:
try:
builtin_vars[name] = builtin_ns[name]
except KeyError:
unbound_names.add(name)
return ClosureVars(nonlocal_vars, global_vars,
builtin_vars, unbound_names)
# -------------------------------------------------- stack frame extraction
Traceback = namedtuple('Traceback', 'filename lineno function code_context index')
def getframeinfo(frame, context=1):
"""Get information about a frame or traceback object.
A tuple of five things is returned: the filename, the line number of
the current line, the function name, a list of lines of context from
the source code, and the index of the current line within that list.
The optional second argument specifies the number of lines of context
to return, which are centered around the current line."""
if istraceback(frame):
lineno = frame.tb_lineno
frame = frame.tb_frame
else:
lineno = frame.f_lineno
if not isframe(frame):
raise TypeError('{!r} is not a frame or traceback object'.format(frame))
filename = getsourcefile(frame) or getfile(frame)
if context > 0:
start = lineno - 1 - context//2
try:
lines, lnum = findsource(frame)
except OSError:
lines = index = None
else:
start = max(start, 1)
start = max(0, min(start, len(lines) - context))
lines = lines[start:start+context]
index = lineno - 1 - start
else:
lines = index = None
return Traceback(filename, lineno, frame.f_code.co_name, lines, index)
def getlineno(frame):
"""Get the line number from a frame object, allowing for optimization."""
# FrameType.f_lineno is now a descriptor that grovels co_lnotab
return frame.f_lineno
FrameInfo = namedtuple('FrameInfo', ('frame',) + Traceback._fields)
def getouterframes(frame, context=1):
"""Get a list of records for a frame and all higher (calling) frames.
Each record contains a frame object, filename, line number, function
name, a list of lines of context, and index within the context."""
framelist = []
while frame:
frameinfo = (frame,) + getframeinfo(frame, context)
framelist.append(FrameInfo(*frameinfo))
frame = frame.f_back
return framelist
def getinnerframes(tb, context=1):
"""Get a list of records for a traceback's frame and all lower frames.
Each record contains a frame object, filename, line number, function
name, a list of lines of context, and index within the context."""
framelist = []
while tb:
frameinfo = (tb.tb_frame,) + getframeinfo(tb, context)
framelist.append(FrameInfo(*frameinfo))
tb = tb.tb_next
return framelist
def currentframe():
"""Return the frame of the caller or None if this is not possible."""
return sys._getframe(1) if hasattr(sys, "_getframe") else None
def stack(context=1):
"""Return a list of records for the stack above the caller's frame."""
return getouterframes(sys._getframe(1), context)
def trace(context=1):
"""Return a list of records for the stack below the current exception."""
return getinnerframes(sys.exc_info()[2], context)
# ------------------------------------------------ static version of getattr
_sentinel = object()
def _static_getmro(klass):
return type.__dict__['__mro__'].__get__(klass)
def _check_instance(obj, attr):
instance_dict = {}
try:
instance_dict = object.__getattribute__(obj, "__dict__")
except AttributeError:
pass
return dict.get(instance_dict, attr, _sentinel)
def _check_class(klass, attr):
for entry in _static_getmro(klass):
if _shadowed_dict(type(entry)) is _sentinel:
try:
return entry.__dict__[attr]
except KeyError:
pass
return _sentinel
def _is_type(obj):
try:
_static_getmro(obj)
except TypeError:
return False
return True
def _shadowed_dict(klass):
dict_attr = type.__dict__["__dict__"]
for entry in _static_getmro(klass):
try:
class_dict = dict_attr.__get__(entry)["__dict__"]
except KeyError:
pass
else:
if not (type(class_dict) is types.GetSetDescriptorType and
class_dict.__name__ == "__dict__" and
class_dict.__objclass__ is entry):
return class_dict
return _sentinel
def getattr_static(obj, attr, default=_sentinel):
"""Retrieve attributes without triggering dynamic lookup via the
descriptor protocol, __getattr__ or __getattribute__.
Note: this function may not be able to retrieve all attributes
that getattr can fetch (like dynamically created attributes)
and may find attributes that getattr can't (like descriptors
that raise AttributeError). It can also return descriptor objects
instead of instance members in some cases. See the
documentation for details.
"""
instance_result = _sentinel
if not _is_type(obj):
klass = type(obj)
dict_attr = _shadowed_dict(klass)
if (dict_attr is _sentinel or
type(dict_attr) is types.MemberDescriptorType):
instance_result = _check_instance(obj, attr)
else:
klass = obj
klass_result = _check_class(klass, attr)
if instance_result is not _sentinel and klass_result is not _sentinel:
if (_check_class(type(klass_result), '__get__') is not _sentinel and
_check_class(type(klass_result), '__set__') is not _sentinel):
return klass_result
if instance_result is not _sentinel:
return instance_result
if klass_result is not _sentinel:
return klass_result
if obj is klass:
# for types we check the metaclass too
for entry in _static_getmro(type(klass)):
if _shadowed_dict(type(entry)) is _sentinel:
try:
return entry.__dict__[attr]
except KeyError:
pass
if default is not _sentinel:
return default
raise AttributeError(attr)
# ------------------------------------------------ generator introspection
GEN_CREATED = 'GEN_CREATED'
GEN_RUNNING = 'GEN_RUNNING'
GEN_SUSPENDED = 'GEN_SUSPENDED'
GEN_CLOSED = 'GEN_CLOSED'
def getgeneratorstate(generator):
"""Get current state of a generator-iterator.
Possible states are:
GEN_CREATED: Waiting to start execution.
GEN_RUNNING: Currently being executed by the interpreter.
GEN_SUSPENDED: Currently suspended at a yield expression.
GEN_CLOSED: Execution has completed.
"""
if generator.gi_running:
return GEN_RUNNING
if generator.gi_frame is None:
return GEN_CLOSED
if generator.gi_frame.f_lasti == -1:
return GEN_CREATED
return GEN_SUSPENDED
def getgeneratorlocals(generator):
"""
Get the mapping of generator local variables to their current values.
A dict is returned, with the keys the local variable names and values the
bound values."""
if not isgenerator(generator):
raise TypeError("'{!r}' is not a Python generator".format(generator))
frame = getattr(generator, "gi_frame", None)
if frame is not None:
return generator.gi_frame.f_locals
else:
return {}
# ------------------------------------------------ coroutine introspection
CORO_CREATED = 'CORO_CREATED'
CORO_RUNNING = 'CORO_RUNNING'
CORO_SUSPENDED = 'CORO_SUSPENDED'
CORO_CLOSED = 'CORO_CLOSED'
def getcoroutinestate(coroutine):
"""Get current state of a coroutine object.
Possible states are:
CORO_CREATED: Waiting to start execution.
CORO_RUNNING: Currently being executed by the interpreter.
CORO_SUSPENDED: Currently suspended at an await expression.
CORO_CLOSED: Execution has completed.
"""
if coroutine.cr_running:
return CORO_RUNNING
if coroutine.cr_frame is None:
return CORO_CLOSED
if coroutine.cr_frame.f_lasti == -1:
return CORO_CREATED
return CORO_SUSPENDED
def getcoroutinelocals(coroutine):
"""
Get the mapping of coroutine local variables to their current values.
A dict is returned, with the keys the local variable names and values the
bound values."""
frame = getattr(coroutine, "cr_frame", None)
if frame is not None:
return frame.f_locals
else:
return {}
###############################################################################
### Function Signature Object (PEP 362)
###############################################################################
_WrapperDescriptor = type(type.__call__)
_MethodWrapper = type(all.__call__)
_ClassMethodWrapper = type(int.__dict__['from_bytes'])
_NonUserDefinedCallables = (_WrapperDescriptor,
_MethodWrapper,
_ClassMethodWrapper,
types.BuiltinFunctionType)
def _signature_get_user_defined_method(cls, method_name):
"""Private helper. Checks if ``cls`` has an attribute
named ``method_name`` and returns it only if it is a
pure python function.
"""
try:
meth = getattr(cls, method_name)
except AttributeError:
return
else:
if not isinstance(meth, _NonUserDefinedCallables):
# Once '__signature__' will be added to 'C'-level
# callables, this check won't be necessary
return meth
def _signature_get_partial(wrapped_sig, partial, extra_args=()):
"""Private helper to calculate how 'wrapped_sig' signature will
look like after applying a 'functools.partial' object (or alike)
on it.
"""
old_params = wrapped_sig.parameters
new_params = OrderedDict(old_params.items())
partial_args = partial.args or ()
partial_keywords = partial.keywords or {}
if extra_args:
partial_args = extra_args + partial_args
try:
ba = wrapped_sig.bind_partial(*partial_args, **partial_keywords)
except TypeError as ex:
msg = 'partial object {!r} has incorrect arguments'.format(partial)
raise ValueError(msg) from ex
transform_to_kwonly = False
for param_name, param in old_params.items():
try:
arg_value = ba.arguments[param_name]
except KeyError:
pass
else:
if param.kind is _POSITIONAL_ONLY:
# If positional-only parameter is bound by partial,
# it effectively disappears from the signature
new_params.pop(param_name)
continue
if param.kind is _POSITIONAL_OR_KEYWORD:
if param_name in partial_keywords:
# This means that this parameter, and all parameters
# after it should be keyword-only (and var-positional
# should be removed). Here's why. Consider the following
# function:
# foo(a, b, *args, c):
# pass
#
# "partial(foo, a='spam')" will have the following
# signature: "(*, a='spam', b, c)". Because attempting
# to call that partial with "(10, 20)" arguments will
# raise a TypeError, saying that "a" argument received
# multiple values.
transform_to_kwonly = True
# Set the new default value
new_params[param_name] = param.replace(default=arg_value)
else:
# was passed as a positional argument
new_params.pop(param.name)
continue
if param.kind is _KEYWORD_ONLY:
# Set the new default value
new_params[param_name] = param.replace(default=arg_value)
if transform_to_kwonly:
assert param.kind is not _POSITIONAL_ONLY
if param.kind is _POSITIONAL_OR_KEYWORD:
new_param = new_params[param_name].replace(kind=_KEYWORD_ONLY)
new_params[param_name] = new_param
new_params.move_to_end(param_name)
elif param.kind in (_KEYWORD_ONLY, _VAR_KEYWORD):
new_params.move_to_end(param_name)
elif param.kind is _VAR_POSITIONAL:
new_params.pop(param.name)
return wrapped_sig.replace(parameters=new_params.values())
def _signature_bound_method(sig):
"""Private helper to transform signatures for unbound
functions to bound methods.
"""
params = tuple(sig.parameters.values())
if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
raise ValueError('invalid method signature')
kind = params[0].kind
if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
# Drop first parameter:
# '(p1, p2[, ...])' -> '(p2[, ...])'
params = params[1:]
else:
if kind is not _VAR_POSITIONAL:
# Unless we add a new parameter type we never
# get here
raise ValueError('invalid argument type')
# It's a var-positional parameter.
# Do nothing. '(*args[, ...])' -> '(*args[, ...])'
return sig.replace(parameters=params)
def _signature_is_builtin(obj):
"""Private helper to test if `obj` is a callable that might
support Argument Clinic's __text_signature__ protocol.
"""
return (isbuiltin(obj) or
ismethoddescriptor(obj) or
isinstance(obj, _NonUserDefinedCallables) or
# Can't test 'isinstance(type)' here, as it would
# also be True for regular python classes
obj in (type, object))
def _signature_is_functionlike(obj):
"""Private helper to test if `obj` is a duck type of FunctionType.
A good example of such objects are functions compiled with
Cython, which have all attributes that a pure Python function
would have, but have their code statically compiled.
"""
if not callable(obj) or isclass(obj):
# All function-like objects are obviously callables,
# and not classes.
return False
name = getattr(obj, '__name__', None)
code = getattr(obj, '__code__', None)
defaults = getattr(obj, '__defaults__', _void) # Important to use _void ...
kwdefaults = getattr(obj, '__kwdefaults__', _void) # ... and not None here
annotations = getattr(obj, '__annotations__', None)
return (isinstance(code, types.CodeType) and
isinstance(name, str) and
(defaults is None or isinstance(defaults, tuple)) and
(kwdefaults is None or isinstance(kwdefaults, dict)) and
isinstance(annotations, dict))
def _signature_get_bound_param(spec):
""" Private helper to get first parameter name from a
__text_signature__ of a builtin method, which should
be in the following format: '($param1, ...)'.
Assumptions are that the first argument won't have
a default value or an annotation.
"""
assert spec.startswith('($')
pos = spec.find(',')
if pos == -1:
pos = spec.find(')')
cpos = spec.find(':')
assert cpos == -1 or cpos > pos
cpos = spec.find('=')
assert cpos == -1 or cpos > pos
return spec[2:pos]
def _signature_strip_non_python_syntax(signature):
"""
Private helper function. Takes a signature in Argument Clinic's
extended signature format.
Returns a tuple of three things:
* that signature re-rendered in standard Python syntax,
* the index of the "self" parameter (generally 0), or None if
the function does not have a "self" parameter, and
* the index of the last "positional only" parameter,
or None if the signature has no positional-only parameters.
"""
if not signature:
return signature, None, None
self_parameter = None
last_positional_only = None
lines = [l.encode('ascii') for l in signature.split('\n')]
generator = iter(lines).__next__
token_stream = tokenize.tokenize(generator)
delayed_comma = False
skip_next_comma = False
text = []
add = text.append
current_parameter = 0
OP = token.OP
ERRORTOKEN = token.ERRORTOKEN
# token stream always starts with ENCODING token, skip it
t = next(token_stream)
assert t.type == tokenize.ENCODING
for t in token_stream:
type, string = t.type, t.string
if type == OP:
if string == ',':
if skip_next_comma:
skip_next_comma = False
else:
assert not delayed_comma
delayed_comma = True
current_parameter += 1
continue
if string == '/':
assert not skip_next_comma
assert last_positional_only is None
skip_next_comma = True
last_positional_only = current_parameter - 1
continue
if (type == ERRORTOKEN) and (string == '$'):
assert self_parameter is None
self_parameter = current_parameter
continue
if delayed_comma:
delayed_comma = False
if not ((type == OP) and (string == ')')):
add(', ')
add(string)
if (string == ','):
add(' ')
clean_signature = ''.join(text)
return clean_signature, self_parameter, last_positional_only
def _signature_fromstr(cls, obj, s, skip_bound_arg=True):
"""Private helper to parse content of '__text_signature__'
and return a Signature based on it.
"""
Parameter = cls._parameter_cls
clean_signature, self_parameter, last_positional_only = \
_signature_strip_non_python_syntax(s)
program = "def foo" + clean_signature + ": pass"
try:
module = ast.parse(program)
except SyntaxError:
module = None
if not isinstance(module, ast.Module):
raise ValueError("{!r} builtin has invalid signature".format(obj))
f = module.body[0]
parameters = []
empty = Parameter.empty
invalid = object()
module = None
module_dict = {}
module_name = getattr(obj, '__module__', None)
if module_name:
module = sys.modules.get(module_name, None)
if module:
module_dict = module.__dict__
sys_module_dict = sys.modules
def parse_name(node):
assert isinstance(node, ast.arg)
if node.annotation != None:
raise ValueError("Annotations are not currently supported")
return node.arg
def wrap_value(s):
try:
value = eval(s, module_dict)
except NameError:
try:
value = eval(s, sys_module_dict)
except NameError:
raise RuntimeError()
if isinstance(value, str):
return ast.Str(value)
if isinstance(value, (int, float)):
return ast.Num(value)
if isinstance(value, bytes):
return ast.Bytes(value)
if value in (True, False, None):
return ast.NameConstant(value)
raise RuntimeError()
class RewriteSymbolics(ast.NodeTransformer):
def visit_Attribute(self, node):
a = []
n = node
while isinstance(n, ast.Attribute):
a.append(n.attr)
n = n.value
if not isinstance(n, ast.Name):
raise RuntimeError()
a.append(n.id)
value = ".".join(reversed(a))
return wrap_value(value)
def visit_Name(self, node):
if not isinstance(node.ctx, ast.Load):
raise ValueError()
return wrap_value(node.id)
def p(name_node, default_node, default=empty):
name = parse_name(name_node)
if name is invalid:
return None
if default_node and default_node is not _empty:
try:
default_node = RewriteSymbolics().visit(default_node)
o = ast.literal_eval(default_node)
except ValueError:
o = invalid
if o is invalid:
return None
default = o if o is not invalid else default
parameters.append(Parameter(name, kind, default=default, annotation=empty))
# non-keyword-only parameters
args = reversed(f.args.args)
defaults = reversed(f.args.defaults)
iter = itertools.zip_longest(args, defaults, fillvalue=None)
if last_positional_only is not None:
kind = Parameter.POSITIONAL_ONLY
else:
kind = Parameter.POSITIONAL_OR_KEYWORD
for i, (name, default) in enumerate(reversed(list(iter))):
p(name, default)
if i == last_positional_only:
kind = Parameter.POSITIONAL_OR_KEYWORD
# *args
if f.args.vararg:
kind = Parameter.VAR_POSITIONAL
p(f.args.vararg, empty)
# keyword-only arguments
kind = Parameter.KEYWORD_ONLY
for name, default in zip(f.args.kwonlyargs, f.args.kw_defaults):
p(name, default)
# **kwargs
if f.args.kwarg:
kind = Parameter.VAR_KEYWORD
p(f.args.kwarg, empty)
if self_parameter is not None:
# Possibly strip the bound argument:
# - We *always* strip first bound argument if
# it is a module.
# - We don't strip first bound argument if
# skip_bound_arg is False.
assert parameters
_self = getattr(obj, '__self__', None)
self_isbound = _self is not None
self_ismodule = ismodule(_self)
if self_isbound and (self_ismodule or skip_bound_arg):
parameters.pop(0)
else:
# for builtins, self parameter is always positional-only!
p = parameters[0].replace(kind=Parameter.POSITIONAL_ONLY)
parameters[0] = p
return cls(parameters, return_annotation=cls.empty)
def _signature_from_builtin(cls, func, skip_bound_arg=True):
"""Private helper function to get signature for
builtin callables.
"""
if not _signature_is_builtin(func):
raise TypeError("{!r} is not a Python builtin "
"function".format(func))
s = getattr(func, "__text_signature__", None)
if not s:
raise ValueError("no signature found for builtin {!r}".format(func))
return _signature_fromstr(cls, func, s, skip_bound_arg)
def _signature_from_function(cls, func):
"""Private helper: constructs Signature for the given python function."""
is_duck_function = False
if not isfunction(func):
if _signature_is_functionlike(func):
is_duck_function = True
else:
# If it's not a pure Python function, and not a duck type
# of pure function:
raise TypeError('{!r} is not a Python function'.format(func))
Parameter = cls._parameter_cls
# Parameter information.
func_code = func.__code__
pos_count = func_code.co_argcount
arg_names = func_code.co_varnames
positional = tuple(arg_names[:pos_count])
keyword_only_count = func_code.co_kwonlyargcount
keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
annotations = func.__annotations__
defaults = func.__defaults__
kwdefaults = func.__kwdefaults__
if defaults:
pos_default_count = len(defaults)
else:
pos_default_count = 0
parameters = []
# Non-keyword-only parameters w/o defaults.
non_default_count = pos_count - pos_default_count
for name in positional[:non_default_count]:
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_POSITIONAL_OR_KEYWORD))
# ... w/ defaults.
for offset, name in enumerate(positional[non_default_count:]):
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_POSITIONAL_OR_KEYWORD,
default=defaults[offset]))
# *args
if func_code.co_flags & CO_VARARGS:
name = arg_names[pos_count + keyword_only_count]
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_VAR_POSITIONAL))
# Keyword-only parameters.
for name in keyword_only:
default = _empty
if kwdefaults is not None:
default = kwdefaults.get(name, _empty)
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_KEYWORD_ONLY,
default=default))
# **kwargs
if func_code.co_flags & CO_VARKEYWORDS:
index = pos_count + keyword_only_count
if func_code.co_flags & CO_VARARGS:
index += 1
name = arg_names[index]
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_VAR_KEYWORD))
# Is 'func' is a pure Python function - don't validate the
# parameters list (for correct order and defaults), it should be OK.
return cls(parameters,
return_annotation=annotations.get('return', _empty),
__validate_parameters__=is_duck_function)
def _signature_from_callable(obj, *,
follow_wrapper_chains=True,
skip_bound_arg=True,
sigcls):
"""Private helper function to get signature for arbitrary
callable objects.
"""
if not callable(obj):
raise TypeError('{!r} is not a callable object'.format(obj))
if isinstance(obj, types.MethodType):
# In this case we skip the first parameter of the underlying
# function (usually `self` or `cls`).
sig = _signature_from_callable(
obj.__func__,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
if skip_bound_arg:
return _signature_bound_method(sig)
else:
return sig
# Was this function wrapped by a decorator?
if follow_wrapper_chains:
obj = unwrap(obj, stop=(lambda f: hasattr(f, "__signature__")))
if isinstance(obj, types.MethodType):
# If the unwrapped object is a *method*, we might want to
# skip its first parameter (self).
# See test_signature_wrapped_bound_method for details.
return _signature_from_callable(
obj,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
try:
sig = obj.__signature__
except AttributeError:
pass
else:
if sig is not None:
if not isinstance(sig, Signature):
raise TypeError(
'unexpected object {!r} in __signature__ '
'attribute'.format(sig))
return sig
try:
partialmethod = obj._partialmethod
except AttributeError:
pass
else:
if isinstance(partialmethod, functools.partialmethod):
# Unbound partialmethod (see functools.partialmethod)
# This means, that we need to calculate the signature
# as if it's a regular partial object, but taking into
# account that the first positional argument
# (usually `self`, or `cls`) will not be passed
# automatically (as for boundmethods)
wrapped_sig = _signature_from_callable(
partialmethod.func,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
sig = _signature_get_partial(wrapped_sig, partialmethod, (None,))
first_wrapped_param = tuple(wrapped_sig.parameters.values())[0]
new_params = (first_wrapped_param,) + tuple(sig.parameters.values())
return sig.replace(parameters=new_params)
if isfunction(obj) or _signature_is_functionlike(obj):
# If it's a pure Python function, or an object that is duck type
# of a Python function (Cython functions, for instance), then:
return _signature_from_function(sigcls, obj)
if _signature_is_builtin(obj):
return _signature_from_builtin(sigcls, obj,
skip_bound_arg=skip_bound_arg)
if isinstance(obj, functools.partial):
wrapped_sig = _signature_from_callable(
obj.func,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
return _signature_get_partial(wrapped_sig, obj)
sig = None
if isinstance(obj, type):
# obj is a class or a metaclass
# First, let's see if it has an overloaded __call__ defined
# in its metaclass
call = _signature_get_user_defined_method(type(obj), '__call__')
if call is not None:
sig = _signature_from_callable(
call,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
else:
# Now we check if the 'obj' class has a '__new__' method
new = _signature_get_user_defined_method(obj, '__new__')
if new is not None:
sig = _signature_from_callable(
new,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
else:
# Finally, we should have at least __init__ implemented
init = _signature_get_user_defined_method(obj, '__init__')
if init is not None:
sig = _signature_from_callable(
init,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
if sig is None:
# At this point we know, that `obj` is a class, with no user-
# defined '__init__', '__new__', or class-level '__call__'
for base in obj.__mro__[:-1]:
# Since '__text_signature__' is implemented as a
# descriptor that extracts text signature from the
# class docstring, if 'obj' is derived from a builtin
# class, its own '__text_signature__' may be 'None'.
# Therefore, we go through the MRO (except the last
# class in there, which is 'object') to find the first
# class with non-empty text signature.
try:
text_sig = base.__text_signature__
except AttributeError:
pass
else:
if text_sig:
# If 'obj' class has a __text_signature__ attribute:
# return a signature based on it
return _signature_fromstr(sigcls, obj, text_sig)
# No '__text_signature__' was found for the 'obj' class.
# Last option is to check if its '__init__' is
# object.__init__ or type.__init__.
if type not in obj.__mro__:
# We have a class (not metaclass), but no user-defined
# __init__ or __new__ for it
if (obj.__init__ is object.__init__ and
obj.__new__ is object.__new__):
# Return a signature of 'object' builtin.
return signature(object)
else:
raise ValueError(
'no signature found for builtin type {!r}'.format(obj))
elif not isinstance(obj, _NonUserDefinedCallables):
# An object with __call__
# We also check that the 'obj' is not an instance of
# _WrapperDescriptor or _MethodWrapper to avoid
# infinite recursion (and even potential segfault)
call = _signature_get_user_defined_method(type(obj), '__call__')
if call is not None:
try:
sig = _signature_from_callable(
call,
follow_wrapper_chains=follow_wrapper_chains,
skip_bound_arg=skip_bound_arg,
sigcls=sigcls)
except ValueError as ex:
msg = 'no signature found for {!r}'.format(obj)
raise ValueError(msg) from ex
if sig is not None:
# For classes and objects we skip the first parameter of their
# __call__, __new__, or __init__ methods
if skip_bound_arg:
return _signature_bound_method(sig)
else:
return sig
if isinstance(obj, types.BuiltinFunctionType):
# Raise a nicer error message for builtins
msg = 'no signature found for builtin function {!r}'.format(obj)
raise ValueError(msg)
raise ValueError('callable {!r} is not supported by signature'.format(obj))
class _void:
"""A private marker - used in Parameter & Signature."""
class _empty:
"""Marker object for Signature.empty and Parameter.empty."""
class _ParameterKind(enum.IntEnum):
POSITIONAL_ONLY = 0
POSITIONAL_OR_KEYWORD = 1
VAR_POSITIONAL = 2
KEYWORD_ONLY = 3
VAR_KEYWORD = 4
def __str__(self):
return self._name_
_POSITIONAL_ONLY = _ParameterKind.POSITIONAL_ONLY
_POSITIONAL_OR_KEYWORD = _ParameterKind.POSITIONAL_OR_KEYWORD
_VAR_POSITIONAL = _ParameterKind.VAR_POSITIONAL
_KEYWORD_ONLY = _ParameterKind.KEYWORD_ONLY
_VAR_KEYWORD = _ParameterKind.VAR_KEYWORD
class Parameter:
"""Represents a parameter in a function signature.
Has the following public attributes:
* name : str
The name of the parameter as a string.
* default : object
The default value for the parameter if specified. If the
parameter has no default value, this attribute is set to
`Parameter.empty`.
* annotation
The annotation for the parameter if specified. If the
parameter has no annotation, this attribute is set to
`Parameter.empty`.
* kind : str
Describes how argument values are bound to the parameter.
Possible values: `Parameter.POSITIONAL_ONLY`,
`Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
`Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
"""
__slots__ = ('_name', '_kind', '_default', '_annotation')
POSITIONAL_ONLY = _POSITIONAL_ONLY
POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
VAR_POSITIONAL = _VAR_POSITIONAL
KEYWORD_ONLY = _KEYWORD_ONLY
VAR_KEYWORD = _VAR_KEYWORD
empty = _empty
def __init__(self, name, kind, *, default=_empty, annotation=_empty):
if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
_VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
raise ValueError("invalid value for 'Parameter.kind' attribute")
self._kind = kind
if default is not _empty:
if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
msg = '{} parameters cannot have default values'.format(kind)
raise ValueError(msg)
self._default = default
self._annotation = annotation
if name is _empty:
raise ValueError('name is a required attribute for Parameter')
if not isinstance(name, str):
raise TypeError("name must be a str, not a {!r}".format(name))
if not name.isidentifier():
raise ValueError('{!r} is not a valid parameter name'.format(name))
self._name = name
def __reduce__(self):
return (type(self),
(self._name, self._kind),
{'_default': self._default,
'_annotation': self._annotation})
def __setstate__(self, state):
self._default = state['_default']
self._annotation = state['_annotation']
@property
def name(self):
return self._name
@property
def default(self):
return self._default
@property
def annotation(self):
return self._annotation
@property
def kind(self):
return self._kind
def replace(self, *, name=_void, kind=_void,
annotation=_void, default=_void):
"""Creates a customized copy of the Parameter."""
if name is _void:
name = self._name
if kind is _void:
kind = self._kind
if annotation is _void:
annotation = self._annotation
if default is _void:
default = self._default
return type(self)(name, kind, default=default, annotation=annotation)
def __str__(self):
kind = self.kind
formatted = self._name
# Add annotation and default value
if self._annotation is not _empty:
formatted = '{}:{}'.format(formatted,
formatannotation(self._annotation))
if self._default is not _empty:
formatted = '{}={}'.format(formatted, repr(self._default))
if kind == _VAR_POSITIONAL:
formatted = '*' + formatted
elif kind == _VAR_KEYWORD:
formatted = '**' + formatted
return formatted
def __repr__(self):
return '<{} "{}">'.format(self.__class__.__name__, self)
def __hash__(self):
return hash((self.name, self.kind, self.annotation, self.default))
def __eq__(self, other):
if self is other:
return True
if not isinstance(other, Parameter):
return NotImplemented
return (self._name == other._name and
self._kind == other._kind and
self._default == other._default and
self._annotation == other._annotation)
class BoundArguments:
"""Result of `Signature.bind` call. Holds the mapping of arguments
to the function's parameters.
Has the following public attributes:
* arguments : OrderedDict
An ordered mutable mapping of parameters' names to arguments' values.
Does not contain arguments' default values.
* signature : Signature
The Signature object that created this instance.
* args : tuple
Tuple of positional arguments values.
* kwargs : dict
Dict of keyword arguments values.
"""
__slots__ = ('arguments', '_signature', '__weakref__')
def __init__(self, signature, arguments):
self.arguments = arguments
self._signature = signature
@property
def signature(self):
return self._signature
@property
def args(self):
args = []
for param_name, param in self._signature.parameters.items():
if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
break
try:
arg = self.arguments[param_name]
except KeyError:
# We're done here. Other arguments
# will be mapped in 'BoundArguments.kwargs'
break
else:
if param.kind == _VAR_POSITIONAL:
# *args
args.extend(arg)
else:
# plain argument
args.append(arg)
return tuple(args)
@property
def kwargs(self):
kwargs = {}
kwargs_started = False
for param_name, param in self._signature.parameters.items():
if not kwargs_started:
if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
kwargs_started = True
else:
if param_name not in self.arguments:
kwargs_started = True
continue
if not kwargs_started:
continue
try:
arg = self.arguments[param_name]
except KeyError:
pass
else:
if param.kind == _VAR_KEYWORD:
# **kwargs
kwargs.update(arg)
else:
# plain keyword argument
kwargs[param_name] = arg
return kwargs
def apply_defaults(self):
"""Set default values for missing arguments.
For variable-positional arguments (*args) the default is an
empty tuple.
For variable-keyword arguments (**kwargs) the default is an
empty dict.
"""
arguments = self.arguments
if not arguments:
return
new_arguments = []
for name, param in self._signature.parameters.items():
try:
new_arguments.append((name, arguments[name]))
except KeyError:
if param.default is not _empty:
val = param.default
elif param.kind is _VAR_POSITIONAL:
val = ()
elif param.kind is _VAR_KEYWORD:
val = {}
else:
# This BoundArguments was likely produced by
# Signature.bind_partial().
continue
new_arguments.append((name, val))
self.arguments = OrderedDict(new_arguments)
def __eq__(self, other):
if self is other:
return True
if not isinstance(other, BoundArguments):
return NotImplemented
return (self.signature == other.signature and
self.arguments == other.arguments)
def __setstate__(self, state):
self._signature = state['_signature']
self.arguments = state['arguments']
def __getstate__(self):
return {'_signature': self._signature, 'arguments': self.arguments}
def __repr__(self):
args = []
for arg, value in self.arguments.items():
args.append('{}={!r}'.format(arg, value))
return '<{} ({})>'.format(self.__class__.__name__, ', '.join(args))
class Signature:
"""A Signature object represents the overall signature of a function.
It stores a Parameter object for each parameter accepted by the
function, as well as information specific to the function itself.
A Signature object has the following public attributes and methods:
* parameters : OrderedDict
An ordered mapping of parameters' names to the corresponding
Parameter objects (keyword-only arguments are in the same order
as listed in `code.co_varnames`).
* return_annotation : object
The annotation for the return type of the function if specified.
If the function has no annotation for its return type, this
attribute is set to `Signature.empty`.
* bind(*args, **kwargs) -> BoundArguments
Creates a mapping from positional and keyword arguments to
parameters.
* bind_partial(*args, **kwargs) -> BoundArguments
Creates a partial mapping from positional and keyword arguments
to parameters (simulating 'functools.partial' behavior.)
"""
__slots__ = ('_return_annotation', '_parameters')
_parameter_cls = Parameter
_bound_arguments_cls = BoundArguments
empty = _empty
def __init__(self, parameters=None, *, return_annotation=_empty,
__validate_parameters__=True):
"""Constructs Signature from the given list of Parameter
objects and 'return_annotation'. All arguments are optional.
"""
if parameters is None:
params = OrderedDict()
else:
if __validate_parameters__:
params = OrderedDict()
top_kind = _POSITIONAL_ONLY
kind_defaults = False
for idx, param in enumerate(parameters):
kind = param.kind
name = param.name
if kind < top_kind:
msg = 'wrong parameter order: {!r} before {!r}'
msg = msg.format(top_kind, kind)
raise ValueError(msg)
elif kind > top_kind:
kind_defaults = False
top_kind = kind
if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
if param.default is _empty:
if kind_defaults:
# No default for this parameter, but the
# previous parameter of the same kind had
# a default
msg = 'non-default argument follows default ' \
'argument'
raise ValueError(msg)
else:
# There is a default for this parameter.
kind_defaults = True
if name in params:
msg = 'duplicate parameter name: {!r}'.format(name)
raise ValueError(msg)
params[name] = param
else:
params = OrderedDict(((param.name, param)
for param in parameters))
self._parameters = types.MappingProxyType(params)
self._return_annotation = return_annotation
@classmethod
def from_function(cls, func):
"""Constructs Signature for the given python function."""
warnings.warn("inspect.Signature.from_function() is deprecated, "
"use Signature.from_callable()",
DeprecationWarning, stacklevel=2)
return _signature_from_function(cls, func)
@classmethod
def from_builtin(cls, func):
"""Constructs Signature for the given builtin function."""
warnings.warn("inspect.Signature.from_builtin() is deprecated, "
"use Signature.from_callable()",
DeprecationWarning, stacklevel=2)
return _signature_from_builtin(cls, func)
@classmethod
def from_callable(cls, obj, *, follow_wrapped=True):
"""Constructs Signature for the given callable object."""
return _signature_from_callable(obj, sigcls=cls,
follow_wrapper_chains=follow_wrapped)
@property
def parameters(self):
return self._parameters
@property
def return_annotation(self):
return self._return_annotation
def replace(self, *, parameters=_void, return_annotation=_void):
"""Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy.
"""
if parameters is _void:
parameters = self.parameters.values()
if return_annotation is _void:
return_annotation = self._return_annotation
return type(self)(parameters,
return_annotation=return_annotation)
def _hash_basis(self):
params = tuple(param for param in self.parameters.values()
if param.kind != _KEYWORD_ONLY)
kwo_params = {param.name: param for param in self.parameters.values()
if param.kind == _KEYWORD_ONLY}
return params, kwo_params, self.return_annotation
def __hash__(self):
params, kwo_params, return_annotation = self._hash_basis()
kwo_params = frozenset(kwo_params.values())
return hash((params, kwo_params, return_annotation))
def __eq__(self, other):
if self is other:
return True
if not isinstance(other, Signature):
return NotImplemented
return self._hash_basis() == other._hash_basis()
def _bind(self, args, kwargs, *, partial=False):
"""Private method. Don't use directly."""
arguments = OrderedDict()
parameters = iter(self.parameters.values())
parameters_ex = ()
arg_vals = iter(args)
while True:
# Let's iterate through the positional arguments and corresponding
# parameters
try:
arg_val = next(arg_vals)
except StopIteration:
# No more positional arguments
try:
param = next(parameters)
except StopIteration:
# No more parameters. That's it. Just need to check that
# we have no `kwargs` after this while loop
break
else:
if param.kind == _VAR_POSITIONAL:
# That's OK, just empty *args. Let's start parsing
# kwargs
break
elif param.name in kwargs:
if param.kind == _POSITIONAL_ONLY:
msg = '{arg!r} parameter is positional only, ' \
'but was passed as a keyword'
msg = msg.format(arg=param.name)
raise TypeError(msg) from None
parameters_ex = (param,)
break
elif (param.kind == _VAR_KEYWORD or
param.default is not _empty):
# That's fine too - we have a default value for this
# parameter. So, lets start parsing `kwargs`, starting
# with the current parameter
parameters_ex = (param,)
break
else:
# No default, not VAR_KEYWORD, not VAR_POSITIONAL,
# not in `kwargs`
if partial:
parameters_ex = (param,)
break
else:
msg = 'missing a required argument: {arg!r}'
msg = msg.format(arg=param.name)
raise TypeError(msg) from None
else:
# We have a positional argument to process
try:
param = next(parameters)
except StopIteration:
raise TypeError('too many positional arguments') from None
else:
if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
# Looks like we have no parameter for this positional
# argument
raise TypeError(
'too many positional arguments') from None
if param.kind == _VAR_POSITIONAL:
# We have an '*args'-like argument, let's fill it with
# all positional arguments we have left and move on to
# the next phase
values = [arg_val]
values.extend(arg_vals)
arguments[param.name] = tuple(values)
break
if param.name in kwargs:
raise TypeError(
'multiple values for argument {arg!r}'.format(
arg=param.name)) from None
arguments[param.name] = arg_val
# Now, we iterate through the remaining parameters to process
# keyword arguments
kwargs_param = None
for param in itertools.chain(parameters_ex, parameters):
if param.kind == _VAR_KEYWORD:
# Memorize that we have a '**kwargs'-like parameter
kwargs_param = param
continue
if param.kind == _VAR_POSITIONAL:
# Named arguments don't refer to '*args'-like parameters.
# We only arrive here if the positional arguments ended
# before reaching the last parameter before *args.
continue
param_name = param.name
try:
arg_val = kwargs.pop(param_name)
except KeyError:
# We have no value for this parameter. It's fine though,
# if it has a default value, or it is an '*args'-like
# parameter, left alone by the processing of positional
# arguments.
if (not partial and param.kind != _VAR_POSITIONAL and
param.default is _empty):
raise TypeError('missing a required argument: {arg!r}'. \
format(arg=param_name)) from None
else:
if param.kind == _POSITIONAL_ONLY:
# This should never happen in case of a properly built
# Signature object (but let's have this check here
# to ensure correct behaviour just in case)
raise TypeError('{arg!r} parameter is positional only, '
'but was passed as a keyword'. \
format(arg=param.name))
arguments[param_name] = arg_val
if kwargs:
if kwargs_param is not None:
# Process our '**kwargs'-like parameter
arguments[kwargs_param.name] = kwargs
else:
raise TypeError(
'got an unexpected keyword argument {arg!r}'.format(
arg=next(iter(kwargs))))
return self._bound_arguments_cls(self, arguments)
def bind(*args, **kwargs):
"""Get a BoundArguments object, that maps the passed `args`
and `kwargs` to the function's signature. Raises `TypeError`
if the passed arguments can not be bound.
"""
return args[0]._bind(args[1:], kwargs)
def bind_partial(*args, **kwargs):
"""Get a BoundArguments object, that partially maps the
passed `args` and `kwargs` to the function's signature.
Raises `TypeError` if the passed arguments can not be bound.
"""
return args[0]._bind(args[1:], kwargs, partial=True)
def __reduce__(self):
return (type(self),
(tuple(self._parameters.values()),),
{'_return_annotation': self._return_annotation})
def __setstate__(self, state):
self._return_annotation = state['_return_annotation']
def __repr__(self):
return '<{} {}>'.format(self.__class__.__name__, self)
def __str__(self):
result = []
render_pos_only_separator = False
render_kw_only_separator = True
for param in self.parameters.values():
formatted = str(param)
kind = param.kind
if kind == _POSITIONAL_ONLY:
render_pos_only_separator = True
elif render_pos_only_separator:
# It's not a positional-only parameter, and the flag
# is set to 'True' (there were pos-only params before.)
result.append('/')
render_pos_only_separator = False
if kind == _VAR_POSITIONAL:
# OK, we have an '*args'-like parameter, so we won't need
# a '*' to separate keyword-only arguments
render_kw_only_separator = False
elif kind == _KEYWORD_ONLY and render_kw_only_separator:
# We have a keyword-only parameter to render and we haven't
# rendered an '*args'-like parameter before, so add a '*'
# separator to the parameters list ("foo(arg1, *, arg2)" case)
result.append('*')
# This condition should be only triggered once, so
# reset the flag
render_kw_only_separator = False
result.append(formatted)
if render_pos_only_separator:
# There were only positional-only parameters, hence the
# flag was not reset to 'False'
result.append('/')
rendered = '({})'.format(', '.join(result))
if self.return_annotation is not _empty:
anno = formatannotation(self.return_annotation)
rendered += ' -> {}'.format(anno)
return rendered
def signature(obj, *, follow_wrapped=True):
"""Get a signature object for the passed callable."""
return Signature.from_callable(obj, follow_wrapped=follow_wrapped)
def _main():
""" Logic for inspecting an object given at command line """
import argparse
import importlib
parser = argparse.ArgumentParser()
parser.add_argument(
'object',
help="The object to be analysed. "
"It supports the 'module:qualname' syntax")
parser.add_argument(
'-d', '--details', action='store_true',
help='Display info about the module rather than its source code')
args = parser.parse_args()
target = args.object
mod_name, has_attrs, attrs = target.partition(":")
try:
obj = module = importlib.import_module(mod_name)
except Exception as exc:
msg = "Failed to import {} ({}: {})".format(mod_name,
type(exc).__name__,
exc)
print(msg, file=sys.stderr)
exit(2)
if has_attrs:
parts = attrs.split(".")
obj = module
for part in parts:
obj = getattr(obj, part)
if module.__name__ in sys.builtin_module_names:
print("Can't get info for builtin modules.", file=sys.stderr)
exit(1)
if args.details:
print('Target: {}'.format(target))
print('Origin: {}'.format(getsourcefile(module)))
print('Cached: {}'.format(module.__cached__))
if obj is module:
print('Loader: {}'.format(repr(module.__loader__)))
if hasattr(module, '__path__'):
print('Submodule search path: {}'.format(module.__path__))
else:
try:
__, lineno = findsource(obj)
except Exception:
pass
else:
print('Line: {}'.format(lineno))
print('\n')
else:
print(getsource(obj))
if __name__ == "__main__":
_main()
| MalloyPower/parsing-python | front-end/testsuite-python-lib/Python-3.5.0/Lib/inspect.py | Python | mit | 113,311 | [
"VisIt"
] | 5d6cf4394b41ac526c7c142ffc53ade3ba55165a6512c47c95707eb2c2a213a2 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- Python -*-
# coding: shift_jis
"""
DoCoMoChatSrv.py
The project is hosted on GitHub where your could fork the project or report
issues. Visit https://github.com/roboworks/
:copyright: (c) 2015 by Hiroyuki Okada, All rights reserved.
:license: MIT License (MIT), http://www.opensource.org/licenses/MIT
"""
import sys
import time
sys.path.append(".")
import rospy
from std_msgs.msg import String
from trcp_chat.msg import DoCoMoChatRes
from trcp_chat.msg import DoCoMoChatReq
from trcp_chat.srv import DoCoMoChat
from trcp_chat.srv import DoCoMoChatResponse
import urllib2
import urllib
import json
class DoCoMoChatSrv(object):
""" DoCoMoChatSrv class """
def __init__(self):
""" Initializer """
def run(self):
""" run ros node """
# initialize ros node
rospy.init_node('DocomoChatSrv')
rospy.loginfo("start DoCoMoChatSrv node")
service_server = rospy.Service('docomo_chat', DoCoMoChat, self.Chat_handler)
rospy.loginfo("start DoCoMoChat service server")
self.url = rospy.get_param("~chat_url", "https://api.apigw.smt.docomo.ne.jp/dialogue/v1/dialogue")
self.APIKEY = rospy.get_param("~APIKEY", "XXXX")
self.api_url = self.url + '?APIKEY=%s'%(self.APIKEY)
rospy.spin()
def Chat_handler(self, query):
rospy.loginfo("DoCoMoChatSrv Querry :%s", query)
req = query.request
if req.utt == '':
return DoCoMoChatResponse(success=False)
req_data ={}
req_data['utt'] = req.utt
req_data['context'] = req.context
req_data['nickname'] = req.nickname
req_data['nickname_y'] = req.nickname_y
req_data['sex'] = req.sex
req_data['bloodtype'] = req.bloodtype
req_data['birthdateY'] = req.birthdateY
req_data['birthdateM'] = req.birthdateM
req_data['birthdateD'] = req.birthdateD
req_data['age'] = req.age
req_data['constellations'] = req.constellations
req_data['place'] = req.place
req_data['mode'] = req.mode
req_data['t'] = req.t
req = urllib2.Request(self.api_url, json.dumps(req_data))
req.add_header('Content-Type', 'application/json')
try:
res = urllib2.urlopen(req)
except Exception as e:
print e
return DoCoMoChatResponse(success=False)
resp_json = json.load(res)
res = DoCoMoChatRes()
res.utt = resp_json['utt'].encode('utf-8')
res.yomi = resp_json['yomi'].encode('utf-8')
res.mode = resp_json['mode'].encode('utf-8')
res.da = int(resp_json['da'])
res.context = resp_json['context'].encode('utf-8')
rospy.loginfo("DoCoMoChatSrv Querry :%s", res.utt)
return DoCoMoChatResponse(success=True, response=res)
if __name__ == '__main__':
try:
node = DoCoMoChatSrv()
node.run()
except rospy.ROSInterruptException:
pass
| okadahiroyuki/trcp | trcp_chat/nodes/DoCoMoChatSrv.py | Python | mit | 3,049 | [
"VisIt"
] | 2aa81efe9c5029e8207a65f16aad0450cace9f1d2c077227fb947c7f08500e04 |
#-*- coding: utf-8 -*-
import datetime
sms = local_import('sms')
m = sms.sms.Sms()
with open("/home/kam/web2py_test", "a") as f:
notifications = db(db.powiadomienia).select()
for notification in notifications:
now = datetime.datetime.now().hour * 100 + datetime.datetime.now().minute
then = int(notification['godzina'][0:2]) * 100 + int(notification['godzina'][3:5])
if now >= then:
if not notification['status']:
date1 = (datetime.datetime.now().date() + datetime.timedelta(days=notification['wyprzedzenie'])).isoformat()
f.write(date1 + "\n")
rows = db(
(db.visit.visit_day == date1)
).select()
for visit in rows:
patient = db(
(db.auth_user.id == visit.id_patient)
).select().first()
m.send(patient['phone_number'], "Przypominamy o wizycie w dniu jutrzejszym o godzinie %s.".decode('utf-8') % visit['visit_hour'])
f.write("\t%s\n" % str(patient['phone_number']))
notification.update_record(status=1)
else:
notification.update_record(status=0)
| alatar-/iwm-project | cron/notifications.py | Python | mit | 1,241 | [
"VisIt"
] | a0e021f0f71307ef0ea37f7a6598595f1d74e63953d0d2bae8a44b53cda5f872 |
'''
Created on 02.03.2014
@author: bluesbreaker
'''
from CSUStAn.astng.astng import ASTNGHandler
from CSUStAn.astng.control_flow import UCFRLinker
from CSUStAn.cross.duck_typing import DuckTypeHandler
from CSUStAn.exceptions import CSUStAnException
from lxml import etree
class UCFRBuilder(ASTNGHandler,DuckTypeHandler):
_project_name = None
_out_xml = None
_linker = None
_criteria = None
_threshold = None
_add_value = None
def __init__(self,project,out_xml,criteria,threshold,add_value):
self._project_name = project
self._out_xml = out_xml
ASTNGHandler.__init__(self,[project])
self._add_value = add_value
self._criteria = criteria
self._threshold = threshold
self.run()
def run(self):
self._linker = UCFRLinker(self._project_name,self._out_xml)
self._linker.visit(self.project)
print self._linker.dbg
self.link_duck_typing(self._linker.get_frames(),self._linker.get_classes())
print "Processed project", self._project_name
print "Writing",self._out_xml
self._linker.write_result(self.project)
def link_duck_typing(self,frames,classes):
err_cnt1 = 0
err_cnt2 = 0
succ_cnt = 0
err_methods = set([])
f_num = 1
f_len = len(frames)
non_empty_ducks = 0
found_ducks = 0
for frame in frames:
print "Processing",f_num,"frame of",f_len
f_num+=1
for name in frame.duck_info.keys():
if not frame.duck_info[name]['methods']:
''' Duck without methods access doesn't need linking'''
continue
all_calls = set([])
for m in frame.duck_info[name]['methods'].keys():
all_calls |= frame.duck_info[name]['methods'][m]
linked = {}
for m in all_calls:
linked[m] = set([])
if frame.duck_info[name]['attrs'] or frame.duck_info[name]['methods']:
non_empty_ducks += 1
found = False
for c in classes:
result = self.check_candidate(frame.duck_info[name]['attrs'], frame.duck_info[name]['methods'], c,self._criteria)
if result >= self._threshold :
target_methods = self.get_complete_signature(c)['methods']
for method_name in frame.duck_info[name]['methods'].keys():
if not target_methods.has_key(method_name):
''' This method is missed in class candidate. It can happens if capacity criteria used'''
continue
target_method = target_methods[method_name]
for call in frame.duck_info[name]['methods'][method_name]:
call_node = self._linker.get_call(call)
if call_node is not None:
if not hasattr(target_method,'id'):
''' Non-project methods or something strange '''
err_cnt1 +=1
err_methods.add(target_method)
else:
succ_cnt +=1
childs = [c for c in call_node.getchildren() if c.tag=="Getattr"]
if len(childs)==1:
"TODO fix bug!!!!!!"
if(target_method in linked[call]):
continue
if( not found):
found = True
found_ducks +=1
linked[call].add(target_method)
target_subnode = etree.Element("Target")
target_subnode.set("type","method")
target_subnode.set("cfg_id",str(target_method.id))
if self._add_value:
target_subnode.set("type_value",str(result))
childs[0].append(target_subnode)
else:
''' TODO calls in for, if etc. not handled yet'''
err_cnt2 +=1
print "Number of duck local_names",non_empty_ducks
print "Found ducks:",found_ducks,"percentage from non-empty ducks:",found_ducks*100.0/non_empty_ducks,"%"
# print err_cnt1, err_cnt2, succ_cnt
# if called=='function':
# target_subnode.set("type","function")
# if label is not None:
# target_subnode.set("label",label)
# elif called=='class':
# target_subnode.set("type","method")
# class_subnode = etree.Element("TargetClass")
# if label is not None:
# class_subnode.set("label",label)
# target_subnode.append(class_subnode)
# else:
# target_subnode.set("type","unknown")
# if called_id is not None:
# target_subnode.set("cfg_id",str(called_id))
# call_node.append(call_subnode)
| exbluesbreaker/csu-code-analysis | logilab-astng XML Generator/src/CSUStAn/ucfr/builder.py | Python | gpl-2.0 | 5,752 | [
"VisIt"
] | d33eeb57232f08944b289d7d00f101c069b35527294b4fec2699dc505cbda203 |
#!/usr/bin/env python
# Greg Von Kuster
"""
Subtract an entire query from another query
usage: %prog in_file_1 in_file_2 begin_col end_col output
"""
import sys, sets, re
from galaxy import eggs
import pkg_resources; pkg_resources.require( "bx-python" )
from bx.cookbook import doc_optparse
assert sys.version_info[:2] >= ( 2, 4 )
def get_lines(fname, begin_col='', end_col=''):
lines = set([])
i = 0
for i, line in enumerate(file(fname)):
line = line.rstrip('\r\n')
if line and not line.startswith('#'):
if begin_col and end_col:
"""Both begin_col and end_col must be integers at this point."""
try:
line = line.split('\t')
line = '\t'.join([line[j] for j in range(begin_col-1, end_col)])
lines.add( line )
except: pass
else:
lines.add( line )
if i: return (i+1, lines)
else: return (i, lines)
def main():
# Parsing Command Line here
options, args = doc_optparse.parse( __doc__ )
try:
inp1_file, inp2_file, begin_col, end_col, out_file = args
except:
doc_optparse.exception()
begin_col = begin_col.strip()
end_col = end_col.strip()
if begin_col != 'None' or end_col != 'None':
"""
The user selected columns for restriction. We'll allow default
values for both begin_col and end_col as long as the user selected
at least one of them for restriction.
"""
if begin_col == 'None':
begin_col = end_col
elif end_col == 'None':
end_col = begin_col
begin_col = int(begin_col)
end_col = int(end_col)
"""Make sure that begin_col <= end_col (switch if not)"""
if begin_col > end_col:
tmp_col = end_col
end_col = begin_col
begin_col = tmp_col
else:
begin_col = end_col = ''
try:
fo = open(out_file,'w')
except:
print >> sys.stderr, "Unable to open output file"
sys.exit()
"""
len1 is the number of lines in inp1_file
lines1 is the set of unique lines in inp1_file
diff1 is the number of duplicate lines removed from inp1_file
"""
len1, lines1 = get_lines(inp1_file, begin_col, end_col)
diff1 = len1 - len(lines1)
len2, lines2 = get_lines(inp2_file, begin_col, end_col)
lines1.difference_update(lines2)
"""lines1 is now the set of unique lines in inp1_file - the set of unique lines in inp2_file"""
for line in lines1:
print >> fo, line
fo.close()
info_msg = 'Subtracted %d lines. ' %((len1 - diff1) - len(lines1))
if begin_col and end_col:
info_msg += 'Restricted to columns c' + str(begin_col) + ' thru c' + str(end_col) + '. '
if diff1 > 0:
info_msg += 'Eliminated %d duplicate/blank/comment/invalid lines from first query.' %diff1
print info_msg
if __name__ == "__main__":
main()
| dbcls/dbcls-galaxy | tools/new_operations/subtract_query.py | Python | mit | 3,034 | [
"Galaxy"
] | 55b89b6f5ceb4cf09f7c6203727339f83bbfe68917992a6197b14b9b82960191 |
"""
Test Logger Wrapper
"""
__RCSID__ = "$Id$"
#pylint: disable=invalid-name
import unittest
import logging
import sys
from StringIO import StringIO
from DIRAC.FrameworkSystem.private.logging.Logger import Logger
from DIRAC.FrameworkSystem.private.standardLogging.LoggingRoot import LoggingRoot
from DIRAC.FrameworkSystem.private.standardLogging.Logging import Logging
oldgLogger = Logger()
gLogger = LoggingRoot()
def cleaningLog(log):
"""
Remove date and space from the log string
"""
log = log[20:]
log = log.replace(" ", "")
return log
class Test_Logging(unittest.TestCase):
"""
Test get and set levels.
"""
def setUp(self):
"""
Initialize at debug level with a sublogger and a special handler
"""
# Reinitialize the system/component name after other tests
# because LoggingRoot is a singleton and can not be reinstancied
Logging._componentName = 'Framework'
gLogger.setLevel('debug')
self.log = gLogger.getSubLogger('log')
self.buffer = StringIO()
oldgLogger.setLevel('debug')
self.oldlog = oldgLogger.getSubLogger('log')
self.oldbuffer = StringIO()
sys.stdout = self.oldbuffer
gLogger.showHeaders(True)
gLogger.showThreadIDs(False)
oldgLogger.showHeaders(True)
oldgLogger.showThreadIDs(False)
# modify the output to capture the log into a buffer
if logging.getLogger('dirac').handlers:
logging.getLogger('dirac').handlers[0].stream = self.buffer
# reset the levels
logging.getLogger('dirac').getChild('log').setLevel(logging.NOTSET)
self.log._levelModified = False
if __name__ == '__main__':
from DIRAC.FrameworkSystem.test.testLogging.Test_DisplayOptions import Test_DisplayOptions
from DIRAC.FrameworkSystem.test.testLogging.Test_Levels import Test_Levels
from DIRAC.FrameworkSystem.test.testLogging.Test_LogRecordCreation import Test_LogRecordCreation
from DIRAC.FrameworkSystem.test.testLogging.Test_SubLogger import Test_SubLogger
from DIRAC.FrameworkSystem.test.testLogging.Test_ConfigForExternalLibs import Test_ConfigForExternalLibs
suite = unittest.defaultTestLoader.loadTestsFromTestCase(Test_Logging)
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(Test_DisplayOptions))
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(Test_Levels))
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(Test_LogRecordCreation))
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(Test_SubLogger))
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(Test_ConfigForExternalLibs))
testResult = unittest.TextTestRunner(verbosity=2).run(suite)
| arrabito/DIRAC | FrameworkSystem/test/testLogging/Test_Logging.py | Python | gpl-3.0 | 2,659 | [
"DIRAC"
] | 8e60cf52cfde050c49c23528e6a73af35aed40dff8cf9ac3c3bce9c7901dccbe |
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program 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) version 2.1, February 1999.
#
# This program 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 terms and
# conditions of 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 program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Opencv(CMakePackage):
"""OpenCV is released under a BSD license and hence it's free for both
academic and commercial use. It has C++, C, Python and Java interfaces and
supports Windows, Linux, Mac OS, iOS and Android. OpenCV was designed for
computational efficiency and with a strong focus on real-time applications.
Written in optimized C/C++, the library can take advantage of multi-core
processing. Enabled with OpenCL, it can take advantage of the hardware
acceleration of the underlying heterogeneous compute platform. Adopted all
around the world, OpenCV has more than 47 thousand people of user community
and estimated number of downloads exceeding 9 million. Usage ranges from
interactive art, to mines inspection, stitching maps on the web or through
advanced robotics.
"""
homepage = 'http://opencv.org/'
url = 'https://github.com/Itseez/opencv/archive/3.1.0.tar.gz'
git = 'https://github.com/opencv/opencv.git'
version('master', branch='master')
version('3.4.1', 'a0b7a47899e67b3490ea31edc4f6e8e6')
version('3.4.0', '170732dc760e5f7ddeccbe53ba5d16a6')
version('3.3.1', 'b1ed9aea030bb5bd9df28524d97de84c')
version('3.3.0', '98a4e4c6f23ec725e808a891dc11eec4')
version('3.2.0', '1ea44a1d98c126ad40079d8eb914a72e')
version('3.1.0', 'a0669e22172dfc3225835b180744c9f0')
version('2.4.13.2', 'fe52791ce523681a67036def4c25261b')
version('2.4.13.1', 'f6d354500d5013e60dc0fc44b07a63d1')
version('2.4.13', '8feb45a71adad89b8017a777477c3eff')
version('2.4.12.3', '2496a4a4caf8fecfbfc294fbe6a814b0')
version('2.4.12.2', 'bc0c60c2ea1cf4078deef99569912fc7')
version('2.4.12.1', '7192f51434710904b5e3594872b897c3')
# Standard variants
variant('shared', default=True,
description='Enables the build of shared libraries')
variant('lapack', default=True, description='Include Lapack library support')
variant('powerpc', default=False, description='Enable PowerPC for GCC')
variant('vsx', default=False, description='Enable POWER8 and above VSX (64-bit little-endian)')
variant('fast-math', default=False,
description='Enable -ffast-math (not recommended for GCC 4.6.x)')
# OpenCV modules
variant('calib3d', default=True, description='calib3d module')
variant('core', default=True, description='Include opencv_core module into the OpenCV build')
variant('dnn', default=True, description='Build DNN support')
variant('features2d', default=True, description='features2d module')
variant('flann', default=True, description='flann module')
variant('highgui', default=True, description='Include opencv_highgui module into the OpenCV build')
variant('imgproc', default=True, description='Include opencv_imgproc module into the OpenCV build')
variant('java', default=True,
description='Activates support for Java')
variant('ml', default=True, description='Build ML support')
variant('python', default=True,
description='Enables the build of Python extensions')
variant('stitching', default=True, description='stitching module')
variant('superres', default=True, description='superres module')
variant('ts', default=True, description='Include opencv_ts module into the OpenCV build')
variant('video', default=True, description='video module')
variant('videostab', default=True, description='videostab module')
variant('videoio', default=True, description='videoio module')
# Optional 3rd party components
variant('cuda', default=True, description='Activates support for CUDA')
variant('eigen', default=True, description='Activates support for eigen')
variant('ipp', default=True, description='Activates support for IPP')
variant('ipp_iw', default=True, description='Build IPP IW from source')
variant('jasper', default=True, description='Activates support for JasPer')
variant('jpeg', default=True, description='Include JPEG support')
variant('opencl', default=True, description='Include OpenCL Runtime support')
variant('opencl_svm', default=True, description='Include OpenCL Shared Virtual Memory support')
variant('openclamdfft', default=True, description='Include OpenCL AMD OpenCL FFT library support')
variant('openclamdblas', default=True, description='Include OpenCL AMD OpenCL BLAS library support')
variant('openmp', default=True, description='Activates support for OpenMP threads')
variant('pthreads_pf', default=True, description='Use pthreads-based parallel_for')
variant('png', default=True, description='Include PNG support')
variant('qt', default=False, description='Activates support for QT')
variant('gtk', default=True, description='Activates support for GTK')
variant('tiff', default=True, description='Include TIFF support')
variant('vtk', default=True, description='Activates support for VTK')
variant('zlib', default=True, description='Build zlib from source')
# Patch to fix conflict between CUDA and OpenCV (reproduced with 3.3.0
# and 3.4.1) header file that have the same name.Problem is fixed in
# the current development branch of OpenCV. See #8461 for more information.
patch('dnn_cuda.patch', when='@3.3.0:3.4.1+cuda+dnn')
depends_on('eigen~mpfr', when='+eigen', type='build')
depends_on('zlib', when='+zlib')
depends_on('libpng', when='+png')
depends_on('jpeg', when='+jpeg')
depends_on('libtiff', when='+tiff')
depends_on('jasper', when='+jasper')
depends_on('cuda', when='+cuda')
depends_on('gtkplus', when='+gtk')
depends_on('vtk', when='+vtk')
depends_on('qt', when='+qt')
depends_on('java', when='+java')
depends_on('py-numpy', when='+python', type=('build', 'run'))
depends_on('protobuf@3.1.0', when='@3.3.0: +dnn')
depends_on('ffmpeg', when='+videoio')
depends_on('mpi', when='+videoio')
extends('python', when='+python')
def cmake_args(self):
spec = self.spec
# Standard variants
args = [
'-DBUILD_SHARED_LIBS:BOOL={0}'.format((
'ON' if '+shared' in spec else 'OFF')),
'-DENABLE_PRECOMPILED_HEADERS:BOOL=OFF',
'-DWITH_LAPACK={0}'.format((
'ON' if '+lapack' in spec else 'OFF')),
'-DENABLE_POWERPC={0}'.format((
'ON' if '+powerpc' in spec else 'OFF')),
'-DENABLE_VSX={0}'.format((
'ON' if '+vsx' in spec else 'OFF')),
'-DENABLE_FAST_MATH={0}'.format((
'ON' if '+fast-math' in spec else 'OFF')),
]
# modules
args.extend([
'-DBUILD_opencv_calib3d={0}'.format((
'ON' if '+calib3d' in spec else 'OFF')),
'-DBUILD_opencv_core:BOOL={0}'.format((
'ON' if '+core' in spec else 'OFF')),
'-DBUILD_opencv_dnn:BOOL={0}'.format((
'ON' if '+dnn' in spec else 'OFF')),
'-DBUILD_opencv_features2d={0}'.format((
'ON' if '+features2d' in spec else 'OFF')),
'-DBUILD_opencv_flann={0}'.format((
'ON' if '+flann' in spec else 'OFF')),
'-DBUILD_opencv_highgui:BOOL={0}'.format((
'ON' if '+highgui' in spec else 'OFF')),
'-DBUILD_opencv_imgproc:BOOL={0}'.format((
'ON' if '+imgproc' in spec else 'OFF')),
'-DBUILD_opencv_java:BOOL={0}'.format((
'ON' if '+java' in spec else 'OFF')),
'-DBUILD_opencv_ml={0}'.format((
'ON' if '+ml' in spec else 'OFF')),
'-DBUILD_opencv_stitching={0}'.format((
'ON' if '+stitching' in spec else 'OFF')),
'-DBUILD_opencv_superres={0}'.format((
'ON' if '+superres' in spec else 'OFF')),
'-DBUILD_opencv_ts={0}'.format((
'ON' if '+ts' in spec else 'OFF')),
'-DBUILD_opencv_video={0}'.format((
'ON' if '+video' in spec else 'OFF')),
'-DBUILD_opencv_videostab={0}'.format((
'ON' if '+videostab' in spec else 'OFF')),
'-DBUILD_opencv_videoio={0}'.format((
'ON' if '+videoio' in spec else 'OFF')),
])
# 3rd party components
args.extend([
'-DBUILD_IPP_IW:BOOL={0}'.format((
'ON' if '+ipp_iw' in spec else 'OFF')),
'-DWITH_CUDA:BOOL={0}'.format((
'ON' if '+cuda' in spec else 'OFF')),
'-DWITH_EIGEN:BOOL={0}'.format((
'ON' if '+eigen' in spec else 'OFF')),
'-DWITH_IPP:BOOL={0}'.format((
'ON' if '+ipp' in spec else 'OFF')),
'-DWITH_JASPER:BOOL={0}'.format((
'ON' if '+jasper' in spec else 'OFF')),
'-DWITH_JPEG:BOOL={0}'.format((
'ON' if '+jpeg' in spec else 'OFF')),
'-DWITH_OPENCL:BOOL={0}'.format((
'ON' if '+opencl' in spec else 'OFF')),
'-DWITH_OPENCL_SVM:BOOL={0}'.format((
'ON' if '+opencl_svm' in spec else 'OFF')),
'-DWITH_OPENCLAMDFFT:BOOL={0}'.format((
'ON' if '+openclamdfft' in spec else 'OFF')),
'-DWITH_OPENCLAMDBLAS:BOOL={0}'.format((
'ON' if '+openclamdblas' in spec else 'OFF')),
'-DWITH_OPENMP:BOOL={0}'.format((
'ON' if '+openmp' in spec else 'OFF')),
'-DWITH_PTHREADS_PF:BOOL={0}'.format((
'ON' if '+pthreads_pf' in spec else 'OFF')),
'-DWITH_PNG:BOOL={0}'.format((
'ON' if '+png' in spec else 'OFF')),
'-DWITH_QT:BOOL={0}'.format((
'ON' if '+qt' in spec else 'OFF')),
'-DWITH_TIFF:BOOL={0}'.format((
'ON' if '+tiff' in spec else 'OFF')),
'-DWITH_VTK:BOOL={0}'.format((
'ON' if '+vtk' in spec else 'OFF')),
])
# Media I/O
if '+zlib' in spec:
zlib = spec['zlib']
args.extend([
'-DZLIB_LIBRARY_{0}:FILEPATH={1}'.format((
'DEBUG' if 'build_type=Debug' in spec else 'RELEASE'),
zlib.libs[0]),
'-DZLIB_INCLUDE_DIR:PATH={0}'.format(
zlib.headers.directories[0])
])
if '+png' in spec:
libpng = spec['libpng']
args.extend([
'-DPNG_LIBRARY_{0}:FILEPATH={1}'.format((
'DEBUG' if 'build_type=Debug' in spec else 'RELEASE'),
libpng.libs[0]),
'-DPNG_INCLUDE_DIR:PATH={0}'.format(
libpng.headers.directories[0])
])
if '+jpeg' in spec:
libjpeg = spec['jpeg']
args.extend([
'-DBUILD_JPEG:BOOL=OFF',
'-DJPEG_LIBRARY:FILEPATH={0}'.format(libjpeg.libs[0]),
'-DJPEG_INCLUDE_DIR:PATH={0}'.format(
libjpeg.headers.directories[0])
])
if '+tiff' in spec:
libtiff = spec['libtiff']
args.extend([
'-DTIFF_LIBRARY_{0}:FILEPATH={1}'.format((
'DEBUG' if 'build_type=Debug' in spec else 'RELEASE'),
libtiff.libs[0]),
'-DTIFF_INCLUDE_DIR:PATH={0}'.format(
libtiff.headers.directories[0])
])
if '+jasper' in spec:
jasper = spec['jasper']
args.extend([
'-DJASPER_LIBRARY_{0}:FILEPATH={1}'.format((
'DEBUG' if 'build_type=Debug' in spec else 'RELEASE'),
jasper.libs[0]),
'-DJASPER_INCLUDE_DIR:PATH={0}'.format(
jasper.headers.directories[0])
])
# GUI
if '+gtk' not in spec:
args.extend([
'-DWITH_GTK:BOOL=OFF',
'-DWITH_GTK_2_X:BOOL=OFF'
])
elif '^gtkplus@3:' in spec:
args.extend([
'-DWITH_GTK:BOOL=ON',
'-DWITH_GTK_2_X:BOOL=OFF'
])
elif '^gtkplus@2:3' in spec:
args.extend([
'-DWITH_GTK:BOOL=OFF',
'-DWITH_GTK_2_X:BOOL=ON'
])
# Python
if '+python' in spec:
python_exe = spec['python'].command.path
python_lib = spec['python'].libs[0]
python_include_dir = spec['python'].headers.directories[0]
if '^python@3:' in spec:
args.extend([
'-DBUILD_opencv_python3=ON',
'-DPYTHON3_EXECUTABLE={0}'.format(python_exe),
'-DPYTHON3_LIBRARY={0}'.format(python_lib),
'-DPYTHON3_INCLUDE_DIR={0}'.format(python_include_dir),
'-DBUILD_opencv_python2=OFF',
])
elif '^python@2:3' in spec:
args.extend([
'-DBUILD_opencv_python2=ON',
'-DPYTHON2_EXECUTABLE={0}'.format(python_exe),
'-DPYTHON2_LIBRARY={0}'.format(python_lib),
'-DPYTHON2_INCLUDE_DIR={0}'.format(python_include_dir),
'-DBUILD_opencv_python3=OFF',
])
else:
args.extend([
'-DBUILD_opencv_python2=OFF',
'-DBUILD_opencv_python3=OFF'
])
return args
@property
def libs(self):
shared = "+shared" in self.spec
return find_libraries(
"libopencv_*", root=self.prefix, shared=shared, recursive=True
)
| krafczyk/spack | var/spack/repos/builtin/packages/opencv/package.py | Python | lgpl-2.1 | 14,992 | [
"VTK"
] | 6da26f62164b7342ee06e63b7e61dffdee1fb3d7335f717f57467d8e7b06facf |
""" Using FFT image registration to find larger offsets between the platepar and the image. """
from __future__ import print_function, division, absolute_import
try:
import imreg_dft
IMREG_INSTALLED = True
except ImportError:
IMREG_INSTALLED = False
import os
import sys
import copy
import shutil
import argparse
import numpy as np
import matplotlib.pyplot as plt
from RMS.Astrometry import ApplyAstrometry
from RMS.Astrometry.Conversions import date2JD, jd2Date, JD2HourAngle, raDec2AltAz
import RMS.ConfigReader as cr
from RMS.Formats import CALSTARS
from RMS.Formats.FFfile import getMiddleTimeFF
from RMS.Formats import Platepar
from RMS.Formats import StarCatalog
from RMS.Math import rotatePoint
# Import Cython functions
import pyximport
pyximport.install(setup_args={'include_dirs':[np.get_include()]})
from RMS.Astrometry.CyFunctions import subsetCatalog
def addPoint(img, xc, yc, radius):
""" Add a point to the image. """
img_w = img.shape[1]
img_h = img.shape[0]
sigma, mu = 1.0, 0.0
# Generate a small array with a gaussian
grid_arr = np.linspace(-radius, radius, 2*radius + 1, dtype=np.int)
x, y = np.meshgrid(grid_arr, grid_arr)
d = np.sqrt(x**2 + y**2)
gauss = 255*np.exp(-((d - mu)**2/(2.0*sigma**2)))
# Overlay the Gaussian on the image
for xi, i in enumerate(grid_arr):
for yj, j in enumerate(grid_arr):
# Compute the coordinates of the point
xp = int(i + xc)
yp = int(j + yc)
# Check that the point is inside the image
if (xp >=0) and (xp < img_w) and (yp >= 0) and (yp < img_h):
# Set the value of the gaussian to the image
img[yp, xp] = max(gauss[yj, xi], img[yp, xp])
return img
def constructImage(img_size, point_list, dot_radius):
""" Construct the image that will be fed into the FFT registration algorithm. """
# Construct images using given star positions. Map coordinates to img_size x img_size image
img = np.zeros((img_size, img_size), dtype=np.uint8)
# Add all given points to the imge
for point in point_list:
x, y = point
img = addPoint(img, x, y, dot_radius)
return img
def findStarsTransform(config, reference_list, moved_list, img_size=256, dot_radius=2, show_plot=False):
""" Given a list of reference and predicted star positions, return a transform (rotation, scale, \
translation) between the two lists using FFT image registration. This is achieved by creating a
synthetic star image using both lists and searching for the transform using phase correlation.
Arguments:
config: [Config instance]
reference_list: [2D list] A list of reference (x, y) star coordinates.
moved_list: [2D list] A list of moved (x, y) star coordinates.
Keyword arguments:
img_size: [int] Power of 2 image size (e.g. 128, 256, etc.) which will be created and fed into the
FFT registration algorithm.
dot_radius: [int] The radius of the dot which will be drawn on the synthetic image.
show_plot: [bool] Show the comparison between the reference and image synthetic images.
Return:
angle, scale, translation_x, translation_y:
- angle: [float] Angle of rotation (deg).
- scale: [float] Image scale difference.
- translation_x: [float]
- translation_y: [float]
"""
# If the image registration library is not installed, return nothing
if not IMREG_INSTALLED:
print("WARNING:")
print('The imreg_dft library is not installed! Install it by running either:')
print(' a) pip install imreg_dft')
print(' b) conda install -c conda-forge imreg_dft')
return 0.0, 1.0, 0.0, 0.0
# Set input types
reference_list = np.array(reference_list).astype(np.float)
moved_list = np.array(moved_list).astype(np.float)
# Rescale the coordinates so the whole image fits inside the square (rescale by the smaller image axis)
rescale_factor = min(config.width, config.height)/img_size
reference_list /= rescale_factor
moved_list /= rescale_factor
# Take only those coordinates which are inside img_size/2 distance from the centre, and
# shift the coordinates
shift_x = img_size/2 - config.width/(2*rescale_factor)
shift_y = img_size/2 - config.height/(2*rescale_factor)
reference_list[:, 0] += shift_x
reference_list[:, 1] += shift_y
moved_list[:, 0] += shift_x
moved_list[:, 1] += shift_y
# Construct the reference and moved images
img_ref = constructImage(img_size, reference_list, dot_radius)
img_mov = constructImage(img_size, moved_list, dot_radius)
# Run the FFT registration
try:
res = imreg_dft.imreg.similarity(img_ref, img_mov)
except ValueError:
print('imreg_dft error: The scale correction is too high!')
return 0.0, 1.0, 0.0, 0.0
except IndexError:
print('imreg_dft error: Index out of bounds!')
return 0.0, 1.0, 0.0, 0.0
angle = res['angle']
scale = res['scale']
translate = res['tvec']
# Extract translation and rescale it
translation_x = rescale_factor*translate[1]
translation_y = rescale_factor*translate[0]
print('Platepar correction:')
print(' Rotation:', angle, 'deg')
print(' Scale:', scale)
print(' Translation X, Y: ({:.2f}, {:.2f}) px'.format(translation_x, translation_y))
# Plot comparison
if show_plot:
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
ax1.imshow(img_ref, cmap='gray')
ax1.set_title('Reference')
ax2.imshow(img_mov, cmap='gray')
ax2.set_title('Moved')
ax3.imshow(res['timg'], cmap='gray')
ax3.set_title('Transformed')
ax4.imshow(np.abs(res['timg'].astype(np.int) - img_ref.astype(np.int)).astype(np.uint8), cmap='gray')
ax4.set_title('Difference')
plt.tight_layout()
plt.show()
return angle, scale, translation_x, translation_y
def alignPlatepar(config, platepar, calstars_time, calstars_coords, scale_update=False, show_plot=False):
""" Align the platepar using FFT registration between catalog stars and the given list of image stars.
Arguments:
config:
platepar: [Platepar instance] Initial platepar.
calstars_time: [list] A list of (year, month, day, hour, minute, second, millisecond) of the middle of
the FF file used for alignment.
calstars_coords: [ndarray] A 2D numpy array of (x, y) coordinates of image stars.
Keyword arguments:
scale_update: [bool] Update the platepar scale. False by default.
show_plot: [bool] Show the comparison between the reference and image synthetic images.
Return:
platepar_aligned: [Platepar instance] The aligned platepar.
"""
# Create a copy of the config not to mess with the original config parameters
config = copy.deepcopy(config)
# Try to optimize the catalog limiting magnitude until the number of image and catalog stars are matched
maxiter = 10
search_fainter = True
mag_step = 0.2
for inum in range(maxiter):
# Load the catalog stars
catalog_stars, _, _ = StarCatalog.readStarCatalog(config.star_catalog_path, config.star_catalog_file, \
lim_mag=config.catalog_mag_limit, mag_band_ratios=config.star_catalog_band_ratios)
# Get the RA/Dec of the image centre
_, ra_centre, dec_centre, _ = ApplyAstrometry.xyToRaDecPP([calstars_time], [platepar.X_res/2], \
[platepar.Y_res/2], [1], platepar, extinction_correction=False)
ra_centre = ra_centre[0]
dec_centre = dec_centre[0]
# Compute Julian date
jd = date2JD(*calstars_time)
# Calculate the FOV radius in degrees
fov_y, fov_x = ApplyAstrometry.computeFOVSize(platepar)
fov_radius = ApplyAstrometry.getFOVSelectionRadius(platepar)
# Take only those stars which are inside the FOV
filtered_indices, _ = subsetCatalog(catalog_stars, ra_centre, dec_centre, jd, platepar.lat, \
platepar.lon, fov_radius, config.catalog_mag_limit)
# Take those catalog stars which should be inside the FOV
ra_catalog, dec_catalog, _ = catalog_stars[filtered_indices].T
catalog_xy = ApplyAstrometry.raDecToXYPP(ra_catalog, dec_catalog, jd, platepar)
catalog_x, catalog_y = catalog_xy
catalog_xy = np.c_[catalog_x, catalog_y]
# Cut all stars that are outside image coordinates
catalog_xy = catalog_xy[catalog_xy[:, 0] > 0]
catalog_xy = catalog_xy[catalog_xy[:, 0] < config.width]
catalog_xy = catalog_xy[catalog_xy[:, 1] > 0]
catalog_xy = catalog_xy[catalog_xy[:, 1] < config.height]
# If there are more catalog than image stars, this means that the limiting magnitude is too faint
# and that the search should go in the brighter direction
if len(catalog_xy) > len(calstars_coords):
search_fainter = False
else:
search_fainter = True
# print('Catalog stars:', len(catalog_xy), 'Image stars:', len(calstars_coords), \
# 'Limiting magnitude:', config.catalog_mag_limit)
# Search in mag_step magnitude steps
if search_fainter:
config.catalog_mag_limit += mag_step
else:
config.catalog_mag_limit -= mag_step
print('Final catalog limiting magnitude:', config.catalog_mag_limit)
# Find the transform between the image coordinates and predicted platepar coordinates
res = findStarsTransform(config, calstars_coords, catalog_xy, show_plot=show_plot)
angle, scale, translation_x, translation_y = res
### Update the platepar ###
platepar_aligned = copy.deepcopy(platepar)
# Correct the rotation
platepar_aligned.pos_angle_ref = (platepar_aligned.pos_angle_ref - angle)%360
# Update the scale if needed
if scale_update:
platepar_aligned.F_scale *= scale
# Compute the new reference RA and Dec
_, ra_centre_new, dec_centre_new, _ = ApplyAstrometry.xyToRaDecPP([jd2Date(platepar.JD)], \
[platepar.X_res/2 - platepar.x_poly_fwd[0] - translation_x], \
[platepar.Y_res/2 - platepar.y_poly_fwd[0] - translation_y], [1], platepar, \
extinction_correction=False)
# Correct RA/Dec
platepar_aligned.RA_d = ra_centre_new[0]
platepar_aligned.dec_d = dec_centre_new[0]
# # Update the reference time and hour angle
# platepar_aligned.JD = jd
# platepar_aligned.Ho = JD2HourAngle(jd)
# Recompute the FOV centre in Alt/Az and update the rotation
platepar_aligned.az_centre, platepar_aligned.alt_centre = raDec2AltAz(platepar.RA_d, \
platepar.dec_d, platepar.JD, platepar.lat, platepar.lon)
platepar_aligned.rotation_from_horiz = ApplyAstrometry.rotationWrtHorizon(platepar_aligned)
###
return platepar_aligned
if __name__ == "__main__":
### COMMAND LINE ARGUMENTS
# Init the command line arguments parser
arg_parser = argparse.ArgumentParser(description="Align the platepar with the extracted stars from the CALSTARS file. The FF file in CALSTARS with most detected stars will be used for alignment.")
arg_parser.add_argument('dir_path', nargs=1, metavar='DIR_PATH', type=str, \
help='Path to night folder.')
arg_parser.add_argument('-c', '--config', nargs=1, metavar='CONFIG_PATH', type=str, \
help="Path to a config file which will be used instead of the default one.")
# Parse the command line arguments
cml_args = arg_parser.parse_args()
#########################
dir_path = cml_args.dir_path[0]
# Load the config file
config = cr.loadConfigFromDirectory(cml_args.config, dir_path)
# Get a list of files in the night folder
file_list = os.listdir(dir_path)
# Find and load the platepar file
if config.platepar_name in file_list:
# Load the platepar
platepar = Platepar.Platepar()
platepar_path = os.path.join(dir_path, config.platepar_name)
platepar.read(platepar_path, use_flat=config.use_flat)
else:
print('Cannot find the platepar file in the night directory: ', config.platepar_name)
sys.exit()
# Find the CALSTARS file in the given folder
calstars_file = None
for calstars_file in file_list:
if ('CALSTARS' in calstars_file) and ('.txt' in calstars_file):
break
if calstars_file is None:
print('CALSTARS file could not be found in the given directory!')
sys.exit()
# Load the calstars file
calstars_list = CALSTARS.readCALSTARS(dir_path, calstars_file)
calstars_dict = {ff_file: star_data for ff_file, star_data in calstars_list}
print('CALSTARS file: ' + calstars_file + ' loaded!')
# Extract star list from CALSTARS file from FF file with most stars
max_len_ff = max(calstars_dict, key=lambda k: len(calstars_dict[k]))
# Take only X, Y (change order so X is first)
calstars_coords = np.array(calstars_dict[max_len_ff])[:, :2]
calstars_coords[:, [0, 1]] = calstars_coords[:, [1, 0]]
# Get the time of the FF file
calstars_time = getMiddleTimeFF(max_len_ff, config.fps, ret_milliseconds=True)
# Align the platepar with stars in CALSTARS
platepar_aligned = alignPlatepar(config, platepar, calstars_time, calstars_coords, show_plot=False)
# Backup the old platepar
shutil.copy(platepar_path, platepar_path + '.bak')
# Save the updated platepar
platepar_aligned.write(platepar_path)
### Testing
sys.exit()
# class Config(object):
# def __init__(self):
# self.width = 1280
# self.height = 720
# config = Config()
# # Generate some random points as stars
# npoints = 100
# reference_list = np.c_[np.random.randint(-100, config.width + 100, size=npoints),
# np.random.randint(-100, config.height + 100, size=npoints)]
# # Create a list of shifted stars
# moved_list = np.copy(reference_list)
# # Move the dots
# moved_list[:, 0] += 50
# moved_list[:, 1] += 40
# # Rotate the moved points
# rot_angle = np.radians(25)
# origin = np.array([config.width/2, config.height/2])
# for i, mv_pt in enumerate(moved_list):
# moved_list[i] = rotatePoint(origin, mv_pt, rot_angle)
# # Choose every second star on the moved list
# moved_list = moved_list[::2]
# # Find the transform between the star lists
# print(findStarsTransform(config, reference_list, moved_list, img_size=128, dot_radius=2))
| CroatianMeteorNetwork/RMS | RMS/Astrometry/FFTalign.py | Python | gpl-3.0 | 14,794 | [
"Gaussian"
] | fdd152b23c8ec8349debf868ee784e5454be2930a8584187463cf4d74434cae6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.